text:
Q: The property of self-normalizing subgroup $G$ is a finite solvable group. Let $\{P_{1}, P_{2}, \dotsc , P_{s}\}$ be a Sylow basis of $G$. We have that $G=P_{1}P_{2}\dotsm P_{s}$. Set
\begin{equation}
\begin{aligned}
    %% The alignment is never used ….
T=\prod\limits_{t=1}^{s-1}P_t,
H=\prod\limits_{k\neq3}^sP_k,
K=\prod\limits_{r\neq2}^sP_r.\nonumber
\end{aligned}
\end{equation}
Suppose that $T$ is nilpotent (i.e. $T=P_{1}\times P_{2}\times P_{3}\times \dotsb \times P_{s-1}$), $N_H(P_s)=P_s$ and $N_K(P_s)=P_s$.
Can we get that $N_G(P_s)=P_s$?

A: Yes. Nilpotency of $T$ is not needed. Assume that $N_G(P_s)>P_s$. Then for some $i<s$, $N_G(P_s)$ has a
Sylow $p_i$-subgroup $Q_i\ne 1$. Assume without loss that $p_i$
divides $|H|$. Then $P_iP_s$ is a Hall $\{p_i,p_s\}$-subgroup of $H$
and $G$. By Hall's extension of Sylow's theorems to solvable groups,
$(Q_iP_s)^g\le P_iP_s$ for some $g\in G$. Then $P_s$ and $P_s^g$ are
Sylow $p_s$-subgroups of $P_iP_s$, so for some $k\in P_iP_s$,
$P_s^{gk}=P_s$. Now $Q_i^{gk}P_s=(Q_iP_s)^{gk}\le P_iP_s\le H$. But
$Q_i$ normalizes $P_s$, so $Q_i^{gk}$ normalizes
$P_s^{gk}=P_s$. Therefore $Q_i^{gk}$ is a non-identity $p_i$-subgroup
of $N_H(P_s)=P_s$, an impossibility.


text:
Q: Quarkus kubernetesMockServer for application initialization I am working on a Quarkus application to acct as an Operator in a OpenShift/Kubernetes cluster. When writing the tests using a kubernetesMockServer it is working fine for REST calls to developed application but when code runs inside an Initialization Block it is failing, in the log I see that mock server is replying with a 404 error:
2020-02-17 11:04:12,148 INFO  [okh.moc.MockWebServer] (MockWebServer /127.0.0.1:53048) MockWebServer[57577] received request: GET /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions HTTP/1.1 and responded: HTTP/1.1 404 Client Error

On the TestCode I have:
@QuarkusTestResource(KubernetesMockServerTestResource.class)
@QuarkusTest
class TestAIRController {

    @MockServer
    KubernetesMockServer mockServer;

    private CustomResourceDefinition crd;
    private CustomResourceDefinitionList crdlist;

    @BeforeEach
    public void before() {
        crd = new CustomResourceDefinitionBuilder()
            .withApiVersion("apiextensions.k8s.io/v1beta1")
            .withNewMetadata().withName("types.openshift.example-cloud.com")
            .endMetadata()
            .withNewSpec()
            .withNewNames()
            .withKind("Type")
            .withPlural("types")
            .endNames()
            .withGroup("openshift.example-cloud.com")
            .withVersion("v1")
            .withScope("Namespaced")
            .endSpec()
            .build();
        crdlist = new CustomResourceDefinitionListBuilder().withItems(crd).build();
        mockServer.expect().get().withPath("/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions")
            .andReturn(200, crdlist)
            .always();
    }

    @Test
    void test() {
        RestAssured.when().get("/dummy").then().body("size()", Is.is(0));
    }

}

The dummy rest is using the same code for searching the CRD, and in fact when running withouth the class observing the startup event it works fine
@Path("/dummy")
public class Dummy {

    private static final Logger LOGGER =LoggerFactory.getLogger(Dummy.class);

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response listCRDs(){
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("CRD NAME is {}", crd.getMetadata().getName());
        return Response.ok(new ArrayList<String>()).build();
    }
}

Finally this is an except of the
@ApplicationScoped
public class AIRWatcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(AIRWatcher.class);

    void OnStart(@Observes StartupEvent ev) {
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("Using {}", crd.getMetadata().getName());

    }

}

It's like for some reason the mock server is still not initialized for the Startup event, is there any way to solve it?

A: The problem is that the Mock Server is only configured to respond right before the test execution, while this code:
void OnStart(@Observes StartupEvent ev) {
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("Using {}", crd.getMetadata().getName());

    }

runs when the application is actually comes up (which is before any @BeforeEach runs).
Can you please open an issue on the Quarkus Github? This should be something we provide a solution for

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between "merged" questions and "closed (exact duplicate)" questions? While looking at What abilities are moderators given? I noticed that the question has been merged:

What is the difference between a merged question, and one that has been closed as a duplicate?

A: If you look at the text of a Closed as Duplicate post (example) it says:

This question covers exactly the same ground as earlier questions on
  this topic; its answers may be merged with another identical question.
  See the FAQ.

When questions are merged the answers from both questions are placed into the original question.
This will be handy when someone provides a good answer to a duplicate question. After a merge there will only be one question with all the answers, thus making it easier to search and get answers. Also, the answers won't be part of a closed question any more.


text:
Q: SQL server Openquery equivalent to PostgresQL Is there query equivalent to sql server's openquery or openrowset to use in postgresql to query from excel or csv ?

A: You can use PostgreSQL's COPY
As per doc:

COPY moves data between PostgreSQL tables and standard file-system
  files. COPY TO copies the contents of a table to a file, while COPY
  FROM copies data from a file to a table (appending the data to
  whatever is in the table already). COPY TO can also copy the results
  of a SELECT query

COPY works like this:
Importing a table from CSV
Assuming you already have a table in place with the right columns, the command is as follows
COPY tblemployee FROM '~/empsource.csv'  DELIMITERS  ','  CSV;

Exporting a CSV from a table.
COPY (select * from tblemployee) TO '~/exp_tblemployee.csv' DELIMITERS ',' CSV;

Its important to mention here that generally if your data is in unicode or need strict Encoding, then Always set client_encoding before running any of the above mentioned commands.
To set CLIENT_ENCODING parameter in PostgreSQL
set client_encoding to 'UTF8'

or
set client_encoding to 'latin1'

Another thing to guard against is nulls, while exporting , if some fields are null then PostgreSQL will add '/N' to represent a null field, this is fine but may cause issues if you are trying to import that data in say SQL server.
A quick fix is modify the export command by specifying what would you prefer as a null placeholder in exported CSV
COPY (select * from tblemployee ) TO '~/exp_tblemployee.csv' DELIMITERS ',' NULL as E'';

Another common requirement is import or export with the header.
Import CSV to table with Header for columns present in first row of csv file.
COPY tblemployee FROM '~/empsource.csv'  DELIMITERS  ','  CSV HEADER

Export a table to CSV with Headers present in the first row.
COPY (select * from tblemployee) TO '~/exp_tblemployee.csv' DELIMITERS ',' CSV HEADER


