text:
Q: Heat pumps: can $COP\leq 1$ and when does $COP=\frac{1}{\eta}$ hold? Heat pump COP is defined as $$\xi=\frac{|Q_{HOT}|}{|W|}$$
Where $Q_{HOT}$ is the heat given to the hot source. I have two linked doubts about it

*

*Under what conditions I can say that $\xi=\frac{1}{\eta}$ where $\eta$ is the efficiency of the system if it works as an heat engine (instead of heat pump)?

*Can $\xi\leq1$?

$1)$ We have $$\eta=\frac{W}{Q_{HOT}}\implies \xi=\frac{1}{\eta}$$
But is it always possible to talk about an hypotetical heat engine that works between the same sources and exchanges same heats and work?
My guess would be that the conditions is that the heat engine must be reversible. So in that case, $(2)$ would be valid iff the engine is reversible. Is that correct or is the condition different?

$2)$ Looking at point $1$ it seems impossible that $\xi=1$ because that would mean $\eta =1$. More in general it should be $\xi \geq 1$ (since $\eta \leq 1$).
But consider the heat pump in the diagram. I listed the trasformations below.

$$A \rightarrow B= \mathrm{reversible \, isothermic \, compression \, from \, V_A \, to \, V_B}$$
$$B \rightarrow C= \mathrm{adiabatic \, expansion \, from \, V_B \, to \, V_C}$$
$$C \rightarrow  A= \mathrm{ (irreversible) \,adiabatic \, compression \, from \, V_C \, to \, V_A}$$
(The blue curve is an irreversible process and thus should not be represented as I did)
We have $Q_{cycle}=Q_{A->B}<0$ so $W_{cycle}=Q_{A->B}<0$ so in this case $\xi=1$. And this heat pump seems possible to me because we have $\Delta S_{universe}=-\Delta S_{A->B,system}>0$.
In the end this is just a system that takes work and trasform it entirely in heat, which is (as far as I understood) allowed by the laws of thermodynamics.

I would really appreciate any suggestion on these two points on heat pumps which are not clear to me.

Just to clarify the sign convention I use is the one in picture

A: Say there are two heat reservoirs, one at higher temperature than the other. Heat pump extracts heat $Q_{cold}$ from colder reservoir, adds energy due to work $W$ to it and dumps the total $Q_{hot}=Q_{cold}+W$ into the hotter reservoir. An engine works in the opposite sequence: It extracts $Q_{hot}$ from hotter reservoir, converts part of it into work $W$, and rejects the rest to colder reservoir $Q_{cold}=Q_{hot}-W$, as is required by second law.
Now for heat pump $COP=\frac{Q_{hot}}{W}$ and for engine $\eta=\frac{W}{Q_{hot}}$, and for given $Q_{hot}$, only when both of them run on reversible cycle will they be equal. Otherwise, for a given $Q_{hot}$, $W$ for heat pump is always more than that for engine.
Now $COP=1$ is possible, in fact it is the worst case scenario (the most inefficient heat pump). But $COP<1$ is not possible because it violates energy conservation. You have extracted $Q_{cold}$ and added $W$ to it, so what you dump into hot reservoir must necessarily be equal to sum of the two and therefore always $\geq W$.


text:
Q: Calculated Property in MVC 5 ViewModel instead of Model Class
I have searched StackOverflow and MSDN and found several pages that I
  felt would help me, but once I tried implementing the solutions there
  was always something slightly different with what I needed so now I am
  here after hours of hair pulling.

Problem: I have a calculated property in my Model Class. The Class name is Render and represents a model for Photo Renderings. The calculated property will be used as a name for a Zip File I will package together on ONE VIEW for the user depending on which Render Detail page they are on. Obviously we don't want to do this in the Model because not every view or even a majority of views will be using it.
Question: How can I move this calculated property into my ViewModel?
Below you will see my current and working..

*

*Render Class

*View Model

*Controller &

*Applicable Razor Code

Render Class
public class Render
{
    public Render()
    {

    }

    public int RenderId { get; set; }
    public string ClientName { get; set; }
    public string Title { get; set; }
    public string JobId { get; set; }
    public string Comment { get; set; }

    public ICollection<Image> Images { get; set; }

    public string ZipFileName
    {
        get { return (ClientName + "-" + Title + "-" + JobId)
                .Replace(" ", string.Empty); }
    }
}

View Model
public class RenderDetailViewModel
{
    public IEnumerable<Render> AllRenders { get; set; }
    private readonly RenderLibContext _db = new RenderLibContext();

    public void PopulateRenderDetailModel(int id)
    {
        AllRenders = _db.Renders.Include("Images")
            .Where(r => r.RenderId == id)
            .ToList();
    }
}

Controller
public ActionResult Detail(int id=1)
{

    var render = _db.Renders.Include("Images")
                    .Include(r => r.Comments.Select(c => c.CommentImages))
                    .Include("VenueType").Include("ScreenCount")
                    .FirstOrDefault(r => r.RenderId == id);

    var model = new RenderDetailViewModel()
    {
        RenderId = render.RenderId,
        ClientName = render.ClientName,
        Title = render.Title,
        JobId = render.JobId,
        RenderMonth = render.RenderMonth,
        RenderYear = render.RenderYear,
        Comment = render.Comment,
        Venue = render.Venue,
        Mapping = render.Mapping,
        DefaultImageId = render.DefaultImageId

    };

    return View(model);
}

Razor Code (Abbreviated)
@model RenderLib.ViewModels.RenderDetailViewModel
...
@foreach (var group in Model.Images.Select(i => i.Version).Distinct().ToList())
{
  Set @counter
  Download
  ...
}
@foreach (var images in Model.Images
.Where(i => i.RenderId == Model.RenderId && i.Version == Request.QueryString["Set"]))
{

}

Everything above this line works fine, but my calculated property is in the wrong place, I would like it to be in my ViewModel
I know that a lot of you would like to see someone who is asking a question like this to show anything they have already tried to make sure I'm not just asking for answers without attempting something first so below is an example of one of the many attempts to create a calculated property in my ViewModel:
View Model (My Attempt)
public class RenderDetailViewModel
{
    public IEnumerable<Render> RenderById { get; set; }
    private static readonly RenderLibContext _db = new RenderLibContext();

    private readonly Render _model;
    public RenderDetailViewModel(Render r)
    { _model = r; }

    public string ClientName { get { return _model.ClientName; } }
    public string Title { get { return _model.Title; } }
    public string JobId { get { return _model.JobId; } }

    public string ZipFileName
    {
        get {
            return (ClientName + "-" + Title + "-" + JobId)
                        .Replace(" ", string.Empty);
        }
    }

    public void PopulateRenderDetailModel(int id)
    {
        RenderById = _db.Renders.Include("Images")
            .Where(r => r.RenderId == id)
            .ToList();
    }
}

This attempt screwed up my controller and expected me to pass in an argument. That is not what I was aiming to do. Any help would be greatly appreciated. I hope I included everything needed to aid anyone who might be able to help.

A: A view model should not contain any database logic. It should have simple properties only. Also there is no way that you could use this in any edit scenario where you need to post back because a) you do not have a parameterless constructor (will throw an exception) and you properties have no setters. Just copy the properties from your data model to your view model and do the mapping in the controller (and then you can delete the ZipFileName in the data model)
public class RenderViewModel
{
  public int RenderId { get; set; }
  public string ClientName { get; set; }
  ....
  public IEnumerable<Image> Images { get; set; }
  public string ZipFileName
  {
    get { return (ClientName + "-" + Title + "-" + JobId)
            .Replace(" ", string.Empty); }
  }
}

Controller
public ActionResult Detail(int id)
{
  var render = db.Renders.Include("Images").Where(r => r.RenderId == id).FirstOrDefault();
  var model = new RenderViewModel()
  {
    RenderId = render.RenderId,
    ClientName = render.ClientName,
    ....,
    Images = render.Images.Select(...), // not sure what your trying to do here
  });
  return View(model);
}

View
@model RenderViewModel
@Html.DisplayFor(m => m.ClientName)
....
@foreach (var group in renders.Images)
{
  // better to use helpers to generate the link
  @Html.ActionLink("Download", "Download", "Renders", new { ID = Model.RenderId, fn = Model.ZipFileName })
}

Note, I'm confused by what you trying to do when selecting the images associated with each render. For each image you generating an identical link (based on the RenderId and ZipFileName of the render). Is there a property in Image that should included in the route parameters so each link downloads something different?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass empty string (double quote) argument to dockerfile My project wrapped by Docker and run in 2 environments: behind proxy or no proxy.
In this case, I use php:apache image and install ext via pecl, so I must set proxy manually
FROM php:apache

RUN pear config-set http_proxy $http_proxy
# RUN pecl install mongodb && docker-php-ext-enable mongodb

The $http_proxy arg will passed from docker-compose in 2 values: http://server:port or "" (double quote)
But when build the custom image in case "", the $http_proxy arg was null, and show error in the config command

Step 4/4 : RUN pear config-set http_proxy $http_proxy
—> Running in 19b69d089ff2
config-set expects 2 or 3 parameters

A: Since it is a RUN command, you can add a test:
docker build -t my_apache .  --build-arg http_proxy=....

With a Dockerfile:
ARG http_proxy
RUN if [ "x$http_proxy" != "x" ] ; then  pear config-set http_proxy $http_proxy; fi

You actually don't need the ARG http_proxy as it is one of the predefined ones.


text:
Q: Cannot access my GitHub Pages website by IP Address
My custom domain works with GitHub Pages but I would like to understand how it actually works.
For this example I am not using my custom domain at all. My GitHub Pages repository does not contain a CNAME file.

E.g. Given a GitHub Pages repository without a CNAME file: example.github.io
DNS request for example.github.io resolves to 185.31.16.133
running the ping command for example.github.io also returns the same IP address: 185.31.16.133
When I open the website http://example.github.io in the browser, the browser show the contents of the actual website.
When I type an IP address 185.31.16.133 instead or make an HTTP GET request with a tool like Postman, all I see is a GitHub Pages 404 error.
Why can't I access my GitHub User page by an IP address directly? I thought that browsers replace hostname part of the URL with the IP address response of a DNS lookup, prior to making an HTTP request.

A: Yes, web browsers does a DNS lookup and uses that ip address for the connection. They also take the original host name and send it as part of the Host http header. This allows a web server to serve multiple web sites from the same ip address.
curl http://185.31.16.133/

vs.
curl --header "Host: jzelenkov.github.io" http://185.31.16.133/

