text:
Q: Uneven space after last row of the grid inside listview in xamarin.forms I am working in xamarin.forms. I am facing the very silly issue and already wasted 5 hours on it. It's designing issue.
<Grid x:Name="MaingrdForms">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <ListView Grid.Row="0" x:Name="lstLatestProducts" HasUnevenRows="True"
                          ItemAppearing="LstLoadmore"
                          IsPullToRefreshEnabled="true"
                          Refreshing="LstPulled"
                          CachingStrategy="RecycleElement">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <ViewCell.View>
                                    <Grid Padding="10">
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="2*"/>
                                            <ColumnDefinition Width="4*"/>
                                            <ColumnDefinition Width="0.5*"/>
                                        </Grid.ColumnDefinitions>
                                        <Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" HeightRequest="100" WidthRequest="100"
                                               Source="{Binding ProductImg}" Margin="5" VerticalOptions="Center" HorizontalOptions="Center" />
                                        <Label Grid.Row="0" Grid.Column="1" Text="{Binding ProductName}" Style="{StaticResource LabelHeaderStyle}"/>
                                        <Label Grid.Row="1" Grid.Column="1" Text="{Binding ProductDesc}" Style="{StaticResource LabelDescStyle}"/>
                                        <StackLayout Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
                                            <Image Source="icon_password.png"/>
                                            <Label Text="{Binding SubscriptionCategory}" VerticalOptions="Center" HorizontalOptions="Start"/>
                                            <Image Source="icon_password.png"/>
                                            <Label Text="{Binding CreatedDate}" VerticalOptions="Center" HorizontalOptions="Start"/>
                                        </StackLayout>
                                        <Image Grid.Row="0" Grid.Column="2" Grid.RowSpan="3" VerticalOptions="Start" Source="erecall.png"/>
                                    </Grid>
                                </ViewCell.View>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Label Grid.Row="0" x:Name="lblNoRecordFound" Text="No Record found" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
            </Grid>

In List, I am taking HasUnevenRow=true to set row height but in every row, there is some space after the last row. the height of that space is also different. I can't figure out where is the actual issue.


text:
Q: How to combine two cucumber runners Let's say I have 2 runners (A.class & B.class) which extend parent class and this parent class has @beforeclass{initialize all util methods} and @afterclass{ once the methods are successfully invoked close the connection} implementation. A.class is a cucumber test runner and let's say, when ran has 1000 tests. B.class is another cucumber test runner and when ran has 500 tests to be passed. So, now how do I combine these two classes(i.e., A.class and B.class) into a single runner so that I can run all 1500 tests in a single runner instead of using two different runners.?
I tried creating an another class with these two classes loaded in it to run one after another, but once A.class is initialized it's successfully able to pass all tests from A.class and couldn't establish connection to B.class as the extended parent class has @beforeclass and @afterclass which disconnects when the tests are ran for A.class.
Do i need to look upon VM arguments.?
FYR,
@RunWith(Cucumber.class)
@CucumberOptions(
    features = "----",
    plugin = {"pretty", "json:target/cucumber/cucumber.json", "junit:target/cucumber/cucumber-junit.xml"},
    tags = {"@--", "~@--"}
)

public class A extends parentclass {
}
----------------------------------------------------
@RunWith(Cucumber.class)
@CucumberOptions(
    features = "----",
    plugin = {"pretty", "json:target/cucumber/cucumber.json", "junit:target/cucumber/cucumber-junit.xml"},
    tags = {"@--", "~@--"}
)

public class B extends parentclass {
}

How do i combine these two classes to execute all in one extending this parent class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error getting a simple example to work in Rails / Turbo / Hotwire I am learning Hotwire-rails, following both the gorails.com and the Hotwire.dev examples. I am running Ruby 3.0.2 and Rails 6.1.4.1. The symptom is at the very start. After rails new xxx, I edit Gemfile to add gem 'hotwire-rails', then bundle install. At this point my app/javascript/packs/application.js is now:
cat app/javascript/packs/application.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

Rails.start()
Turbolinks.start()
ActiveStorage.start()

So that looks ok. But then rails Hotwire:install. Here is what I see (with the error messages in red.) It is as if it can't find the file.
/mydev/public_samples/rails/hotwire_error (master) rails hotwire:install
Create controllers directory
      create  app/javascript/controllers
      create  app/javascript/controllers/index.js
      create  app/javascript/controllers/application.js
      create  app/javascript/controllers/hello_controller.js
You must import "./controllers" in your JavaScript entrypoint
Install Stimulus
         run  yarn add @hotwired/stimulus from "."
yarn add v1.22.10
[1/4]   Resolving packages...
[2/4]   Fetching packages...
[3/4]   Linking dependencies...
[4/4]   Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ @hotwired/stimulus@3.0.1
info All dependencies
└─ @hotwired/stimulus@3.0.1
✨  Done in 3.00s.
You must import @hotwired/turbo-rails in your JavaScript entrypoint file
Install Turbo
         run  yarn add @hotwired/turbo-rails from "."
yarn add v1.22.10
[1/4]   Resolving packages...
[2/4]   Fetching packages...
[3/4]   Linking dependencies...
[4/4]   Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
info Direct dependencies
└─ @hotwired/turbo-rails@7.0.1
info All dependencies
├─ @hotwired/turbo-rails@7.0.1
└─ @hotwired/turbo@7.0.1
✨  Done in 3.73s.
Enable redis in bundle
        gsub  Gemfile
         run  bundle install
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Using rake 13.0.6
Using concurrent-ruby 1.1.9
Using minitest 5.14.4
Using zeitwerk 2.5.1
Using builder 3.2.4
Using erubi 1.10.0
Using racc 1.6.0
Using crass 1.0.6
Using rack 2.2.3
Using nio4r 2.5.8
Using websocket-extensions 0.1.5
Using marcel 1.0.2
Using mini_mime 1.1.2
Using public_suffix 4.0.6
Using bindex 0.8.1
Using msgpack 1.4.2
Using bundler 2.2.23
Using byebug 11.1.3
Using matrix 0.4.2
Using regexp_parser 2.1.1
Using childprocess 4.1.0
Using ffi 1.15.4
Using method_source 1.0.0
Using thor 1.1.0
Using rb-fsevent 0.11.0
Using redis 4.5.1
Using rexml 3.2.5
Using rubyzip 2.3.2
Using tilt 2.0.10
Using semantic_range 3.0.0
Using spring 3.0.0
Using sqlite3 1.4.2
Using turbolinks-source 5.2.0
Using i18n 1.8.11
Using tzinfo 2.0.4
Using nokogiri 1.12.5 (x86_64-darwin)
Using rack-test 1.1.0
Using websocket-driver 0.7.5
Using mail 2.7.1
Using addressable 2.8.0
Using bootsnap 1.9.1
Using sprockets 4.0.2
Using rb-inotify 0.10.1
Using puma 5.5.2
Using rack-mini-profiler 2.3.3
Using rack-proxy 0.7.0
Using sassc 2.4.0
Using selenium-webdriver 4.0.3
Using turbolinks 5.2.1
Using activesupport 6.1.4.1
Using loofah 2.12.0
Using xpath 3.2.0
Using listen 3.7.0
Using webdrivers 5.0.0
Using rails-dom-testing 2.0.3
Using rails-html-sanitizer 1.4.2
Using globalid 0.5.2
Using activemodel 6.1.4.1
Using capybara 3.36.0
Using jbuilder 2.11.2
Using actionview 6.1.4.1
Using activejob 6.1.4.1
Using activerecord 6.1.4.1
Using actionpack 6.1.4.1
Using actioncable 6.1.4.1
Using activestorage 6.1.4.1
Using actionmailer 6.1.4.1
Using railties 6.1.4.1
Using sprockets-rails 3.2.2
Using actionmailbox 6.1.4.1
Using actiontext 6.1.4.1
Using sassc-rails 2.1.2
Using web-console 4.1.0
Using webpacker 5.4.3
Using rails 6.1.4.1
Using sass-rails 6.0.0
Using turbo-rails 0.8.3
Using stimulus-rails 0.7.2
Using hotwire-rails 0.1.3
Bundle complete! 19 Gemfile dependencies, 79 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
Switch development cable to use redis
        gsub  config/cable.yml

Notice in particular the two errors: You must import "./controllers" in your JavaScript entrypoint and You must import @hotwired/turbo-rails in your JavaScript entrypoint file
Looking at the stimulus source code, it looks like a different file is being checked:
if (Rails.root.join("app/javascript/application.js")).exist?

So that's inconsistent with what I thought I needed to do.
Now I assumed these were innocuous but I am having a little trouble getting the example to work so before going crazy debugging that I wanted to chase down those error messages. Nobody else seems to be getting them. Is it a newly introduced bug or something?

A: In my case I was using the stimulus-rails library and the same message popped up.

You must import "./controllers" in your JavaScript entrypoint

After digging further I discovered that in the source code, it is expecting an application.js in the root of your app/javascript folder.
if (Rails.root.join("app/javascript/application.js")).exist?
say "Import Stimulus controllers"
append_to_file "app/javascript/application.js", %(import "./controllers"\n)
else
say %(You must import "./controllers" in your JavaScript entrypoint), :red
end
If that file doesn't exist, it shows the error that.
There are two solutions to this.

*

*Add application.js to the app/javascript folder, run rails stimulus:install again and the application.js the entry point of your app

*Add import "../controllers"  to the entry point of you rails javascript. In my case, it was the app/javascript/packs/application.js and everything should work fine when you reload the page.

A: With a default install of rails with webpacker there should be an entrypoint file at app/javascript/packs/application.js already with some default code. If not did you enable webpacker? Try rails webpacker:install and then you should have the entrypoint where you can add import '../controllers' and import '@hotwired/turbo'.

A: This seems like everything is working correctly rails just likes to output what its doing to the console but it should have added those to your file.