text:
Q: Is there a way to reuse the filter in these EF queries? I have three queries and i would like to make them more simple so its easier to see which fields are different and which are the same. Is there a way to do this so it still works as a query against a SQl Server?
    using var context = ContextFactory.Create();

    var aDataSet= aDataSetGetter(context);
    var bDataSet = bDataSetGetter(context;
    var firstQuery = aDataSet.Where(a => bDataSet.Any(b=>
        b.f1 == a.f1 && b.f2 == a.f2 && b.f3 == a.f3 //Same in eache query
        && b.f4 < a.f4 //Different
    ));

    var secondQuery = aDataSet.Where(a => bDataSet.Any(b=>
        b.f1== a.f1 && b.f2 == a.f2 && b.f3 == a.f3
        && b.f4 >= a.f4
    ));

    var thirdQuery = aDataSet.Where(a => !bDataSet.Any(b =>
        b.f1== a.f1 && b.f2 == a.f2 && b.f3 == a.f3
    ));

In this example this is almost readable but in reality the fieldnames are much longer and it could get more complicated so i would like to have a way in my toolbox to reuse the parts that are the same.
Something like this:
    var myfilter= (a,b)=>b.f1 == a.f1 && b.f2 == a.f2 && b.f3 == a.f3;

    var firstQuery = aDataSet.Where(a => bDataSet.Any(b=>
        myfilter(a,b)
        && b.f4 < a.f4 //Different
    ));

    var secondQuery = aDataSet.Where(a => bDataSet.Any(b=>
        myfilter(a,b)
        && b.f4 >= a.f4
    ));

I think it should be somehow possible but i dont know how. Also this still has to be run against an SQL-Server so it should not run only in LINQ.
Is it possible?


text:
Q: R package Bio3D tutorial reproducing I started working with R package called Bio3D
(http://thegrantlab.org/bio3d/index.php)
and encountered a problem during reproducing examples from "Protein Structure Networks with Bio3D" tutorial
(http://thegrantlab.org/bio3d/tutorials/protein-structure-networks).
Here is the fragment I am trying to do:
"
The code snippet below first sets the file paths for the example HIVpr starting structure (pdbfile) and trajectory data (dcdfile), then reads these files (producing the objects dcd and pdb).
dcdfile <- system.file("examples/hivp.dcd", package = "bio3d")
pdbfile <- system.file("examples/hivp.pdb", package = "bio3d")

# Read MD data
dcd <- read.dcd(dcdfile)
pdb <- read.pdb(pdbfile)

inds <- atom.select(pdb, resno = c(24:27, 85:90), elety = "CA")
trj <- fit.xyz(fixed = pdb$xyz, mobile = dcd,
               fixed.inds = inds$xyz, mobile.inds = inds$xyz)

Once we have the superposed trajectory frames we can asses the extent to which the atomic fluctuations of individual residues (in this very short example simulation) are correlated with one another and build a network from this data:
cij <- dccm(trj)
net <- cna(cij)
plot(net, pdb)

"
And till this moment everything works well.
# View the correlations in pymol
view.dccm(cij, pdb, launch = FALSE)

Here I open generated pdb file corr.inpcrd with pymol.
But instead of nice cartoon 3D model I see just aminoacid residues represented by dots.
Tried to solve the problem with pymol using settings for cartoons, ribbons, colors, transparency and command show but it changed nothing.
Would be grateful for your suggestions!
I have not enough reputation to illustrate expected and obtained outcome with images but probably I will be able to send them directly if necessary.
Thank you!

A: Try setting launch=TRUE in your call to the view.dccm() function to have both PDB and pymol script loaded for you.

A: Typically this will work if pymol is in your path for executables (see here: http://tinyurl.com/lzhpz3w for more about where bio3d expects to find pymol and muscle).
view.dccm(cij, pdb, launch = FALSE)

I don't use windows myself but if you post this question on the bio3d bitbucket issues page https://bitbucket.org/Grantlab/bio3d/issues you will get help from experienced windows bio3d users including the author of this function.


text:
Q: Unexpected output after linking I have two C files:
main.c
#include <stdio.h>

int sum(int n);

double array[2] = { 0.001, 1.0001 };

int main()
{
    int val = sum(2);
    printf("%d\n", val);
    return 0;
}

sum.c
extern int array[2];

int sum(int n)
{
    int i, ret = 0;

    for (i = 0; i < n; i++) {
        ret += array[i];
    }

    return ret;
}

I compile and link the files and then run the executable, but I am getting some unexpected output:
306318409

Why is that happening?

A: C Standard section 6.2.7/2 says

All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

So anything could have happened.  That's what you get when you lie to the compiler.

A: This really helps to make out the difference between compiling and linking .
When these two files where compiled :
main.c

*

*implicitly declares a sum() function with return type as int*.

*Has an array variable of type double* in it's list of variables
sum.c :

*

*externed variable array allowed by compiler to get a value at link time and added to it's list of symbols .

*defines a function sum which now uses the variable array with type as int* whose information was maintained by the compiler independently for this program that was externed  .

Now at link time :

*

*sum() call in main.c gets resolved from sum.c

*sum.c had maintained the type of array variable as int* , while the extern variable was resolved by the double* type ,which however does not change the behaviour of variable array decided in sum() definition at compile time .

An array of doubles  is stored with each in 8 bytes , while the sum() function assumed it would be stored per 4 bytes . So array[0] read the first 4 bytes and array[1] read the next 4 bytes , while however the number 0.001 in main.c from it's array[0] was itself stored in 8 bytes , leading to this undefined behavior.


text:
Q: CWnd::OnCreate function never get called Overview:
I have 2 utilities and both have same common interface i.e. open a dialog box to "request for username".
The code for "requesting username" is written in different library and both these utilities call that library .
ISSUE:
In 1 utility it works fine and I got this this dialog box which request username but in other utility it doesn't come up.
MY Investigation:
ON deeper investigation I found that both these utilities call CDialog::DoModal() which in turns call onCreate() . In my other utility breakpoint never hits onCreate function . Any idea why ?
sample code
// IN actual Utility
//somewhere in code

Dialog_for_common_interface dlg( message.c_str(), "Please enter username:" );

        CString username;

        bool is_correct = ( dlg.DoModal(username) == IDOK )

// IN Dialog_for_common_interface

int  Dialog_for_common_interface::DoModal ( CString &_reply_c )
{
    int result_i = CDialog::DoModal(); // break point hits this but value of result_i = -1;

    if ( result_i == IDOK )
    {
        _reply_c = reply_c;
    }

    return result_i;
}

// Breakpoint nver hits the below function

int Dialog_for_common_interface::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    if (CDialog::OnCreate(lpCreateStruct) == -1)
        return -1;

    SetWindowText( title_c );

    return 0;
}

A: Copy the dialog resource into both exe projects. And make sure they both use the same ID value for the dialog resource.


text:
Q: Uncaught TypeError encountered in Magento I am trying to get my jQuery to work with my Magento. I have added the links for jquery and foundation(both JS and CSS). But when I try to load my jquery, the Uncaught Type error:
Uncaught TypeError: Object #<HTMLDocument> has no method 'foundation'

I did add the NoConflict() for my jquery, which is why I don't understand why it should not work.
My code for the head is(in the page.xml):
<reference name="head">
   <action method="addJs"><script>foundation/modernizr.js</script></action>
   <action method="addJs"><script>foundation/jquery.js</script></action>
   <action method="addJs"><script type="text/javascript">
        // <![CDATA[
            // noConflict so we can use both libraries
                $.noConflict();
            // your current code here
            //]]>
    </script></action>
   <action method="addJs"><script>foundation/foundation.min.js</script></action>
                 <action method="addCss"><stylesheet>css/foundation.css</stylesheet></action>
                <action method="addCss"><stylesheet>css/style.css</stylesheet></action>
                <action method="addCss"><stylesheet>css/flexslider.css</stylesheet></action>
                <action method="addCss"><stylesheet>css/main.css</stylesheet></action>
 </reference>

while on my header.phtml I have added this bunch of code after the html part:
<script>
$.noConflict();
$(document).foundation();
</script>

<script type="text/javascript">
    $(window).load(function(){
    $('.flexslider').flexslider({
        animation: "fade",
        controlNav: true,
        directionNav: false,
        slideshowSpeed: 5000,
        animationSpeed: 900,
        start: function(slider){
    $('body').removeClass('loading');
            }
        });
    });
</script>

What seems to be the problem?


text:
Q: Laravel 5.7 email verify broken link I followed Laravels docs (link) about Email verification. Everything seems to work except for a 403 - invalid signature. This errors shows when clicking on the email link. I'm using shared hosting.
Url is similar to this:

[..]email/verify/21?expires=154270[..]&signature=920dcb9ac2fbf5[..]

would appreciate all the help I could get! Thanks!

A: Here is the answer: https://stackoverflow.com/a/44839664
You have to generate a key: php artisan key:generate


text:
Q: Azure SQL metric I am not able to find few SQL metrics in Azure. Can anyone help in how to set metrics for below topics.
1)Under utilized capacity
2)Number of databases outside of pool
3)Scale up
4)Connection timeout
Thanks in advance.

A: Your looking for some very different things here, so these would need to come from different places.

*

*Under Utilized Capacity - you should be looking at metrics like CPU, Memory or DTU use on your SQL databases to see what capacity is being used. These are all available from Azure Monitor

*Number of databases outside of pool - not entirely clear what you want here, but I am guessing you want to see SQL database that are not in an elastic pool? If so then you can use Azure Resource Explore to query for databases not in an elastic pool

*Scale up - again not sure what you are looking for. If you want to know when you need to scale your DB up, then again look at Azure Monitor for metrics on CPU, Memory etc.

*Connection Timeout - This is really a client side thing, not something you can measure from SQL


text:
Q: TPL Dataflow Blocks Question: Why using a WriteOnceBlock (or BufferBlock) for getting back the answer (like sort of callback) from another BufferBlock<Action> (getting back the answer happens in that posted Action) causes a deadlock (in this code)?
I thought that methods in a class can be considered as messages that we are sending to the object (like the original point of view about OOP that was proposed by - I think - Alan Kay). So I wrote this generic Actor class that helps to convert and ordinary object to an Actor (Of-course there are lots of unseen loopholes here because of mutability and things, but that's not the main concern here).
So we have these definitions:
public class Actor<T>
{
    private readonly T _processor;
    private readonly BufferBlock<Action<T>> _messageBox = new BufferBlock<Action<T>>();

    public Actor(T processor)
    {
        _processor = processor;
        Run();
    }

    public event Action<T> Send
    {
        add { _messageBox.Post(value); }
        remove { }
    }

    private async void Run()
    {
        while (true)
        {
            var action = await _messageBox.ReceiveAsync();
            action(_processor);
        }
    }
}

public interface IIdGenerator
{
    long Next();
}

Now; why this code works:
static void Main(string[] args)
{
    var idGenerator1 = new IdInt64();

    var idServer1 = new Actor<IIdGenerator>(idGenerator1);

    const int n = 1000;
    for (var i = 0; i < n; i++)
    {
        var t = new Task(() =>
        {
            var answer = new WriteOnceBlock<long>(null);

            Action<IIdGenerator> action = x =>
            {
                var buffer = x.Next();

                answer.Post(buffer);
            };

            idServer1.Send += action;

            Trace.WriteLine(answer.Receive());
        }, TaskCreationOptions.LongRunning); // Runs on a separate new thread
        t.Start();
    }

    Console.WriteLine("press any key you like! :)");
    Console.ReadKey();

    Trace.Flush();
}

And this code does not work:
static void Main(string[] args)
{
    var idGenerator1 = new IdInt64();

    var idServer1 = new Actor<IIdGenerator>(idGenerator1);

    const int n = 1000;
    for (var i = 0; i < n; i++)
    {
        var t = new Task(() =>
        {
            var answer = new WriteOnceBlock<long>(null);

            Action<IIdGenerator> action = x =>
            {
                var buffer = x.Next();

                answer.Post(buffer);
            };

            idServer1.Send += action;

            Trace.WriteLine(answer.Receive());
        }, TaskCreationOptions.PreferFairness); // Runs and is managed by Task Scheduler
        t.Start();
    }

    Console.WriteLine("press any key you like! :)");
    Console.ReadKey();

    Trace.Flush();
}

Different TaskCreationOptions used here to create Tasks. Maybe I am wrong about TPL Dataflow concepts here, just started to use it (A [ThreadStatic] hidden somewhere?).

A: The problematic issue with your code is this part: answer.Receive().
When you move it inside the action the deadlock doesn't happen:
var t = new Task(() =>
{
    var answer = new WriteOnceBlock<long>(null);
    Action<IIdGenerator> action = x =>
    {
        var buffer = x.Next();
        answer.Post(buffer);
        Trace.WriteLine(answer.Receive());
    };
    idServer1.Send += action;
});
t.Start();

So why is that? answer.Receive();, as opposed to await answer.ReceiveAsnyc(); blocks the thread until an answer is returned. When you use TaskCreationOptions.LongRunning each task gets its own thread, so there's no problem, but without it (the TaskCreationOptions.PreferFairness is irrelevant) all the thread pool threads are busy waiting and so everything is much slower. It doesn't actually deadlock, as you can see when you use 15 instead of 1000.
There are other solutions that help understand the problem:

*

*Increasing the thread pool with ThreadPool.SetMinThreads(1000, 0); before the original code.

*Using ReceiveAsnyc:

Task.Run(async () =>
{
    var answer = new WriteOnceBlock<long>(null);
    Action<IIdGenerator> action = x =>
    {
        var buffer = x.Next();
        answer.Post(buffer);
    };
    idServer1.Send += action;
    Trace.WriteLine(await answer.ReceiveAsync());
});


text:
Q: What is this, when i debug xaml (Univesal) apps? Does anyone knows wat those black boxes are when you debug an xaml app?
It shows also on top of visual studio.
Can I disable this?
Thanxxx.

A: It is FPS counter. Remove this line from App.xaml.cs to disable it.
this.DebugSettings.EnableFrameRateCounter = true;


text:
Q: How to change default value of date filter in metabase? I am trying to write dynamic sql query in metabase-
I added date filter like that (using snowflake for query):
select * from my_table where date > {{date_filter}}

after that I needed to set default value of yesterday to date_filter, so I write this:
select * from my_table where date > [[{{date_filter}} #]]dateadd(DAY, -1, GETDATE())

and it worked, when I ran this query- I got the right output.
BUT- when I changed the date in the calendar that metabase provided for date types- I got this error:
SQL compilation error: syntax error line 1 at position 142 unexpected '#D'. syntax error line 1 at position 156 unexpected '-'. syntax error line 1 at position 172 unexpected '('.

How can I change date_filter default value without getting this error?

A: finally found a workaround that solve the problem.
in UI settings, define date_filter as REQUIRED and assign static default value- for example 01.01.2015 if my table contains data starting of 2016.
in sql query- I wrote that:
select * from my_table where date > case when year({{date_filter}}) = 2015 then dateadd(DAY, -1, GETDATE()) else {{date_filter}} end

which means:
if I won't select any date in date_filter calender- date_filter year value will be 2015 (as I defined date_filter = 01.01.2015) so I will compare DATE against dateadd(DAY, -1, GETDATE()).
but if I WILL select value in date_filter calender, then year(date_filter) will be different than 2015 (as I said, I won't choose date before 2016 because I have no data before 2016 in my table) so I will compare DATE against {{date_filter}} value which I just selected.


text:
Q: How to substract 2 hours I would like to to substract hour that is displayed in textview1 from hour that is displayed in textview2. Im setting the hour in textview by pressing buttons
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String sdf = new SimpleDateFormat("HH:mm", Locale.US).format(new Date());
            textView.setText(sdf);
            button1.setVisibility(View.GONE);
            button2.setVisibility(View.VISIBLE);

        }
    });
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String sdf = new SimpleDateFormat("HH:mm", Locale.US).format(new Date());
            textView2.setText(sdf);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);