A: I think that your site is not the only site that is on that ip, even because if every project on github has a unique ip.
On that server probably there are configured hundred of sites of github users.
And probably they are configured using a virtual host structure.
In that case the apache server has many entries in the format of:
    <VirtualHost *:80>
    DocumentRoot "/blablabla"
    ServerName example.gihub.io

   <Directory "/blablabla">
      ....
   </Directory>

   </VirtualHost>

The ip that you use is just the ip of the server that hosts your site. So many sites share the same ip.
This is why you cannot access your page directly.
And probably they set a 404 error for all requests that doesn't use a valid virtual host. And this is why you are receiving a 404 not found error.
For access directly the page using the ip, refer to andol answer, using curl --header etc.


text:
Q: SQL % increased over time I hope someone can help. I am using SQL Server 2016 and I have data that looks like the below;
OrderID    Value        SubscriptionLengthInMonths  SubscriptionStart   SubscriptionEnd   Renew
2344        1920                       24                   14/05/2018   14/05/2020          1
2555        5376                       12                   01/03/2018   01/03/2019          1

What I need is the monthly payment value adding as a column, broken down by year. We work out the monthly value by dividing SubscriptionValue by SubscriptionLengthInMonths.
What makes it tricky is sometimes there is a flag on my data (autorenew) which means if the value is 1, the subscription will renew automatically on the SubscriptionEnd, for the same period of months as the original subscription. When this happens, a 2% increase is added to the monthly fee. I need columns that show the monthly fee of each subscription, broken down by year. An ideal output of the above example would look like the below
OrderID SubscriptionValue   SubscriptionLengthInMonths  2018    2019    2020    2021
2344       1920                         24               80      80     81.6    81.6
2555       5376                         12               448    456.96  466.06  475.36

The reason the OrderID 2344 payment is 80 in both 2018 and 2019 is because this is a 2 year (24 month) subscription which doesn't auto renew until 2020. This renews again in 2020 (which reflects in the below as the % has been added on for 2020 and 2021)
OrderID 2555 renews every 12 months which is why the % increase is applied across all years.
I understand this is complex, just hoping someone can show me how to achieve this. Thanks, Jess

A: If I understand correctly, you want the monthly amount incremented by 2.0 for each subscription period.
The arithmetic logic is something like this:
select t.*,
       (power(1.02,
              datediff(month, subscriptionStart, '2018-12-31') / SubscriptionLengthInMonths
             ) * (SubscriptionValue / SubscriptionLengthInMonths)
       ) monthly_2018,
       (power(1.02,
              datediff(month, subscriptionStart, '2019-12-31') / SubscriptionLengthInMonths
             ) * (SubscriptionValue / SubscriptionLengthInMonths)
       ) monthly_2019,
       . . .
from t;

This should work for your data.  I'm not sure how the autorenew logic comes into play.


text:
Q: The import org.hibernate.validator.Length cannot be resolved? Here is my pom:
<dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.16</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>com.google.code</groupId>
            <artifactId>struts2-fullhibernatecore-plugin</artifactId>
            <version>2.2.2-GA</version>
        </dependency>

         <!-- validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <!-- for annotations like @Entity,@Table -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.4.0.GA</version>
        </dependency>

        <!-- dependencies of hibernate-core -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

How to resolve this error :
The import org.hibernate.validator.Length cannot be resolved

Edit :
[ERROR]   symbol:   class Length
  location: class User

Thank you!

A: Since you have the hibernate-validator dependency set, you will have to run
mvn clean install

in order to get it added to the classpath.

A: You seem to be missing the constraints package name in your code
import org.hibernate.validator.constraints.Length;


text:
Q: How to check UITextField is not blank in Swift 2.0? Is there better way to count the string? I am try to check textfield is blank or not and what I am trying is
if(EmailTextField.text.characters.count>0)
{
}

but I can't use relation operator on this count method. Why?

A: You can use the String's isEmpty property:
//if EmailTextField is a UITextField instance
if EmailTextField.text != nil && !EmailTextField.text!.isEmpty {

}

if let text = EmailTextField.text where !text.isEmpty {

}

A: By extension... To ensure that its not even take any blank spaces...
extension String {

var isBlank: Bool {
       get {
            let trimmed = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
            return trimmed.isEmpty
        }
   }
}

Usage:
if !EmailTextField.text!.isBlank{
   //TextField is not blank
}


text:
Q: parsing yaml in ruby If I have a yaml file like so:
-  name: James
   categories: "charming fun loving caring smart"
   description: "Blah blah"
-  name: Arthur
   categories: "loving funny smart"
   description: "Blah blah"

And I want to iterate over every single category in the yaml file also merging each tag in the categories entry and then eliminating the duplicates to make a complete list of all the categories, how can I do this?
I can map the categories fine with
data.products.map(&:categories)

but I also need to merge the individual words per category into the array as well.
data.products.map{|x| x.categories.split(" ")}.uniq!.each do |tag|

I'm a bit lost between maping all the categories and also marging the multple words per category.

A: You think you just need a flatten in there :)
data.products.map { |x|
  x.categories.split
}.flatten.uniq


text:
Q: Vim mapping characters in insert mode OK this may be pretty basic question but I just learned how to make custom key mappings.
I am trying to make vim automatically "end" two lines lower when typing "class"
so I wrote following in .vimrc :
:imap class class<CR><CR>end

So that worked fine except now when I start typing "class" vim is over typing each letter of "class" until I finish typing it or what I'm typing no longer matches "class".
Is there a way to avoid this behavior, I want to be able to see what I am typing as I'm typing it even when it matches a mapped key sequence?
Not sure if I'm explaining it correctly.
Thanks for help

A: You're looking for
:inoreab class class<cr><cr>end

The same (nore) would have worked with mappings as well, but mappings are less fitted for such snippets.
BTW, the abbreviation should be declared specific to the filetype where you will use it (Ruby ?) ->
" in ~/.vim/ftplugin/ruby/my_snippets.vim
:inoreab <buffer> class class<cr><cr>end

Note, that you won't be able to type "class" from within a string or a comment without seeing it expanded. You'll either have to rely on functions that'll take care of the context, or snippets (which will be much easier to maintain)
For instance, with lh-bracket, you could define:
:Inoreab <buffer> class <c-r>=InsertSeq('class', 'class !cursorhere!\<cr\>!mark!\<cr\>end!mark!')<cr>

But I really recommend you to use a snippet engine instead (mu-template, utilsnip, snipmate, ... There are plenty)


text:
Q: How to train in Keras when I don't have enough memory for loading all training data I want to train my model in Keras, so tried to load images as numpy array and resizing them, but it failed because I don't have enough memory.
MemoryError when I normalize images by img/255
My task is semantic segmentation. I have two folders. One is for the input images and the other is for desired output images. The corresponding images have the same name.
Are there useful API in Keras?

A: Yes, you should use a generator and the fit_generator function to train with it. Basically in a generator function you have a lot of freedom on how to load the data and in which quantities, so you can load data while the model is training, and only keep one batch of data in memory at a time (plus a queue used by Keras).

A: For the preprocessing part: Is it an option to load the images in small batches, do preprocessing and save them again in a one file per batch fashion?
Normally after preprocessing the images should be smaller and maybe even small enough to load completely into memory for training.
Also, you can use the train_on_batch or fit_generator function from the model API. Then you can train the images without having them all in-memory at the same time.


text:
Q: on . change is not working in jquery latest version .on('change') function is not working
Html Code
 <div class="col-md-2 col-sm-2 col-xs-4">
    <select class="form-control" id="pagesize">
        <option value="10">10 Results</option>
        <option value="20">20 Results</option>
        <option value="30">30 Results</option>
        <option value="40">40 Results</option>
        <option value="50">50 Results</option>
        <option value="60">60 Results</option>
    </select>
</div>

Jquery
    $("#pagesize").on('click', function () {
        alert("tretr");
        var pagesize = $('#pagesize').val();
        alert(pagesize);

    });

click function is not working

A: Yes it has been updated, use it like :
$('body').on("click", '#pagesize', function(){
        alert("tretr");
        var pagesize = $(this).val();
        alert(pagesize);

});

FIDDLE

A: Use $(this) for get current object reference and change the event to .change()
$("#pagesize").on('change', function () {
        var pagesize = $(this).val();
        alert(pagesize);
 });

Fiddle

A: It is working fine.
http://jsfiddle.net/kdmLy5zg/
With jQuery version 1.11.0


text:
Q: error while validating form from ini file Hii...
When I tried to validate zend form using ini file, I am getting the following error message, please help how to fix this
Uncaught Zend_Config_Exception, code: 0
Message: parse_ini_file(views/config/adminvalidate.ini) [function.parse-ini-file]: failed to open stream: No such file or
directory

Thanks

A:
Message: parse_ini_file(views/config/adminvalidate.ini)

Your config file is in the views folder?
Update
I usually need to provide an absolute path to the Zend_Config_Ini constructor:
APPLICATION_PATH . '/views/config/adminvalidate.ini'


text:
Q: Xamarin Forms Shell toolbar Height I am new to Xamarin and was working on a few scenarios with Xamarin Forms Shell in Navigation bar. My requirement is to set Image to Navigation bar in shell. I am able to update the image in Navigation bar using Shell Custom Renderers for both android and ios. In Android, I was able to increase the height of the navigation bar/toolbar
In iOS, Image is not shown fully. I am currently facing an issue with setting the height of the navigation bar in iOS. Can someone help me with how to increase the height of toolbar (navigation bar) using shell custom renderers?

A: Welcome to SO!
Unfortunately , we can't modify the height of NavigationBar in iOS . We only can custom a toolbar view in iOS to do that . If using the default NavigationBar , Aplle not allows us to modify .
Have a look at this discussion : iOS11 customize navigation bar height


text:
Q: extract a single column I have a list of 701 given csv files. Each one has the same number of columns (7) but different number of rows (between 25000 and 28000).
Here is an extract of the first file:
Date,Week,Week Day,Hour,Price,Volume,Sale/Purchase
18/03/2011,11,5,1,-3000.00,17416,Sell
18/03/2011,11,5,1,-1001.10,17427,Sell
18/03/2011,11,5,1,-1000.00,18055,Sell
18/03/2011,11,5,1,-500.10,18057,Sell
18/03/2011,11,5,1,-500.00,18064,Sell
18/03/2011,11,5,1,-400.10,18066,Sell
18/03/2011,11,5,1,-400.00,18066,Sell
18/03/2011,11,5,1,-300.10,18068,Sell
18/03/2011,11,5,1,-300.00,18118,Sell