text:
Q: Hamiltonicity criteria for sparse graphs Given a sparse graph, how can one go about proving that it is Hamiltonian? (Assuming it actually is, of course).
There are three main classes of criteria for Hamiltonicity that I am aware of:

*

*Dirac-type conditions ($\delta \geq \frac{n}{2}$, i.e. high minimum degree).

*Spectral conditions.

*Erdos-Chvatal-type conditions ($\kappa \geq \alpha$, i.e. connectivity greater than independence number).
However, none of these approaches is able to settle even the Hamiltonicity of $C_{n}$, the $n$-cycle! Apparently, the reason is that these approaches work best for dense graphs.
Is there an alternative criterion that works well for sparse graphs?

A: Partial answer.
According to Eppstein

It is known that it is NP-complete to test whether a Hamiltonian cycle exists in a 3-regular graph, even if it is planar (Garey, Johnson, and Tarjan, SIAM J. Comput. 1976) or bipartite (Akiyama, Nishizeki, and Saito, J. Inform. Proc. 1980) or to test whether a Hamiltonian cycle exists in a 4-regular graph, even when it is the graph formed by an arrangement of Jordan curves (Iwamoto and Toussaint, IPL 1994).

So in general you can't expect complete answer to your question.
Another reason for Hamiltonicity are forbidden subgraphs, which
force Hamiltonicity (possibly with a finite number of exceptions).
Not sure if this works for sparse graphs, perhaps search the web.
Found this: Forbidden subgraphs, hamiltonicity and closure
in claw-free graphs
There are theorems of the form:

Every 2-connected $XY$-free graph is hamiltonian.

Where $X,Y$ are explicit small graphs.
For certain type of graphs polynomial time
algorithms exist for HC, so if the they work for sparse
graphs you can find a cycle, e.g. this paper


text:
Q: How do I modify this code to write to a file? I am attempting to modify this Heap's Algorithm that shows all possible permutations of an input of strings.  I am trying to modify the code to be able to be used with the Scanner class with a writer file.  When I try to write to a new file, it does not add all 24 strings as it should, but rather adds the first 4.  Because it is a void method, I cannot use pw.println(obj.heapPermutation(a, a.length, a.length)). Any suggestions to fix this issue?
Thanks
P.S. I found this code online, and I acknowledge that it is not mine.
import java.util.Scanner;
import java.io.*;
import static java.lang.System.*;

class HeapAlgo
{

    void heapPermutation(String a[], int size, int n) throws IOException
    {
       FileWriter fw = new FileWriter("note.txt");
       PrintWriter pw = new PrintWriter(fw);

 // if size becomes 1 then prints the obtained
 // permutation
       if (size == 1)
          for (int i=0; i<n; i++)
          {
              System.out.println(a[i] + "");

          }

          for (int i=0; i<size; i++)
          {
             heapPermutation(a, size-1, n);

// if size is odd, swap first and last
// element
                if (size % 2 == 1)
                {
                    String temp = a[0];
                    a[0] = a[size-1];
                    a[size-1] = temp;
                }

// If size is even, swap ith and last
// element
                else
                {
                   String temp = a[i];
                   a[i] = a[size-1];
                   a[size-1] = temp;
                }

         }

  }

public static void main(String args[]) throws IOException
{

   HeapAlgo obj = new HeapAlgo();
   String a[] = new String["abcd","bbbb","cccc","dddd"];
   obj.heapPermutation(a, a.length, a.length);

A: Your PrintWriter is initilized inside the heapPermutation method, which because it's called recursively heapPermutation(a, size-1, n) will be overridden each time. I believe the default behaviour for this is to replace the file, not append to it.
You should create a constructor to initialize the PrintWriter so it is not reinitilized each time.
class HeapAlgo {
    // create a writer at the class level
    private PrintWriter _pw;

    // Create a constructor to assign the writer
    public HeapAlgo(PrintWriter pw) {
       this._pw = pw;
    }

    void heapPermutation(String a[], int size, int n) throws IOException {
    // if size becomes 1 then prints the obtained
    // permutation
        if (size == 1)
            for (int i=0; i<n; i++) {
                System.out.println(a[i] + "");
                this._pw.print(a[i] + ""); // print here I belive?
            }

        for (int i=0; i<size; i++) {
            heapPermutation(a, size-1, n);

            // if size is odd, swap first and last
            // element
            if (size % 2 == 1) {
                String temp = a[0];
                a[0] = a[size-1];
                a[size-1] = temp;
            }

            // If size is even, swap ith and last
            // element
            else {
               String temp = a[i];
               a[i] = a[size-1];
               a[size-1] = temp;
            }
        }
    }
}

public static void main(String args[]) throws IOException {
    FileWriter fw = new FileWriter("note.txt");
    PrintWriter pw = new PrintWriter(fw);
    HeapAlgo obj = new HeapAlgo(pw); // Pass in a writer
    String a[] = new String["abcd","bbbb","cccc","dddd"];
    obj.heapPermutation(a, a.length, a.length);


text:
Q: How to Deal with transactions in RESTful web services? A REST client goes through a sequence of steps with a server in a flow. The client would like to cancel the flow and undo all the changes done to the data in that flow.
For example, we have a below method. It has three different steps in it. First two are rest calls where third one is data insertion. Now if restCall1(), restCall2() are success but third step is failed. Everything done in first two steps should be reverted back.
method(){
    restCall1(); // Rest Call to the server, perform DB operations
    restCall2(); // Rest call to the server, perform file operations
    insertData(); // Perform DB operations
}

What is the best practice to deal with this transaction problem. One way is to build a custom transaction framework and rollback steps. Is there any framework/tool that can give solution to deal with this problem?

A: A REST client can only maintain it's own state in REST call and there is no synchronization between state of REST client and resources managed by server.You will have to maintain the synchronization among the various REST calls to web service which violates the stateless communication.If you intend to do that you have to maintain the synchronization of states among the various REST calls and co-ordinate accordingly.
More here
However there are workarounds.Retro is a model which supports the transactions for REST in an error prone and scalable way.
See this as well.Hope it helps.


text:
Q: Show only number in laravel I have a data in my database, which contains number and text both like [ 4,First Appeal ].Now fetch the data and want to show only the TEXT not the NUMBER part.How can I do

   Case type :{{ $case_details->case_type }}

Thanks in advance....

A: You can use explode on a string if it is always going to be comma separated. I would probably add some checking as the [0] could fail if there is no comma in the data. Secondly, I would suggest you revaluate how you are storing your data as it seems like this structure is not very efficient for multiple reasons. One suggestion would be be to only refer type to a number which has a config on the server which has the corresponding First Appeal or maybe a separate table of types with a foreign key to the types on case_details.

   Case type :{{ explode(",", $case_details->case_type)[0] }}


text:
Q: How to map query parameters to route parameters after GET-form submission There is a simple GET-form on my page with one parameter (lets say query). If I submit form, it redirects me to /Controller/Action?query=value. I would like to be redirected to /Controller/Action/value.
How I can achieve that? URL rewrite mechanism? Something with routing configuration?

A: You could use URL Redirect to implement that.Try to refer to my below demo:
1.Create a RewriteRules class
public class RewriteRules
{
    public static void RedirectRequests(RewriteContext context)
    {
        var request = context.HttpContext.Request;

        if (request.Query["SearchString"].ToString() != "")
        {
            var xx = $"{context.HttpContext.Request.Path.Value}/{request.Query["SearchString"].ToString()}";
            context.HttpContext.Response.Redirect ($"{context.HttpContext.Request.Path.Value}/{request.Query["SearchString"].ToString()}");
        }
    }
}

2.Configure it as middleware in startup.cs
app.UseRewriter(new RewriteOptions()
            .Add(RewriteRules.RedirectRequests)
            );

3.My view:
<form asp-controller="Home" asp-action="TestUrl" method="get">
<p>
    Title: <input type="text" name="SearchString">
    <input type="submit" value="Filter" />
</p>
</form>

4.My action:
[HttpGet("Home/TestUrl/{searchString?}")]
public async Task<IActionResult> TestUrl(string searchString)
    {
        return Json(searchString);
    }

When you send /Home/TestUrl?searchString=hello, it will redirect to /Home/TestUrl/hello and return "hello".

A: I would suggest you handle this with a Get request from javascript where you can handle the URL format to make a Get to the desired action method. By default the binding of a getform passes the parameter as part of the query string on the URL.
Before submitting the data get the data from the form and make a Get request via Ajax if you want passing the parameter to the correct url.

A: I think you are looking for WebApi routing configurations. If my guess is correct then you need to write this in your WebApi.config file in App_start folder.
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });

So based on the route request it will map with the corresponding route direction and it will take you to the particular controller and action method as per the request.

A: You just need to include the parameter in a route template, and it'll do this for you. Given this example controller:
[Route("[controller]")]
public class TestController : Controller
{
    [HttpGet("something/{value}")]
    // -------^^^^^^^^^^^^^^^^^ is the route template.
    public IActionResult Something(string value)
    {
        return View();
    }
}

you can call Something with /test/something/5 and value will be 5.


text:
Q: Yoast SEO: convert og:description to meta name descriptions? I am working on a website with 100+ pages and somehow I forgot all about the meta descriptions. Yoast however, has automatically added "og:description" tags which actually has the content I need for meta name="description" on each page. So how can I get or duplicate the og:descriptions into meta name descriptions? Something to do with setting up the Yoast page meta templates? Please help. Thanks.

A: You can set a template for meta description in Yoast (SEO->Search Appearance->Content types). This will set meta descriptions for all pages unless they are individually overridden.


text:
Q: Trying to Pluralize in C# I get 'Entity' does not exist in System.Data I have a T4 template include that starts like this:
<#@ template debug="true" hostSpecific="true" language="C#" #>
<#@ Assembly Name="System.Data" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="System.Globalization" #>

<#@ output extension=".generated.cs" #>

string tableName = Path.GetFileNameWithoutExtension(Host.TemplateFile);

When I try to add a reference to Pluralizer, like this:
<#@ template debug="true" hostSpecific="true" language="C#" #>
<#@ Assembly Name="System.Data" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.Data.Entity.Design.PluralizationServices" #>

<#@ output extension=".generated.cs" #>

string tableName = Path.GetFileNameWithoutExtension(Host.TemplateFile);
string pluralTable = PluralizationService.CreateService(new CultureInfo("en-US")).Pluralize(tableName);

I get the message:

Compiling transformation: The type or namespace name 'Entity' does not exist in the namespace 'System.Data' (are you missing an assembly reference?)

I do reference System.Data.Entity.Design in the Project. We are using EF6.


text:
Q: ASP.net queue length vs Application Pool queue length I am looking to to make my web application scalable and was going through articles in which it was said that the queue length should be increased by a factor of say 1.5 * the number of users.
Settings:

*

*IIS-> Application Pool Default Settings -> Queue Length

*IIS ->ASP.NET-> Queue Length
Question:
What is the difference between the queue length properties?
I am aware that one says it handles HTTP.sys requests and the other concurrent asp.net requests. However, how will it help an application scale i.e. will changing only one suffice or both are performing some different role.

A: The application pool can handle multiple websites, so the queue is for every site inside the pool. The ASP.NET queue is restricted for that website.
Answer 1: Appilcation Pool Default Settings -> Queue Length:

Optional uint attribute.
Indicates to HTTP.sys how many requests to queue for an application
  pool before rejecting future requests.
When the value set for this property is exceeded, IIS rejects
  subsequent requests with a 503 error. If the loadBalancerCapabilities
  setting is true, the connection is closed instead of rejecting
  requests with a 503.
https://learn.microsoft.com/en-us/iis/configuration/system.applicationhost/applicationpools/applicationpooldefaults/

Answer 2: IIS -> ASP.NET -> Queue Length:

Its the same, but related to the website selected.


text:
Q: how to show events link in .net calendar control? I want to develop a calendar that could show events link on it. The events will have datetime field used to locate date on calendar and it also have a link field to make hyperlink on calendar. If don't use 3rd party software, how to develop such a calendar? Any suggestion is appreciated.

A: If you're interested in 3rd party commercial ASP.NET controls where the work is already done for you, check out these solutions (in no particular order):

*

*ComponentOne Scheduler

*Infragistics WebSchedule

*Telerik Scheduler

*ComponentArt Scheduler

*DevExpress ASPxScheduler
If none of those are suitable or if you're really looking for something free or open source, check out the answers to the question What is a good (cheap/free) calendar/schedule control for ASP.NET?


text:
Q: zeromq conversion between datatypes Hello I am trying to understand and learn how to work with ZeroMQ and while this could be basic, I didn't find a way to fix it. In this code, I am trying to create a server to forward messages from one client to another one. The server compiled just fine but there are some major issues (almost all of them regarding datatypes) so I couldn't even test my server.
server.cpp:
#include "zmq.hpp"
#include <string>
#include <iostream>
#include <unistd.h>
int main ()
{
    zmq::message_t board (9);
    zmq::context_t context (1);
    zmq::socket_t socket1 (context, ZMQ_REP);
    socket1.bind ("tcp://*:20000");
    zmq::socket_t socket2 (context, ZMQ_REP);
    socket1.bind ("tcp://*:20001");
    int jogo=9;
    while (jogo)
    {
        zmq::message_t request;
        if (jogo%2!=0)
        {
            socket1.recv (&request);
            memcpy ((void *) board.data (), request.data(), 9);
            socket2.send (board);
        }
        else
        {
            socket2.recv (&request);
            memcpy ((void *) board.data (), request.data(), 9);
            socket1.send (board);
        }
        --jogo;
    }
    return 0;
}

jogo_client.cpp
#include "zmq.hpp"
#include <string>
#include <iostream>

int main ()
{
    int player,port=20000,jogo=9,ganhou=0;
    std::string game;
    std::cin >> player;
    port+=player;
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REQ);
    std::cout << "Connecting to game server…" << std::endl;
    //-std=gnu++11
    socket.connect (std::string("tcp://localhost:")+std::to_string(port));
    zmq::message_t board (9);
    if(player)
    {
        while(jogo)
        {
            if (jogo%2!=0)
            {
                memcpy ((void *) board.data (), "Hi from 1", 9);
                std::cout << "Sending Hi" << std::endl;
                socket.send (board);
            }
            else
            {
                socket.recv (&board);
                memcpy ((void *) ,game, request.data (), 9);
                std::cout << "Got from 2: " << std::endl;
                std::cout << game << std::endl;
            }
            --jogo;
        }
    }
    else
    {
        while(jogo)
        {
            if (jogo%2!=0)
            {
                socket.recv (&board);
                memcpy ((void *) ,game, request.data (), 9);
                std::cout << "Getting from 2 " << std::endl;
                std::cout << game << std::endl;
            }
            else
            {
                emcpy ((void *) board.data (), "Hi from 2", 9);
                std::cout << "Sending Hi" << std::endl;
                socket.send (board);
            }
            --jogo;
        }
    }
 return 0;
}