now after clicking button2 i also want to substract hours and set result of substraction in textview3. I tried to get TextViews value and put it to strings, but i guess that's not the correct way to do this. If you guys could show me how to do this, please.

A: I recommend using the new Java 8 (and 9) libraries.
For illustration, see the method below, doing this pretty simply. You can construct a correct DateTimeFormatter for your exact purposes, but I utilise the standard ISO_TIME one for illustration.
public static LocalTime subtract2Hours(String timeString) {
    return LocalTime.parse(timeString, DateTimeFormatter.ISO_TIME).minusHours(2);
}

You can format a LocalTime to String using LocalTime.format(DateTimeFormatter), of which DateTimeFormatter.ISO_TIME is an example. Simply then provide that String back.
If you were to do the type conversions in one step, you could change the method signature. But if you're only going to use it once, you could probably in-line it all into one long chain using your IDE.


text:
Q: How do i fill all arguments of a function/class with 0? Assuming i have a class Student(), with multiple arguments, how would i fill all the arguments with 0, regardless of how many arguments there are.
i was thinking to use *args like this:
Student(*0)
but that didnt work.

A: Explicit is better than implicit. If you want to set each parameter to 0, do so explicitly.
s = Student(0, 0, 0, 0, 0)  # E.g., 5 arguments

If you want to hide that from the caller, provide a class method makes the call for you.
class Student:
    ...

    @classmethod
    def from_zeros(cls):
        return cls(0, 0, 0, 0, 0)

s = Student.from_zeros()

A: Assuming Student.__init__ doesn't have any keyword-only arguments, you can use
n = Student.__init__.__code__.co_argcount - 1 # subtract 1 for "self"
s = Student(*[0]*n)


text:
Q: htaccess: Redirect vs. Redirect 301 I was just looking in one of my .htaccess files and noticed the following:
Redirect /old-page /new-page

I was expecting to see Redirect 301 or Redirect 302, but it only said Redirect and works just fine.
I'm curios if 301 or 302 isn't indicated what does the redirect default to? 301? 302? Something else?

A: This line:
Redirect /old-page /new-page

Means use 302 since 302 is default value here.
To use 301:
Redirect 301 /old-page /new-page

See 301 directive documentation


text:
Q: What is a better approach to communicate with tab items than partial class I have a WPF project which is simply a collection of tens of small tools. I put each tool on a tabitem of a main tabcontrol and wrote a partial MainWinow class for each tabitem. However, since there is very little relationship between the tools, I would prefer to seal each tool so that they won't interfere with each other. Besides, I heard that partial class is evil. The problem here is a class other than MainWindow is very difficult to communicate with UI items (according to my knowledge). Any suggestions of where I should go?
Thanks a lot.
Upon Blam's request, here is a much simplified version of my current code. The original code is too large to paste here.
xaml:
<Window x:Class="WpfApplication7.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TabControl Margin="0,0,0,0" Name="tabControl1">
        <TabItem Header="Tool1" Name="Tool1">
            <Grid>
                <Label Name="lblTool1"/>
            </Grid>
        </TabItem>
        <TabItem Header="Tool2" Name="Tool2">
            <Grid>
                <Label Name="lblTool2"/>
            </Grid>
        </TabItem>
    </TabControl>
</Grid>
</Window>

Partial class 1 (MainWindow.xaml.cs):
namespace WpfApplication7
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string caption = "Tool Collection";
        public MainWindow()
        {
            InitializeComponent();
            this.Title = caption;

            InitialTool1();
            InitialTool2();

        }
        /*
            Some other methods for main window, including those for menu bar, tool bar, ...
        */
    }
}

Partial class 2 (Tool1.cs):
namespace WpfApplication7
{
    string tool1Details = "This is tool 1";
    /*
        Other parameters related to tool1
    */
    public partial class MainWindow : Window
    {

        public void InitialTool1()
        {
            lblTool1.Content = tool1Details;

        }
        /*
            Some other methods that communicate with tabitem1
        */
    }
}

Partial Class 3 (Tool2.cs):
namespace WpfApplication7
{
    public partial class MainWindow : Window
    {
        string tool2Detail = "This is tool 2";
        /*
             Other parameters related to tool2
        */
        public void InitialTool2()
        {
            lblTool2.Content = tool2Detail;

        }
        /*
            Some other methods that communicate with tabitem2
         */

    }
}

The purpose of split them into partial class is that we can put them in different files.

A: Why not just pull
    public void InitialTool2()
    {
        lblTool2.Content = "This is tool 2";
        /*
           Lot of codes that communicate with tabitem2
         */
    }

And all other InitializeX into the first Partial class.   The are separated into methods and yet can communicate with them?