I made a nonlinear regression of the supply curve of the ninth hour for the year 2012. The datas for 2012 are in 290. to 654. csv files.
allenamen <- dir(pattern="*.csv")
alledat <- lapply(allenamen, read.csv, header = TRUE, sep = ",", stringsAsFactors = FALSE)
h <- list()
for(i in 290:654) {
g <- function(a, b, c, d, p) {a*atan(b*p+c)+d}
f <- nlsLM(Volume ~ g(a,b,c,d,Price), data=subset(alledat[[i-289]], (Hour==9) & (Sale.Purchase == "Sell") & (!Price %in% as.character(-50:150))), start = list(a=4000, b=0.1, c=-5, d=32000))
h[[i-289]] <- coef(f)
}

This works and I get the coefficients a, b, c and d for every day in 2012.
This is the head(h):
[[1]]
        a             b             c             d
2.513378e+03  4.668218e-02 -3.181322e+00  2.637142e+04

[[2]]
        a             b             c             d
2.803172e+03  6.696201e-02 -4.576432e+00  2.574454e+04

[[3]]
        a             b             c             d
 3.298991e+03  5.817949e-02 -3.425728e+00  2.393888e+04

[[4]]
        a             b             c             d
 2.150487e+03  3.810406e-02 -2.658772e+00  2.675609e+04

[[5]]
        a             b             c             d
2.326199e+03  3.044967e-02 -1.780965e+00  2.604374e+04

[[6]]
        a             b             c             d
2934.0193270     0.0302937    -1.9912913 26283.0300823

And this is dput(head(h)):
list(structure(c(2513.37818972349, 0.0466821822063123, -3.18132213466142,
26371.4241646124), .Names = c("a", "b", "c", "d")), structure(c(2803.17230054557,
0.0669620116294894, -4.57643230249848, 25744.5376725213), .Names = c("a",
"b", "c", "d")), structure(c(3298.99066895304, 0.0581794881246528,
-3.42572804902504, 23938.8754575156), .Names = c("a", "b", "c",
"d")), structure(c(2150.48734655237, 0.0381040636898022, -2.65877160023262,
26756.0907073567), .Names = c("a", "b", "c", "d")), structure(c(2326.19873555633,
0.0304496684589379, -1.7809654498454, 26043.735374657), .Names = c("a",
"b", "c", "d")), structure(c(2934.01932702805, 0.0302937043170001,
-1.99129130343521, 26283.0300823458), .Names = c("a", "b", "c",
"d")))

Now I am trying to get just a column with h$a but I get NULL. How can I get just the a column?
In addition to this I want to plot the single coefficients and Date. I tried this code:
koeffreihe <- function(x) {
files <- list.files(pattern="*.csv")
df <- data.frame()
for(i in 1:length(files)){
xx <- read.csv(as.character(files[i]))
xx <- subset(xx, Sale.Purchase == "Sell" & Hour == 3)
df <- rbind(df, xx)
g <- function(a, b, c, d, p) {a*atan(b*p+c)+d}
f <- nlsLM(Volume ~ g(a,b,c,d,Price), data=subset(alledat[[i]], (Hour==9) & (Sale.Purchase == "Sell") & (!Price %in% as.character(-50:150))), start = list(a=4000, b=0.1, c=-5, d=32000))
h[[i]] <- coef(f)
}
df$Date <- as.Date(as.character(df$Date), format="%d/%m/%Y")
plot(h$x ~ Date, df, xlim = as.Date(c("2012-01-01", "2012-12-31")))
}

koeffreihe(a)

But I get this error:
invalid type (NULL) for variable 'h$x'

So the problem is that h$a is NULL. If someone can fix this problem I guess the code will work too.
Thank you for your help!

A: First transform your list into a data.frame:
h.df <- setNames(do.call(rbind.data.frame, h), names(h[[1]]))
#         a          b         c        d
#1 2513.378 0.04668218 -3.181322 26371.42
#2 2803.172 0.06696201 -4.576432 25744.54
#3 3298.991 0.05817949 -3.425728 23938.88
#4 2150.487 0.03810406 -2.658772 26756.09
#5 2326.199 0.03044967 -1.780965 26043.74
#6 2934.019 0.03029370 -1.991291 26283.03

Then you can extract variables easily:
h.df$a
#[1] 2513.378 2803.172 3298.991 2150.487 2326.199 2934.019

Alternatively you can iterate over the list to extract the variable:
sapply(h, "[", "a")
#       a        a        a        a        a        a
#2513.378 2803.172 3298.991 2150.487 2326.199 2934.019

A: In this line, although x is a variable, h$x is looking for a column named x in h:
plot(h$x ~ Date, df, xlim = as.Date(c("2012-01-01", "2012-12-31")))

You probably want h[[x]] instead.
From ?'[[':
x$name is equivalent to x[["name", exact = FALSE]].

That is, you are looking for a column literally named x.


text:
Q: SerialPort C# incorrect byte in frame I have designed program in C# that speaks to a microcontroller by UART ( There is FT232 between).
I have improved my application to send/calculate and validate checksum.
I have the problem that randomly for some variables I get number 63 in a random position of my byte frame. Only when data is sent back from the microcontroller to PC.
I have checked it and in microcontrollers send buffer everything is fine but it comes to PC with 63 in one place. Not for every variable, I send. It is about 40 of them, and only 8 gets faulty with that 63 number.
My UART Baud rate is 921600.  Maybe it is too fast?
Has anybody had experience with that fault?
Best regards,
Chris


text:
Q: Sencha Touch: reference not generated I'm using Sencha Touch 2.4, with Sencha Cmd 6.1.x (so I believe I'm using Ext JS 6). I've got the following model and store:
Ext.define('App.model.User', {
extend: 'Ext.data.Model',

fields: [{
    name: 'organizationId',
    type :'int',
    reference: {
        type: 'Organization',
        association: 'UsersByOrganization',
        role: 'organization',
        inverse: 'users'
    }
}, {
    "name": "matricola",
    "type": "int"
}]

});
and
 Ext.define('App.model.Organization', {
 extend: 'Ext.data.Model',
 fields: ['name']

});
I load my stores (with a 'sql' proxy) using the usual way, but I cannot find my reference anywhere. I simply get the records and I cannot call "users" or its inverse.
Any idea?

A: Sencha Touch 2.4 and ExtJS 6 are two different toolkits. Syntax for creating models and stores are similar in both, but not in all cases.
I believe what you are looking for is the StoreManager. If you have defined a store like so:
Ext.define('App.store.User', {
   extend: 'Ext.data.Store',
   storeId: 'User',
   model: 'User'
});

Then you can reference the store like so:
 // Return a list of users
 Ext.getStore('User').getRange();

A: The code below works for me on Ext JS 6.  Maybe you can model yours after this example:
Ext.define('App.model.Customer', {
    extend: 'Ext.data.Model',
    idProperty: 'customerNumber',
    fields: [
        { name: 'customerNumber', type: 'int' },
        { name: 'customerName', type: 'string' },
        { name: 'contactLastName', type: 'string' },
        { name: 'contactFirstName', type: 'string' }
    ],
    proxy: {
        type: 'ajax',
        url: '../../../api/CustomersAssociationsReference',
        reader: {
            type: 'json',
            rootProperty: 'customers',
            totalProperty: 'count'
        }
    }
});

Ext.define('App.model.Order', {
    extend: 'Ext.data.Model',
    idProperty: 'orderNumber',
    fields: [
        { name: 'orderNumber', type: 'int' },
        {
            name: 'customerNumber', reference: {
                type: 'App.model.Customer',
                inverse: 'orders'
            }
        },
        { name: 'orderDate', type: 'string' },
        { name: 'status', type: 'string' }
    ],
    proxy: {        // Note that proxy is defined in the Model, not the Store
        type: 'ajax',
        url: '../../../api/OrdersAssociationsReference',
        reader: {
            type: 'json',
            rootProperty: 'orders',
            totalProperty: 'count'
        }
    }
});

Ext.application({
    name: 'App',
    models: ['Customer', 'Order'],
    stores: ['Customers', 'Orders'],
    launch: function () {

        var customersStore = Ext.getStore('Customers');
        customersStore.load(function (records, operation, success) {

            var customer = records[0],
                orders = customer.orders(),
                order;
            orders.load(function (records, operation, success) {
                console.log('Orders for ' + customer.get('customerName') + ':\n-------------------------------------------------------');
                for (i = 0, len = records.length; i < len; i++) {
                    order = records[i];
                    console.log('orderNumber: ' + order.get('orderNumber'));
                    console.log('orderDate: ' + order.get('orderDate'));
                    console.log('status: ' + order.get('status'));
                    console.log('-------------------------------');
                }
            })
        });
    }
});


text:
Q: PARSENAME function behaves wierd When I use the PARSENAME function in a Stored Procedure, sometimes it returns the correct value and sometimes it returns a NULL value. I'm bit confused here what would be the reason?
SELECT parsename(Replace('the big bang Theory',' ','.'),4)

A:
PARSENAME (Transact-SQL) Returns the specified part of an object name.
  The parts of an object that can be retrieved are the object name,
  owner name, database name, and server name.
PARSENAME ( 'object_name' , object_piece )    Arguments 'object_name'
  Is the name of the object for which to retrieve the specified object
  part. object_name is sysname. This parameter is an
  optionally-qualified object name. If all parts of the object name are
  qualified, this name can have four parts: the server name, the

database name, the owner name, and the object name.

object_piece Is the object part to return. object_piece is of type
  int, and can have these values: 1 = Object name 2 = Schema name 3 =
  Database name 4 = Server name

SELECT PARSENAME('[Server].database.schema.table', 1) AS 'Object Name';
SELECT PARSENAME('[Server].database.schema.table', 2) AS 'Schema Name';
SELECT PARSENAME('[Server].database.schema.table', 3) AS 'Database Name';
SELECT PARSENAME('[Server].database.schema.table', 4) AS 'Server Name';

SELECT PARSENAME('database..table', 1) AS 'Object Name';
SELECT PARSENAME('database..table', 2) AS 'Schema Name';  -- will return NULL
SELECT PARSENAME('database..table', 3) AS 'Database Name';
SELECT PARSENAME('database..table', 4) AS 'Server Name'; -- will return NULL

A: First of all PARSENAME() was intended to parse object_name of type SYSNAME.
Possible scenarios:
SELECT c, PARSENAME(REPLACE(sub.c, ' ', '.'), 4) AS part
FROM  (
    SELECT 'a b c d e'                 -- more than 4 parts
    UNION ALL
    SELECT 'a b c d'
    UNION ALL
    SELECT REPLICATE('a', 129) + ' b c d'  -- too long part
    UNION ALL
    SELECT REPLICATE('a', 128) + ' b c d'
    UNION ALL
    SELECT 'a b c  d'                  -- more than one space
    UNION ALL
    SELECT CAST('a b c d' AS CHAR(30)) -- padded with spaces
)sub(c)