compile errors:
jogo_client.cpp: In function 'int main()':
jogo_client.cpp:14:73: error: no matching function for call to 'zmq::socket_t::connect(std::basic_string<char>)'
jogo_client.cpp:14:73: note: candidate is:
In file included from jogo_client.cpp:1:0:
zmq.hpp:384:21: note: void zmq::socket_t::connect(const char*)
zmq.hpp:384:21: note:   no known conversion for argument 1 from 'std::basic_string<char>' to 'const char*'
jogo_client.cpp:29:26: error: expected primary-expression before 'void'
jogo_client.cpp:29:26: error: expected ')' before 'void'
jogo_client.cpp:43:26: error: expected primary-expression before 'void'
jogo_client.cpp:43:26: error: expected ')' before 'void'


text:
Q: What values are == NULL but not === NULL in PHP?
Possible Duplicate:
Null vs. False vs. 0
How does php cast boolean variables?

I know that some values will return true for $value == NULL and not for $value === NULL but is there a complete list of these values?
Also, is isset($value) equivalent to $value === NULL and empty($value) equivalent to $value == NULL?

A: http://www.php.net/manual/en/types.comparisons.php

A: NULL === NULL
Nothing else does. So if a function returns NULL then checking with === will return true.

Also, is isset($value) equivalent to $value === NULL and empty($value) equivalent to $value == NULL?

No, not strictly. Those two are "language constructs" and not functions. They only accept variable names, isset accepts multiple parameters, and warnings are relaxed when using unset variables.

A: The purpose of the triple equals is to ensure the types match as well.  Using only ==, PHP performs truthy/falsy logic, meaning 0==null, 0=='', null=='' are all true, but 0===null, 0==='', null==='' are all false.
Also, '90210'==90210 is true, but '90210'===90210 is false.

A: I suggest you these readings:

About NULL: http://php.net/manual/en/language.types.null.php
  About empty(): http://php.net/manual/en/function.empty.php (you are wrong about it!)
  About isset(): http://php.net/manual/en/function.isset.php

From the offical documentation, they are very explanatory.

A: Anything that evaluates to FALSE when converted to a boolean is == NULL.
So that would be:
  (bool) FALSE
   (int) 0
 (float) 0.0
(string) '' // an empty string
(string) '0'
 (array) array()
 // An object with zero member variables (PHP 4 only)
 // SimpleXML objects created from empty tags

And, obviously, NULL itself. But only NULL and variables with no value are === NULL.
This may help clarify some things.


text:
Q: What is the equation for plotting points on a curve with fixed end points? What is the equation for plotting points on an exponential curve with fixed end points?
For example, if I want to plot 10 point along a curve that starts with 10,000 (x=1, y=10000) and ends with 30,000 (x=10, y=30000) the formula is y=10000*(1.129831^(x-1)).
But if I change 1.129831 to some different value, 2 for example, then the curve tops out at 5,120,000. I'd like to be able to change that base number to adjust the shape of the curve and still have the curve start at a y value of 10,000 and end at a y value of 30,000.
What I need to know is the formula for calculating points along a curve of varying shape, but fixed end points.
Thank you for your help!

A: If you have two points, you have two equations in two unknowns.  In the case you cite, you have the points $(x_1,y_1)=(1,10000)$ and $(x_2,y_2)=(10,30000).$  If you claim the equation is $y=ka^x$ by taking the log you can solve for $k$ and $a$ and you don't have any choice. (note that you can absorb the $-1$ in the exponent in your solution into $k$-that just shifts $x_1$ down to $0$)
If you know the $y$ values of interest and want to specify $a$ (as $2$ in your example) you need to provide another degree of freedom.  Maybe letting $x_2$ vary will satisfy your need.  In that case, you need $a^{(x_2-x_1)}=\frac{y_2}{y_1}$, so in your example if $\frac{y_2}{y_1}=3$ and $a=2, x_2-x_1=\log_23$, so you can space $10$ points from $1$ to $1+\log_23$