text:
Q: Is it possible to look at response headers from a video request started via video.js? The media server API I'm using is returning some info I would like to use to better track buffering events, but I'm not sure how to tap into the video request. Is this possible?
Ideally, I am looking for something like this:
const player = videojs(videoElement, options);
player.on('serverResponseReceived', (data, headers) => ...


text:
Q: Corresponding Receive Routine of MPI_Bcast What would be the corresponding MPI receive routine of the broadcast routine, MPI_Bcast.
Namely, one processor broadcasts a message to a group, let's say all world, how I can have the message in these processes?
Thank you.
Regards
SRec

A: MPI_Bcast is both the sender and the receiver call.
Consider the prototype for it.
int MPI_Bcast ( void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm )

All machines except for the machine with id = root are receivers.  The machine that has the id = root is the sender.


text:
Q: Polynomial divided by a monomial in some extended Collatz Shortcut function Quirks of the Collatz shortcut function.
One example and some basic questions.
The functions here are defined as:
$$C_d(n):\mathbb{Z^+}\rightarrow\mathbb{Z^+}$$
$$n\in\mathbb{Z^+}$$
The definition of stopping time (in this text) is the time it takes for the iterates to reach 1.
As I mostly study in base $2$, I use $(-1)^x$ for parity checking when translating to base $10$. $x$ is always an integer, so a fraction will be floored with integer division. I'd like to note with subscript of the function - the largest exponent to the power of $2$ that divides $3n+1$. I.e the standard shortcut function I note shortcut$_{2}$ function or $C_{2}(n)$ because it divides one time (since $3n+1$ always is even). If is twice even we can divide by $4$ (i.e. two times) so shortcut$_{4}$ or $C_{4}(n)$. So basically we can divide "up" by $4$. So $d$ is the largest power of $2$ in $C_d$. Note I also use $:=$ to show the trajectory of $C_d$.
Standard shortcut form of the Collatz function
Define $C_2$ to be:
$$C_2(n) = \begin{cases} n/2 &\text{if } n \equiv 0 \\ (3n+1)/2 & \text{if } n\equiv 1\end{cases} \pmod{2}.$$
To recap
the standard Shortcut$_{2}$ function when $n=27$ has stopping time of $70$:
$C(27)_{2}:=27\rightarrow41\rightarrow62\rightarrow31\rightarrow47\rightarrow71\rightarrow107\rightarrow161\rightarrow242\rightarrow121\rightarrow182\rightarrow91\rightarrow137\rightarrow206\rightarrow103\rightarrow155\rightarrow233\rightarrow350\rightarrow175\rightarrow263\rightarrow395\rightarrow593\rightarrow890\rightarrow445\rightarrow668\rightarrow334\rightarrow167\rightarrow251\rightarrow377\rightarrow566\rightarrow283\rightarrow425\rightarrow638\rightarrow319\rightarrow479\rightarrow719\rightarrow1079\rightarrow1619\rightarrow2429\rightarrow3644\rightarrow1822\rightarrow911\rightarrow1367\rightarrow2051\rightarrow3077\rightarrow4616\rightarrow2308\rightarrow1154\rightarrow577\rightarrow866\rightarrow433\rightarrow650\rightarrow325\rightarrow488\rightarrow244\rightarrow122\rightarrow61\rightarrow92\rightarrow46\rightarrow23\rightarrow35\rightarrow53\rightarrow80\rightarrow40\rightarrow20\rightarrow10\rightarrow5\rightarrow8\rightarrow4\rightarrow2\rightarrow1.$
Expanded form of the shortcut function
From the polynomial of degree $1$ divided by a monomial I found this expression:
$$\frac{a+b+3c+7}{4}$$
All divisions are done with integer division. So we can use the floor function.
Then let
$$a = (-1)^{\lfloor\frac{9n+3}{4}\rfloor}$$
$$b = (-1)^{\lfloor\frac{3n+1}{4}\rfloor}$$
$$c = (-1)^{\lfloor\frac{3n+1}{2}\rfloor}$$
$$C_{8}(n) = \frac{3n+1} {2^{\lfloor\frac{a + b + 3c+7}{4}\rfloor} } $$
we insert $a$, $b$ and $c$ and also account for even versus odd $n$'s:
$$C_8(n) = \begin{cases}{n/2}&\text{if } n \equiv 0\pmod{2} \\{\frac{3n+1}{2^{\lfloor\frac{{(-1)^{{\lfloor\frac{9n+3}{4}\rfloor}} + (-1)^{{\lfloor\frac{3n+1}{4}\rfloor}} + 3(-1)^{\lfloor\frac{3n+1}{2}\rfloor}+7}}{4}\rfloor} }}&\text{if } n\equiv 1\pmod{2}\end{cases}$$
For odd $n$'s here's the boolean expression in C-language:
(3*n+1)>>((-2*(-6+3*(1&(3*n+1)>>1)+(1&(3*n+1)>>2)+(1&(3+9*n)>>2)))>>2)

The boolean expression was fully simplified with Wolfram Alpha.
Now this exploited Shortcut$_{8}$ function when $n=27$ gives stopping time of $46$:
$C(27)_{8}:=27\rightarrow41\rightarrow31\rightarrow47\rightarrow71\rightarrow107\rightarrow161\rightarrow121\rightarrow91\rightarrow137\rightarrow103\rightarrow155\rightarrow233\rightarrow175\rightarrow263\rightarrow395\rightarrow593\rightarrow445\rightarrow167\rightarrow251\rightarrow377\rightarrow283\rightarrow425\rightarrow319\rightarrow479\rightarrow719\rightarrow1079\rightarrow1619\rightarrow2429\rightarrow911\rightarrow1367\rightarrow2051\rightarrow3077\rightarrow1154\rightarrow577\rightarrow433\rightarrow325\rightarrow122\rightarrow61\rightarrow23\rightarrow35\rightarrow53\rightarrow20\rightarrow10\rightarrow5\rightarrow2\rightarrow1$
Even thought the above expression looks more complicated it does some more shortcuts. I can now divide up to $8$. This can also be extended to $16$,$32$,$64..$ and so on, but it gets even more complicated.
I have not found a more general polynom or expression for the highest exponent $y$ to the power of $2$ that divides $3n+1$.
Does it exist? Can a polynomial of integer coefficients have infinite terms?
There are a more clean expression than the one above but where the degree of the polynom increases as the number of divisions of $2$ increases, but extending it to reach all odds up to a certain limit causes the formula to be quite big and messy.
Can I ask wether a polynomial of degree one with infinite terms divided by a monomial exist for a power of two exponent that divides $3n+1$? Or does not such polynomial exist?
I need someone to confirm that this Collatz shortcut function: $C_8$ (that is for divisions up to $8$) does indeed work.

A: First I'm checking your proposal of the first three functions
$$    \begin{array} {}
        a(n) &=& \left \lfloor  {9n+3 \over 4} \right  \rfloor  &  \\
        b(n) &=&\left  \lfloor  {3n +  1 \over 4} \right \rfloor  &\\
        c(n) &=&\left  \lfloor  {3n + 1 \over 2 }\right \rfloor  & \\
 \text{ and} \\
        s(n) &=&\Large\left  \lfloor  {(-1)^{a(n)} + (-1)^{b(n)} + 3(-1)^{c(n)} + 7 \over 4} \right \rfloor \end{array} \\
$$
Used in Pari/GP:
 a(n)= floor( (9*n+3 )/4)
 b(n)= floor( (3*n+1 )/4)
 c(n)= floor( (3*n+1 )/2)

 s(n) =floor( ((-1)^a(n)+(-1)^b(n) + 3*(-1)^c(n)+7)/4)

 forstep(n=1,63,2, print([n,3*n+1,2^s(n),"|"])) \\ to be formatted into 2 columns

This gives the following protocol:
 odd n      |    odd n     |
            |              |
 n 3n+1  den|   n 3n+1  den| "den" means denominator.
--------------------------------
 1    4  4  |   3   10  2  |
 5   16  8  |   7   22  2  |
 9   28  4  |  11   34  2  |
13   40  8  |  15   46  2  |
17   52  4  |  19   58  2  |
21   64  8  |  23   70  2  |
25   76  4  |  27   82  2  |
29   88  8  |  31   94  2  |
33  100  4  |  35  106  2  |
37  112  8  |  39  118  2  |
41  124  4  |  43  130  2  |
45  136  8  |  47  142  2  |
49  148  4  |  51  154  2  |
53  160  8  |  55  166  2  |
57  172  4  |  59  178  2  |
61  184  8  |  63  190  2  |

Now a bit analysis. Let's write $e(n)$ if we talk generally about one of the three first functions.
First, we observe that the functions $a(n),b(n),c(n)$ are used only as exponents at $(-1)$ so each $(-1)^{e(n)}$ gives only periodically with increasing $n$ only $2$ values, and we can as well use the modular residue $\pmod 2$ of the floor expressions.
Since we have $3$ functions $e(n)$ we can generate at most $8$ different combinations and can thus code the sum $s(n)$ by evaluating the $8$ residue classes of $n \pmod 8$ only.
So we can look at the functions $e(n)$ when $n=8k+r$ and get
$$    \begin{array} {}    a(8k+r) &=& \left \lfloor 18k + {9r+3 \over 4} \right  \rfloor  &\pmod {2}  \\
    b(8k+r) &=&\left  \lfloor \phantom 1 6k + {3r +  1 \over 4} \right \rfloor  &\pmod {2}   \\
    c(8k+r) &=&\left  \lfloor 12k + {3r + 1 \over 2 }\right \rfloor  &\pmod {2}  \end{array} $$
We see that the result is independent from the $k$-term because it is integer, can be taken out of the floor and is then congruent to zero by $\pmod 2$.
So indeed we can look at the $8$ residues of $n \pmod 8$ only and the empirical test for the $4$ odd residue classes $ n \pmod 8$ show (for instance in the above protocol) that your coding of the problem is valid.

This answers the last question of your post to the positive.

Second a way to better generalizability.
There is another scheme to arrive at your $C_8()$ function and which is more obvious how to be generalized.

We establish the following actiontable with the function $\nu_2^*(x)=\min(3,\nu_2(x))$ giving the exponent to which the prime $2$ is factor of $x$ but restricted to a max value of $3$ (because we want look at this modulo $8$ here) .
$$ \begin{array} {r|r|r|r|r|r|r}
 n & n^* & \nu_2^*(n^*)   && n & n^* & \nu_2^*(n^*) \\
   &\Tiny =n  &                &&   & \Tiny =3n+1 &            \\ \hline
 0& 0& 3 && 1 & 4 & 2 \\\
 2&2 & 1 && 3 & 10 & 1\\\
 4&4 & 2 && 5 & 16 & 3\\\
 6&6 & 1 && 7 & 22 & 1\\\
\end{array} $$
We can now define for the even and odd residue classes using the $\text{mod}$ symbol for getting the modular residue as in some programming languages reproducing the $\nu^*()$ values by sum-of-floors, let's denote them as $E_\text{even}(n)$ and $E_\text{odd}(n)$ for even and odd $n$ respectively:
$$ E_\text{even}(n) = 1
+ \left \lfloor 1- {n \text{ mod } 4 \over 4} \right \rfloor
+ \left \lfloor 1- {n \text{ mod } 8 \over 8} \right \rfloor \\\
 E_\text{odd}(n) = 1
+ \left \lfloor 1- {n -1 \text{ mod } 4 \over 4} \right \rfloor
+ \left \lfloor 1- {n -5 \text{ mod } 8 \over 8} \right \rfloor
$$
With this one can define the $C_8()$-transformation either
$$ C_8(n) =  \begin{cases}
            {n \over 2} & \text { if $n$ is even}  \\\
            {3n+1 \over 2^{E_\text{odd}(n)}} & \text { if $n$ is odd}
    \end{cases} $$
or
$$ C_8(n) =  \begin{cases}
            {n \over 2^{E_\text{even}(n)}} & \text { if $n$ is even}  \\\
            {3n+1 \over 2^{E_\text{odd}(n)}} & \text { if $n$ is odd}
    \end{cases} $$
This way of defining seems meaningful for me especially when one wants to generalize to larger modules.
additional remark
using the "iverson-bracket" in the following form $\displaystyle [a:b]= \begin{cases} 1& \text{ if $b$ divides $a$ } \\ 0 & \text{ else } \end{cases}$ then we have the much much shorter notation
$$ \begin{array}{} E_\text{even}(n) &= 1 & + [n:4]& + [n:8] \\
 E_\text{odd}(n) &= 1 &+[n-5:4] &+ [n-5:8]  \end{array}
$$
and the way to generalization to larger moduli is immediately obvious

Third the generalization using the "actiontable" allows also to define polynomials (which you mentioned in your question as well) instead. In Pari/GP this can be done by the polinterpolate() function and gives

pol_e=polinterpolate([0,2,4,6],[3,1,2,1])
pol_o=polinterpolate([1,3,5,7],[2,1,3,1])

\\ here we get
\\ pol_e : -5/48*x^3 + x^2 - 31/12*x + 3
\\ pol_o : -7/48*x^3 + 27/16*x^2 - 257/48*x + 93/16

\\ making polynomial functions
E_even(n) = n=n % 8 ; return(-5/48*n^3 + n^2 - 31/12*n + 3 );
E_odd(n)  = n=n % 8 ; return(-7/48*n^3 + 27/16*n^2 - 257/48*n + 93/16);
\\ alternatively
\\  E_odd(n) = E_even(n-5)


text:
Q: If Statement and toggleClass I'm a bit of noob when it comes to Javascript. Basically I have a simple ul with 5 li's attached
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    border: 1px solid #e7e7e7;
    background-color: rgba(255,255,255,.5);
}

li {
    float: left;
}

li a {
    display: block;
    color: #000000;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-family: 'Open Sans', sans-serif;
}

li a:hover:not(.active) {
    background-color: rgba(221,221,221,.5);
}

li a:hover {
    background-color:rgba(221,221,221,.5);
}
.active {
    background-color: rgba(22,47,127,.25);
}

Display Points

Display States

Display Counties

$("ul a").click(function(){
//this works fine at just toggling the boxes
    $(this).toggleClass("active");

});

Here's the tricky part...an if statements that says
If li item 2 is active (state layer), then de-activate li item 3 (county layer)
Else li 3 is active (county layer), then de-activate li item 2 (state layer)
I know it's possible in jQuery I'm just having trouble referencing the individual items in the list and then toggling the active state.

A: I think this is what you're looking for
$("ul a").click(function(){
    //first remove all instances of the class
    $("ul a").removeClass("active");
    //then set the active
    $(this).addClass("active");
});

https://jsfiddle.net/xzsa7py3/
if you want the first anchor to toggle independently you can add a class to the others and use something like this
$("ul a").click(function(){
    //remove class from anchors that have class 'should-toggle'
    $("ul a.should-toggle").removeClass("active");
    //add class to selected
    $(this).toggleClass("active");
});

A: You are looking for jQuery's .index(). This can get you the index of whatever li element there is. Keep in mind this is 0 based.
You can just set var elementIndex = $('li').index($(this).parent());

$(document).on('click', 'li a', function(){

  console.log(
    $('li').index($(this).parent())
  );

});

List Item 1

List Item 2

List Item 3

List Item 4

List Item 5

Documentation
.index() - https://api.jquery.com/index/


text:
Q: how to change margin between items in popupmenu I want to change the space between items in my popupmenu on android
the space i mean is this one:

I hope there is a straight foward solution, but as i know android it shall not be so simple
anyway i would like also to set the maxHeight of my popUp...
In this case popup is achored by the TextView "Select the prize" so it fills the space above it, but not all the items fit in that space so android automatically creates an scrow view (on vertical)
the thing is, I know 100% of users wont use this scroll so the items in my menu bellow "Travel" will never be seen.
How can i set the height in order to make enough space to all items?
=============UPDATE================
Just to make it clear, this isn't a spinner it is a popupmenu
this.popupCategories = new PopupMenu(this, this.categoryLabel);
for (Giveaway.GiveawayCategoryGroup catGroup : categoryGroups) {

            SubMenu submenu = this.popupCategories.getMenu().addSubMenu(catGroup.getDescription(lang));
            for (Giveaway.GiveawayCategory cat : (Collection<? extends Giveaway.GiveawayCategory>) catGroup.getCategories()) {
                if (cat.isActive())
                    submenu.add(Menu.NONE, cat.getValue().hashCode(), (int) cat.getOrder(), cat.getDescription(lang));
            }
        }

A: You need to set your preferred item row height in your AppTheme inside styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:listPreferredItemHeightSmall">20dp</item>
</style>

You may need to modify this number a bit to get the correct value, but it determines the height of those rows. Make sure to replace Theme.AppCompat.Light.DarkActionBar with whatever you're currently using.
As for setting a maximum height, I'm afraid you'll have to create your own extension class for that, as in this example.

A: PopupMenu items are just regular MenuItem; it's the same attribute, but another parent style:
<style name="customPopupMenuStyle" parent="@android:style/Widget.PopupMenu">
    <item name="android:listPreferredItemHeightSmall">32dp</item>
</style>

this only affects the PopupMenu to which the style had been assigned to.
also there one could set a custom ActionView (per individual item, not as a template):
MenuItem item = menu.findItem(R.id.itemMenu);
MenuItemCompat.setActionView(item, R.layout.layout_menu);

A: You can create a layout for popup menu and initialize it in your activity as follows
XML
> <?xml version="1.0" encoding="utf-8"?> <LinearLayout
> xmlns:android="http://schemas.android.com/apk/res/android"
>     android:layout_width="match_parent"
>     android:layout_height="match_parent"
>     android:gravity="center"
>     android:background="@android:color/transparent">
>     <LinearLayout
>         android:layout_width="wrap_content"
>         android:layout_height="YOUR MAX HEIGHT"
>         android:gravity="center"
>         android:weightsum="YOUR NUMBER OF ITEMS"
>         android:orientation="vertical"
>         android:layout_gravity="center"
>         >
>         <TextView
>             android:layout_width="wrap_content"
>             android:layout_height="0dp"
>             android:weight="1" /> ...no of views items
>     </LinearLayout> </LinearLayout>