Rextester Demo
Keep in mind that a.b.c.d.e is not valid object_name. Also SYSNAME is alias for NVARCHAR(128) so longer parts will be invalid.
The point is that when you use it to do different job (parsing any user string) you may get error.


text:
Q: DevExpress XtraGrid - ImageButton in each row I would like to add a custom method for each row i.e. an open detail form that show details for the grid row the button has been clicked for.
Is there any easy solution for that?
EDIT:
What's wrong with my code to style the button?
Image img = imageList1.Images[5];
            repositoryItemButtonEdit1.Buttons.Clear();
            repositoryItemButtonEdit1.Buttons.Add(new EditorButton(ButtonPredefines.Left, "View Filter", 16, true, true, true, ImageLocation.Default, img));
            repositoryItemButtonEdit1.ButtonPressed += new ButtonPressedEventHandler(repositoryItemButtonEdit1_ButtonPressed);

ANSWER (use Glyph)
Image img = imageList1.Images[5];
repositoryItemButtonEdit1.Buttons.Clear();
repositoryItemButtonEdit1.Buttons.Add(
    new EditorButton(
        ButtonPredefines.Glyph,
        "",
        16,
        true,
        true,
        true,
        ImageLocation.Default,
        img
    )
 );
 repositoryItemButtonEdit1.ButtonPressed += newButtonPressedEventHandler(repositoryItemButtonEdit1_ButtonPressed);

A: The easiest way to do that is to add a RepositoryItemButtonEdit as the ColumnEdit for the column.
Make sure you set the TextEdit property of the RepositoryItemButtonEdit to hidden, and configure the buttons property so that it has your image button.
Then handle the ButtonPressed Event of the repository item.
A simple event handler might look something like:
c#
private void RepositoryItemButtonEdit1_Click(object sender, System.EventArgs e)
{
    WhateverClass MyData = (WhateverClass)GridView1.GetFocusedRow();
    Form1 frmEdit = new Form1(MyData);
    frmEdit.Show();
}

vb.net
Private Sub RepositoryItemButtonEdit1_Click(sender As Object, e As System.EventArgs) Handles RepositoryItemButtonEdit1.Click
    Dim MyData As WhateverClass= CType(GridView1.GetFocusedRow(), WhateverClass)
    Dim frmEdit As New Form1(MyData)
    frmEdit.Show()
End Sub

A: just some addition to the answer above, because I faced a similar problem earlier.

*

*If you want to use an Image for the RepositoryItemButtonEdit button, don't forget to set the Button's Kind property to Glyph.

*If you want to display the editor button's Caption as well, you have to set the ImagePosition to other then MiddleCenter.

*I'd rather use the ButtonClick event, and check for the editor button's Index property.

*This link describes an interesting situation about this scenario.

Hope it will be also helpful.
Regards,
Zoltán


text:
Q: Spring Integration - Message Delivery Exception We are posting a request file to FTP location using Spring Integration MessageChannel API. During this process, the file successfully sent but we are getting MessageDeliveryException during this process. PFB the stacktrace for your reference. Looking for a solution. Please guide.
Note: Exception says that its trying to delete but we are not trying to do so.
2015-10-13 08:33:26.000439 [INFO] [task-scheduler-8] | com.dnb.fatca.service.impl.FTPChannelManagerImpl | isSuccess Val........false
2015-10-13 08:33:26.000439 [ERROR] [task-scheduler-8] | com.dnb.fatca.service.impl.FTPChannelManagerImpl | Error handling message for file [/dnbusr2/fatca/temp/execution/batch/8293/8293.APN -> 8293.APN]
org.springframework.integration.MessageDeliveryException: Error handling message for file [/dnbusr2/fatca/temp/execution/batch/8293/8293.APN -> 8293.APN]
       at org.springframework.integration.file.remote.RemoteFileTemplate$1.doInSession(RemoteFileTemplate.java:227)
       at org.springframework.integration.file.remote.RemoteFileTemplate$1.doInSession(RemoteFileTemplate.java:190)
       at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:297)
       at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:190)
       at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:182)
       at org.springframework.integration.file.remote.handler.FileTransferringMessageHandler.handleMessageInternal(FileTransferringMessageHandler.java:112)
       at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73)
       at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115)
       at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102)
       at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
       at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178)
       at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149)
       at com.dnb.fatca.service.impl.FTPChannelManagerImpl.pushFileToChannel(FTPChannelManagerImpl.java:309)
       at com.dnb.fatca.service.impl.FTPChannelManagerImpl.pushToGBFChannelFTP(FTPChannelManagerImpl.java:209)
       at com.dnb.fatca.batch.tasklet.GBFInputDataSender.execute(GBFInputDataSender.java:222)
       at sun.reflect.GeneratedMethodAccessor201.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
       at java.lang.reflect.Method.invoke(Method.java:606)
       at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
       at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
       at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
       at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
       at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
       at com.sun.proxy.$Proxy43.execute(Unknown Source)
       at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406)
       at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330)
       at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
       at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271)
       at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77)
       at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368)
       at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
       at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144)
       at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257)
       at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:198)
       at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
       at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64)
       at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67)
       at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:162)
       at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:141)
       at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134)
       at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:304)
       at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
       at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
       at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128)
       at com.dnb.fatca.batch.trigger.GBSResponseMQTrigger.triggerGBSResponse(GBSResponseMQTrigger.java:405)
       at sun.reflect.GeneratedMethodAccessor933.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
       at java.lang.reflect.Method.invoke(Method.java:606)
       at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:63)
       at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:95)
       at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:44)
       at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:258)
       at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:84)
       at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:114)
       at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:111)
       at org.springframework.integration.util.AbstractExpressionEvaluator.evaluateExpression(AbstractExpressionEvaluator.java:144)
       at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:268)
       at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:142)
       at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:73)
       at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:67)
       at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:142)
       at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73)
       at org.springframework.integration.endpoint.PollingConsumer.handleMessage(PollingConsumer.java:74)
       at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:199)
       at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:51)
       at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:143)
       at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:141)
       at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:273)
       at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:52)
       at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
       at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:49)
       at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:268)
       at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
       at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
       at java.util.concurrent.FutureTask.run(FutureTask.java:262)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
       at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.integration.MessagingException: Failed to write to '/puts/8293.APN.writing' while uploading the file
       at org.springframework.integration.file.remote.RemoteFileTemplate.sendFileToRemoteDirectory(RemoteFileTemplate.java:392)
       at org.springframework.integration.file.remote.RemoteFileTemplate.access$500(RemoteFileTemplate.java:56)
       at org.springframework.integration.file.remote.RemoteFileTemplate$1.doInSession(RemoteFileTemplate.java:213)
       ... 82 more
****Caused by: org.springframework.core.NestedIOException: Failed to delete file /puts/8293.APN; nested exception is org.springframework.core.NestedIOException: Failed to remove file: 3: Permission denied**.**
       at org.springframework.integration.sftp.session.SftpSession.rename(SftpSession.java:200)
       at org.springframework.integration.file.remote.RemoteFileTemplate.sendFileToRemoteDirectory(RemoteFileTemplate.java:388)
       ... 84 more
Caused by: org.springframework.core.NestedIOException: Failed to remove file: 3: Permission denied.
       at org.springframework.integration.sftp.session.SftpSession.remove(SftpSession.java:83)
       at org.springframework.integration.sftp.session.SftpSession.rename(SftpSession.java:194)
       ... 85 more
2015-10-13 08:33:26.000441 [INFO] [task-scheduler-8] | com.dnb.fatca.service.impl.FTPChannelManagerImpl | Message '[/dnbusr2/fatca/temp/execution/batch/8293/8293.APN]' Sent Status : false
2015-10-13 08:33:26.000480 [INFO] [task-scheduler-8] | com.dnb.fatca.batch.listeners.AppendDataRequestPPListener | 8293Execution completed

A: Let's take a looks to the StackTrace closer!
Caused by: org.springframework.core.NestedIOException: Failed to remove file: 3: Permission denied.
       at org.springframework.integration.sftp.session.SftpSession.remove(SftpSession.java:83)
       at org.springframework.integration.sftp.session.SftpSession.rename(SftpSession.java:194)

So, exactly through the rename you do remove :-).
And it is because:
if (logger.isDebugEnabled()) {
    logger.debug("Initial File rename failed, possibly because file already exists. Will attempt to delete file: "
                + pathTo + " and execute rename again.");
}

And I guess you don't have permissions to rename file as well.
The rename operation is initiated from the RemoteFileTemplate only if useTemporaryFileName == true.
So, to fix your issue try to configure it like use-temporary-file-name="false" on the <int-sftp:outbound-channel-adapter>


text:
Q: Change UITextField and UIButton font name, Color of UIAlertView I want to change my UITextField font name and UIButton (Cancel, OK) color to black of AlertView.
But it doesn't change to what I have expected.
- (IBAction)newGroup:(id)sender{
    self.alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"새 그룹의 이름을 입격" delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
    self.alertView.tag = new_group;
    self.alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [self.alertView show];
}

// Custom font name, color of UIAlertView's control
- (void)willPresentAlertView:(UIAlertView)alertView{
  if(alertView.tag == new_group){
    for(UIView *subView in alertView){
       if([subView isKindOfClass:[UIButton class]]){
         UIButton *button = (UIButton *)subView;
         button.titleLabel.textColor = [UIColor blackColor];
       }else if([subView isKindOfClass:[UITextField class]]){
         UITextField *textView = (UITextField *)subView;
         textView.font = [UIFont fontWithName:@"Helvetica" size:30.0f];
       }
    }
  }
}

The UITextField font name and font size, UIButton (Cancel, OK) still look the same from the default.


text:
Q: Prove that at least two of these inequalities are true: $|a-b|\le2$, $|b-c|\le2$, $|c-a|\le2$. It's given that: $$\begin{cases}a,b,c>0\\a+b+c\le4\\ab+bc+ac\ge4\end{cases}$$
Prove without using calculus that it's true that at least two of these are correct inequalities:$$\begin{cases}|a-b|\le2\\|b-c|\le2\\|c-a|\le2\end{cases}$$
If you think about it, we may as well prove that at least two of these are correct:$$\begin{cases}(a-b)^2\le4\\(b-c)^2\le4\\(c-a)^2\le4\end{cases}$$
We could square one of the inequalities (since both sides are positive):$$(a+b+c)^2\le16\Rightarrow a^2+b^2+c^2+2(ab+bc+ac)\le16$$
$$a^2+b^2+c^2+8\le a^2+b^2+c^2+2(ab+bc+ac)\le16\Rightarrow a^2+b^2+c^2\le 8$$
So now we know that: $$\begin{cases}a,b,c>0\\a+b+c\le4\\a^2+b^2+c^2\le8\\ab+bc+ac\ge4\end{cases}$$
Does anyone see how to solve this? Thanks.