A: I think I phrased my question poorly.
I want to plot $y$ at any point $x$ on a curve across any given number of points $n$ greater than 0 using growth $b$ and I want to adjust the scale and base of the curve by specifying the minimum $y_1$ and maximum $y_n$.
I believe this is how to write the formula:
$y=y_1+\frac{(y_1b^{x-1}-y_1)(y_n-y_1)}{y_1b^{n-1}-y_1}$
In Excel you would use the following formula. I'm using named ranges in the formula to make it easier to follow.
=Minimum+(((Minimum*Growth^(Position-1))-Minimum)*(Maximum-Minimum)/((Minimum*Growth^(Periods-1))-Minimum))
Here's an example result set that describes a steep curve:
$n = 10$
$b = 2$
$(x_1, y_1) = (1, 10000)$
$(x_n, y_n) = (n, 30000)$
Gives:
$(x_1, y_1) = (1, 10000)$
$(x_2, y_2) = (2, 10039)$
$(x_3, y_3) = (3, 10117)$
$(x_4, y_4) = (4, 10274)$
$(x_5, y_5) = (5, 10587)$
$(x_6, y_6) = (6, 11213)$
$(x_7, y_7) = (7, 12466)$
$(x_8, y_8) = (8, 14971)$
$(x_9, y_9) = (9, 19980)$
$(x_{10}, y_{10}) = (10, 30000)$
Here's another example result set that describes a shallow curve:
$n = 10$
$b = 1.1$
$(x_1, y_1) = (1, 10000)$
$(x_n, y_n) = (n, 30000)$
Gives:
$(x_1, y_1) = (1, 10000)$
$(x_2, y_2) = (2, 11473)$
$(x_3, y_3) = (3, 13093)$
$(x_4, y_4) = (4, 14875)$
$(x_5, y_5) = (5, 16835)$
$(x_6, y_6) = (6, 18992)$
$(x_7, y_7) = (7, 21364)$
$(x_8, y_8) = (8, 23973)$
$(x_9, y_9) = (9, 26843)$
$(x_{10}, y_{10}) = (10, 30000)$
Hopefully someone else will find this useful. Maybe someone can even find a way to simplify it.
Thanks!


text:
Q: jQuery asynchronous function call, no AJAX request This seems silly, but I can't find how to do an asynchronous function call with jQuery that doesn't involve some server-side request.  I have a slow function that iterates through a lot of DOM elements, and I want the browser to not freeze up while this function is running.  I want to display a little indicator before the slow function is called, then when the slow function returns, I want to hide the indicator.  I have the following:
$('form#filter', parentNode).submit(function() {
  var form = $(this);
  indicator.show();
  var textField = $('input#query', form);
  var query = jQuery.trim(textField.val());
  var re = new RegExp(query, "i");
  slowFunctionCall(); // want this to happen asynchronously; all client-side
  indicator.hide();
  return false;
});

Currently I submit the form and the indicator isn't displayed, the browser freezes, and then slowFunctionCall is finished.
Edit: I used Vivin's answer, specifically the Sitepoint link to get the following solution:
var indicator = $('#tagFilter_loading', parentNode);
indicator.hide();
var spans = $('div#filterResults span', parentNode);
var textField = $('input#query', parentNode);
var timer = undefined, processor = undefined;
var i=0, limit=spans.length, busy=false;
var filterTags = function() {
  i = 0;
  if (processor) {
    clearInterval(processor);
  }
  indicator.show();
  processor = setInterval(function() {
    if (!busy) {
      busy = true;
      var query = jQuery.trim(textField.val()).toLowerCase();
      var span = $(spans[i]);
      if ('' == query) {
        span.show();
      } else {
        var tagName = span.attr('rel').toLowerCase();
        if (tagName.indexOf(query) == -1) {
          span.hide();
        }
      }
      if (++i >= limit) {
        clearInterval(processor);
        indicator.hide();
      }
      busy = false;
    }
  }, 1);
};
textField.keyup(function() {
  if (timer) {
    clearTimeout(timer);
  }
  /* Only start filtering after the user has finished typing */
  timer = setTimeout(filterTags, 2000);
});
textField.blur(filterTags);

This shows and hides the indicator and also doesn't freeze the browser.  You get to watch the DOM elements being hidden as it works, which is what I was going for.

A: I was going to suggest looking at a timeout but alas.  This post by John Resig (of jQuery) explains a bit about how JavaScript handles its single thread.  http://ejohn.org/blog/how-javascript-timers-work/
This article also explains: "One thing to remember when executing functions asynchronously in JavaScript, is all other JavaScript execution in the page halts until a function call is completed. This is how all the current browsers execute JavaScript, and can cause real performance issues if you are trying to call too many things asynchronously at the same time. A long running function will actually "lock up" the browser for the user. The same is true for synchronous function calls too."
All that said, it's possible you could simulate an asynchronous function call yourself by breaking whatever loop you are doing into a smaller chunk and using setTimeout().
For instance this function:
// Sync
(function() {
  for(var x = 0; x < 100000; ++x) {console.log(x)}
})()

// ASync
var x = 0;
setTimeout(function() {
   console.log(x++);
   if(x < 100000) setTimeout(arguments.callee, 1);
} ,1)

A: You might want web workers!
Edit: I'm surprised how many people jumped to "its not possible" so I will elaborate. Web Workers are part of the HTML 5 spec. They allow you to spawn threads to run scripts in the background without blocking the UI. They must be external js files, are invoked by
var worker = new Worker('my_task.js');

and are communicated to via events.

A: Javascript runs in a single thread and therefore if you have a slow function it will block everything else.
UPDATE
That will do some of what you want, but keep in mind that they are not widely supported supported in IE (I think they will be in IE10).
Some resources on Web Workers:

*

*Using Web workers

*Wikipedia article on Web Workers

*WHATWG: Web Workers
Here are a few resources on accomplishing multi-threading without web workers. It's important to note that this isn't "true" multi-threading:

*

*Multi-threading in Javascript (title is a little misleading; it's not true multi-threading)

*Why doesn't Javascript support multi-threading?

*Is there some way to do multi-threading in Javascript?

*Simulating multi-threading using IFRAMEs (I'm not sure how viable this method is; it might be more trouble than it's worth and the law of diminishing returns probably applies.)


text:
Q: Getting list of blocked websites in proxy server I want to have a diagnostic to ensure that my application will not be blocked to access the remote server because of the proxy setting. Is there a way to get the list of a blocked websites in proxy server from the client (.NET)?  I suppose I could use WebRequest and try to call simple echo method in the server and whether I get a 403 or not but wondering if there is other way to do that.
Thanks.

A: This fully depends on your proxy. There is no standard way to achieve this, but your proxy may implement an interface that allows you to retrieve such information through a management API.


text:
Q: Is it possible to create a Fetch Request for core data entities within Scene Delegate for SwiftUI I'm trying to keep synchronize my core data entities with a webservice i'm using. The issue is the web service updates the items every day, so I'm trying to create a fetch request to compare the cached items with the remote items and update the cached items if there are any changes, deletions, or additions.
Ideally I'd like to have this operation completed before the user enters the app. So i'm trying to create a fetch request inside my Scene Delegate.
The logic is this: On app load, I parse the items from my json webservice. At the same time I create a fetch request for the existing local core data entities, compare the local items with the remote items and update the cached items if needed.
Is this possible? Any suggestions or advice on how and when to do this would be greatly appreciated!

A: it's not that complex. You are already have a context in a sceneDelegate when creating a View. Just perform fetch.
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest: NSFetchRequest<YourEntity> = YourEntity.fetchRequest()
    fetchRequest.sortDescriptors = []
    //fetchRequest.predicate = //some filters
    let result = try? context.fetch(fetchRequest)//it always returns an array but it may be empty. Fetch may throw if disc is unavailable or some other reasons
    //do what you need
    let contentView = ContentView().environment(\.managedObjectContext, context)

in general, you can store an UUID as an object version. Every time you modify the object in backend, you can update the version with new UUID. Therefore, you need only to check versions - if it differs, you need to update object. But it only in case user can't modify the object offline. If he can, there must be some complex logic for collision solving.


text:
Q: how to change props of material ui component (MonthView.DayScaleLayoutProps.rowComponent) I am trying to change the number of cells for material ui component called "Month view"
I could access the props of the component and determine which one that I will need to change but I don't know how to change it (style overriding methods didn't work)

what I am trying to do is make the 30 days in a month in one long row with a scroll bar instead of 7-days per row like here

any idea how to do that?


text:
Q: How to include PostgreSQL functions in Django migrations? I would like to include some PostgreSQL functions as part of the database migration.
The two ways I can see are:

*

*Editing the migrations file (generated by python manage.py makemigrations)

*Hooking post table creation

The first seems easier, but laborious if the migration needs to be remade. What would you recommend the best way to go about it?

A: Answering my own question to clear up the question (thanks to all the comments):
First I made an empty migration (python manage.py makemigrations --empty app_name)
Then, to operations add the function's SQL:
migrations.RunSQL(
    ('CREATE OR REPLACE FUNCTION my_function() ...'),
    ('DROP FUNCTION IF EXISTS my_function();')
)

The two lines are for migrate and unmigrate SQL, read more here:
https://docs.djangoproject.com/en/2.1/ref/migration-operations/#runsql
The custom migration will be run automatically after the main migrations.


text:
Q: The max_connections in MySQL 5.7 I met a problem, the value of max_connction in MySQL is 214 after I set it 1000 via edit the my.cnf, just like below:
hadoop@node1:~$ mysql -V
mysql  Ver 14.14 Distrib 5.7.15, for Linux (x86_64) using  EditLine wrapper

MySQL version: 5.7
OS version   :   ubuntu 16.04LTS
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 151   |
+-----------------+-------+
1 row in set (0.00 sec)

As we can see, the variable value of max_connections is 151. Then , I edit the configuration file of MySQL.
yang2@node1:~$ sudo vi /etc/mysql/my.cnf
[mysqld]

character-set-server=utf8
collation-server=utf8_general_ci
max_connections=1000

Restart MySQL service after save the configraion.
yang2@node1:~$ service mysql restart
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to restart 'mysql.service'.
Multiple identities can be used for authentication:
 1.  yangqiang,,, (yang2)
 2.  ,,, (hadoop)
Choose identity to authenticate as (1-2): 1
Password:
==== AUTHENTICATION COMPLETE ===
yang2@node1:~$

Now, we guess the max_connection is 1000, really?
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 214   |
+-----------------+-------+
1 row in set (0.00 sec)

It is 214. I do not really understand this result, who can help me? thx!