INITIALIZE IT AS
View parentv = findViewById(R.id.activityview); //id of parent view of activity in which popup will be shown
LayoutInflater layoutInflater
                = (LayoutInflater) getBaseContext()
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View popupView = layoutInflater.inflate(R.layout.YOURPOPUPMENU, null);
        final PopupWindow popupWindow = new PopupWindow(
                popupView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        TextView tv = popupView.findViewById(R.id.textviewid); //to do something with textview
        tv.setText("Fashion");
        popupWindow.setOutsideTouchable(true); //if you want to dismiss popup if clicked outside
        popupWindow.setFocusable(true);
        // Removes default background.
        popupWindow.setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(android.graphics.Color.TRANSPARENT));
//        popupWindow.setAnimationStyle(R.style.righttoleftstyle); can put animation to slide in popupmenu by defining any animation
        popupWindow.showAtLocation(parentv, Gravity.START | Gravity.TOP,0,0);

//will show popup on top left corner of the screen of the activity view you can try some iterations for it to show where on screen according to your needs
I hope it will help!


text:
Q: C# Is there a faster way than FileInfo.Length with multiple files comparison? I have been trying to compare files from two differents environments. Both environment are accessed via a network drive.
First, I checked if the file is present in both environments (to save time), then I ask for a FileInfo on both files to compare their filesizes (FileInfo.Length).
My goal is to populate a listview with every files that does not have the same size to investigate on these later.
I find it hard to understand that windows explorer gets the filesize of a lot of files so quickly and that FileInfo is taking so long...
Thanks.
Ben

A: If you use DirectoryInfo.GetFiles(some-search-pattern) to get the files, then use the FileInfo-instance returned from that call, then the property FileInfo.Length will be cached from the search.
Whether this will be of any help obviously depends on how the search performs in comparison to the check you are currently doing (if the search is slower, you may not gain anything). Still, it may be worth looking into.

A: You can try doing it the operating system way.  You call via win32 system calls.  You can start with this page,
http://www.pinvoke.net/default.aspx/kernel32.getfilesize


text:
Q: How do I get the displayed value from a dropdown that returns an id? Hey I'm using jsp and servlets. Here is my dropdown
<label>Disposition: </label>
        <select name="petDisposition" id="petDisposition">
            <c:forEach items="${dispoList}" var="dispoList">
                 <option value="${dispoList.dispoId}" ${dispoList.dispoId == dispoId ?
"selected='selected'" : ""}>
                    <c:out value="${dispoList.longDesc}"/></option>
                </option>
            </c:forEach>
        </select><br>

In my servlet I call it using
String petDisposition = request.getParameter("petDisposition");

I can only return it as a number. How do I get the displayed text from this?

A: I would encourage you searching a little bit more first before posting a question.
You could just erase the value from your option. You are setting the value ${dispoList.dispoId} as a value and the selected option sends that value to your servlet.
You could change the value to the text you want to get, if you have a method/field with the text in your dispoList <option value="${dispoList.myText}">
See Link and please also Link
The second link will you help you with a better design for this.


text:
Q: Rails 3 polymorphic association with Carrierwave and Simple Form I'm trying to set up a polymorphic association for photo uploads which are processed using Carrierwave. I'm using Simple Form to build my forms. I feel like the association is correct so I'm wondering if my problem is just something with the form or controller.
Here are my associations:
property.rb:
class Property < ActiveRecord::Base
  attr_accessible :image
  ...
  has_many :image, :as => :attachable
  ...
end

unit.rb
class Unit < ActiveRecord::Base
  attr_accessible :image
  ...
  has_many :image, :as => :attachable
end

image.rb
class Image < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true
  mount_uploader :image, PhotoUploader
end

properties_controller.rb:
def edit
    @property = Property.find params[:id]
    @property.image.build if @property.image.empty?
end

def update
    @property = Property.find params[:id]
    if @property.update_attributes params[:property]
        redirect_to admin_properties_path, :notice => 'The property has been successfully updated.'
    else
        render "edit"
    end
end

Snippet from properties/_form.html.erb
<%= f.input :image, :label => 'Image:', :as => :file %>