A: Suppose two of these are false. Then
$$8<(a-b)^2+(a-c)^2+(b-c)^2=2(a^2+b^2+c^2)-2(ab+ac+bc)\le 16-8$$
i.e. $8<8$, a contradiction.

A: It is easy!
first, we know that
$a^2+b^2+c^2<=8$, therefore
$2a^2+2b^2+2c^2<=16$   ............. ine1
and we know $ab+ba+ca>=4$,so
$-2ab-2bc-2ca<=-8$           .........        ine2
so ine1+ine2, we get
$(a-b)^2+(b-c)^2+(a-c)^2<=8$
so ,it is easy to explain your inequalities:
$\begin{cases}(a-b)^2\le4\\(b-c)^2\le4\\(c-a)^2\le4\end{cases}$
at least two of there are right.


text:
Q: How do you check if an async void method is completed in Dart? How do you check if an async void method is completed in Dart?

A: Method 1:
await voidFoo();
print("the above function was completed");

Future<void> voidFoo() async{
  await Future.delayed(Duration(seconds:1));
}

Method 2:
Using a boolean variable like this,
bool isCompleted = false;
...
await voidFoo();

Future<void> voidFoo() async{
  await Future.delayed(Duration(seconds:1));
  isCompleted = true; //assuming isCompleted can be accessed here
}

A: There are too many methods to do this
i prefer to do this
Future<void> myFunction() async {
await Future.delayed(Duration(seconds: 3)); // your future operation
 }

main() async {
await myFunction();
print("finished");
  }

A: You can use dart Completer.
import 'dart:async';

void main() async {
  final completer = Completer<String>();

  Future<String> getHttpData()async{
    return Future.delayed(const Duration(seconds: 1), () => "Future Result");
  }

Future<String> asyncQuery()async {

  final httpResponse = await getHttpData();
  completer.complete(httpResponse);

  return completer.future;
}

 print('IsCompleted: ${completer.isCompleted}');
 await asyncQuery();
 print('IsCompleted: ${completer.isCompleted}');
}

Result;
IsCompleted: false
IsCompleted: true


text:
Q: Swift 5: Add decimal separators whitout NumberFormatter I need to create a function to add the decimal and thousands separators to a number that is a string, I know I could use numberFormatter but I want to practice another way of doing it. For example if I have "454685" the result will be "$ 4,546.85".
This is my code:
let number = "111234567"

let firstIndex = number.startIndex
let firstNumber = number[firstIndex]

let lastIndex = number.index(before: number.endIndex)
let lastNumber = String(number[lastIndex])

let beforeLastIndex = number.index(number.endIndex, offsetBy: -2)
let beforeLastNumber = String(number[beforeLastIndex])

var decimalPart = beforeLastNumber + lastNumber
let decimalindex = number.index(number.endIndex, offsetBy: -2)

let intPart = String(number[..<decimalindex])

let totalNumber = "$" + intPart + "," + decimalPart
print(totalNumber)

var thousandSeparators = intPart.count % 3 == 1

I'm stuck here, I separated the decimal part from the integer part, but then I don't know how to add the thousand separator "." to string number.

A: You can achieve this by creating a function for a string that split the string as per the length passes in parameter and the direction for splitting.
extension String {

    func split(length:Int, fromBack: Bool = false) -> [Substring] {
        guard length > 0 && length < count else { return [suffix(from:startIndex)] }
        if fromBack {
            return (0 ... (count - 1) / length).map { dropLast($0 * length).suffix(length) }.reversed()
        }
        return (0 ... (count - 1) / length).map { dropFirst($0 * length).prefix(length) }
    }

}

how to use this function:
let number = "111234567"

let firstIndex = number.startIndex
let firstNumber = number[firstIndex]

let lastIndex = number.index(before: number.endIndex)
let lastNumber = String(number[lastIndex])

let beforeLastIndex = number.index(number.endIndex, offsetBy: -2)
let beforeLastNumber = String(number[beforeLastIndex])

var decimalPart = beforeLastNumber + lastNumber
let decimalindex = number.index(number.endIndex, offsetBy: -2)

let intPart = String(number[..<decimalindex])

let intWithThousandSeparators = intPart.split(length: 3, fromBack: true).joined(separator: ".")

let totalNumber = "$" + intWithThousandSeparators + "," + decimalPart
print(totalNumber)

Output:

You can refer to this answers list for split strings into groups.


text:
Q: Adding Microsoft Graph to existing Entity Framework Core I got an API on .NET 5, made with Entity Framework Core.
The query-URLs with methods are something like GET https://api.mydomain.ch/v1/applicationusers
This would retrieve all application users (which makes sense).
In C# this looks:
[HttpGet]
public async Task<ActionResult<ApplicationUser>> Get()
{
    return Ok(await _applicationUserRepository.GetAll());
}

Now a client that consumes my API wants to request: GET https://api.mydomain.ch/v1/applicationusers?$filter=startswith(givenName,'Peter')
I have seen this matches the Microsoft Graph API and its query parameters. And my client also wants to use the other implementations for this (https://learn.microsoft.com/en-us/graph/query-parameters)
I couldn't find any implementation example that works with Entity Framework Core. Is it possible to implement this with an easy way, and not to make big modifications on the database?
Do I need to implement the functions completely on my own? Or is there support from Microsoft between those query parameter functions and Entity Framework Core?

A: Okay the answer is quite simple and it's not the Microsoft Graph that needs to be implemented, but simply OData.
For .NET 5 it's not well documented, since the NuGet for this .NET-version is still in RC-state (pre-release).
To implement OData, we need to add Microsoft.AspNetCore.OData in nuget packages. My answer is written with state from 8.0.0-rc. For v7.x the calls look bit different but are better documented.
What we need to do is:
Add OData in StartUp.ConfigureServices:
ODataConventionModelBuilder builder = new(new DefaultAssemblyResolver());
builder.EntitySet<ApplicationUser>("ApplicationUser");
IEdmModel model =  builder.GetEdmModel();

services.AddOData(opt =>
{
    opt
        .AddModel("api/v1", model)
        .Select()
        .Expand()
        .OrderBy()
        .Filter()
        .Count();
});

with .Select().Expand().OrderBy().Filter().Count() you add the api-query-parameters for $select, $expand,...
My UseEndpoints call in Configure() looks this way:
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

Make sure, the controller inherit from ODataApiController.
An action looks like this:
[HttpGet]
[EnableQuery]
public async Task<ActionResult<ApplicationUser>> Get()
{
    return Ok(await _applicationUserRepository.GetAll());
}

This would not execute the expected query. We need to return the IQueryable<T> to make this work, so we don't query for all records:
[HttpGet]
[EnableQuery]
public IQueryable<ApplicationUser> Get()
{
    return _applicationUserRepository.GetAll();
}


text:
Q: How to add radius to map of over 32,000 zip codes I'm incredibly new to creating these types of maps, but I'm trying to create a coverage map not unlike the cell companies show their coverage. Our database simply has lists of ZIP codes that our service covers and I want to display these on a map, colored in, like the cell phone companies do.
I have figured out how to do this on my own (using QGIS and joining my CSV list with the shapefile from the USPS of zip codes)... But the thing I can't figure out how to do is to show a radius around each zip coded area. Our coverage extends 100 miles (50 miles in each direction) from the center point of each zip code.
With a list of over 32,000 zip codes, is there a way to easily extend the coloring area around each zip code to include this extra area?

A:
"show a radius around each zip coded area. Our coverage extends 100
  miles (50 miles in each direction) from the center point of each
  zip code."

*

*Convert your Zip Codes to Centroids. Vector - Geometry Tools - Polygon Centroids.

*Buffer the Points. Vector - Geometry Tools - Buffer

Some things to consider.
Use a projected coordinate system that is in meters then your buffer distance will be 885139 meters.  I would suggest SR-ORG:7301 as you are working in the USA and desire a unit that is stable (ie not degrees).

A: Once you've done your join, right-click the joined polygon layer and 'Save as' and create a new shapefile containing all the joined data. (note: here you can change the coordinate system as you save to the new file)
Then Use the Vector > Geometry Tools > Polygon centroids to turn all your zip code polygons to points
Then use Vector > Geoprocessing > Buffer to buffer your points by 50mi
But - you'll have to make sure your zip code polygons (or points) are in a coordinate system that is in FEET so when you use the buffer tool
So - what area do your zip codes cover?


text:
Q: How do i add item ordering options to k2 category admin in Joomla? I made a modification to some of the k2 core files to add another ordering option for items in a category (order by category id). Ive made modifications to the following files to achieve this:
com_k2/models/itemlist.php on line 279 added
     case 'catid':
         $orderby = 'i.catid ASC';
         break;

com_k2/views/itemslist/tmpl/category.xml on line 81 added
<option value="catid">Category</option>

com_k2/views/itemslist/tmpl/generic.xml on line 22 added
<option value="catid">Category</option>

The hacks i've made seem to work fine, but only if i change the params field in the jos_k2_categories table by hand in the database. Whenever i make changes to the category via the admin, the "item ordering" field reverts to "default". It seems to me that adding the option to xml files should make this option available, but i have limited knowledge of extension developement in Joomla.  Is there some where else that add this new option to?  How do i get the new ordering option i added to show up in the Joomla admin?

A: You didn't specify what kind of hacks you did, but I believe you need to make changes in the components/com_k2/views/itemlist/tmpl/category.xml
Here you can set the options about item ordering that you'll find in your admin panel.
You can go for something like:
<param name="itemOrdering" type="list" default="" label="Item ordering" description="Select the order of items">
   <option value="date">Oldest first</option>
   <option value="rdate">Most recent first</option>
   <option value="alpha">Title Alphabetical</option>
   <option value="order">Ordering</option>
   <option value="rand">Random ordering</option>
</param>

Many values are loaded into components/com_k2/views/itemlist/view.html.php, you call the $item_ordering = $params->get('itemOrdering') and pass it to your model. Look into that file for inspiration, I haven't been mangling with Joomla for a while.


text:
Q: Invalid URI supplied error when trying to clone a site to localhost I'm trying to clone a copy of a production site to run on MAMP. I've downloaded all the site's files (a whopping 4+GB) and took a copy of the database. I ran a searhc and replace on the production URL to use the localhost URL e.g 127.0.0.1/magento (no underscores in it).
I updated the local.xml to use the local copy of the database.
I'm nowhere near a Magento expert but offered to install a new theme with some small CSS updates for a friend so any help would be very much appreciated as I wasn't planning on spending hours getting a clone of the site to work.
One thing I did notice, and the link doens't work, is that the link to the error report has the port listed in it twice for some reason http://127.0.0.1:8888:8888/magento/errors/report.php?id=489737565032&skin=default

A: Figure it out! I just needed to clear the cache folders. Found the solution in this video https://www.youtube.com/watch?v=oUU9t2RGqMg


text:
Q: Show related records in Envelope with DocuSign Apex Toolkit I am working to sent out documents within Salesforce on a daily basis when certain CPQ Quotes meet certain criteria. This would be a scheduled process and I created a DocuSign Envelope Template for the document that needs sent out. I am leveraging the Apex Toolkit since this is meant to be an automated process.
In the Document, I need to show the related child Quote Line records in a table as well. With the toolkit I can add in simple tabs using anchor text placed in the document. I attempted to configure the anchor text in the template builder UI within Salesforce but haven't had luck with that pulling in the data that I need.
Is the Toolkit capable of building a table for related records or is it leveraged more for very simple tabs to show data and not build something so dynamic?

A: You can take the records in Salesforce with the SOQL query and put that data into the tab. For example, in the case of setting the recipient, you can retrieve the Contact record in Salesforce with SOQL query and send the envelope by putting that data into the Recipient object.
//we will use a Salesforce contact record as a Recipient here
Contact myContact = [SELECT Id, Name, Email FROM Contact LIMIT 1];

//use the Recipient.fromSource method to create the Recipient
dfsle.Recipient myRecipient = dfsle.Recipient.fromSource(
            myContact.Name, // Recipient name
            myContact.Email, // Recipient email
            null, //Optional phone number
            'Signer 1', //Role Name. Specify the exact role name from template
            new dfsle.Entity(myContact.Id)); //source object for the Recipient

//add Recipient to the Envelope
myEnvelope = myEnvelope.withRecipients(new List<dfsle.Recipient> { myRecipient });


text:
Q: How do I search for a specific cell in a DataGridView? How can I get the cell index in a DataGridView where the column header text = "something" and the row contains "somethings"?

A: You can't access a DataGridView column directly by its name. You'd need to do something like this:
int FindCellRowIndex( string columnName, string rowContent ){
    foreach (DataGridViewRow row in dgView.Rows){
           foreach (DataGridViewCell cell in row.Cells){
               if( cell.OwningColumn.Name() == columnName && cell.Value != null && Convert.Tostring(cell.Value) == rowContent)
                  return row.Index;
           }
    }
    return -1;
}

A: You should iterate through the GridViewRowCollection and then each cell of the individual GridViewRow. If you do that, then you can get the cell's text property. Another option is to use FindControl and extract the appropriate property. You can use the .FindControl() method to find actual controls (label, literal, checkbox, etc) inside cells or go through them by index GridView.Rows.Cells[index]


text:
Q: EarPods Sound Works but Remote Control Doesn't? I have a pair of EarPods that came with my iPhone 5s. They worked completely fine until the other day. When I plug them into my iPhone or my iPad, the sound worlds completely fine but the remote interface just doesn't work entirely. I have looked into the apple support communities but couldn't find anything. I have tried Cleaning the headphone jack on both devices and I have tried updating to iOS 7.0.6 AND iOS 7.1(I'm a developer). This issue has been bothering me and I would appreciate any help.
Thanks