A: Follow the following steps:
cp /lib/systemd/system/mysql.service /etc/systemd/system/
echo -e "\r\nLimitNOFILE=infinity" >> /etc/systemd/system/mysql.service
echo "LimitMEMLOCK=infinity" >> /etc/systemd/system/mysql.service
sudo systemctl daemon-reload
sudo service mysql restart

And change or add he following line into file /etc/mysql/mysql.conf.d/mysqld.cnf :
[mysqld]
max_connections=110

Just this!
@Mahdi_Mohammadi

A: 1.Edit mysql service file
#sudo cat /etc/systemd/system/multi-user.target.wants/mysql.service
# MySQL systemd service file

[Unit]
Description=MySQL Community Server
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=forking
User=mysql
Group=mysql
PIDFile=/run/mysqld/mysqld.pid
PermissionsStartOnly=true
ExecStartPre=/usr/share/mysql/mysql-systemd-start pre
ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid
TimeoutSec=600
Restart=on-failure
RuntimeDirectory=mysqld
RuntimeDirectoryMode=755
##this bellow for tuneup
LimitNOFILE=infinity
LimitMEMLOCK=infinity

2.edit /etc/mysql/mysql.conf.d/mysqld.cnf
max_connections        = 99999

A: Add session required pam_limits.so in /etc/pam.d/common-session (usually is not present by default).
The in /etc/security/limits.conf you can add some limits:
*   hard    nofile  8192
*   soft    nofile  4096

Also check using ulimit -a the open files limit.
This you can increase with ulimit -n 4096
Make sure you reboot at the end.

A: You may set the value manually, e.g.
set global max_connections=500;

however, after a restart of MySQL the value is reset to 214.
The solution depends on the (version of) OS and the MySQL version. With Ubuntu 16.04 and MySQL >= 5.7.7 following works:
systemctl edit mysql
Enter
[Service]
LimitNOFILE=8000

save, this will create a new file
/etc/systemd/system/mysql.service.d/override.conf
and restart the server:
systemctl daemon-reload
systemctl restart mysql

For other environments:  Can not increase max_open_files for Mysql max-connections in Ubuntu 15

A: As MySQL documentation on max_connections setting says:

Increasing this value increases the number of file descriptors that
  mysqld requires. If the required number of descriptors are not
  available, the server reduces the value of max_connections.

This means that probably your MySQL server does not have enough resources to maintain the required number of descriptors.
MySQL documentation on How MySQL Opens and Closes Tables makes it clear that:

The table_open_cache and max_connections system variables affect the
  maximum number of files the server keeps open. If you increase one or
  both of these values, you may run up against a limit imposed by your
  operating system on the per-process number of open file descriptors.
  Many operating systems permit you to increase the open-files limit,
  although the method varies widely from system to system. Consult your
  operating system documentation to determine whether it is possible to
  increase the limit and how to do so.


text:
Q: Reusable NSMutableDictionary Someone in that forum proposed me a code solution that worked great, but for my understanding, I would like to know what is the difference between the 2 blocks of code:
Block 1
NSMutableDictionary* step_info = [NSMutableDictionary dictionary];

Block 2
NSMutableDictionary* step_info = nil;
step_info = [NSMutableDictionary dictionary];

It is may be also important to mention that step_info has to be filled and reuse repeatedly to load into another NSmutabledictionary.
Thank's for your help

A: None. The compiler optimises step_info = nil away and you're left with the exact same code.
The following is another approach you could take:
NSMutableDictionary *step_info;
step_info = [NSMutableDictionary dictionary];

A: Having NSMutableDictionary* step_info; first allows you to use step_info = [NSMutableDictionary dictionary] later in the same block of code.
If you wish to assign a value to step_info in multiple methods, it'd be better if you add NSMutableDictionary* step_info in the @interface section of the header file.
That way you can use step_info = [[NSMutableDictionary alloc] init] in any method in your implementation file, then assign values and keys this way: [step_info setValue: value forKey: key];


text:
Q: Conditional Clauses I wonder if you could tell me the difference(s) between the following questions:

*

*If you could have lived in another period, which period would you choose?

*If you could live in another period, which period would you choose?

A: To keep it simple, the first example is in Past Tense, while the second is in Present Tense.

If you could have lived in another period, which period would you choose?

Here, one (person) asks another if he/she had gotten a chance to live in another period, the which would it have been.

If you could live in another period, which period would you choose?

Here, one (person) asks another if he/she gets a chance to live in another period, which will it be.


text:
Q: Win32 LoadImage() from File Error Sorry if this is duplicate but I can't find answer elsewhere. I am simply trying to load an image during runtime using the LoadImage() function of WINAPI. I receive the error code(8) which indicates that there is not enough storage space(error codes found here).
the file is relatively small(2.5kb) so I wonder if there is problem with my code:
void OnCreate()
{
...
HBITMAP hbmDeck = (HBITMAP)LoadImage(hInstance, L"standard.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE);

    DWORD err = GetLastError();
    HBITMAP hbmT = SelectBitmap(hdc, hbmDeck);
    if(!hbmT)
    {
        MessageBox(NULL, L"Failed to LoadImage - 'hbmDeck'", L"OnCreate()", MB_OK);
        PostMessage(hwnd, WM_DESTROY, NULL, NULL);
    }
...
}

A: Yeah, some of the API return error codes are a bit cryptic and don't fit the error.
The file you are trying to load "standard.bmp" is a file on the disk NOT in the resource section right?   Well to load a file from the disk, the fist parameter of LoadImage (hInst) has to be NULL and the fuLoad flag needs to include LR_LOADFROMFILE which you correctly have.


text:
Q: An equivalent of text for the imageView Hello I would like to know what is the equivalent of this :
textView!!.text = getResources().getString(R.string.text)

But in my case I have an ImageView and I want to change it in the Kotlin code I tried :
image!!.getResources().getString(R.drawable.image)

But it does not work...Could you help me please ?
Thank you !

A: You can set like this,
image!!.resources.getDrawable(R.drawable.image)

A: You can set an image with setImageDrawable() or setImageResource()
image?.setImageResource(R.drawable.image)

Or the equivalent, but longer version:
image?.setImageDrawable(getResources().getDrawable(R.drawable.image))

(Also note the question mark instead of double exclamation marks. Now, if image is null, it just skips this line instead of throwing an exception)


text:
Q: How to inject different subclasses as ManagedProperty JSF 2? I'm new to JSF and I'm wondering if it's possible to inject different subclasses of a base class as a MangedProperty, depending on different situations? For instance, I have this managed bean:
@ManagedBean
@SessionScoped
public class Claim implements Serializable {
    private Loss lossDetails; //need to inject one of two subclasses
}

And the following base class:
public class Loss implements Serializable {
    private String lossCause;
    private String lossDescription;
}

Which has two subclasses:
public class AutoLoss extends Loss implements Serializable {
    private List<String> vehicles;
    //...
}

public class PropLoss extends Loss implements Serializable {
    private String property;
    private boolean weatherRelated;
    //...
}

Depending on selections that are made on my application's JSF pages, I want to inject one of the subclasses as the lossDetails ManagedProperty in the Claim managed bean. Since I can't give the two subclasses the same managed bean name and I don't know ahead of time which one needs to be injected, is this something that can be accomplished in JSF? Or is there a different approach I should be considering?
Thanks!

A: You can't and shouldn't.

*

*It's not possible to inject a request scoped value as managed property in a session scoped bean.

*Entities should not be treated as managed beans.

Rather pass it as method argument instead:
<h:dataTable value="#{lossManager.losses}" var="loss">
    <h:column>
        <h:commandButton value="Claim" action="#{claim.doAction(loss)}" />
    </h:column>
</h:dataTable>

With in Claim managed bean:
public void doAction(Loss loss) {
    // ...
}


text:
Q: Stop dropdown from expanding div above Fellow Coders,
I encountered a problem while putting dropdown menu into my app's navigation. When I drag my mouse over my dropdown element, menu below expands together expanding div element above (which is dropdown menu's name) and pushing all other items in navigation's menu to the right side. Here is my code:
const listItems = links.map((link_name) =>

<DropDown name={link_name} />

);
return (

        <Link to="/" className="navbar-brand">

        </Link>

        {listItems}

        {this.renderLinks()}

          <input type="search" ref="city" placeholder="Search"/>

);
const styles = {
 style_r: {
  margin: 10,
  top: 5,
  right: 17,
  bottom: 20,
  left: 'auto',
  position: 'fixed',
 },
 style_l: {
  margin: 5,
  top: 10,
  left: 134,
  bottom: 20,
  position: 'absolute',
 },
 style_img: {
  margin: 5,
  left: 10,
  width: 100,
  height: 42,
 }
 };

dropdown is defined as:
if(this.state.menuActive) {
  menu =

First Item

Second Item

Third Item

} else {
  menu = "";
}
return (

{this.props.name}

    <ReactCSSTransitionGroup transitionName = "menu" transitionEnterTimeout={1000} transitionLeaveTimeout={1000}>
      {menu}
    </ReactCSSTransitionGroup>

)

if I put style={{ position: absolute }} on div (dropdown_name), in my nav bar every element collides into one gibberish weird looking unreadable name...
and here's mine css:
    .menu-enter {
      max-height: 0px;
      -webkit-transition: max-height;
      overflow: hidden;
      width: 100%;
    }

    .menu-enter.menu-enter-active {
      height: auto;
      max-height: 100px;
      width: 100%;
    }

    .menu-leave {
      max-height: 100px;
      -webkit-transition: max-height;
      width: 100%;
    }

    .menu-leave.menu-leave-active {
      overflow: hidden;
      max-height: 0px;
      width: 100%;
    }

    ul.drop {
      margin-top: 7px;
      background-color: #333333;
      color: #6D6D6D;
      border: #333333 solid 7px;
      -moz-border-radius: 7px;
      -webkit-border-radius: 7px;
      width: 100%;
      padding-left:0.4em;
      font-size: 12pt;
      list-style-type: none;
    }