Here is the error I get when submitting with an image attached:
undefined method `each' for #<ActionDispatch::Http::UploadedFile:0x00000102291bb8>

And here are the params:
{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"lvB7EMdc7juip3gBZD3XhCLyiv1Vwq/hIFdb6f1MtIA=",
 "property"=>{"name"=>"Delaware Woods",
 "address"=>"",
 "city"=>"",
 "state"=>"",
 "postal_code"=>"",
 "description"=>"2 bedroom with large kitchen.  Garage available",
 "incentives"=>"",
 "active"=>"1",
 "feature_ids"=>[""],
 "user_ids"=>[""],
 "image"=>#<ActionDispatch::Http::UploadedFile:0x00000102291bb8 @original_filename="wallpaper-4331.jpg",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"property[image]\"; filename=\"wallpaper-4331.jpg\"\r\nContent-Type: image/jpeg\r\n",
 @tempfile=#<File:/tmp/RackMultipart20120608-3102-13f3pyv>>},
 "commit"=>"Update Property",
 "id"=>"18"}

I'm looking everywhere for help on polymorphic associations and am getting nowhere. I've seen simple examples that look pretty straight forward. One thing I've noticed is that it seems like in a lot of the examples the has_many association in my case should be images and not image. However when I do that I get an error:
Can't mass-assign protected attributes: image

I've tried updating my form to use fields_for as I've seen in other blogs like so:
<%= f.input :image, :label => "Photo", :as => :file %>

<% f.simple_fields_for :images do |images_form| %>
        <%= images_form.input :id, :as => :hidden %>
        <%= images_form.input :attachable_id, :as => :hidden %>
        <%= images_form.input :attachable_type, :as => :hidden %>
        <%= images_form.input :image, :as => :file %>
<% end %>

All I know is I'm having a heck of a time getting this to work. I'm pretty new to Rails so even debugging it is difficult. It doesn't help that the debugger doesn't really work in 3.2 :(

A: Since your models have_many :images (it should be :images, not :image), you'll want to use nested_forms in your views. You should set up accepts_nested_attributes_for :images on the unit and property models and change the attr_accessible from :image to :image_attributes.
Check out http://railscasts.com/episodes/196-nested-model-form-part-1 for a good guide on getting going with it.


text:
Q: How to create AppData folder for a domain user added to a local group I have added a domain user into group Users using Add User wizard in Windows 7.
Unfortunatelly the folder for user data (c:\Users\<NewUser>\AppData) was not created.
How can I instruct Windows to create this folder with appropriate permissions and structure?
I am experiencing the same issue on Windows Server 2008 R2.
Background
The domain user was assigned to us as a login to Database. Since we want to use Integrated Security to connect from our ASP.NET application, we added this domain user to our web server OS and configured him as the identity of the IIS AppPool.
Now the application needs to load PFX certificate from a file, which requires R/W permissions for the folder
C:\Users\<NewUser>\AppData\Roaming\Microsoft\Crypto\RSA\

This folder does not exist in the system and so the application fails with the following exception:
System.Security.Cryptography.CryptographicException:
    The specified network password is not correct.

A: The only way to create the application data folder (and contents) is for the user to log in.
If the user has logged in, but c:\Users\xxx\AppData was not created, the most likely reason is that the application data folder has been redirected by group policy.
In this scenario, your customer probably just needs to find the user's RSA folder (which is probably sitting on a file server somewhere) and make a copy of it in the location your software is expecting.


text:
Q: How do I remove a build configuration from an Xcode project from a script? I'm currently using AppleScript to clean up an Xcode project. I'd like my script to remove some build configurations that won't be relevant to other developers on my team.
For example, if I have "Debug", "DebugTest", and "Release", I would like the script to remove "DebugTest".
I'm currently using the following script:
tell application "Xcode"
open myXcodeProject
    set targetProject to project of active project document
    set targetConfigurations to build configurations of targetProject
    repeat with c in targetConfigurations
        if (name of c is equal to "DebugTest") then
            delete c
        end if
    end repeat
end tell

However, I'm getting the following error when I run the script, which leads me to beleive that I'm not deleting the configuration correctly:
Xcode got an error: AppleEvent handler failed. (-10000)
Thanks!

A: try this...
tell application "Xcode"
    set targetProject to project of active project document
    tell targetProject
        delete (first build configuration type whose name is "DebugTest")
    end tell
end tell


text:
Q: Python pandas how to join two files to one and use sql? This is my code:
important panda as pd
df1= pd.read_csv("efwfewfw.csv")
df2= pdf.read_csv("efwefewf.csv")
df3= pd.concat([df1,df2]).drop_duplicates().reset_index(drop=true)

sql_query = ?
Mission= i want to combine df1 and df2 to one file but without duplicates in terms of column title and row content.
Question one= in df3 i wrote ([ ]) what does that mean?
Question two= i wrote .drop_duplicates() what does this round bracket does?
question three= i did read something about an sql_query so that i can use in python panda sql commands in order to filter for certain things?
question four= why does my whole code not work, when i run it in python?

A: you can two way: merge and append:
df1= pd.read_csv("efwfewfw.csv")
df2= pdf.read_csv("efwefewf.csv")
#1
both = df1.append(df2)
#2
both = pd.merge(df1, df2[['col1', 'col2']], on = ['col1'], how='left')


text:
Q: Move file and override I'm trying to move a file even if a file with the same name already exists.
NSFileManager().moveItemAtURL(location1, toURL: location2)

Does NSFileManager's method moveItemAtURL have an override option?  How can I replace the existing file?

A: You can always check if the file exists in the target location.
if it does, delete it and move your item.
Swift 2.3
let filemgr = NSFileManager.defaultManager()

if !filemgr.fileExistsAtPath(location2)
{
  do
  {
    try filemgr.moveItemAtURL(location1, toURL: location2)
  }
  catch
  {
  }
}
else
{
  do
  {
    try filemgr.removeItemAtPath(location2)
    try filemgr.moveItemAtURL(location1, toURL: location2)
  }
  catch
  {

  }
}

Swift 3+
try? FileManager.default.removeItem(at: location2)
try FileManager.default.copyItem(at: location1, to: location2)


text:
Q: Tearing in Xubuntu 14.04 I have tearing problem in Xubuntu 14.04 (both 64 and 32 bit)

I'm using an Aspire s3:
http://www.itp.net/587066-acer-aspire-s3-ms2346?tab=specs
I have already installed the Intel driver but the tearing is present in every video player i use, how do i enable vertical sync?

A: I added a ppa from https://launchpad.net/~oibaf/+archive/ubuntu/graphics-drivers and updated my system.
I then added below lines to file /etc/X11/xorg.conf.d/20-intel.conf
Section "Device"
Identifier "Intel Graphics"
Driver "intel"
Option "AccelMethod" "sna"
Option "TearFree" "true"
EndSection

and restarted the System.
Now my system(with Intel graphics) is completely tear free and can use 'compositing' from "windows manager tweaks".

A: To enable vsync you first need to enable xfce composite in the Window Manager Settings:

A: I can advise you to try Compton if standard tear-free option did not help you. It is Xcompmgr fork.
http://duncanlock.net/blog/2013/06/07/how-to-switch-to-compton-for-beautiful-tear-free-compositing-in-xfce/
I am using it with Nvidia, should work with Intel too. Do you have problem only in video or also in DE? In first case try other video drivers output in video player settings.


text:
Q: powershell Syntax error ')' in script im a writing a script in powershell that show services running on a computer and start the services that is not running.
My command is the following
Show all services on Powershell with startmode "Auto"
$shse = Get-CimInstance -ClassName win32_service -Computername pshells '
    -Filter "startmode = 'auto'" |
    ConvertTo-Html

Service start all services with status = stopped.
$Service = (Get-CimInstance -ClassName win32_service - Computername pshells '
    -Filter "startmode = 'auto'")

If ($Service.status -eq "Stopped"){
        Start-Service}

Else {}

Convert Output to HTML.
ConvertTo-Html -body "$shse " |

Out-File C:\Scripts\Service.htm

When running this in powershell i get this error
At line:6 char:30
+     -Filter "startmode = 'auto'")
+                                 ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExceptio
   n
    + FullyQualifiedErrorId : UnexpectedToken

A: try this:
Get-Service -ComputerName pshells  | where {$_.StartType -EQ 'Automatic' -and $_.Status -eq 'Stopped'} | Start-Service

A: Replace your existing code with this:
$Services =Get-CimInstance -ClassName win32_service -Computername pshells -Filter "startmode = 'auto'"
foreach($service in $Services)
{
    If ($Service.state -eq "Stopped"){Start-Service}
    Else {"Service is already running."}
}

Few things you need to keep in mind , if you wish to use a line continuation then you should use baktick(`) not single-quote(') .
You are getting all the services status and you wish to start them all if stopped. So as a whole it will all the return you as OK since you were checking status. You should check state not status.
As a whole if it is returning and in case any of them is already running, then PS will have conflict in the condition, thats when you should use foreach loop.
Iterate each value you got in $services, check the state and take necessary action and loop over ; proceed with the same for the next one unless the list is exhausted.
Hope it helps you.

A: So i got the command to work, i typed in the following
Do
{

$shse = Get-CimInstance -ClassName win32_service -Computername WIN-9HMIGR3QFE6 -Filter "startmode = 'auto'" |
    ConvertTo-Html

$Service = (Get-CimInstance -ClassName win32_service -Computername WIN-9HMIGR3QFE6 -Filter "startmode = 'auto'")

If ($Service.status -eq "Stopped"){

        Start-Service}

Else {}

ConvertTo-Html -body "$shse " |

Out-File C:\Test\Service01.html

Start-sleep -Seconds 600

}until ($infinity)

It created an html, where i can look at the services... But there is one problem, when i close down a service, the script is set to start all scripts again after 600 seconds, but service never gets up again.. So now the stopped-start service function is not working correctly

A: On the line:
$Service = (Get-CimInstance -ClassName win32_service - Computername pshells '
    -Filter "startmode = 'auto'")

You aren't using a back-tick (`) you're using a single quote (').  It should be a back-tick to escape the new line.


text:
Q: How to observe c++ destructor destroys basic data types? I have two classes one is main and other is Test,  for the Test class, I have Test.cpp and Test.h

//-----Test.h--------//
#pragma once
class Test
{
private:
    int num;
public:
    Test(void);
    Test(int n);
    ~Test(void);
};

//------Test.cpp------//

#include "Test.h"

#include<iostream>
using namespace std;

Test::Test(void)
{
}

Test::Test(int n)
{
    num = n;
}

Test::~Test(void)
{
    cout << "Deleted" << endl;
    cout << "num = " << num << endl ;
}

//---------main.cpp--------------//

#include "Test.h"

#include<iostream>
using namespace std;

int main()
{
    Test t1 = Test(5);
    return 0;
}

The output which I have expected is
Deleted
num = 0
But Real Output is
Deleted
num = 5
Why this occurs, why destructor, dint free the memory
or dint delete the basic data type, How can I delete the variable,
Using what method I can observe basic datatype getting deleted?

A: Destruction of an object does not mean setting values to zero. That would be unnecessary work. Rather, all that is required is that resources be released. Bits are typically left as-is (representing 5 in your example) unless there is a compelling reason to do otherwise.
Furthermore, members are destroyed after the class. In your example, first ~Test() is run to destroy t1, then t1.num would be destroyed. The destructor of Test cannot view the destruction of Test::num.

A:
why destructor, dint free the memory or dint delete the basic data type

You did not have any memory allocated in the heap, so there is no need to free anything.
All you have is a basic type int which does not need any memory deallocation.
If instead you had some pointer member variable:
private:
    int* num;

and you allocated it somewhere in your constructor: new int(6); then sure you must deallocate/free it inside your destructor.

A: In this case, probably a shared-pointer may help, which automatically is destroyed just after the destructor:
std::shared_ptr<int> num;

But it has to be constructed, in the constructor you need:
Test::Test(int n)
: num(std::make_shared<int>(n)
{
    // *n == 100
}

To see if the data is deleted use Valgrind.


text:
Q: How to know if user closes the page? I am trying to know if user closes the page, not clicking back button or write another website in url bar to leave. I have tried this,
$(window).bind('beforeunload', function () {

logout();

});

It works, but it fires also when user clicks back button or write another url and go.
My question is, is it possible to know if user closes the page ?

A: There's an alternative but it's expensive and also really depends on the user case. It works wonders for me at a simple chat we did. You can have the javascript to constantly (every few seconds) call a page with the user id, example.com/misc/alive/456457, where 456457 is the id of the user. You introduce then that call in a database table as a new row. If the user doesn't call back in more than X seconds, you assume he's gone.
Of course, you don't get an action just when the user 'is gone', you just get a database that then you've got to analyse to know when the user 'probably' left. For the chat example, it was as easy as calling it every 2 seconds and then checking if there was any user online in the last 5 seconds and delete duplicate ids (to give it some threshold).


text:
Q: Java: Builder, Inheritance, Generics Redux I need to create a set of Builder classes with inheritance through a multi-level hierarchy, whereby the builders need to reside outside of the to-be-built classes as well as in a different package.
Going out from this example: https://onelostlogician.wordpress.com/2016/10/10/inheritance-generics-and-builders/ the code below was created by changing as per the requirements: 1. moving builders to top level, 2. putting builders and to-be-built in different packages and adding setters to the latter, 3. moving static newXYZ() methods into the builders and removing their type parameters to get rid of erasure clash. This would be a suitable model of the desired product.
package other;

public abstract class BaseClass {
    protected Integer field1;

    BaseClass () {
    }

    public Integer getField1 () {
        return field1;
    }

    public void setField1 (Integer field1) {
        this.field1 = field1;
    }
}

package my;

import other.BaseClass;

public abstract class BaseClassBuilder<T extends BaseClass, BU extends BaseClassBuilder> {
    protected T obj;

    protected BaseClassBuilder (T obj) {
        this.obj = obj;
    }

    protected final BU getThis () {
        return (BU) this;
    }

    public BU withField1 (Integer field1) {
        obj.setField1(field1);
        return getThis();
    }

    public T build () {
        return this.obj;
    }
}

package other;

import java.util.UUID;

public class SubClass extends BaseClass {
    protected UUID field2 = null;

    public SubClass () {
    }

    public UUID getField2 () {
        return field2;
    }

    public void setField2 (UUID field2) {
        this.field2 = field2;
    }
}

package my;

import java.util.UUID;

import other.SubClass;

public class SubClassBuilder<T extends SubClass, BU extends SubClassBuilder> extends BaseClassBuilder<T, BU> {
    protected SubClassBuilder (T obj) {
        super(obj);
    }

    public BU withField2 (UUID field2) {
        obj.setField2(field2);
        return getThis();
    }

    public T build () {
        return this.obj;
    }

    public static SubClassBuilder neu () {
        return new SubClassBuilder<>(new SubClass());
    }
}

package other;

public class SubSubClass extends SubClass {
    protected String field3 = null;

    public SubSubClass () {
    }

    public String getField3 () {
        return field3;
    }

    public void setField3 (String field3) {
        this.field3 = field3;
    }
}

package my;

import other.SubSubClass;

public class SubSubClassBuilder<T extends SubSubClass, BU extends SubSubClassBuilder<T, BU>> extends SubClassBuilder<T, BU> {
    protected SubSubClassBuilder (T obj) {
        super(obj);
    }

    public BU withField3 (String field3) {
        obj.setField3(field3);
        return getThis();
    }

    public T build () {
        return this.obj;
    }

    public static SubSubClassBuilder neu () {
        return new SubSubClassBuilder<>(new SubSubClass());
    }
}

Result: SubSubClassBuilder.neu().withField1(..) returns a BaseClassBuilder and withField2(..) a SubClassBuilder, as shown per code completion in Android Studio 3.0.1. Overriding getThis() in each builder did not work, either.
Back to square one, what am I missing?
Edit: Following a hint from Java: builder pattern, inheritance and generics it was also tried with static (inner) builder classes like so, but to the same effect:
    package my;

    import java.util.UUID;

    import other.BaseClass;
    import other.SubClass;
    import other.SubSubClass;

    public class Builders {

        private Builders () {}

        abstract static class BaseClassBuilder<T extends BaseClass, BU extends BaseClassBuilder> {
            protected T obj;

            protected BaseClassBuilder (T obj) {
                this.obj = obj;
            }

            protected final BU getThis () {
                return (BU) this;
            }

            public BU withField1 (Integer field1) {
                obj.setField1(field1);
                return getThis();
            }

            public T build () {
                return this.obj;
            }
        }

        public static class SubClassBuilder<T extends SubClass, BU extends SubClassBuilder> extends BaseClassBuilder<T, BU> {
            protected SubClassBuilder (T obj) {
                super(obj);
            }

            public BU withField2 (UUID field2) {
                obj.setField2(field2);
                return getThis();
            }

            public T build () {
                return this.obj;
            }

            public static SubClassBuilder neu () {
                return new SubClassBuilder<>(new SubClass());
            }
        }

        public static class SubSubClassBuilder<T extends SubSubClass, BU extends SubSubClassBuilder<T, BU>> extends SubClassBuilder<T, BU> {
            protected SubSubClassBuilder (T obj) {
                super(obj);
            }

            public BU withField3 (String field3) {
                obj.setField3(field3);
                return getThis();
            }

            public T build () {
                return this.obj;
            }

            public static SubSubClassBuilder neu () {
                return new SubSubClassBuilder<>(new SubSubClass());
            }
        }
    }

A: The good news : it can be done. What makes your approach impossible is that you want the intermediate builder subclasses to both make concrete their own self type and keep it open for extension by subclassing. This proves to be impossible.
To make it work you'll have to, at each level, have an abstract subclass, that adds the necessary methods and allows further extension for subtypes, and a concrete subclass that specifies itself as a specific builder.

Here is my adapted implementation :
To start, the base class. What I've changed, is mostly the passing of the self type's class in the constructor.
portected abstract class BaseClassBuilder<T extends BaseClass, BU extends BaseClassBuilder<T, BU>> {
    protected T obj;
    private BU self;

    protected BaseClassBuilder (T obj, Class<?> selfType) {
        this.obj = obj;
        this.self = (BU) selfType.cast(this);
    }

    final BU getThis () {
        return self;
    }

    public BU withField1 (Integer field1) {
        obj.setField1(field1);
        return getThis();
    }

    public T build () {
        return this.obj;
    }
}

Now for the abstract version of the SubClassBuilder. This one adds all the methods we need to build instances of SubClass, but is still abstract, so it can still serve to be extended.
public abstract class AbstractSubClassBuilder<T extends SubClass, BU extends AbstractSubClassBuilder<T, BU>> extends BaseClassBuilder<T, BU> {

    protected AbstractSubClassBuilder(T obj, Class<?> selfType) {
        super(obj, selfType);
    }

    public BU withField2 (UUID field2) {
        obj.setField2(field2);
        return getThis();
    }
}

This allows us to make a concrete builder class for SubClass instances quite easily :
public final class SubClassBuilder extends AbstractSubClassBuilder<SubClass, SubClassBuilder> {

    private SubClassBuilder(SubClass obj) {
        super(obj, SubClassBuilder.class);
    }

    public static SubClassBuilder neu () {
        return new SubClassBuilder(new SubClass());
    }
}

The next level works just the same; an abstract class to add the extra builder methods, and to allow further extension, it extends AbstractSubClassBuilder :
public class AbstractSubSubClassBuilder<T extends SubSubClass, BU extends AbstractSubSubClassBuilder<T, BU>> extends AbstractSubClassBuilder<T, BU> {

   protected AbstractSubSubClassBuilder (T obj, Class<BU> selfType) {
        super(obj, selfType);
    }

    public BU withField3 (String field3) {
        obj.setField3(field3);
        return getThis();
    }
}

Making it concrete, takes another class, but now the static factory method doesn't shadow one from its parent (neu : are you German?)
public class SubSubClassBuilder extends AbstractSubSubClassBuilder<SubSubClass, SubSubClassBuilder> {

    private SubSubClassBuilder(SubSubClass obj) {
        super(obj, SubSubClassBuilder.class);
    }

    public static SubSubClassBuilder neu () {
        return new SubSubClassBuilder(new SubSubClass());
    }
}

And now building instances of either class is easy as pie.
SubSubClass subSubClass = SubSubClassBuilder.neu()
        .withField2(UUID.randomUUID())
        .withField1(5)
        .withField3("3")
        .build();

SubClass subClass = SubClassBuilder.neu()
        .withField1(66)
        .withField2(UUID.randomUUID())
        .build();

(credit to AssertJ where I've seen this done first)


text:
Q: Proof that gravitational force is conservative It is a well accepted fact that gravitational force is conservative in nature, i.e, the work done on an object in gravitational field is independent of the path taken.
To prove the above statement, I want to have

*

*An intuitive proof based on understanding and thought experiments.

*A formal and rigorous mathematical proof.

*Can the same logic be extended to prove the conservative nature of other forces as well?


text:
Q: List Properties and Controller Actions for Creation and Editting First of all, please help me by telling where the question is not clear, as am not used to ask questions off the internet.
Problem in a Nutshell:
The framework makes it very easy to create editors for a viewmodel with simple scalar properties. However it does not scale well when we want to edit viewmodels that have lists of other objects. The framework should not assume the availability of a session neither javascript.
Code Sample
I posted all the meaningful code here, which should give much better context than describing the problem with words. I kept it as simple as possible:
namespace Simple{
    class SimpleController{
        public Html CreateA(){
            return View(new A());
        }

        // this is usually an http post responding to a button under the displayed listing of Bs in the main form
        [HttpPost]
        public Html CreateA(A a, FormCollection collection){
            // ***  This is only necessary in the case of lists ***
            // ***  what happens in the "MoreInvolved" case is
            //     terrifying. I didn't post any attempt. ***
            if(collection["button"] == "AddB"){
                a.listB.Add(new B());
                return View(a);
            }
            else{
                // save a to database
                // return redirect either to list or to details of created object
            }
        }
    }

    class A {
        public string a1;
        public string a2;
        public string a3;
        public List<B> listB;
    }

    class B {
        public string b1;
        public string b2;
    }
}

namespace MoreInvolved {
    class A {
        public string a1;
        public string a2;
        public string a3;
        public List<B> listB;
    }

    class B {
        public string b1;
        public string b2;
        public List<C> listC;
    }

    class C {
        public string c1;
        public string c2;
    }
}

The views are not included in the code for the simple case, but it has been tested and it works well. I used expression trees for that matter to make it easier, but that's not posted in the code. However, in the more involved case, I have not completed, and I have not yet envisioned a simple solution other than pondering the bizarre and strange
In the code above, the simple case is working as I expect. I can add B's to an A without using any session or Javascript. However I had to add a sub-route in the controller's CreateA() to check when I've actually pressed an add button.
In the more involved scenario, even more changes to the controller become necessary. The subroute will have to decide which B a new C needs to be added to.
It shows two cases, one of which I have tested to work well. Do assume that the view used returns html that once posted gets bound back into deep objects.
The Problem
Notice, in the code, how once we are in the more involved case, the programmer is immediately stomped with how a new object should be inserted when dealing with a second level child. Specifically, I don't want to have an if condition to add a C into a specific B within the controller for A. It's annoying if I had to write the same code if List<B> existed under another parent, say D.
Is the control model totally obliterated from MVC, doesn't that mean some things are extremely harder to do?
I believe I am flirting with the need for user controls and some way to create controls that are reusable so that I can have a controller for B with its children (C's) then reuse all of that when implementing a CRUD interface for A.
There's an imbalance between the ease of creating editors for scalar types, or an object consisting of scalar types on one hand and editors for lists of objects on the other
The real issue is, there are automatic editors for scalar types, but none for lists of them. The solutions that I came up with are redundant, and introduce seemingly unnecessary additional code and headache.
Final Notes: The reason am going all the trouble is that am trying to see how far I can push statelessness and keeping the code clean and within the limits of the MVC pattern. I wish there were more examples of places where a pattern fails rather than all the marketing like material on patterns. That way we can immediately spot where and where not to use certain pattern oriented products. I believe, regular ASP.NET would deal with my case here with a breeze using its viewstate and event flow model.

A: Not totally sure I understand what you mean but I feel you are you are in need of ViewModels. And more precisely ViewModels that inherit from each other. You don't want to keep writing the same code over and over (DRY) so you should design a class model for your ViewModels where the most general classes are at the top (i.e. holding data which you need on almost every page of your site) and the more page specific classes at the bottom. The more page specific classes inherit from the more general classes.
But you can also add methods to your ViewModels if you need to build certain data frequently. For example if you need to build a SortedDictionary with the option items for a select box you can add a method for that to a class at the appropriate level. Or you can have that class always build it by doing it from the constructor.
Hope this helps...


text:
Q: What is this value? printf("%d", "10+10");

then I get "17661648" and similar thing in too
printf("%d", "Hello");

What is this value?
sum of "1,0,+,1,0" "H,e,l,l,o" as ASCII code in decimal number? or just a garbage value?

A: According the the C11 standard n1570 (see its §7.21.6.1) you've got undefined behavior (UB), which is also documented here or in printf(3). So be very scared, since arbitrarily bad things could happen. So take the habit of reading the documentation of every function that you are using.
If you ask your compiler to disassemble the generated form of your program (e.g. by compiling with gcc -S -O -fverbose-asm if you use GCC, on Linux/x86-64) you'll discover that the address of the string literal "10+10" is passed (on 64 bits) and then truncated (inside printf, because of the %d) to an int. So the 17661648 could correspond to the lowest 32 bits of that address.
Details are of course implementation specific (and could vary from one run to the next one because of ASLR, depends upon the compiler and the ABI and the target system). To actually understand and explain the behavior requires diving into many details (your particular computer, your particular compiler and optimization flags, your particular operating system, the compiler generated assembler & machine code, your particular C standard library, etc....) and you don't want to do that (because it could take years).
You should take several hours to read more about UB. It is an essential notion to understand when programming in C, and you should avoid it.
Any good compiler would have warned you, and then you should improve your code to get no warnings. If using GCC, be sure to compile with gcc -Wall -Wextra -g to get all warnings and debug info. Then use the gdb debugger to understand the actual behavior of your program on your system. In all cases, be sure to configure your C compiler to enable all warnings and debug info, and learn to use your debugger. Read How To Debug Small Programs.

A: Someting like this should work:
printf("Hello");
total = 20;
printf("10+10 = %d", total);


text:
Q: Laravel: checking two columns if one matches display the result     $locationId=Auth::user()->location_id;
    $parcelDetails = $this->model
        ->whereBetween('date',array($fromDate, $toDate))
        ->where('source_from',$locationId)
        ->orWhere('destination_to',$locationId)
        ->with('sourceFrom', 'destinationTo')
        ->paginate($perPage);
        //get();
    return $parcelDetails;

i want to get the results where my source_from or destination_to matches $locationId with the dates given.

A: You can use a nested where to accomplish that:
$locationId=Auth::user()->location_id;
$parcelDetails = $this->model
    ->whereBetween('date',array($fromDate, $toDate))
    ->where(function($q){
        $q->where('source_from', $locationId);
        $q->orWhere('destination_to', $locationId);
    })
    ->with('sourceFrom', 'destinationTo')
    ->paginate($perPage);
    //get();
return $parcelDetails;


text:
Q: Explanation of `< /dev/urandom tr -dc _A-Z-a-z-0-9` In this article, I came across the following command:
< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32}

I haven't seen this kind of expression in Bash yet. Specifically, the < at the start and the concatenation of /dev/urandom and tr surprised me. As far as I interpret this command, we're reading data from /dev/urandom into the tr command, but why is the < /dev/urandom first?

A: Redirection operators can be placed anywhere in a simple command (see What are the shell's control and redirection operators? — "simple" is in the POSIX sense here, as opposed to compound).
Placing the input redirection first helps make the data flow clearer: reading from left to right, data is read from /dev/urandom, processed by tr, then piped to head.
Reading
tr -dc _A-Z-a-z-0-9 < /dev/urandom | head -c${1:-32}

instead means not knowing where tr gets its data from until after its arguments; there aren't many here, but with more complex commands it can make quite a difference.


text:
Q: SSRS Result on Multiple Value Parameters I have an SSRS report that takes multiple valued parameter, when I try to generate the sp's with the multiple values, I get the desired result on the contrary when I'm on the SSRS env (test), even if I select multiple values, I only get the top row as a result, below is my source;
sp to generate the multiple rows
SELECT RIGHT('0'+StoreCode,4) + ' - ' + LTRIM(RTRIM(StoreName)) AS Result
FROM tblInterface_Branch
WHERE StoreCode IN (SELECT * FROM list_to_tbl(@var))

function, which i've copied from a tutorial
-- from http://www.sommarskog.se/arrays-in-sql-2005.html
-- original name: iter$simple_intlist_to_tbl
ALTER FUNCTION list_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos        int,
       @nextpos    int,
       @valuelen   int

SELECT @pos = 0, @nextpos = 1

WHILE @nextpos > 0
BEGIN
  SELECT @nextpos = charindex(',', @list, @pos + 1)
  SELECT @valuelen = CASE WHEN @nextpos > 0
                          THEN @nextpos
                          ELSE len(@list) + 1
                     END - @pos - 1
  INSERT @tbl (number)
     VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
  SELECT @pos = @nextpos
END
RETURN
END

Is there something I'm missing?


text:
Q: NPE in ModelAttribute while sending empty list I'm experiencing problem with feign client (spring-boot-starter 2.4.4, spring-cloud-starter-openfeign 3.0.2). When I'm trying to send an empty list inside @ModelAttribute annotated object feign client throws feign.codec.EncodeException with NullPointerException cause. Problem does not occur when list has at least one element.
Does anybody know how to properly override feign encoder to enable passing empty list without errors?

A: You will want to create a class that implements the feign Encoder (https://github.com/OpenFeign/feign/blob/master/core/src/main/java/feign/codec/Encoder.java)
e.g.
public class EnableEmptyListEncoder implements Encoder {
   @Override
   public void encode(Object object, Type bodyType, RequestTemplate template) {
    // empty list encode logic here
   }
}

How you point to that encoder depends on your setup:
-- via the application.yml:
feign:
    client:
        config:
            feignName:
                encoder: com.example.EnableEmptyListEncoder

-- via  a buider:
Feign.builder()
    .encoder( new EnableEmptyListEncoder()  )

-- a bean in the config class
@Bean
public EnableEmptyListEncoder encoder() {
    return new EnableEmptyListEncoder();
}


text:
Q: SQL update value to be the sum of a selection of products I have order_items with an order_id, quantity, and a unit_price
I want my orders, total_price column to equal the sum of all associated order_items quantity multiplied by the unit_price
This is my failing SQL-statement:
update orders set total_price=SUM(select quantity*unit_price from order_items where orders_id=?) where id=?

Table structure:
orders:
id;
total_price;
order_items:
order_id (references order(id));
quantity;
unit_price;
How can I execute this operation through SQL?

A: Just move the sum() inside the subquery:
update orders o
    set total_price = (select sum(quantity*unit_price) from order_items where orders_id=?)
    where id=?;

Note:  by using a correlated subquery, you can do this with just one parameter:
update orders o
    set total_price = (select sum(oi.quantity * oi.unit_price)
                       from order_items oi
                       where oi.orders_id = o.id
                      )
    where id=?;


text:
Q: Build only when a file contains specific text I would like to know how to continue with a build only when a file contains specific text?
I want the build to fail if the text is incorrect, otherwise continue with build.

A: update your script to return a nonzero exit status when the file doesn't contain the text. run your shell script via an sh step like this:
sh '/path/to/your/script_that_checks_another_file_for_certain_text.sh'

full pipeline:
pipeline {
  agent { label 'docker' }
  stages {
    stage('build') {
      steps {
        sh '/path/to/your/script_that_checks_another_file_for_certain_text.sh'
        echo 'this will not happen if the above script returns a bad exit status'
      }
    }
  }
}


text:
Q: Как из списка получить полное слово по части слова? Есть текст(в самом низу)
Как я могу из него получить все STEAM_1:X:XXXXXXXXX?
Не знаю, как правильно записывать в список, но нашел такой способ (дважды enter нужно нажать)
words = []
text = input()

while text != '':
    words.append([str(s) for s in text.split()])
    text = input()

print(words)

Текст:
# 302 2 "Aggressor™" STEAM_1:1:109153194 14:28 64 0 active 128000
# 256 3 "S0CI3TY" STEAM_1:0:58822435 44:27 78 0 active 196608
# 325 4 "P. Ratoshnuk™" STEAM_1:1:86892362 10:01 66 0 active 196608
# 330 5 "mouse." STEAM_1:1:566589724 04:25 86 0 active 786432
# 227 6 "Zeref272" STEAM_1:0:569915494 49:12 60 0 active 196608
# 321 7 "Naffa" STEAM_1:1:67113228 10:55 51 0 active 196608
# 336 8 "Dream" STEAM_1:0:449033455 00:43 66 0 active 196608
# 229 9 "kak dela? ¯ \ _ (ツ) _ / ¯" STEAM_1:1:90790453 47:25 61 0 active 786432
# 288 10 "ZOZO" STEAM_1:1:608871615 28:23 74 0 active 786432
# 331 11 "BBC" STEAM_1:1:427531434 03:55 81 0 active 250000

A: txt ='# 302 2 "Aggressor™" STEAM_1:1:109153194 14:28 64 0 active 128000\n' \
   '# 256 3 "S0CI3TY" STEAM_1:0:58822435 44:27 78 0 active 196608\n' \
   '# 325 4 "P. Ratoshnuk™" STEAM_1:1:86892362 10:01 66 0 active 196608\n' \
   '# 330 5 "mouse." STEAM_1:1:566589724 04:25 86 0 active 786432\n' \
   '# 227 6 "Zeref272" STEAM_1:0:569915494 49:12 60 0 active 196608\n' \
   '# 321 7 "Naffa" STEAM_1:1:67113228 10:55 51 0 active 196608\n' \
   '# 336 8 "Dream" STEAM_1:0:449033455 00:43 66 0 active 196608\n' \
   '# 229 9 "kak dela? ¯ \ _ (ツ) _ / ¯" STEAM_1:1:90790453 47:25 61 0 active 786432\n' \
   '# 288 10 "ZOZO" STEAM_1:1:608871615 28:23 74 0 active 786432\n' \
   '# 331 11 "BBC" STEAM_1:1:427531434 03:55 81 0 active 250000'
for th in txt.split('\n'):
    hh = th.find('STEAM')
    nn = th[hh:].split(' ')[0]
    print(nn)

STEAM_1:1:109153194
STEAM_1:0:58822435
STEAM_1:1:86892362
STEAM_1:1:566589724
STEAM_1:0:569915494
STEAM_1:1:67113228
STEAM_1:0:449033455
STEAM_1:1:90790453
STEAM_1:1:608871615
STEAM_1:1:427531434

A: steamids1 = re.findall('\\bSTEAM_1:0:\w+\\b', str(words))
steamids2 = re.findall('\\bSTEAM_1:1:\w+\\b', str(words))
steamids = steamids1 + steamids2


text:
Q: 64-bit app calling 32-bit Windows service - VS 2013 debug 64-bit C# app calls into a 32-bit C# Windows service.  We can step through the 32-bit code after attaching to the service, but we cannot see the value of any variables.  We need the 32-bit service to access legacy 32-bit dlls.

A: https://blogs.msdn.microsoft.com/visualstudioalm/2013/10/16/switching-to-managed-compatibility-mode-in-visual-studio-2013/
Explains the fix nicely, though this variant of the cause is not mentioned.  Considering how often this trips folks up, I think this might be called a Microsoft design flaw.


text:
Q: SpringBoot integrated tomcat: configure to limit requests Ahoi,
I build a little RESTful Webservice with spring boot with integrated tomcat. Then I tried to test how robust it is I found that sending many HTTP requests (with apache benchmark) dramatically increases memory usage until the service fails because of an OutOfMemoryException - also it seems not to be able to recover within reasonable time.
I could not find any documentation on how to configure the integrated tomcat e.g. to limit the amount of requets by IP (or what else would make sense?). Also I wonder if there are any known memory leaks, as a few 1000 requests shouldnt really bring the tomcat down (I run the .jar with -Xms512m -Xmx1024m)
I appreciate your help!

A: I don't think Tomcat has such a filter built in, but it should be pretty trivial to add a javax.servlet.Filter of your own for this purpose. The RateLimiter class from Guava is an excellent resource for limiting something like how many requests allowed per IP in a time window.


text:
Q: Mod Rewrite URL issue I need to build SEO friendly URLs, I have this URL:
http://www.misite.com?search=&area=$1&cityid=$1&lang=es&subcatid=66&view=ads&catid=9

I need to make them look like this SEO friendly URL:
http://www.misite.com/sale-houses-california

So far, I've added this code to htaccess this:
RewriteRule ^sale-houses-([-]?[a-z]+)? ?search=&area=$1&cityid=$1&lang=es&subcatid=66&view=ads&catid=9 [QSA]

I have cities, categories and subcategories combining all so I need an easy solution for all of the combinations
I don't know the correct expression: ([-]?[0-9]+)? / ([-]?[a-z]+) or similar.
The URL structure is ^text-text-text in lower case
Is it possible to make something more general like this (see below) or do I have to write a line per each category?
RewriteRule ^([-]?[a-z]+)-([-]?[a-z]+)-([-]?[a-z]+)? ?search=&área=$1&cityid=$1&lang=es&subcatid=$1&view=ads&catid=$1 [QSA]


text:
Q: combobox Control Xamarin forms I have a combobox control declared in XAML. Here is the code:
<border:SfBorder
                    BorderColor="{Binding Source={x:Reference DefectPicker}, Path=IsFocused, Converter={StaticResource ColorConverter}, ConverterParameter=3}"
                    Style="{StaticResource BusinessFormBorderStyle}">
                <combobox:SfComboBox
                            x:Name="DefectPicker"
                            SelectedValue="{Binding Defect, Mode=TwoWay}"
                            Style="{StaticResource ComboBoxStyle}"
                            Watermark="Enter Defect"
                            VerticalOptions="CenterAndExpand">
                    <combobox:SfComboBox.ComboBoxSource>
                        <ListCollection:List x:TypeArguments="x:String">
                            <x:String>Sole Proprietorship</x:String>
                            <x:String>Partnership</x:String>
                            <x:String>Limited Partnership</x:String>
                            <x:String>Corporation</x:String>
                            <x:String>Limited Liability Company</x:String>
                            <x:String>Cooperative</x:String>
                        </ListCollection:List>
                    </combobox:SfComboBox.ComboBoxSource>
                    <combobox:SfComboBox.DropDownButtonSettings>
                        <combobox:DropDownButtonSettings>
                            <combobox:DropDownButtonSettings.View>
                                <Label
                                                FontFamily="{StaticResource FontIcons}"
                                                FontSize="25"
                                                HorizontalTextAlignment="Center"
                                                Text="{StaticResource DropDownButtonIcon}"
                                                TextColor="{DynamicResource Gray-600}"
                                                VerticalTextAlignment="Center" />
                            </combobox:DropDownButtonSettings.View>
                        </combobox:DropDownButtonSettings>
                    </combobox:SfComboBox.DropDownButtonSettings>
                </combobox:SfComboBox>
            </border:SfBorder>

How can I declare this code in C#. Exact fields mentioned here ! It be a new method for me to learn !

A: Due to i do not find the Converter, Style and something else in your xaml, I make a simple structure in code. You could take the code below for reference.
List<string> list = new List<string>()
{
    "Sole Proprietorship", "Partnership","Limited Partnership","Corporation","Limited Liability Company","Cooperative"
};

SfBorder sfBorder = new SfBorder() { BorderColor = Color.Red };

SfComboBox sfComboBox = new SfComboBox();
sfComboBox.ComboBoxSource = list;

sfBorder.Content = sfComboBox;

this.Content = sfBorder;

Screenshot:


text:
Q: Do we need encrypt session id before saving it into database I want to use database as session storage. I design a simple table containing 3 columns:
SessionID, Key, Value ( Session ID & Key will be primary key).
My question is should I encrypt user Session ID before saving it into the table? In my opinion, I should do it because it prevents someone (who has access database) seeing active session ids.

A: You could encrypt the session, but it's not standard practice. Typically, the database is well protected, with only the web/application server being able to access it.
Also, since sessions should expire (and time out), the damage is mitigated to a small window of time even if it were accessed.
If you do decide to encrypt the session ID, it should be fairly easy, especially if you have an object oriented approach. You can simply encrypt the session near the persistence layer.
A more common problem is having the session ID sniffed off the wire. Ensure you're forcing HTTPS between the client/browser and application/web server to prevent that.
Also, you can request the password again on any serious operations to further mitigate session hijacking issues.