A: That sounds like a hardware issue with the EarPods.
If you have an apple store nearby you can take them in and try a new set. I've gotten one set of earbuds and one set of EarPods replaced with very little trouble.

A: I think you should get a new pair of Earpods / Headphones.
It doesn't cost much, it should be around £25.00 (UK) and $29.00 (US). I have encountered this problem a lot of times, i'd buy a new pair.


text:
Q: How to select all elements and remove a CSS class I have the following JS function which on click is making the chosen element to be selected(is changing the background color) and should make all other elements to remove this class. However, for some reason onClick the "menu-category-hover" class is not removed.
function GetData(allMenuItems, theCategoryId) {

    // Remove selected class on other Elements
    allMenuEl = document.querySelectorAll('menu-category');
    for (var i = 0; i < allMenuEl; i++) {
        allMenuEl[i].classList.remove("menu-category-hover");
    }

    .....

    // On element Click
    var hoverEl = document.getElementById("menu_cat_" + theCategoryId);
    hoverEl.classList.add("menu-category-hover");
}

Burgers

A: Check this

function GetData(allMenuItems, theCategoryId) {

    // Remove selected class on other Elements
    allMenuEl = document.querySelectorAll('.menu-category'); //<--- class indicator `.`
    for (var i = 0; i < allMenuEl.length; i++) { //<-- not added allMenuEl.length
        allMenuEl[i].classList.remove("menu-category-hover");
    }

    .....

    // On element Click
    var hoverEl = document.getElementById("menu_cat_" + theCategoryId);
    hoverEl.classList.add("menu-category-hover");
}


text:
Q: Получить выделенную радиокнопку? Есть список радиокнопок.

                <input type="radio" id="who_you1" name="type_bid" value="Прямой заказчик" <?if ($users['type_bid']=='Прямой заказчик'){?>checked=""<?;}?>>
                  Прямой заказчик

                <input type="radio" id="who_you2" name="type_bid" value="Диспетчер" <?if ($users['type_bid']=='Диспетчер'){?>checked=""<?;}?>>
                  Диспетчер

                <input type="radio" id="who_you3" name="type_bid" value="Логистическая компания" <?if ($users['type_bid']=='Логистическая компания'){?>checked=""<?;}?>>
                  Логистическая компания

Пот нажатии на кнопку save нужно получить выбранную радиокнопку.
Так не работает
var type_bid = $("input[name='type_bid']").val();

Что делать? как получить посредством jquery

A:

$("#x").click(function() {
  console.log($("input[name='type_bid']:checked").val());
})

  <input type="radio" id="who_you1" name="type_bid" value="Прямой заказчик" <?if ($users[ 'type_bid']=='Прямой заказчик' ){?>checked=""
  <?;}?>>
      Прямой заказчик

  <input type="radio" id="who_you2" name="type_bid" value="Диспетчер" <?if ($users[ 'type_bid']=='Диспетчер' ){?>checked=""
  <?;}?>>
      Диспетчер

  <input type="radio" id="who_you3" name="type_bid" value="Логистическая компания" <?if ($users[ 'type_bid']=='Логистическая компания' ){?>checked=""
  <?;}?>>
      Логистическая компания

<button id="x">Click me</button>


text:
Q: Looping through a text file containing domains using bash script I have written a script that reads href tag of a webpage and fetches the links on that webpage and writes them to a text file. Now I have a text file containing links such as these for example:
http://news.bbc.co.uk/2/hi/health/default.stm
http://news.bbc.co.uk/weather/
http://news.bbc.co.uk/weather/forecast/8?area=London
http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/overview/default.stm
http://purl.org/dc/terms/
http://static.bbci.co.uk/bbcdotcom/0.3.131/style/3pt_ads.css
http://static.bbci.co.uk/frameworks/barlesque/2.8.7/desktop/3.5/style/main.css
http://static.bbci.co.uk/frameworks/pulsesurvey/0.7.0/style/pulse.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/ie6.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/ie7.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/ie8.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/css/bundles/main.css
http://static.bbci.co.uk/wwhomepage-3.5/1.0.48/img/iphone.png
http://www.bbcamerica.com/
http://www.bbc.com/future
http://www.bbc.com/future/
http://www.bbc.com/future/story/20120719-how-to-land-on-mars
http://www.bbc.com/future/story/20120719-road-opens-for-connected-cars
http://www.bbc.com/future/story/20120724-in-search-of-aliens
http://www.bbc.com/news/

I would like to be able to filter them such that I return something like:
http://www.bbc.com : 6
http://static.bbci.co.uk: 15

The values on the the side indicate the number of times the domain appears in the file. How can i be able to achieve this in bash considering I would have a loop going through the file. I am a newbie to bash shell scripting?

A: $ cut -d/ -f-3 urls.txt | sort | uniq -c
3 http://news.bbc.co.uk
1 http://newsvote.bbc.co.uk
1 http://purl.org
8 http://static.bbci.co.uk
1 http://www.bbcamerica.com
6 http://www.bbc.com

A: Just like this
egrep -o '^http://[^/]+' domain.txt | sort | uniq -c

Output of this on your example data:
3 http://news.bbc.co.uk/
1 http://newsvote.bbc.co.uk/
1 http://purl.org/
8 http://static.bbci.co.uk/
6 http://www.bbc.com/
1 http://www.bbcamerica.com/

This solution works even if your line is made up of a simple url without a trailing slash, so
http://www.bbc.com/news
http://www.bbc.com/
http://www.bbc.com

will all be in the same group.
If you want to allow https, then you can write:
egrep -o '^https?://[^/]+' domain.txt | sort | uniq -c

If other protocols are possible, such as ftp, mailto, etc. you can even be very loose and write:
egrep -o '^[^:]+://[^/]+' domain.txt | sort | uniq -c


text:
Q: How to make same margins in the different browser? UL margins UL element margins same but Firefox and IE showing different.

FULL CODE:

                        YABAN'da bugün

00:00TROFE ODASI

01:00YERLİ YABAN

01:30HEDEF

02:00İZCİ

02:30KUŞLAR

A: Add this to your first ul declaration:
ul { padding: 0; margin: 0; list-style: none }

You will need to adjust your other ul declaration (i.e. margin-left: 10px) to suit your needs, but this rule will zero it out the differences.
The reason is that each browser uses a different combination of padding and margin to indent the ul. By zeroing out both, and setting only one (i.e. padding or margin) you can keep the display consistent.
Additionally, you need to use a valid DOCTYPE in your code so modern browsers don't revert to Quirks mode. Something like this goes at the very top of your HTML file with NOTHING in front of it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

A: You need to set the padding on the ul as well. E.g.
ul {
    padding: 0;
}


text:
Q: Fix three div's at the bottom of the page My footer is in fixed position and I am seeing the same view on every device. I also want to fix the LinkedIn logo in white div and orange div above it. So that my website will have same view on every device. but I am not to fix them. Can anyone please help?. I have been trying from last 2 weeks.
I am not able to add my codes here. so attaching the same in screenshot
html code
css code
This how my website currently looks like//i.stack.imgur.com/VNVDN.jpg
This is how I want my website to look like//i.stack.imgur.com/VNVDN.jpg