How can I prevent dropdown from expanding my dropdown's name above? I want that my divs that represent dropdown's names would remain the same width.

A: From MDN:

The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static).

Keep your absolute positioning on the dropdown component, and place a position: relative; style on the dropdown's container component (nav-link). This will allow the dropdown to be positioned relative to it's containing nav link.
It seems like your issue with every element combining when you added the absolute position was because they were all being absolutely positioned to the body element.


text:
Q: How to display multiple notifications on different days? I need help and I am a novice regarding notifications and alarms managers on different days and different notifications for example:
I have 2 calendars already defined
calendar.set (2020,5,15,0,0,0);
notificationManager.notify(0, NotifyBuilder.build());
This is showing the notification "We remind you that you can request a process now"
calendar.set (2020,5,20,0,0,0);
notificationManager.notify(1, NotifyBuilder1.build());
This is showing the notification "We remind you that you can request a process that ends in 10 days"
This code is of MainActivity()
Calendar c1 = Calendar.getInstance();
c1.set(2020,5,15,0,0,0);

Calendar c2 = Calendar.getInstance();
c2.set(2020,5,20,0,0,0);

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, c1.getTimeInMillis(), pendingIntent);

Intent intent2 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, 1,intent2, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager am1 = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am1.set(AlarmManager.RTC_WAKEUP, c2.getTimeInMillis(), pendingIntent1);

This code is a class AlarmReceiver()
public class AlarmReceiver extends BroadcastReceiver {

    int id = 0;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.notification)
                .setContentTitle("Notification")
                .setContentText("We remind you that you can request a process now").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})

        notificationManager.notify(id, mNotifyBuilder.build());
        Log.i("TEST", "Count: "+id);

        long when2 = System.currentTimeMillis();
        NotificationManager notificationManager2 = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent2 = new Intent(context, MainActivity.class);
        notificationIntent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 1,
                notificationIntent2, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound2 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder2 = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.notification)
                .setContentTitle("Notification")
                .setContentText("We remind you that you can request a process that ends in 10 days").setSound(alarmSound2)
                .setAutoCancel(true).setWhen(when2)
                .setContentIntent(pendingIntent2)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
        notificationManager2.notify(++id, mNotifyBuilder2.build());
        Log.i("TEST", "Count: "+id);
        }
    }

BUT IN THE NOTIFICATION OF THE DATE 06/15/2020 I GET THE TWO NOTIFICATIONS AT THE SAME TIME AND IN THE SAME WAY OF THE OTHER DATE 06/20/2020
The "id" is correctly of for .notify() but i dont now problem

A: At the moment you are creating two notifications in your onReceive()-method regardless of which intent triggered the broadcast.
You need to check which intent triggered the broadcast (this is the Intent parameter in onReceive()) and then send an appropriate notification.
You could do this, for example, by initialising your intent and intent2 in MainActivity with unique actions (for example, Intent intent = "new Intent("com.myapp.ALARM1")) and then checking in onReceive() for the actions and acting based on them. Note, that this would require you to set up intent-filters for your actions in your manifest file.
So in your onReceive() you might have something like this:
@Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("com.myapp.MY_ALARM1")) {
            // notification here
        }
        if (intent.getAction().equals("com.myapp.MY_ALARM2")) {
            // other notification here
        }

A: Thanks to @Mike M's comment the solution is:
Calendar c1 = Calendar.getInstance();
c1.set(2020,5,15,0,0,0);
Calendar c2 = Calendar.getInstance();
c2.set(2020,5,20,0,0,0);

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra(Intent.EXTRA_TEXT, "We remind you that you can request a process now");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);

    am.set(AlarmManager.RTC_WAKEUP, c1.getTimeInMillis(), pendingIntent);

Intent intent2 = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra(Intent.EXTRA_TEXT, "We remind you that you can request a process thats end in 10 days");
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, 1,intent2, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am1 = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);

    am1.set(AlarmManager.RTC_WAKEUP, c2.getTimeInMillis(), pendingIntent1);

Class ALarmReceiver
public class AlarmReceiver extends BroadcastReceiver {

int id = 0;
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
@Override

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);

Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
        notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
        context).setSmallIcon(R.drawable.notification)
        .setContentTitle("Notification")
        .setContentText(text)
.setSound(alarmSound)
        .setAutoCancel(true).setWhen(when)
        .setContentIntent(pendingIntent)
        .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})

notificationManager.notify(id, mNotifyBuilder.build());

}


text:
Q: next-auth get session fails with ECONNREFUSED I'm using ingress nginx to deploy my app to kubernate with hostname bakugallery.com.
I use getSession inside the getServerSideProps as below.
export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const session = await getSession(context)
  console.log('session', session)

  if (!session) {
    context.res.writeHead(302, { Location: '/' })
    context.res.end()
    return {
      props: {
        user: null,
      }
    }
  }
  return {
    props: {
      user: session?.user,
    },
  }
}

And getting session fails with connect ECONNREFUSED 127.0.0.1:443. Below is the stacktrace.
https://next-auth.js.org/errors#client_fetch_error request to https://bakugallery.com/api/auth/session failed, reason: connect ECONNREFUSED 127.0.0.1:443 {
[client]   error: {
[client]     message: 'request to https://bakugallery.com/api/auth/session failed, reason: connect ECONNREFUSED 127.0.0.1:443',
[client]     stack: 'FetchError: request to https://bakugallery.com/api/auth/session failed, reason: connect ECONNREFUSED 127.0.0.1:443\n' +
[client]       '    at ClientRequest.<anonymous> (/app/node_modules/next/dist/compiled/node-fetch/index.js:1:65756)\n' +
[client]       '    at ClientRequest.emit (node:events:513:28)\n' +
[client]       '    at TLSSocket.socketErrorListener (node:_http_client:494:9)\n' +
[client]       '    at TLSSocket.emit (node:events:513:28)\n' +
[client]       '    at emitErrorNT (node:internal/streams/destroy:157:8)\n' +
[client]       '    at emitErrorCloseNT (node:internal/streams/destroy:122:3)\n' +
[client]       '    at processTicksAndRejections (node:internal/process/task_queues:83:21)',
[client]     name: 'FetchError'
[client]   },
[client]   url: 'https://bakugallery.com/api/auth/session',
[client]   message: 'request to https://bakugallery.com/api/auth/session failed, reason: connect ECONNREFUSED 127.0.0.1:443'
[client] }

It says request to https://bakugallery.com/api/auth/session failed, but when I manually access this url with brower, it works fine.

Any idea how to fix this?


text:
Q: How do i express this nftables command using firewalld rich rules, direct or policy method? I had issues with access to a service listening on the interface lxcxxx (172.XX). this because requests are arriving through  eth0, and firewalld was blocking the forwarding on the FWD filter
[30772.997987] filter_FWD_external_REJECT: IN=eth0 OUT=lxc24220340d98f MAC=96:00:01:a7:b1:a7:d2:74:7f:6e:37:e3:08:00 SRC=XXX.XXX.XXX DST=172.20.4.140 LEN=60 TOS=0x00 PREC=0x00 TTL=57 ID=43937 DF PROTO=TCP SPT=41302 DPT=443 WINDOW=64240 RES=0x00 SYN URGP=0

with this nftables command, the problem goes away:
nft add rule inet firewalld   filter_FWD_external_allow  iifname  "eth0" tcp dport { 80, 443, 25, 587}  accept

but of course it will disppear on reboot/ firewalld reload. How do i add something similar to firewall-cmd? I tried with rich rules, and policy, but im not sure whether its because of the lack of ordering in the tables, but the reject happens, here is something using the direct rules:
firewall-cmd --direct   --add-rule ipv4 filter FORWARD   1 -i eth0  -p tcp  --dport  443  -j ACCEPT

this does not work, the reject chain in  the firewalld table  is reached seemingly before this forward chain is reached. With the policy method i could not think of how to do this. Allowing masquerade also is insufficient.  How do i change the filter_FWD_external_allow  through firewalld so change persists?


text:
Q: Why can't I get images from my S3 bucket when all public access blocked? 403 Forbidden But static files load fine My Django website allows users to upload photos. When the s3 bucket is on public the media content loads fine on the site. However once i block all public access the content no longer loads and a 403 forbidden error is shown. In my code I have added the values needed to allow for authenticate requests. There are no bucket policy's or any CORS configurations. I have tried several different suggestions from blogs and tutorials but nothing seems to work.
I have a user which has programmatic access and set the secret variables in the heroku environment and still get 403 error.
I have tried hard setting the secret variables and still no success.
settings.py
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

MEDIA_LOCATION = 'MediaStorage'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION)
MEDIA_FILE_STORAGE = 'MediaStorage'

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_LOCATION = 'static'
STATICFILES_LOCATION = 'StaticStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATIC_LOCATION)

django_heroku.settings(locals())

storage_backends.py
from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings

class StaticStorage(S3Boto3Storage):
    location = settings.STATICFILES_LOCATION

class MediaStorage(S3Boto3Storage):
    location = settings.MEDIA_FILE_STORAGE
    file_overwrite = False
    custom_domain = False

All static files load fine but media files do not load at all.
I expect the files to load when displaying them in the view web page. however i just get a 403 forbidden error.

A: In your settings.py your have set?
AWS_DEFAULT_ACL = 'public-read'

Look this example is an public project for my state in Brazil.
Project

A: So after many iterations it came down to a line of code missing in the storage_backends.py file missing the line
custom_domain = False
I have updated the original post to match the correct storage_backends.py file


text:
Q: Version loaded from file does not comply with PEP 440 As the title states, I am getting this ERROR when I run python -m build locally using a version file. I  have read the PEP 440 and to me, it appears compliant. I cannot see from the documentation on setuptools why I would be running into this issue
I would really appreciate some help on this since I don't see how I am able to run a debugger on python -m build or get some more understanding of specifically why the _parse_version of setuptools/config.py is unhappy with my version file.
More details:
I have a project structured as follows:
src/
   mypackage/
      __init__.py
      VERSION
pyproject.toml
setup.cfg
setup.py

VERSION
0.0.1

setup.cfg
name = mypackage
version = file: src/mypackage/VERSION
# etc. etc. etc.

setup.py
#!/usr/bin/env python
# Used to create editable installs
import setuptools

setuptools.setup()

pyproject.toml
[build-system]
# Minimum requirements for the build system to execute.
requires = [
    "setuptools>=42",
    "wheel"]  # PEP 508 specifications.
build-backend = "setuptools.build_meta"

More detail on the error:
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/build_meta.py", line 154, in get_requires_for_build_wheel
    return self._get_build_requires(
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/build_meta.py", line 135, in _get_build_requires
    self.run_setup()
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/build_meta.py", line 150, in run_setup
    exec(compile(code, __file__, 'exec'), locals())
  File "setup.py", line 5, in <module>
    setuptools.setup()
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/__init__.py", line 153, in setup
    return distutils.core.setup(**attrs)
  File "/usr/lib/python3.8/distutils/core.py", line 121, in setup
    dist.parse_config_files()
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/_virtualenv.py", line 21, in parse_config_files
    result = old_parse_config_files(self, *args, **kwargs)
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/dist.py", line 778, in parse_config_files
    parse_configuration(self, self.command_options,
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/config.py", line 157, in parse_configuration
    meta.parse()
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/config.py", line 463, in parse
    section_parser_method(section_options)
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/config.py", line 436, in parse_section
    self[name] = value
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/config.py", line 220, in __setitem__
    value = parser(value)
  File "/tmp/build-env-2kboopyp/lib/python3.8/site-packages/setuptools/config.py", line 553, in _parse_version
    raise DistutilsOptionError(tmpl.format(**locals()))
distutils.errors.DistutilsOptionError: Version loaded from file: src/mypackage/VERSION does not comply with PEP 440:

ERROR Backend subproccess exited when trying to invoke get_requires_for_build_wheel

A: I have solved this though I'm not happy with the current documentation or error messaging, as it stands I feel it's quite easy to fall into this trap.
So the solution was to create a MANIFEST.in file with the line:
include src/mypackage/VERSION at top level of my repo:
src/
   mypackage/
      __init__.py
      VERSION
pyproject.toml
setup.cfg
setup.py
MANIFEST.in

Additionally, the following must be added to the setup.cfg
[options]
include_package_data = True

From docs:

include_package_data If set to True, this tells setuptools to automatically include any data files it finds inside your package directories that are specified by your MANIFEST.in file. For more information, see the section on Including Data Files.

The setuptools documentation V57.1.0 had me believe it would be included:

Automatically include all relevant files in your source distributions, without needing to create a MANIFEST.in file, and without having to force regeneration of the MANIFEST file when your source tree changes.

And intuitively I would have thought a file: key word with the path would be sufficient, or that the error message which as it turns out was produced because there was no such file, might have clued me in some more. This is also not apparent from the packaging-projects
But I suppose it can be inferred from the MANIFEST.in documentation.
I say all this since incase anyone has anything useful to add or counter reason my current feeling: that there might be an omission from the current guides regarding using a version file.


text:
Q: Creating Eclipse-like line markers bar in Java text editor My Java GUI app contains a scrollable text window. Besides a standard scrollbar, I need a vertical bar with colored line markers, like in Eclipse. Hopefully you know what am I speaking about. This bar is not scrollable, markers positions are arranged proportionally to the height of the whole text. When user clicks on any marker, text box scrolls to the corresponding line.
I were not able to find such control in SWT widget suites. Obviously SWT contains it somewhere. The ideal option for me would be Swing component because application is Swing-based.
Many thanks in advance.

A: I don't think there is a component bundled with Swing and I don't know of any library supplying such a component, bu you should be able to do it yourself.
Provide a panel next to the scrollpane and whenever the scrollpane/textpane are rerendered rerender that panel, too. Then place markers (could be JLabels in a first step, later draw your own and add mouse handling) according to the lines - the layout manager should be null in this case.
The position could be calculated by using line/numlines * height(panel), e.g. for line 20 of 100 and a panel height of 200, the position of the marker would be at height 20/100 * 200 pixels = 40 pixels.

A: The ruler you want is not from SWT. Its from the jface-text plugin. The class you are looking for is org.eclipse.jface.text.source.CompositeRuler

A: In case you are still asking, here is a (not-free) marker bar component:
http://www.sideofsoftware.com/marker_bar.htm


text:
Q: Turn off php warnings in cPanel Is there any specific way to turn off PHP warnings in cPanel? Or is there a way to disable PHP warnings using code? The reason for this question is following error,

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/fteeloco/public_html/login_process.php:1) in /home/fteeloco/public_html/login_process.php on line 2

The reason for this error is (as I think ) adding white space before the PHP start tag.
Please help.

A: Move the session_start() in first line of your page. Error will be resolved.
Note: Add it in header file if you you have header (eg: header.php) file separately. Remove from login_process.php

A: Add session_start() to the start of php pages where you are using Session variables (if not added).

A: I want to start by saying that: you are wrong! That is not the reason that you see that warning. The reason is that you started the session before, and then you started it again. So look in your code for 2 lines with "session_start()". Even if this is not right, session_start() must be the first line in your script!!!
Now to answer your question!
There are 2 ways to do this:

*

*disable warnings from php.ini
Open PHP.ini file.
In this file search for the phrase " error_reporting = E_ALL" ,[without inverted commas]
Here replace this with "error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING "
(Show all errors, except for notices and coding standards warnings)
Make sure you change the real enabled part of this , there are certain other examples given in the file.
Restart your PHP + Apache

*use the error_reporting() function in PHP like is described in the PHP manual HERE
But I must warn you, nither of this are considered good practice. It is not ok to disable warning, notice or error messages.
Hope this helps! :D


text:
Q: Generate an absolute url in a razor view I would like generate an absolute Url in a razor view
It might look something like this:
@Html.ActionLink("Register Now", "action", "controller",
      new { area = "Area", id = @Model.Id }, null)

I have seen many attempts at this but have not found something that gives me the full link I need.

A: I don't believe there is a way to use Html.ActionLink to generate a link with an absolute URL. For example, using the Html.ActionLink from your question will produce the following HTML output:
@Html.ActionLink("Register Now", "Action", "Controller", new { @area = "Area", @id = Model.Id}, null)
// output: Register Now

To generate absolute URLs, I suggest implementing a custom extension method.
public static string AbsoluteActionUrl(this UrlHelper url, string actionName, string controllerName, object routeValues)
{
    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
    return url.Action(actionName, controllerName, routeValues, scheme);
}

Of course, you will have to write the HTML markup yourself and use the extension to generate the URL for the href attribute, like so:
Register Now

You don't have to create the custom extension method, but then you would need to use a magic string to specify the scheme when using Url.Action.
The MSDN documentation for the Url.Action overload used above is available here. There are also other overloads available.


text:
Q: FxCop1.36 and failonerror I am running FxCop using Apache Ant. For version 1.36, if all the dependency information are not given by the user, the analysis returns an error code, but a report is created, which might suggest there are no issues with the code base.
Setting failonerror to true fixes this issue, but the problem is that even if the error is not fatal (error code 1), the analysis fails. This is the issue I am facing. I want the analysis to fail only if the returned error code is 1, that is fatal error (In other worlds, act as if failonerror is true). For other errors, I want the analysis to continue (i.e. as if failonerror is set as false).
Can someone please help me with this issue, since this issue has become one of the highest priority ones?
Thanks in advance.

A: Does Ant allow you to query the FxCop result?  If so, set failonerror to false and then add a step to check the FxCop result afterward.  Depending on the result, you can set the build to fail.


text:
Q: How does "std::cout << std::endl;" compile? Most IO stream manipulators are regular functions with the following signature:
std::ios_base& func( std::ios_base& str );

However some manipulators (including the most frequently used ones - std::endl and std::flush) are templates of the following form:
template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& func(std::basic_ostream<CharT, Traits>& os);

Then, how does the compilation of std::cout << std::endl; succeed given that the following example fails:
$ cat main.cpp
#include <iostream>

int main()
{
    auto myendl = std::endl;
    std::cout << myendl;
}

$ g++ -std=c++11    main.cpp   -o main
main.cpp: In function 'int main()':
main.cpp:5:24: error: unable to deduce 'auto' from 'std::endl'
     auto myendl = std::endl;
                        ^

It is clear that the context (in std::cout << std::endl;) helps the compiler to disambiguate the reference to std::endl. But what are the rules that govern that procedure? It looks like a real challenge for overloading resolution, which has to answer two questions at once:

*

*Which specialization of std::endl<CharT, Traits>() does std::endl refer to?

*Which function does the operator<< refer to?

Template argument deduction (1) should happen before overload resolution (2), but it seems that (at least some part of) (2) is required to be performed in order for (1) to succeed.

Somewhat related but no-way duplicate questions are:

*

*Does std::endl work with both cout and wcout?

*Why does endl(std::cout) compile

*How does std::flush work?
None of those questions and neither answers to them address the workings of template argument deduction that should precede overload resolution but must be helped by the latter.

Follow-up question: How does overload resolution work when an argument is an overloaded function?

A: Given a statement expression of the form
 std::cout << std::endl;

The compiler has information about the type of std::cout - which is a specialisation of the templated std::basic_ostream which looks something like (omitting the containing namespace std).
template <class charT, class traits = char_traits<charT> >
    class basic_ostream
{
    public:
        basic_ostream<charT,traits>& operator<<(
            basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&));

        // other members ....
};

Since the compiler has information about the type of std::cout it knows what charT and traits are to specialise the preceeding template.
The above causes std::endl in the expression std::cout << std::endl to match to the specific std::basic_ostream<charT, traits>& endl( std::basic_ostream<charT, traits>&).
The reason type deduction doesn't work in
 auto myendl = std::endl;