A: Actually I made an easy template of what you need. It is pretty simple so I am sure that you will get the point. Please ask me whatever you want.
HTML

text text text

text text text

CSS
    .footer-wrapper {
        width: 100%;
        height: 100px;
        margin: 0px;
        padding: 0px;
        position: relative;
        bottom: 0;
    }
    .orange-container {
        width: 100%;
        height: 40px;
        background: orange;
    }
    .social-container {
        width:100%;
        display: flex;
        justify-content: center;
    }
    .social-container img {
        background: red;
        width: 30px;
        height: 30px;
    }
    .black-container {
        width: 100%;
        background: black;
        padding-top: 1rem;
        color: white;
        display: flex;
        justify-content: center;
        flex-direction: column;
    }
    .black-container p {
        text-align: center;
        margin: 0;
    }

It is better way to use display:flex or display:grid when you want to center something. Padding is used to make small spaces. Also with the display flex or grid you can easily handle the responsive view of your website pretty easy.
Please I am also advising you to check how to make your questions good Click Here
I hope my answer will be helpful for you, and again if not, don't hesitate to ask anything :)

A: You can use flexbox. And assign to the main part flex-grow.

* {
  padding: 0px;
  margin: 0px;
}
.w {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100vh;
}
.header {
  background: orange;
  padding: 5px;
}

.main {
  flex-grow: 1;
}

.footer {
  background: black;
  height: 40px;
  text-align: center;
  color: white;
  padding: 5px;
}

header

main

footer


text:
Q: How can I possibly draw a JavaFX video in a JFrame's canvas? Basically, I want to "add" a JavaFX video to a Java Swing JFrame, but I also want to draw in that canvas, to do other things while playing the video. I use this code to play the video:
    public class ExtVideoPlayer extends Application implements dev.ckitty.kc.utils.interf.MediaPlayer {

    @Override
    public MediaPlayerType[] getAcceptedTypes() {
        return new MediaPlayerType[] { MediaPlayerType.VIDEO };
    }

    @Override
    public void init(File f, String s) {

    }

    @Override
    public void start() {
        ExtVideoPlayer.launch(new String[0]);
    }

    @Override
    public void command(String[] args) {

    }

    @Override
    public void stop() {

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane root = new StackPane();

        File video = new File("C:\\Users\\980001005\\Videos\\IMG_6503.mp4");
        String url = video.toURI().toURL().toString();
        Media media = new Media(url);
        MediaPlayer player = new MediaPlayer(media);
        MediaView mediaView = new MediaView(player);

        root.getChildren().add(mediaView);
        Scene scene = new Scene(root, mediaView.getFitWidth(), mediaView.getFitHeight());

        primaryStage.setScene(scene);
        primaryStage.show();

        player.play();
    }

}

This works fine, but creates other windows! Of course I could just make it pop-out videos but that would look awful.
I want it to look like Youtube, for example. People would be able to vote for a video and the votes would be shown where Youtube shows recommended videos and adds.
There are some tricks I've seen to put the video inside the JFrame as a Component, but I want it to have a Canvas I can use as well. (So I can draw over the playing video or something)
Please Help!
EDIT!
This answer seems like the one I have to use.
EDIT 2
Now I got the canvas and the video in the same JFrame, however, the canvas is not transparent!
The code
   public class LayeredDisplay extends Display {

    protected JLayeredPane pane;
    protected JPanel ontop, behind;
    protected JFXPanel jfxPanel;

    public LayeredDisplay(String title, int w, int h) {
        super(title, w, h, false);
        this.createLayers();
        this.frame.pack();
        this.frame.requestFocus();
        this.frame.setSize(w, h);
        this.frame.setVisible(true);
    }

    protected void createLayers() {

        this.jfxPanel = new JFXPanel();
        this.canvas = new Canvas();

        Dimension dim = new Dimension(this.w, this.h);

        this.canvas.setPreferredSize(dim);
        this.canvas.setMaximumSize(dim);
        this.canvas.setMinimumSize(dim);
        this.canvas.setFocusable(false);

        //this.ontop.add(this.canvas);

        //pane.add(this.ontop, 2);
        //pane.add(this.behind, 1);

        this.frame.add(this.jfxPanel, 0);
        this.frame.add(canvas, 1);
    }

    public JLayeredPane getPane() {
        return this.pane;
    }

    public JPanel getFront() {
        return this.ontop;
    }

    public JPanel getBack() {
        return this.behind;
    }

    public void addComponent(Component comp) {
        this.behind.add(comp);
    }

    public void addVideo(File video1) {
        Util.initJavaFX();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Code to change Swing data.

                File video = new File("C:\\Users\\980001005\\Videos\\IMG_6503.mp4");
                String url = null;

                try {
                    url = video.toURI().toURL().toString();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                Media media = new Media(url);
                MediaPlayer player = new MediaPlayer(media);
                MediaView view = new MediaView(player);

                player.play();
                jfxPanel.setScene(new Scene(new Group(view)));
            }
        });

    }

}

The Display class I'm extending holds the canvas and the JFrame and gives me the Graphics object to draw in the canvas, nothing special.

A: I got the result I needed!
I put the JFXPanel in a class to manage the video. You basically need to add the JFXPanel into a JPanel
public class FramePlayer {

    private Display disp;
    private JFXPanel jfxPanel;
    private int w, h;

    public FramePlayer(Display disp, int w, int h, boolean autoInit) {
        this.disp = disp;
        this.w = w;
        this.h = h;
        if(autoInit) this.init();
    }

    public void init() {
        this.jfxPanel = new JFXPanel();

        Dimension dim = new Dimension(w, h);
        this.jfxPanel.setPreferredSize(dim);
        this.jfxPanel.setBackground(new Color(0, 0, 0, 255));
        this.jfxPanel.setOpaque(false);

        this.disp.getFrame().add(this.jfxPanel, 1);
    }

    public void addVideo(File video1) {
        Util.initJavaFX();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // Code to change Swing data.

                File video = new File("C:\\Users\\980001005\\Videos\\IMG_6503.mp4");
                String url = null;

                try {
                    url = video.toURI().toURL().toString();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                Media media = new Media(url);
                MediaPlayer player = new MediaPlayer(media);
                MediaView view = new MediaView(player);

                Group g = new Group(view);
                Scene s = new Scene(g);
                s.setFill(Paint.valueOf("TRANSPARENT")); // THIS MAKES IT TRANSPARENT!

                player.play();
                jfxPanel.setScene(s);
            }
        });
    }

    public void renderVideo() {
        this.jfxPanel.paint(this.disp.getGfx().get());
    }

    public void renderVideo(KCGraphics gfx) {
        this.jfxPanel.paint(gfx.get());
    }

}