is because std::endl is a templated function, and this declaration provides no information to specialise that template (i.e. picking what charT or traits are).   If it can't specialise the templated std::endl, it can't infer that function's return type, so the type deduction fails.

A: Because basic_ostream has a templated overload of operator<< that expects just such a function pointer:
basic_ostream<charT, traits>& operator<<(basic_ios<charT, traits>& (*pf)(basic_ios<charT, traits>&));

A: The operator<< in question is a member of std::basic_ostream:
namespace std {
    template <class charT, class traits = char_traits<charT> >
    class basic_ostream {
    public:
        basic_ostream<charT,traits>& operator<<(
          basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&));
        // ...
    };
}

Since the call is to std::cout << std::endl, or equivalently std::cout.operator<<(std::endl), we already know the exact instantiation of basic_ostream: std::basic_ostream<char, std::char_traits<char>>, aka std::ostream.  So the member function of cout looks like
std::ostream& operator<<(std::basic_ostream<char, std::char_traits<char>>& (*pf)
    (std::basic_ostream<char, std::char_traits<char>>&));

This member function is not a function template, just an ordinary member function.  So the question remaining, is can it be called with the name std::endl as an argument?  Yes, initializing the function argument is equivalent to a variable initialization, as though we had written
std::basic_ostream<char, std::char_traits<char>>& (*pf)
    (std::basic_ostream<char, std::char_traits<char>>&) = std::endl;

A: You need to put << before the endl. It is a member of ofstream:
namespace std {
template <class charT, class traits = char_traits<charT> >
class basic_ostream {
public:
    basic_ostream<charT,traits>& operator<<(
      basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&));
    // ...
};

}

endl works like a "/n" to skip the line, so you need a cout line to skip


text:
Q: fill missing values with value from previous column I have a data.frame whit some columns with missing values, and I want that the missing values are filled in with data from a previous column. For example:
country <- c('a','b','c')
yr01 <- c(15,16,7)
yr02 <- c(NA,18,NA)
yr03 <- c(20,22,NA)
yr04 <- c(15,18,19)

tab <- data.frame(country,yr01,yr02,yr03,yr04)
tab

  country yr01 yr02 yr03 yr04
1       a   15   NA   20   15
2       b   16   18   22   18
3       c    7   NA   NA   19

How can I make it so that the NA are replaced by the previous value? For example, in country a column yr02 will be equals to 15, and in country c columns year02 and yr03 will be 7. Thanks!

A: It's usually easier to work with columns, but we can apply to rows the standard answer from the R-FAQ Replace NAs with latest non-NA value.
tab[-1] = t(apply(tab[-1], 1, zoo::na.locf))
tab
#   country yr01 yr02 yr03 yr04
# 1       a   15   15   20   15
# 2       b   16   18   22   18
# 3       c    7    7    7   19


text:
Q: socat struggle to create serial ports For testing purposes I want to use socat to create virtual serial ports to use in my Python program.
I have limited success, but struggle again and again with the many options in socat. I use this command in Ubuntu Linux:
sudo socat -d -d  pty,b9600,raw,echo=0,link=/dev/ttyS90    pty,b9600,raw,echo=0,link=/dev/ttyS91

As it should, it creates the virtual ports like /dev/pts/2 and 4, and links them to /dev/ttyS90 and *91. It does not work without sudo (it fails with unable to unlink for the *90, *91 ports, although the regular user is in the dialout group).

But as you see the permissions 'lrwxrwxrwx' look like reading/writing for everybody. However, this is NOT true: I CANNOT use these devices unless I am root. The file manager (=Nemo) gives this result:

The permissions are significantly different. Huh?
After issuing 'sudo chmod 777 /dev/ttyS90' (and same for *91) nothing changes in the terminal output, because it is already, but incorrectly, showing 777 permissions, but the Nemo output changes to

And now I can use the ports as regular user! How comes? Am I doing something wrong?
And one more socat problem: the above socat command gives an 8-bit, no-parity connection, but I really need a 7-bit, even-parity connection. My attempts to implement this by juggling some of the many options all failed. I am lost; any insight?

A: Try changing the permission on /dev/pts/2 and /dev/pts/4 instead of on the link


text:
Q: Does diffClamp method is removed in Reanimated v2 In the previous version I see the Reanimated have a method naming diffClamp but in v2 is there removed or replaced?
Reanimated v1 docs of diffClamp
or how to do diffClamp like previous version?
Thanks


text:
Q: What is the difference between "due North", "N0degreesW" and "N0degreesE"? Is there a difference between "N0°W" and "N0°E"?
These terms have been used in connection with Strike Lines.
The final bearing computed was exactly 0.
Will the direction East and West matter if one is chosen over the other or if "due North" or simply "North" is chosen instead?

A: To expound on this just a little bit.
Yes, there is no difference between any of those values, in most cases it is a matter of style and continuity as to which value you would use.
The Bearing values (N0°W or N0°E) denote which half of north based semi-circle a line segment resides in.
Land surveyors use bearings rather than azimuths to describe the direction of a line.
There are four quadrants each containing 90 degrees in a bearing base system.
N-E, S-E, S-W, N-W.
Bearings have been used to simplify calculations and reduce errors when latitudes and departures (delta y and delta x) were calculated by hand.
NE = +latitude, +departure
SE = -latitude, +departure
SW = -latitude, -departure
NW = +latitude, -departure
To convert a bearing to an azimuth:
The Northeast Quadrant Begins at 0, and values up to 90 degrees are added.
The Southeast Quadrant begins at 180 and the values up to 90 degrees are subtracted.
The Southwest Quadrant begins at 180 and the values up to 90 degrees are added.
The Northwest Quadrant begins 360 and the values up to 90 degrees are subtracted.
It would be considered bad form in many of the places I have worked to have a Bearing of N30°W for a line segment then a bearing for the next line segment that reads N0°E even though it would be correct. It would be considered better form to stay within the same quadrant for those two line segments.

A: As describe in slide 4 of the link in the question, these terms are equivalent. Which one you use is up to you.
In a GIS context, you'd normally expect to see this as 0 with reference to something - at least whether it is true or magnetic north. Note that there is no real reason 0 has to be any kind of north, and that east (i.e. the positive X axis on a Cartesian plane) or some local / engineering reference system is also a reasonable choice for some purposes.


text:
Q: How do I pass data to a component using Props in Vue2? I have created a .Vue file to feature information on a cafe (Cafe Details Page). However, I would like to take parts of this details page and make it its own component, in order to manage any template updates more efficiently.
Therefore, I have created a Component (CafeHeader.vue) inside a components folder. I am trying to pass down the data from my array (Which is being used on my Cafe Details page) to this component using Props. However, I can't seem to get it to work.
The template for my Cafe Details Page is as below:
<template>

            <CafeHeader v-bind:cafes="cafes" />

{{ cafe.cafeDescription }}

</template>

Then, in a components folder I have a component called CafeHeader where I am wanting to use the data from the array which is previously imported to the Cafe Details page;
<template>

Visit: {{cafe.cafeName}}

</template>

If in the CafeHeader component I have cafe in cafes, it does render data from the cafes.js However, it is every cafe in the list and I want just a single cafe.
<template>

Visit: {{cafe.cafeName}}

</template>

A: The component also needed activeCafes on the v-for
<template>

Visit: {{cafe.cafeName}}

</template>


text:
Q: How to create an enum based .textStyle(.title) modifier for Text(...) components in SwiftUI? I want to implement a modifier setting for Texts in a similar way as it already exists for Buttons.
Aka:
Button( ... )
   .buttonStyle(.plain) // <-- .plain and not PlainStyle()

Problem
Of course I cannot use an opaque which is not really the same. If it would be a View I could wrap it in an AnyView but for ViewModifiers I need another solution.

Error: Function declares an opaque return type,but the return statements in its body do not have matching underlying types

Maybe it is a bonus idea to have something like a .textStyle(.title) modifier but in my eyes, it could reduce my code to write enormously.
Source

struct TitleStyle: ViewModifier {
    func body(content: Content) -> some View {
      ...
    }
}

struct BodyStyle: ViewModifier {
    func body(content: Content) -> some View {
      ...
    }
}

enum TextStyle {

    case title
    case body

    // Error: Function declares an opaque return type,
    // but the return statements in its body do not have matching underlying types
    var modifier: some ViewModifier {
        switch self
        {
        case .title: return TitleStyle()
        case .body: return BodyStyle()
        }
    }
}

A: It works different way. As all this is around generics we need to restrict declarations for known concrete types.
So, having TitleStyle and BodyStyle declared and concrete, we can specify
extension ViewModifier where Self == TitleStyle {
    static var title: TitleStyle { TitleStyle() }
}

extension ViewModifier where Self == BodyStyle {
    static var body: BodyStyle { BodyStyle() }
}

and then declare extension to use above like
extension View {
    func textStyle<Style: ViewModifier>(_ style: Style) -> some View {
        ModifiedContent(content: self, modifier: style)
    }
}

so as a result we can do as demo
struct Demo_Previews: PreviewProvider {
    static var previews: some View {
        Text("Demo")
            .textStyle(.title)
    }
}

Prepared with Xcode 13.4 / iOS 15.5
Test module in GitHub


text:
Q: Script to get File Creation and Last Access Date and time (In Solaris 5.10) I want to run a script to acquire file details with file creation date (with time) and last access date (with time). I want to run the script in a directory and want the script to show the details of all files in that directory as well in subdirectories. Here is the script which I tried, but I am not able to get  subdirectory files.
#! /bin/zsh -
zmodload zsh/stat for f (*(DN)) {
    stat -LH s -F %F -- $f &&
    printf '%-58s %s %s\n' $f $s[mtime] $s[atime]
}

*

*OS: Solaris 5.10

*FileSystem: VFS