You need to
1. add the JFXPanel to the JPanel
2. force drawing the JFXPanel into the canvas (well, that's what I had to do..)
3. enjoy!


text:
Q: .htaccess redirect with ignore query string I would like to redirect without looking at the query string, and my redirect result no need append the query string as well, so I add a ? at the end of the RewriteRule.
I tried the following syntax, but the outcome just close to it.
RewriteCond %{QUERY_STRING} .* [NC]
RewriteRule ^exd\.asp$ http://www.example.com/index.php?r=p/consumer? [R=301,L]

and also, i tried to escape the first ?, which I need it, but still the same outcome.
RewriteRule ^exd\.asp$ http://www.example.com/index.php\?r=p/consumer? [R=301,L]

Outcome:
http://www.example.com/index.php?r=p/consumer%3f

I want to get ride of the %3f.
Thanks!

A: You don't need to append a ? at the end if you already have a query string in your target. Just do this:
RewriteCond %{QUERY_STRING} .* [NC]
RewriteRule ^exd\.asp$ http://www.example.com/index.php?r=p/consumer [R=301,L]

By default, query strings get appended, like this:
RewriteRule ^foo$ /bar [L]

You request /foo?blah and you get /bar?blah
However, if you have a ? in your target, query strings won't get appended unless you have the QSA, so:
RewriteRule ^foo1$ /bar? [L]
RewriteRule ^foo2$ /bar?q=2 [L]

You request /foo1?blah and you get /bar, you request /foo2?blah and you get /bar?q=2. If you include a QSA in the rewrite flags, then &blah gets appended to the end.


text:
Q: Typescript definition file for to$q I am hoping that I can get some help. I have been trying use to$q in an angular application that I am trying to describe using typescript. But I am struggling. I have tried to create a type definition file as follows:
/// <reference path="../q/Q.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />

declare module breeze.core {
    export function extendQ(rootScope: ng.IScope, q: Q.Promise<any>): any;
    export function to$q(qPromise: Q.Promise<any>, success: any, fail: any): any;
}

But the javascript code is acting more like a c# extension method and I dont know how to achieve a similar affect with typescript. Note that I have only basic experience in javascript and that breeze is compleletely new to me.

A: $q is defined in angularjs type definitions here
You should not need to reference q.d.ts

A: That's good to know, @basarat.
But more important ... we have deprecated to$q in favor of using $q for promises throughout your Breeze app.  That's right. Breeze no longer depends on Q.js (although that remains the default).
Please use Breeze.Angular.Q instead. It is available as a NuGet package or directly from GitHub. See the Breeze Labs documentation for it.
You simply configure Breeze to use the $q instance for your app module and then write your breeze code against $q promises. For example
var promise = entityManager
   .executeQuery(query)
   .then(successCallback)
   .catch(failCallback)
   .finally(finalCallback);


text:
Q: Binding of lambdas def f(x):
    return x <5
[x for x in filter(lambda x: f(x), ls)]  #[0,1,2,3,4]
def g(x):
    return lambda: x<5
[x for x in filter(lambda x: g(x), ls)]  # [0,1,2,3,4,5,6,7,8,9]
def h(x):
    return lambda x=x: x<5
[x for x in filter(lambda x: h(x), ls)]  # [0,1,2,3,4,5,6,7,8,9]

Can anyone explain why g and h are not equivalent to f?
I think they should be equivalent because x in g and h should bind to the x in the environment that they are defined in (see this question on closures)

A: Here g and h return function object, but filter waits an function which returns a boolean or object wich will convert as boolean . With f it is correct for your expected output, but for g and h, the condition is always true because bool(function object) is always true see here, a python function is a callable object.
Take:
def f(x):
    return x < 5

def g(x):
    return lambda: x < 5

def h(x):
    return lambda x=x: x < 5

I advise to do:
ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print([x for x in ls if f(x)]) # list comprehension
# is equivalent to filter(lambda x: x < 5, ls) iterator
# To get list :
# [x for x in filter(lambda x: x < 5, ls)]
# is equivalent to list(filter(lambda x: x < 5, ls))

Output:
[0,1,2,3,4]

To call g to do:
g(1)() # True

Do:
 print([x for x in ls if g(x)()])

Output:
[0,1,2,3,4]

To call h to do:
h(1)() # True

or
h(1)(5) # False the second argument overrides the first one

Do:
print([x for x in ls if h(x)(x)])
# or print([x for x in ls if h(x)()])

Output:
[0,1,2,3,4]

See documentation to use filter:

Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

See documentation to use lambda expression:
lambda arguments: expression with :
def <lambda>(arguments):
    return expression

A: g(x) and h(x) are returning the lambda function itself (<function __main__.<lambda>>), but not executing it.
Try for example: g(3)() that will return the desired value.
Therefore running g(x)() or h(x)() will work:
[x for x in filter(lambda x: g(x)(), ls)]  # [0,1,2,3,4]
[x for x in filter(lambda x: h(x)(), ls)]  # [0,1,2,3,4]

While running only g(x) or h(x) will return the lambda function itself per each value, which is equivalent to True statement in filter function, and therefore no value is filtered.

and of course, in this case you can just run:
filter(lambda x: x<5, ls)

or even a better list comprehension approach:
[x for x in ls if x<5]


text:
Q: pdf417 barcode creation, Reed Solomon error correction codewords disparity between python and JAVA I created a pdf417 barcode using the Python library pdf417gen.
The barcode was a graphical representation of the string "M1LONG". The barcode has two data columns and the Reed Solomon error correction security level is set to "1". This indicates that with an input of eight data codewords, the number of error correction codewords should be four.
The Python output displays the data code words from D07 to D00 as {8, 389, 902, 11, 900, 344, 396, 900}. The python lists the error correction codewords from C03 to C00 as {718, 801, 313, 877}. Here is the Python that was used to generate all the codewords:
from builtins import range

from .data import ERROR_CORRECTION_FACTORS

def compute_error_correction_code_words(data_words, level):
    assert 0 <= level <= 8

    # Correction factors for the given level
    factors = ERROR_CORRECTION_FACTORS[level]

    # Number of EC words
    count = 2 ** (level + 1)

    # Correction code words list, prepopulated with zeros
    ec_words = [0] * count

    # Do the math
    for data_word in data_words:
        temp = (data_word + ec_words[-1]) % 929

        for x in range(count - 1, -1, -1):
            word = ec_words[x - 1] if x > 0 else 0
            ec_words[x] = (word + 929 - (temp * factors[x]) % 929) % 929

    return [929 - x if x > 0 else x for x in reversed(ec_words)]

The error correction codewords are generated using polynomials, Galois Field arithmetic and complements of modulus 929, which is the number of possible codewords for the pdf417 system. The calculations use a number of factors to simplify the process. For security level 1 the recommended number of factors is four. The factors are 522,568,723,809
http://grandzebu.net/informatique/codbar/pdf417coef.txt
The problem is this. I tried to re-create the error codewords using a JAVA pseudo code obtained from
http://grandzebu.net/informatique/codbar-en/pdf417.htm
I wrote a JAVA program to try and generate the same codewords as the Python software described above, but it does not generate the same error codewords.
The JAVA programme compiles and runs, the math looks alright to my untrained eye, but the error codes produced are not the same. Here is my JAVA, The JAVA variables are termed the same as the Python to make it easier to compare the two programmes.
import java.util.Arrays;

public class reedsolomon{

    public static void main (String[] args){

        int ec_words[] = new int[4];//correction codewords array
        int temp=0;//holding variable
        int count=4; //number of error correction codewords
        int data_words[] = {8,389,902,11,900,344,396,900};// eight data codewords array D7 to D0.
        int factors[]= {522,568,723,809}; //factors or coefficients array.
        for(int i=0; i<data_words.length-1; i++) {
            temp=(data_words[i] + ec_words[count-1])%929;
            for(int x=count-1; x>-1; x--){
                if(x==0){
                    ec_words[x] = (929-(temp*factors[x])%929)%929; //negative values in the Galois Field
                    //GF(929) are equal to the complement of itself if
                    //ec_words[x] > -929
                }
                else{
                    ec_words[x]=(ec_words[x-1]+929-(temp*factors[x])%929) %929; //negative values in the Galois Field
                    //GF(929) are equal to the complement of the
                    //remainder (ec_words[x] /929) if ec_words[x] <= -929.
                }
            }
        }
        for(int j=0; j<count; j++){
            if(ec_words[j] != 0){
                ec_words[j]=929-ec_words[j];
            }
        }System.out.println("Error codewords are " + Arrays.toString(ec_words));
    }
}

I would be most grateful to know what the problem is with the JAVA code that prevents it from generating the same error codewords as the python program contained in the library pdf417gen.

A: There are two problems in your code.

*

*The most important one: you're not processing all words. Your code reads:
for(int i=0; i<data_words.length-1; i++) {

But it should read:
for(int i=0; i < data_words.length; i++) {

In your for-loop you're missing the last data word in data_words[data_words.length-1]

*You're not reversing the ec_words array in the Java code, like you do in python, so the outcome is in the reverse order in ec_words.

With the first fix applied, the outcome from the Java code is:
Error codewords are [877, 313, 801, 718]

A: Some clarification (at least for others reading this thread). The "factors" are actually coefficients to the generator polynomial g(x) = (x-3)(x-3^2)(x-3^3)(x-3^4) in GF(929) = 1 x^4 + 809 x^3 + 723 x^2 + 568 x + 522. The encoding process treats the data as a polynomial m(x), multiplies it by x^4 to create room for the 4 parity bytes, then divides m(x)x^4 / g(x) producing remainder r(x). The encoded code word is then m(x)x^4 - r(x) = 8 x^11 + 389 x^10 + 902 x^9 + 11 x^8 + 900 x^7 + 344 x^6 + 396 x^5 + 900 x^4 + 718 x^3 + 801 x^2 + 313 x + 877 .
Wiki article also uses GF(929) and the same generator polynomial in it's BCH view examples:
https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction#Example_3
The number of possible code words for RS(12,8) GF(929) is 929^8 (a huge number).


text:
Q: How to change date format to hour only i'm trying to calculate the duration of two cells using vba.
I defined t1 as date and t2 as date in my code.
Duration will be t2-t1 and will be presented on another cell.
The format for t1 and t2 is like this : dd/mm/yy hh:mm
I want the duration to be an integer that represent the hour.
But i don't know how to separate the format to get only the time.

A: If you mean you want to calculate how many hours between the two values, you just need to multiple the answer by 24.  Eg in A1 I have 01/09/2021 9:00:00 AM and in cell B1 I have 01/09/2021 2:00:00 PM.  In the following code, hours = 5.
Sub theTime()

Dim t1 As Date
Dim t2 As Date
Dim hours As Integer
t1 = Range("A1").Value
t2 = Range("B1").Value
hours = (t2 - t1) * 24

End Sub

A: Are you looking for the Hour method?
Something like:
MyTimeInHour = Hour(t2-t1)


text:
Q: Simultanously HOT and DENSE in QCD? Take this form of the QCD Phase Diagram for example:

This baryon density is a number density - i.e. number of baryons in some volume.
Why are baryon density and temperature regarded as independent parameters in the QCD Phase Diagram?
The following qualitative reasoning is the source of the trouble:
For conventional matter, the number density and temperature are clearly not independent. If you compress a fixed number of molecules of a gas, thereby increasing the number density, molecules would be closer together, more collisions and hence, higher temperature.
What is the physical reason/ justification for the same, in the context of QCD?
Is it related to the time-scale of a high energy collision (a.k.a. the lab for these sort of things) - i.e. produced particles can't diffuse out fast enough and hence, can be simultaneously hot and dense, at least for the time scale of the collision? (Clearly, this rough hand-waving argument can't be the true reason. So, what is it?)

(Image Source = This )

A: Usually phase diagrams, e.g. of water, are shown as pressure vs temperature. However, we could just as well write a phase diagram as temperature vs density. This is because the equation of state of matter is a relation between pressure, density and temperature.
The above phase diagram should be interpreted as showing: what is the state of matter at a certain density and temperature? For example, for high densities (particles heavily packed together) and high temperatures (large average kinetic energy), which occurs for example at beginning of the universe, the state of matter is expected to be a quark-gluon plasma.
A simple way to see why your reasoning fails is to consider a gas which satisfies $p=n kT$. At high densities (interparticle distance small) and but very low temperatures (small average kinetic energies), the pressure is very low. At low densities (interparticle distance large) and very high temperatures (large average kinetic energy), the pressure is high.

A: I think you are right to be confused by the nuclear phase diagram, but I will rephrase your question to show you why there is no contradiction in "hot and dense".
I believe we all understand that the density can be regarded as a proxy for the specific volume for a fixed number of particles. So I will take it from there.
Below is a typical P-V-T phase diagram. The three parameters P-V-T are not independent, but any two are.

And here cuts perpendicular to the T-axis (constant temperature):

The 3D phase diagram therefore shows you
1) that it is possible to vary the specific volume (read: density) without changing the temperature. 2) what pressure to apply in order to achieve a given $(V,T)$ combination.
In your example: You start with some $(P_0,V_0,T_0)$; you apply pressure getting to $P_1$, in order to decrease the specific volume down to some desired value $V_1$; the value of temperature $T_1$ which you reach will depend on both $V_1$, $T_1$. The phase diagram gives you that dependence.
As regards the nuclear phase diagram, it leaves unclear what happens to the pressure. More precisely, it leaves out the third axis, whatever it is. That would be a different question.
[Edit] I should have added a V-T diagram, to make the analogy with you QCD phase diagram more clear - I am not allowed to post one now, but I am sure you can find one easily.


text:
Q: Custom Post Type category nav isn't highlighting active category I used Types from wp-types to create my custom post type. I have category archive pages and individual post pages set up. The category navigation is highlighting the active category like it's supposed to on the category archive page, but not on the individual post page. What am I doing wrong here?
This is the code for the category list navigation:
<?php
    if (has_nav_menu('work_navigation')) :
        wp_nav_menu(['theme_location' => 'work_navigation', 'walker' => new wp_bootstrap_navwalker(), 'menu_class' => 'nav work-navbar-nav']);
    endif;
?>

Category archive page here: http://designatwork.net/dawnew/category/financial/
Individual post page example here: http://designatwork.net/dawnew/work/212/