Q: how to use datetime minvalue in get/set method when null is the database value I have two functions, in my constructor I read from the database and call all of my set functions:
while (reader.Read())
{
    Status = reader["status"].ToString();
    Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1"));
}

my get and set method for status works fine. for the date field however, i get an error because sometimes the field coming from the database is a NULL value. how would i modify my method to assign the minvalue incase the database returns a NULL?
public DateTime Event_Start_Date1
{
    get
    { return event_start_date1; }
    set
    { event_start_date1 = value; }
}

A: Wrap the logic in a method:
private static DateTime GetDateTimeValue(SqlDataReader reader, string fieldName)
{
    int ordinal = reader.GetOrdinal(fieldName);
    return reader.IsDBNull(ordinal) ? reader.GetDateTime(ordinal) : DateTime.MinValue;
}

...and call it:
Event_Start_Date1 = GetDateTimeValue(reader, "event_start_date1");

A more general and reusable approach could be to make it into an extension method that can (optionally) take a default value as input:
public static class SqlDataReaderExtensions
{
    public static DateTime GetDateTimeValue(this SqlDataReader reader,
        string fieldName)
    {
        return GetDateTimeValue(reader, fieldName, DateTime.MinValue);
    }

    public static DateTime GetDateTimeValue(this SqlDataReader reader,
        string fieldName, DateTime defaultValue)
    {
        int ordinal = reader.GetOrdinal(fieldName);
        return reader.IsDBNull(ordinal)
            ? reader.GetDateTime(ordinal)
            : defaultValue;
    }
}

This assumes that you cannot change the model. If you have that option, go with a Nullable<DateTime> instead, and have the GetDateTimeValue method default to returning null.

A: Check for DBNull and based on that you can assign MinValue.
int ordinal = reader.GetOrdinal("event_start_date1");
Event_Start_Date1 = reader.IsDBNull(ordinal)? DateTime.MinValue: reader.GetDateTime(ordinal);

A: Use a nullable DateTime:
public DateTime? EventStartDate { get; set; }

Which is similar to:
public Nullable<DateTime> EventStartDate { get; set; }

Read more about Nullable Types
To get the default value of DateTime, you can use either DateTime.MinValue or default(DateTime):
while (reader.Read())
{
    Status = reader["status"].ToString();
    var startDate = reader.GetOrdinal("event_start_date1");
    EventStartDate = if reader.IsDBNull(startDate) ?
                        reader.GetDateTime(ordinal) :
                        default(DateTime);
}

Essentially, DateTime is a value-type, not a reference type, and there can't be a null DateTime (or whatever other Value Type) compile-time variable, in order for it to be capable to hold a null value it has to be wrapped in the Nullable<T>).
In .NET all the non-nullable types have a default value which can be obtained via the default keyword (e.g. default(DateTime)).

A: Use DataReader.IsDBNull to check if the value is null:
Event_Start_Date1 = reader.IsDBNull("event_start_date1") ? DateTime.MinValue :
reader.GetDateTime(reader.GetOrdinal("event_start_date1"));

The above sentence is in the following format:

Condition ? accepted action : rejected
  action

A: you can use a try-catch
while (reader.Read())
{
    Status = reader["status"].ToString();
    try{
    Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1"));
    }
catch{
    Event_Start_Date1 = //some other thing
}

or you can use GetSqlDateTime()
while (reader.Read())
{
    Status = reader["status"].ToString();
    Event_Start_Date1 = reader.GetSqlDateTime(reader.GetOrdinal("event_start_date1"));
}


Q: Nested class with numba I tried using numba to speed up the implementation, but when using jitclass, there was a problem with class nesting.
I plan to use numba with multiple nested classes, does anyone know what is causing this error?
from numba.experimental import jitclass
from numba import f8, njit, typeof, void, types
import numpy as np

spec = [
    ("x", f8[:, :])
]

@jitclass(spec)
class Vec:
    def __init__(self, x):
        self.x = x

    @property
    def length(self):
        return np.linalg.norm(self.x, ord=2)

    def __mul__(self, other):
        return np.dot(self.x, other.x.T)

    def __add__(self, other):
        return Vec(self.x + other.x)

    def __sub__(self, other):
        return Vec(self.x - other.x)

spec_next = [
    ("a", Vec.class_type.instance_type),
    ("b", Vec.class_type.instance_type),
    ("ll", types.List(Vec.class_type.instance_type, reflected=True))
]

@jitclass(spec_next)
class Wrapper:
    def __init__(self, a, b, ll):
        self.a = a
        self.b = b
        self.ll = ll

    def bin(self):
        return (self.a + self.b) * (self.a - self.b)

    def sum(self):
        c = Vec(np.array([[0, 0]], dtype=np.float64))
        for i in range(len(self.ll)):
            c = c + self.ll[i]
        return c

if __name__ == "__main__":
    a = Vec(np.array([[1, 3]], dtype=np.float64))
    b = Vec(np.array([[2, 3]], dtype=np.float64))
    # c = a *b
    ll = [Vec(np.array([[1, 1]], dtype=np.float64)) for _ in range(1000)]
    wrap = Wrapper(a, b, ll)
    print(wrap.bin())
    print(wrap.sum())

I got the following error
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
- Resolution failure for literal arguments:
Failed in nopython mode pipeline (step: native lowering)
Failed in nopython mode pipeline (step: nopython frontend)
No conversion from array(float64, 2d, C) to float64 for '$8return_value.3', defined at None

File "test.py", line 45:
    def bin(self):
        return (self.a + self.b) * (self.a - self.b)
        ^

During: typing of assignment at test.py (45)

File "test.py", line 45:
    def bin(self):
        return (self.a + self.b) * (self.a - self.b)
        ^

During: lowering "$22binary_multiply.10 = arrayexpr(expr=(<built-in function mul>, [Var($10binary_add.4, test.py:45), Var($20binary_subtract.9, test.py:45)]), ty=array(float64, 2d, C))" at test.py (45)
- Resolution failure for non-literal arguments:
None

During: resolving callee type: BoundFunction((<class 'numba.core.types.misc.ClassInstanceType'>, 'bin') for instance.jitclass.Wrapper#7faa22b12f50<a:instance.jitclass.Vec#7faa20b19e90<x:array(float64, 2d, A)>,b:instance.jitclass.Vec#7faa20b19e90<x:array(float64, 2d, A)>,ll:reflected list(instance.jitclass.Vec#7faa20b19e90<x:array(float64, 2d, A)>)<iv=None>>)
During: typing of call at <string> (3)

File "<string>", line 3:
<source missing, REPL/exec in use?>

I see in the error code that a float is required, but I'm not sure why a float is required. can anyone tell me how it is determined by jitclass?


Q: How to make complete button process the data ? mean submit i wanna ask how to make the final step process the data ? , i've tried use form method to redirect process but it not work . i'm using modal-steps.
Already search on stackoverflow but i got nothing, if somebody know how to do it please tellme.
i'm using this wizard https://www.jqueryscript.net/other/Wizard-Modal-Bootstrap-jQuery.html

! function(a) {
    "use strict";
    a.fn.modalSteps = function(b) {
        var c = this,
            d = a.extend({
                btnCancelHtml: "Cancel",
                btnPreviousHtml: "Previous",
                btnNextHtml: "Next",
                btnLastStepHtml: "Complete",
                disableNextButton: !1,
                completeCallback: function() {},
                callbacks: {},
                getTitleAndStep: function() {}
            }, b),
            e = function() {
                var a = d.callbacks["*"];
                if (void 0 !== a && "function" != typeof a) throw "everyStepCallback is not a function! I need a function";
                if ("function" != typeof d.completeCallback) throw "completeCallback is not a function! I need a function";
                for (var b in d.callbacks)
                    if (d.callbacks.hasOwnProperty(b)) {
                        var c = d.callbacks[b];
                        if ("*" !== b && void 0 !== c && "function" != typeof c) throw "Step " + b + " callback must be a function"
                    }
            },
            f = function(a) {
                return void 0 !== a && "function" == typeof a && (a(), !0)
            };
        return c.on("show.bs.modal", function() {
            var l, m, n, o, p, b = c.find(".modal-footer"),
                g = b.find(".js-btn-step[data-orientation=cancel]"),
                h = b.find(".js-btn-step[data-orientation=previous]"),
                i = b.find(".js-btn-step[data-orientation=next]"),
                j = d.callbacks["*"],
                k = d.callbacks[1];
            d.disableNextButton && i.attr("disabled", "disabled"), h.attr("disabled", "disabled"), e(), f(j), f(k), g.html(d.btnCancelHtml), h.html(d.btnPreviousHtml), i.html(d.btnNextHtml), m = a("<input>").attr({
                type: "hidden",
                id: "actual-step",
                value: "1"
            }), c.find("#actual-step").remove(), c.append(m), l = 1, p = l + 1, c.find("[data-step=" + l + "]").removeClass("hide"), i.attr("data-step", p), n = c.find("[data-step=" + l + "]").data("title"), o = a("").addClass("label label-success").html(l), c.find(".js-title-step").append(o).append(" " + n), d.getTitleAndStep(m.attr("data-title"), l)
        }).on("hidden.bs.modal", function() {
            var a = c.find("#actual-step"),
                b = c.find(".js-btn-step[data-orientation=next]");
            c.find("[data-step]").not(c.find(".js-btn-step")).addClass("hide"), a.not(c.find(".js-btn-step")).remove(), b.attr("data-step", 1).html(d.btnNextHtml), c.find(".js-title-step").html("")
        }), c.find(".js-btn-step").on("click", function() {
            var m, n, o, p, b = a(this),
                e = c.find("#actual-step"),
                g = c.find(".js-btn-step[data-orientation=previous]"),
                h = c.find(".js-btn-step[data-orientation=next]"),
                i = c.find(".js-title-step"),
                j = b.data("orientation"),
                k = parseInt(e.val()),
                l = d.callbacks["*"];
            if (m = c.find("div[data-step]").length, "complete" === b.attr("data-step")) return d.completeCallback(), void c.modal("hide");
            if ("next" === j) n = k + 1, g.attr("data-step", k), e.val(n);
            else {
                if ("previous" !== j) return void c.modal("hide");
                n = k - 1, h.attr("data-step", k), g.attr("data-step", n - 1), e.val(k - 1)
            }
            parseInt(e.val()) === m ? h.attr("data-step", "complete").html(d.btnLastStepHtml) : h.attr("data-step", n).html(d.btnNextHtml), d.disableNextButton && h.attr("disabled", "disabled"), c.find("[data-step=" + k + "]").not(c.find(".js-btn-step")).addClass("hide"), c.find("[data-step=" + n + "]").not(c.find(".js-btn-step")).removeClass("hide"), parseInt(g.attr("data-step")) > 0 ? g.removeAttr("disabled") : g.attr("disabled", "disabled"), "previous" === j && h.removeAttr("disabled"), o = c.find("[data-step=" + n + "]"), o.attr("data-unlock-continue") && h.removeAttr("disabled"), p = o.attr("data-title");
            var q = a("").addClass("label label-success").html(n);
            i.html(q).append(" " + p), d.getTitleAndStep(o.attr("data-title"), n);
            var r = d.callbacks[e.val()];
            f(l), f(r)
        }), this
    }
}(jQuery);

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

      <form method="post" action="<?php echo base_url(); ?>pemesanan/submitorder">

                  Tanggal Pemesanan
                  <input type="date" class="form-control" name="tanggal_pemesanan" id="tanggal_pemesanan" value="<?php if (empty($this->session->userdata('tanggal_pemesanan'))){
                    echo date('Y-m-d');
                  } else {
                    echo $this->session->userdata('tanggal_pemesanan');
                  } ?>" width="50%">

                  Closer
                       <select name="id_closer" id="id_closer" class="form-control selectpicker" data-live-search="true">
                    <option value="">Pilih Closer</option>
                     <?php
              foreach($listcloser->result() as $closer) { ?>
                    <option value="<?php echo $closer->id_closer; ?>" <?php if ($this->session->userdata('id_closer') == $closer->id_closer ) {
                     echo "selected";
                   } ?>><?php echo $closer->nama_closer; ?></option>
                  <?php } ?>
                  </select>

                  Pelayanan
                  <input type="text" name="pelayanan" class="form-control" id="pelayanan" placeholder="Pelayanan" value="<?php echo $this->session->userdata('pelayanan'); ?>">

                <input type="hidden" name="halaman" value="pemesanan">
                Input Customer Baru

                  <input type="text" class="form-control" placeholder="Nama Customer" name="nama_customer" id="nama_customer">

                  <input type="text" class="form-control" placeholder="No. HP/WA" name="nohp_wa" id="nohp_wa">

                        <input maxlength="100" type="text" id="sumber_informasi" class="form-control" placeholder="Sumber Informasi" />

                  Atau

                          <select class="form-control selectpicker" data-live-search="true">
                          <option value="">Yang sudah ada</option>
                           <?php
                    foreach($listcustomers->result_array() as $cs)
                    {
                      $pilih='';
                      if($cs['id_customer']==$this->session->userdata("id_customer"))
                      {
                        $pilih='selected="selected"';
                        ?>
                          <option value="<?php echo $cs['id_customer']; ?>" <?php echo $pilih; ?>><?php echo $cs['nama_customer']; ?></option>
                           <?php
                      }
                      else
                      {
                        ?>
                          <option value="<?php echo $cs['id_customer']; ?>"><?php echo $cs['nama_customer']; ?></option>
                          <?php
                      }
                    }
                    ?>
                        </select>

                Input Data Anak

                 <input maxlength="100" type="text" id="nama_anak" required="required" class="form-control" placeholder="Nama Anak" />

                <select id="jenis_kelamin" class="form-control" required="required">
                          <option value="">Pilih Jenis Kelamin</option>
                          <option value="Laki-laki">Laki-laki</option>
                          <option value="Perempuan">Perempuan</option>
                        </select>

                        <input maxlength="100" type="date" id="tanggal_lahir" max="<?php echo date('Y-m-d'); ?>" class="form-control" />

                  <input type="text" class="form-control" placeholder="Nama Ayah" name="nama_ayah" id="nama_ayah">

                  <input type="text" class="form-control" placeholder="Nama Ibu" name="nama_ibu" id="nama_ayah">

                        <input maxlength="100" type="text" id="lahir_di" class="form-control" placeholder="Dilahirkan di" />

Data Hewan

            Tipe Hewan
            <select onchange="hitungpaketaqiqahsatuan()" class="form-control" style="width: 100%;" name="id_paketaqiqah" id="id_paketaqiqah" required>
              <option value="">Pilih Tipe Hewan</option>
              <?php
              foreach($listpaketaqiqah->result_array() as $pa)
              {
                ?>
                <option value="<?php echo $pa['id_paketaqiqah']; ?>"><?php echo $pa['tipe_hewan']; ?></option>
              <?php } ?>
            </select>

            Pilih Kandang
            <select onchange="" class="form-control" style="width: 100%;" name="id_kandang" id="id_kandang" required>
              <option value="">Pilih Kandang</option>
                <?php
              foreach($listkandang->result() as $kandang) { ?>
              <option value="<?php echo $kandang->id_lembaga; ?>"><?php echo $kandang->nama_lembaga; ?></option>
              <?php } ?>
            </select>

            Tanggal Pemotongan
            <input type="date" min="<?php  echo $this->session->userdata('tanggal_pemesanan');//date_format(date_add(date_create($this->session->userdata('tanggal_pemesanan')), date_interval_create_from_date_string('1 days')), 'Y-m-d'); ?>" class="form-control pemotongan" name="tanggal_potong" id="tanggal_potong" required >

            Jam Pemotongan

                <input  type="time" class="form-control pemotongan" name="jam_potong1" id="jam_potong1" required>

                <input  type="time" class="form-control pemotongan" name="jam_potong2" id="jam_potong2" required>

            Disaksikan/Tidak
            <select class="form-control pemotongan" style="width: 100%;" name="disaksikan_tidak" id="disaksikan_tidak" required >
              <option value="Disaksikan">Disaksikan</option>
              <option value="Tidak disaksikan">Tidak disaksikan</option>
            </select>

            Catatan untuk kandang
            <textarea class="form-control" rows="4" placeholder="Catatan untuk kandang" name="catatan_untuk_kandang" id="catatan_untuk_kandang"></textarea>

            Jumlah
            <input onchange="hitungpaketaqiqahsatuan()"  type="number" class="form-control" placeholder="Jumlah" name="jumlah_paketaqiqah" id="jumlah_paketaqiqah" min="1" value="1" required>

Paket Nasi Boks

      Pilih Paket
        <select onchange="hitungpaketnasiboxsatuan()" class="form-control chosen-select" style="width: 100%;" name="id_paketnasibox" id="id_paketnasibox" required>
              <option value="">Pilih</option>
              <?php foreach($listpaketnasibox->result() as $pn) { ?>
                <option value="<?php echo $pn->id_paketnasibox; ?>"><?php echo $pn->nama_paketnasibox; ?></option>
              <?php } ?>
            </select>

            Jumlah
            <input onchange="hitungpaketaqiqahsatuan()"  type="number" class="form-control" placeholder="Jumlah" name="jumlah_paketaqiqah" id="jumlah_paketaqiqah" min="1" value="1" required>

            Catatan untuk dapur
            <textarea class="form-control" rows="4" placeholder="Catatan untuk dapur" name="catatan_untuk_dapur" id="catatan_untuk_dapur"></textarea>

       Input Data Pengiriman

                  <textarea class="form-control" placeholder="Alamat" name="alamat" id="alamat"></textarea>

                  Input URL Gmaps
                 <input type="text" name="urlmaps" class="form-control">

                Tanggal Pengiriman
                <input type="date" name="tanggal_kirim" class="form-control" min="<?php  echo date_format(date_add(date_create($this->session->userdata('tanggal_pemesanan')), date_interval_create_from_date_string('1 days')), 'Y-m-d'); ?>" required>

                    Jam Kirim
                    <input type="time" name="jam_kirim" class="form-control" required>

                    Jam Sampai
                    <input type="time" name="jam_sampai" class="form-control" required>

                Tarif / Ongkos
                <input type="number" name="ongkos" class="form-control" min="0">

                Petugas Pengantaran
                <?php foreach ($listdelivery->result() as $ld) { ?>

                      <input type="radio" class="radiopetugaspengantaran" name="petugas_pengantaran"  value="<?php echo $ld->id_lembaga;?>">

                    <input type="text" class="form-control" value="<?php echo $ld->nama_lembaga;?>" readonly>
                     <?php } ?>

                    <input type="radio" class="radiopetugaspengantaran" name="petugas_pengantaran" value="Lainnya">

                  <input type="text" class="form-control" id="petugas_pengantaran" name="petugas_pengantaran_teks" value="Lainnya" disabled>

                  Diskon
                  <input type="number" min="0" onkeyup="hitungtotaldansisa()" onchange="hitungtotaldansisa()" class="form-control" placeholder="Diskon" name="diskon" id="diskon" value="<?php echo $this->session->userdata('diskon'); ?>">

                  DP
                  <input type="number" min="0" onkeyup="hitungtotaldansisa()" onchange="hitungtotaldansisa()"  class="form-control" placeholder="DP" id="dp" name="dp" value="<?php echo $this->session->userdata('dp'); ?>">

                  Mekanisme Pembayaran
                  <select class="form-control" id="mekanisme_pembayaran" name="mekanisme_pembayaran">
                    <option value="TUNAI" <?php if ($this->session->userdata('mekanisme_pembayaran') == "TUNAI" ) {
                     echo "selected";
                   } ?>>Tunai</option>
                   <option value="TRANSFER" <?php if ($this->session->userdata('mekanisme_pembayaran') == "TRANSFER" ) {
                     echo "selected";
                   } ?>>Transfer</option>
                 </select>

                  Sisa

Rp. 0

                  Total Tagihan

Rp. 0

        <button type="button" class="btn btn-default js-btn-step pull-left" data-orientation="cancel" data-dismiss="modal"></button>
    <button type="button" class="btn btn-warning js-btn-step" data-orientation="previous"></button>
    <button type="button" class="btn btn-success js-btn-step" data-orientation="next"></button>

    </form>

A: You can add one more button below the next button. Keep that button hidden till you reach the last step. When you reach the last step make it visible and on click of it write the logic to process your data.


Q: What is the use of software watchdog in a controller? Heyya,
I would like to what is the use of Software Watchdog and why they are used in controllers please..

A: Assuming you mean micro-controllers:

A watchdog timer (sometimes called a computer operating properly or COP timer, or simply a watchdog) is an electronic timer that is used to detect and recover from computer malfunctions.

Source


Q: How to share same instance of domain model in Angular2, and propagate changes? So i have a very simple domain model Shell :
import {Injectable} from 'angular2/core';

@Injectable()
export class Shell {

    public loggedIn: boolean = false;

    Change(item : boolean) {
        this.loggedIn = item;
    }
}

I have an AppComponent which hold this property:
@Component({
    selector: 'my-app',
    providers: [TemplateRef],
    templateUrl: './angular/app/Index.html',
    directives: [ROUTER_DIRECTIVES, NgIf],
    viewProviders: [Shell]
})

export class AppComponent {

    public Shell: Shell

    constructor( @Inject(Shell) _shell: any) {
        this.Shell = _shell;
    }
}

and short piece of index view :
<div *ngIf="Shell.loggedIn">
    LOGGED IN!
</div>

and i have a registerview which wants to change loggedin status on successful registration:
@Component({
    templateUrl: './Angular/app/Html/Account/Register.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [AccountService],
    viewProviders: [Shell]
})

export class RegisterView {
    registerForm: any;
    public Shell: Shell
    model = new RegisterVM();
    constructor(private _formBuilder: FormBuilder,
        private _http: Http,
        private _accountSerivce: AccountService,
        @Inject(Shell) _shell: any) {
        this.Shell = _shell
    }

    onSubmit(event: any) {
        this.Shell.Change(true)
    }

As you can see i attempted to make use of dependency injection, but every single time Shell is returned as a new object.
Do i really need to make Shell singleton? or are there any other ways? I am very new to angular2 so i might have overseen some very basic things, please correct me if i messed up anywhere.

A: For this you need to add your Shell service when bootstrapping your application:
bootstrap(AppComponent, [ Shell ]);

And remove it from all viewProviders attribute of your components:
@Component({
    selector: 'my-app',
    providers: [TemplateRef],
    templateUrl: './angular/app/Index.html',
    directives: [ROUTER_DIRECTIVES, NgIf],
    // viewProviders: [Shell] <-------
})

It's because of the way the "hierarchical injectors" feature of Angular2 works. For more details you could have a look at this question:

*

*What's the best way to inject one service into another in angular 2 (Beta)?

A: Indeed you need to make Shell a singleton. You have to add the service in your bootstrap method as a provider.


Q: Custom device to be emulated in chrome device emulator I am building a mobile webapp for a 10.1 inch screen tablet with 1900x1200 resolution. The device is an HP Elitepad 1000
I would like to know how to set chrome to emulate the specifications above.

A: Just press ALT + CMD + I and the Dev.Tools will open.
With SHIFT + CMD + M you switch to the device-emulator.
At "Screen" fill in your resolution. Reload the page for best results.


Q: Spring - Using property-placeholder to load properties file that is outside the war file or the classpath but is in the filesystem I have configured the loading of the properties file as shown below (Spring 3.1)
my-spring-xml
<context:component-scan base-package="com.mypackage"/>
<context:property-placeholder location="file:///C:/temp/application.properties"/>

web.xml
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        /WEB-INF/my-spring-xml
        </param-value>
    </context-param>

application.properties
expirationOffset = 777

In my java class i have declared the property as follows:
private @Value("${expirationOffset}") String propertyValue;

For some reason the value is not being initialised. When i run the following statement:
System.out.println("VALUE - " + propertyValue);

The output is always
16:03:02,355 INFO  [stdout] (http--127.0.0.1-8080-1) VALUE - ${expirationOffset}

I have tried to move the properties file in to the war file to try and access it while it is in the classpath but still the same problem. Here is how i access it from the classpath.
<context:property-placeholder location="classpath:/conf/application.properties"/>

Ideally i would like to keep the properties file outside the war file as i would not want to have to rebuild the war file because of a simple property change.
Have i missed something?
Edit
I removed the msm-spring.xml initialisation paramters from this context:
<context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/my-spring-xml
            </param-value>
        </context-param>

and moved it to the servlet context as shown below.
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>myservice</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/my-spring-xml
            </param-value>
        </init-param>
    </servlet>

The above change seems to have fixed as i am now getting the correct value. I thought the way i had originally was that i had it on the application context meaning that it will be available throughout the application/webapp.
What is the difference in having the msm-spring in the either of 3 i have listed above?

A: This is a bit of speculation based on the information you have provided:
You probably don't have the <context:property-placeholder.. in your Root Web Application context - the one loaded by ContextLoaderListener, instead you may be having it in the web context(loaded by Dispatcher servlet). Can you please confirm this.
Update: Based on the comment, the issue seems to have been that the <context:propert-placeholder.. was defined in the Root Web application context, but being referred to in a component from Web Context.
The fix is to move the propertyplaceholder to the web context (one defined through MessageDispatcherServlet) in this case.

A: EDIT :
Did you try using setter method with #{expirationOffset}  ??
i.e. :
private String propertyValue;
@Value("#{expirationOffset}")
    public void setPropertyValue(String property) {
        propertyValue = property;
    }

Another Option :
Add Properties bean instead of PropertyPlaceConfigurer like this :
<util:properties id="myProps" location="file:///C:/temp/application.properties" />

OR
<util:properties id="myProps" location="classpath:application.properties" />

And Replace Setter with a slight modification as
private String propertyValue;
@Value("#{myProps.expirationOffset}")
    public void setPropertyValue(String property) {
        propertyValue = property;
    }

You'll have to add xmlns:util="http://www.springframework.org/schema/util" to xmlns decalrations and correcsponding http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd to xsi:schemalocation  in your context configuration xml.
This should definitely work.!
Hope it Helps. :)


Q: Is it possible to develop gtalk plugin? I want to develop a simple plugin for gtalk is this possible? Is there api's or tutorial that shows how to do that?
Thanks


Q: Seam App accessing data via an EJB I have to investigate the possibility of using JBoss and Seam to build user interfaces to data held in a database controlled by an off-the-shelf package. I've been reading through some of the Seam documentation, and various other sources, but I can't seem to clear the confusion I'm currently suffering from.
My problem is that everything I've read so far talks about using JPA/Hibernate to access and persist data directly in a database schema, but the package I'm working with doesn't allow (or actively discourages) direct updates to any schema that it controls. It does however present what looks like a comprehensive data-access API delivered as an EJB. With the basic assumption that it's entirely possible, my question is how would I go about building a Seam app that uses this EJB for all data access? Is it a simple thing or am I heading for a whole heap of pain? Can anyone point me in the direction of reading material that will help me?
Apologies in advance for the newbie nature of this question, but I've been dropped in at the deep end on this and I'm struggling to pick up so much new knowledge. Any help will be very gratefully received.
Many  thanks
Steve

A: Seam is mainly an inversion of control (IoC) container that provides a lot of boilerplate functionality for web development. It has no real hard requirements for you to use JPA/Hibernate. It's just that the most usual scenario for Java web development is a database backend that's mapped by an ORM, of which JPA/Hibernate is probably the de-facto standard.
If your data access layer (DAL) does not exist or is just wrapper around an existing API (web services, REST, etc.), Seam will also handle that scenario very easily and provide you with all its remaining functionality (session management, JSF integration, security, navigation flow management and lots more).
In essence, a simple component (or set of) that exposes the API you mention and handles its state should be enough. Then again, I do not know your requirements, so I can't say that for sure.
A more complex example is the Seam Social module in Seam 3. It uses Twitter, Facebook or other social web APIs to connect to those services and inject them into Seam's contexts', so that your application can leverage their functionality. I don't know if your scenario is so complex that it would require you to build an entire CDI module from scratch (as Seam Social does) but take a look at their documentation. It might give you some ideas on what further investigate.


Q: Double integration with a differentiation inside in R I need to integrate the following function where there is a differentiation term inside. Unfortunately, that term is not easily differentiable.
Is this possible to do something like numerical integration to evaluate this in R?

You can assume 30,50,0.5,1,50,30 for l, tau, a, b, F and P respectively.
UPDATE: What I tried
InnerFunc4 <- function(t,x){digamma(gamma(a*t*(LF-LP)*b)/gamma(a*t))*(x-t)}
InnerIntegral4 <- Vectorize(function(x) { integrate(InnerFunc4, 1, x, x = x)$value})
integrate(InnerIntegral4, 30, 80)$value

It shows the following error:
Error in integrate(InnerFunc4, 1, x, x = x) : non-finite function value

UPDATE2:
InnerFunc4 <- function(t,L){digamma(gamma(a*t*(LF-LP)*b)/gamma(a*t))*(L-t)}

t_lower_bound = 0
t_upper_bound = 30
L_lower_bound = 30
L_upper_bound = 80
step_size = 0.5
integral = 0

t <- t_lower_bound + 0.5*step_size
while (t < t_upper_bound){
  L = L_lower_bound + 0.5*step_size
  while (L < L_upper_bound){
    volume = InnerFunc4(t,L)*step_size**2
    integral = integral + volume
    L = L + step_size
  }
  t = t + step_size
}

A: Since It seems that your problem is only the derivative, you can get rid of it by means of partial integration:

Edit
Not applicable solution for lower integration bound 0.


Q: What kind of language should I design for a particle engine scriptable engine? I was wondering which kind of expressiveness fits a language used to generate particle effects..
Supposing to want an engine as flexible as possible what kind of 'features' should it have? (in addition to trivial ones like color, position, velocity, acceleration)

A: Don't try and design a new language just for your application, instead embed another, well-established language in there. Take a look at the mess it has caused for other applications trying to implement their own scripting language (mIRC is a good example). It will mean users will have to learn another language just to script your application. Also, if you design your own language it will probably end up not as useful as other languages. Don't try to reinvent the wheel.
You might want to look at Lua as it is light-weight, popular, well-established, and is designed to be used by games (users of it include EA, Blizzard, Garry's Mod, etc.), and has a very minimal core library (it is designed to be a modular language).

A: SO everybody's urging you not to reinvent the wheel and that's a great idea, I have a soft spot for Python (which would allow your scripting users to also install and use plenty of other useful math libs &c), but LUA's no doubt even easier to integrate (and other scripting languages such as Ruby would also no doubt be just fine). Not writing your own ad-hoc scripting language is excellent advice.
But reading your question suggests to me that your issue is more about -- what attributes of the objects of my engine (and what objects -- particles, sure, but, what else besides) should I expose to whatever scripting language I ember (or, say via MS COM or .NET, to whatever scripting or non-scripting language my users prefer)?
Specific properties of each particle such as those you list are no doubt worthwhile. Do you have anything else in your engine besides point-like particles, such as, say, surfaces and other non-pointlike entities, off which particles might bounce? What about "forces" of attraction or repulsion? Might your particles have angular momentum / spin?
A great idea would be to make your particles' properties "expando", to use a popular term (other object models express the same idea differently) -- depending on the app using your engine, other programmers may decide to add to particles whatever properties they need... maybe mass, say -- maybe electric charge -- maybe cost in eurocents, for all you know or care;-). This makes life easier for your users compared to just offering a "particle ID" (which you should anyway of course;-) for them to use in hash tables or the like to keep track of the specific attributes they care about!  Allowing them to add "methods" and "triggers" (methods that you call automatically if and when certain conditions hold, e.g. two particles get closer than a certain distance) would be awesome, but maybe a bit harder.
Don't forget, BTW, to allow a good method to "snapshot" the current state of the particle system (INCLUDING user-added expando properties) to a named stream or file and restore from such a snapshot -- that's absolutely crucial in many uses.
Going beyond specific particles (and possibly other objects such as surfaces if you have them) you should probably have a "global environment" with its own properties (including expando ones) and ideally methods and triggers too. E.g., a force field acting on all particles depending on their position (and maybe their charge, mass, etc...!-)...
Hope some of these ideas strike you as interesting -- hard for me to tell, with little idea of your intended field of application!-)

A: Just embed Lua.  It's a great language design, excellent performance, widely used by game developers, and small enough that you can master it in a few days.
Then you can get on with your game design.


Q: Share Maven repository ***only one user connected at a time*** We have a bank of virtual machines used by developers to make changes and perform tests of a large suite of projects using Maven for dependency management. Each user has a unique login, so their local .m2/repository folders are separate from one another. I have read that sharing maven repositories is a bad idea due to lack of thread-safety and general lack of concurrent access support.
My question is, is there a reason not to share local maven "repository" folders when only one user at a time will be using them? The limitation is a limitation of the host operating system - it is not possible for two users to log in to these machines simultaneously.


Q: How to adjustsFontSizeToFitWidth to UIButton label ? ios when i set adjustsFontSizeToFitWidth to the button UILabel, the text go out side of the button frame, I don't know why ?
here is my code:
            shareBtn = UIButton()

            shareBtn.setTitle(IconsConstants.share, forState: UIControlState.Normal)
            shareBtn.titleLabel?.font = UIFont.iconmoonFont(100)
            shareBtn.titleLabel?.adjustsFontSizeToFitWidth = true;
            shareBtn.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
            shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center

            //EdgeInsets

            shareBtn.contentEdgeInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

and here is the result:

A: for single line set
shareBtn.titleLabel?.adjustsFontSizeToFitWidth = YES;

instead of this
factLabel.adjustsFontSizeToFitWidth = true;

for multiple line us use
actLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);


Q: How do i change the clicked button Currently i have 3 buttons with names start_btn , about_btn and stats_btn which are movieClips.All 3 of them are in a container (also a movieClip) with the name of group_btn.So my question is how do i tell the exact element to change its ScaleX and ScaleY when im using only one MouseEventListener for all 3 of them.
I did figure that ill have to detect which one is clicked but then ,after that i dont know what to do .
so i have this code so far :
private function onAddedToStage(eve:Event):void {
        trace("we are good to go");
        this.group_btn.start_btn.addEventListener(MouseEvent.MOUSE_OVER, makeButtonBigger)
        this.group_btn.start_btn.addEventListener(MouseEvent.MOUSE_OUT, makeButtonSmaller)
        this.group_btn.about_btn.addEventListener(MouseEvent.MOUSE_OVER, makeButtonBigger)
        this.group_btn.about_btn.addEventListener(MouseEvent.MOUSE_OUT, makeButtonSmaller)
        this.group_btn.stats_btn.addEventListener(MouseEvent.MOUSE_OVER, makeButtonBigger)
        this.group_btn.start_btn.addEventListener(MouseEvent.MOUSE_OUT, makeButtonSmaller)

    }

private function makeButtonBigger(ev:MouseEvent):void{
        var nameOfButton:String = ev.currentTarget.name;
        //this.group_btn.nameOfButton.scaleX = 1.2  <--- doesnt work
        trace(nameOfButton)

    }

A: You need to access the property using square brackets; the way you have it is implying that there's a button that's literally called 'nameOfButton', which is why it's failing. Try the following:
private function makeButtonBigger(ev:MouseEvent):void{
    var nameOfButton:String = ev.currentTarget.name;
    this.group_btn[nameOfButton].scaleX = 1.2;
    trace(nameOfButton);
}

That will use the actual captured string, rather than the variable name itself.
Although, you can also access the button directly from the event's currentTarget property:
private function makeButtonBigger(ev:MouseEvent):void{
    ev.currentTarget.scaleX = 1.2;
}


Q: How to call loadmore function(only once) on scroll down javascript function? i am using the following code to trigger my onloadmore funciton when user scroll down and reaches bottom of page. But i notice that many times the function get called multiple times on scroll down! could any one tell me why loadmore function get called more then once for same set of data! is it internet connection problem ? I just want loadmore called only once!
     <script>
var nextTagId = null;
       function callLoadMore() {

               $.ajax({
                type: "GET",

                dataType: "jsonp",

                cache: false,

                url: "http://api.sometime.com/api.php?count=100" + ( nextTagId ? "&next_id=" + nextTagId : ""),

        success: function(data) {

         for (var i = 0; i < 100; i++) {

                    document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].pics.standard.path+'\n' ;

                    }
                }

            });

        }
    </script>
<script>
        $(function() {
            $(window).bind("scroll", function (){
                console.log("SCROLL : " + $(window).scrollTop()
                    + " - " + $(window).innerHeight()
                    + " - " + document.body.clientHeight);
                if ($(window).scrollTop() + document.body.clientHeight >= $(window).innerHeight()) {
                            //alert('Bottom!');

                               callLoadMore();

                }
            });
        });
</script>


Q: How to plot ROC-AUC figures without using scikit-learn I have the following list containing multiple tuples of (TP, FP, FN):
[(12, 0, 0), (5, 2, 2), (10, 0, 1), (7, 1, 1), (13, 0, 0), (7, 2, 2), (11, 0, 2)]

each tuple represents the scores for a single image. This means I have 7 images and I have calculated the scores for a object detection task. Now I calculate precision and recall for each image(tuple) using the following function:
def calculate_recall_precision(data):
    precisions_bundle = []
    recalls_bundle = []

    for tp, fp, fn in data:
        precision = tp / (tp + fp)
        recall = tp / (tp + fn)
        precisions_bundle.append(precision)
        recalls_bundle.append(recall)

    return (precisions_bundle, recalls_bundle)

This function returns a tuple which contains two lists. The first one is precision values for each image and the second one is recall values for each image.
Now my main goal is to plot ROC and AUC curves using only matplotlib. Please note that I do not want to use scikit-learn library.

A: You can simply use matplotlib.pyplot.plot method. For example:
import numpy as np
import matplotlib.pyplot as plt

def plot_PR(precision_bundle, recall_bundle, save_path:Path=None):
    line = plt.plot(recall_bundle, precision_bundle, linewidth=2, markersize=6)
    line = plt.title('Precision/Recall curve', size =18, weight='bold')
    line = plt.ylabel('Precision', size=15)
    line = plt.xlabel('Recall', size=15 )

    random_classifier_line_x = np.linspace(0, 1, 10)
    random_classifier_line_y = np.linspace(1, 0, 10)
    _ = plt.plot(random_classifier_line_x, random_classifier_line_y, color='firebrick', linestyle='--')
    if save_path:
        outname = save_path / 'PR_curve_thresh_opt.png'
        _ = plt.savefig(outname, dpi = 100, bbox_inches='tight' )
    return line

and then just use it as plot_PR(precision_bundle, recall_bundle).
Note: here I also added a dashed line for a random classifier and the possibility to save the figure in case you want to


Q: Avoid adding NSWindowWillEnterFullScreenNotification in OS version prior Lion(On Leopard or Snow Leopard) How can I avoid adding NSWindowWillEnterFullScreenNotification in OS version prior to 10.7  because it is only available in OS 10.7 or above and I want to use this notification in above 10.7 but my application got crashed if I run it on prior OS version.
I have check the crash log and it was saying that
Symbol not found NSWindowWillEnterFullScreenNotification
Right now I am checking the OS version using this
   if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_5) {
    /* On a 10.5.x or earlier system */
}
else if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_6) {
    /* On a 10.6 - 10.6.x system */
}  else  {
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(willEnterFull:)
                                                 name:NSWindowWillEnterFullScreenNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didExitFull:)
                                                 name:NSWindowDidExitFullScreenNotification
                                               object:nil];
    }

But app got crashed in prior version as soon as it get launched.
Here is the crash log although I have change the app name to XYZ in the log due to NDA
Process:         XYZ [53319]
Path:            /Applications/XYZ.app/Contents/MacOS/XYZ
Identifier:      com.XYZ.XYZ
Version:         2.0.5 (2.0.5)
Code Type:       X86 (Native)
Parent Process:  launchd [224]

Date/Time:       2012-10-28 07:44:11.717 -0500
OS Version:      Mac OS X 10.6.8 (10K549)
Report Version:  6

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000
Crashed Thread:  0

Dyld Error Message:
  Symbol not found: _NSWindowDidExitFullScreenNotification
  Referenced from: /Applications/XYZ.app/Contents/MacOS/XYZ
  Expected in: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit
 in /Applications/XYZ.app/Contents/MacOS/XYZ

A: Here's what I think happens. The crash happens already in the linker, because it expects NSWindowDidExitFullScreenNotification to exist, but it doesn't in older versions of os x.
I haven't got any experience in this. The solutions seem to be kind of hacky.
Have a look at this question, where someone has an almost exact same question:
How to build a backwards compatible OS X app, when a new API is present?


Q: Error - "Cannot invoke "org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence[])" because "this.UserName" is null I am a newbie in Java and Selenium.
Below are my java classes for POM, Driver Utilites and Test Case.
When I run the Test Case as TestNG test, I have :
FAILED: verifyLogin
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence[])" because "this.userName" is null.
Please help me out. Let me know if further info is needed.
Thanks in advance.
<----------------------------------------POM-------------------------------------------------->
package com.inetBankingV1.pageObjects;

import org.openqa.selenium.WebDriver;

import com.inetBankingV1.utilities.callBrowserDriver;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginPage {

    WebDriver driver;

    @FindBy(how=How.LINK_TEXT, using="Log in")
    WebElement logUser;

    @FindBy(how=How.NAME, using="username")
    WebElement userName;

    @FindBy(how=How.NAME, using="password")
    WebElement passWord;

    //constructor
    public LoginPage(WebDriver driver)
    {
        this.driver=driver;
    }

    public  void loginCheck(String uname,String passwd)
    {
        userName.sendKeys(uname);
        passWord.sendKeys(passwd);
        logUser.click();
    }

}

<----------------------------------------Driver------------------------------------------------>
    package com.inetBankingV1.utilities;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class callBrowserDriver {

    public WebDriver startApplication(String browser, String baseURL, WebDriver driver)

    {

    if(browser.equalsIgnoreCase("firefox"))
            {
        System.setProperty("webdriver.gecko.driver", "./Drivers/geckodriver.exe");
        FirefoxOptions firefoxOptions = new FirefoxOptions();
        firefoxOptions.setCapability("marionette", true);
         driver = new FirefoxDriver(firefoxOptions);

            }

    if(browser.equalsIgnoreCase("chrome"))
            {
        System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
        driver=new ChromeDriver();
            }

    driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.navigate().to(baseURL);

    return driver;

}

}

<--------------------------------------Test Case----------------------------------------------->
    package com.inetBankingV1.testCases;

import com.inetBankingV1.utilities.callBrowserDriver;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

import com.inetBankingV1.pageObjects.LoginPage;

public class TC2_VerifyLogin {

    WebDriver driver;
    callBrowserDriver browserDriver=new callBrowserDriver();

    @Test
    public void verifyLogin()
    {

        driver=browserDriver.startApplication("chrome","https://demosite.com/",this.driver);
        LoginPage login=new LoginPage(driver);

    login.loginCheck("admin","Password");
    }
}

A: See if this works:-
 @FindBy(how=How.ID, using="inline-search-submit")
 WebElement logUser;

 @FindBy(how=How.NAME, using="user")
 WebElement userName;

 @FindBy(how=How.NAME, using="pass")
 WebElement passWord;

A: The issue is resolved after initialising the webelements of the POM class using initElements:
LoginPage login=PageFactory.initElements(driver, LoginPage.class);

A: Use below line in your constructor
PageFactory.initElements( driver, this);

----------------------------------------------

public LoginPage(WebDriver driver)
    {
        this.driver=driver;
        PageFactory.initElements( driver, this);
    }

This should solve your problem.


Q: How to display message if user clicks on browser button? My question is it possible to display a message if browser buttons have been pressed in order to be able to display a message stating if user should leave the page or stay on a page? Also can a message be displayed if user tries to change a url if they are on a certain page?
Thanks

A: *

*Server side is needed for foolproofing this. On the server, when assessment is started, you should first have start screen URL. You must program it so that once assessment is started (after clicking start), it goes to the exam URL, and your assessment is always saved - when user goes back, using server side tricks have it so that instead of showing the start screen, it redirects back to the correct page (in a way that still maintains history), shows the exam with the data still in it, and pops up the warning not to click back button.  Then, if user does it again, it does the same thing, again.

*You have to have it so the exam is saved all the time. unload javascript event can be used to notify via alert() that they shouldn't be leaving the exam, and thats about all. onbeforeunload event can be used to try to give them the choice to stay, but shouldn't be depended on as it doesn't work on every browser.

A: Use onbeforeunload as suggested in a comment. There are various example, like this one: https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm
If you want to call out the buttons that the user must click, you will need to do some browser detection, as most browsers have OK/Cancel buttons on the window that they display, but Chrome has "Leave this page" and "Stay on this page".


Q: TCP Server Applet I have an open Social container and I need to put an applet in that container, the applet is required to act as a tcpServer, I need some guidence how can I do this?

A: The networking tutorial explains, in full detail, how to create a TCP server socket and accept connections from it.
Here's the gist of it:
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 4444.");
        System.exit(1);
    }

    Socket clientSocket = null;
    try {
        clientSocket = serverSocket.accept();
    } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
    }

    // now get the input and output streams from the client socket
    // and use them  to read and write to the TCP connection

    clientSocket.close();
    serverSocket.close();


Q: How to get Current balance of each user from a bunch of transactions in MongoDB using NodeJS? Im using Node.js with Mongoose to Store data in MongoDB.
I need to show a list of all the users with their current available balance.
I tried using multiple for loops, but I kept getting errors somewhere or the other. I'm able to show the list of unique users, but summation of their balance is incorrect.
I felt I was doing it the wrong way.
Could someone suggest a good way to get my required output with lesser and pretty code?
Current Data in My Database:
ID    Name    Amount    Credit
1     Andy     500       true
2     Andy    1000       false
3     Tina     400       false
4     John     700       true
5     Tina    2000       true
6     Andy     100       true
7     Tina     200       false
8     John     300       false

Required Final Output
 ID    Name   Balance
 1     Andy    -400
 2     Tina    1400
 3     John     400

What I have tried till now:
    Accounts.find({}).exec(function (err, transList) {

          var finalArr= [];

          var currentAmount = 0;
          for(var i=0; i<transList.length; i++)
          {

                    if(transList[i].status===true) // Credited
                     {
                           currentAmount = currentAmount + transList[i].amount;
                     }
                     else // Debited
                     {
                           currentAmount = currentAmount - transList[i].amount;
                     }
                if(i===0)
                {

                }
                else if (i===transList.length-1)
                {

                      var obj  = {};
                      obj._id  = transList[i]._id;
                      obj.name  = transList[i].name;
                      obj.amount = currentAmount;
                      finalArr.push(obj);
                }
                else
                {
                   if(transList[i].student._id!=transList[i-1].student._id)
                   {

                      var obj  = {};
                      obj._id  = transList[i-1]._id;
                      obj.name  = transList[i-1].name;
                      obj.amount = currentAmount;
                      finalArr.push(obj);
                      currentAmount = 0;
                   }
                                       }
          }

          data = JSON.stringify({list:finalArr});
          res.end(data);

        });


Q: What is the testability problems of window in javascripts which is solved in $windows in Angular JS As a novice start to learn angular js and with a weak javascript background, could someone give some more illustrative examples and explain further what is the idea/purpose behind the $window, a built-in service in AngularJS?
what is the below mentioned global problem for testing?
Thanks
Reading a book "AngularJS up and running", but do not understand its explanation:

The $window service in AngularJS is nothing but a wrapper around the global window object. The sole reason for its existence is to avoid global state, especially in tests. Instead of directly working with the window object, we can ask for and work with $window. In the unit tests, the $window service can be easily mocked out (available for free with the AngularJS mocking library).

and then visit official documentation of AngularJS:
https://docs.angularjs.org/API/ng/service/$window

A reference to the browser's window object. While the window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Mark bold and italic for the concepts/words that I do not understand.


Q: Function calls in smart contract from script and checking value of variables I am currently using Brownie to learn smart contract and blockchain development. I am having trouble understanding how to call functions and check value of variables from smart contracts using python script. How would I be able to do this?
Below I have a contract DutchAuction where I have defined a function bid() which returns 'Hello world' just for testing purposes that I am trying to call.
pragma solidity ^0.8.10;

import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";

contract DutchAuction {

    uint public startTime;
    uint public endTime;

    uint public price;
    uint public startPrice;

    address public assetOwner;

    constructor(uint _startPrice, uint _endTime) public {
        startTime = block.timestamp;
        price = _startPrice;
        startPrice = _startPrice;
        endTime = _endTime;
        assetOwner = msg.sender;

    }

    function bid() public returns (string calldata) {
        return 'hello world';

    }

}

A: Change the string calldata to string memory in your bid() function returns statement.
The string literal is loaded to memory (not to calldata) and then returned.
If you wanted to return calldata, you'd need to pass the value as calldata first:
function foo(string calldata _str) public pure returns (string calldata) {
    return _str;
}

Docs: https://docs.soliditylang.org/en/v0.8.10/types.html#data-location


Q: Git - Weirdness when using .gitattributes to force consistent line endings So, I've recently added a .gitattributes file to one of our repositories to try to force consistent line endings:
  # All Perl Sources should use Unix style line endings
  *.pl text eol=lf
  *.pm text eol=lf

But both myself and a lot of other developers are encountering a lot of "phantom changes" where git seems to detect the file as "changed" even though there's no change. Every line shows up as added, then deleted.
I suspect it's getting confused about line endings (and thus detecting each line as changed), but what's weird here is:

*

*I can't reset the file (the reset is completed, but the file remains as an unstaged change)

*Changing the line endings in the affected text file does not affect whether it shows up as a changed file.

Has anyone encountered this before, and is there a way to avoid or resolve this issue?

A: With Git 2.16 or more, do at least once:
git add --renormalize .
git commit -m "normalize eol files"
git push

Then try and clone your repo elsewhere, and check that git status behaves as expected.
Make sure you don't have core.autocrlf set to true.
git config core.autocrlf

And you can test for your files eol style.


Q: ios adding a collectionView inside UITableView's header view I've an UICollectionView inside the headerView of my UITableView which is made in other xib file (custom view) . So my question is, should I declare delegate methods on the same class I've declared my tableView or on the custom view which is header of tableView? Which is more convenient?

A: Define the delegates of UITableView & UICollectionView in same controller, set there delegates to the same class as
self.mytableview.delegate = self;
self.mycollectionview.delegate = self;

You can follow this tutorial, Putting a UICollectionView in a UITableViewCell


Q: Subscript indices must either be real positive integers or logicals with interp2 What does the error "Subscript indices must either be real positive integers or logicals" means when using interp2.  X,Y,Z,XI,YI are all vectors of the same length.

A: It means that you trying to access an element in an array by using index as number with decimal point or a negative number, or maybe even using a string that looks like a number e.g. "2".
The only way to access the elements is by using positive integer OR logical (0 or 1).
array = [1 2 3 4 5 6];
array(4)    # returns 4th element of the array, 4.
mask = array > 3; # creates a mask of 0's and 1's (logicals).
array(mask) # return elements greater than 3, 4 5 6.

BUT you can't do:
array(2.0)

Or anything else other than positive integer or logical.
Alex


Q: Using Nokogiri to search through XML file based on user input in Rails app So I've got an XML file (XML file) with a schema (XML schema).
I'm trying to create a quick Rails app to allow users to search through the XML file based on the 'lastName" element that are children of an sdnEntry element.
I don't have any problems setting up the rails app, or the search-form. I was also able to get the XML file loaded using Nokogiri and can run simple commands like...
xmldoc.css("lastName")

...to return a NodeSet with all the 'lastName' elements in them. Unfortunately, that's not good enough, since that lists not just the 'lastName' elements directly underneath an 'sdnEntry' element. Plus that doesn't even get me started to insert the user's input from the form. I was thinking something like this would work...
xmldoc.xpath("/xmlns:sdnList/sdnEntry/lastName[text()='#{param[:name]}']")

...but that didn't work. Oddly, I couldn't even get...
xmldoc.xpath("/xmlns:sdnList/sdnEntry/lastName")

...to work. I just don't know enough about Nokogiri or XPath or CSS queries for XML documents to figure out how to pass the param from user-input form to create the appropriate query that will return the right info for me.
I tried looking through the Nokogiri Documentation and the W3Schools XPath Tutorial. No joy.
I would really appreciate any pointers, code snippets or suggestions. Thank you.

A: Your issue is with the XPath that Nokogiri is using.  You need to specify what the namespace is in attributes.  More info at the Nokogiri documentation.
Here is an example for looking up an item, using your params will probably work as well.
doc = Nokogiri::XML(File.read("sdn.xml"))
doc.xpath("//sd:lastName[text()='INVERSIONES EL PROGRESO S.A.']", "sd"=>"http://tempuri.org/sdnList.xsd")

>> [#<Nokogiri::XML::Element:0x80b35350 name="lastName" namespace=#<Nokogiri::XML::Namespace:0x80b44c4c href="http://tempuri.org/sdnList.xsd"> children=[#<Nokogiri::XML::Text:0x80b34e3c "INVERSIONES EL PROGRESO S.A.">]>]

A: user_input = "CHOMBO"                # However you are getting it
doc = Nokogiri.XML(myxml,&:noblanks) # However you are getting it
doc.remove_namespaces!               # Simplify your life, if you're just reading

# Find all sdnEntry elements with a lastName element with specific value
sdnEntries = doc.xpath("/sdnList/sdnEntry[lastName[text()='#{user_input}']]")

sdnEntries.each do |sdnEntry|
  p [
    sdnEntry.at_xpath('uid/text()').content, # You can get a text node's contents
    sdnEntry.at_xpath('firstName').text      # …or get an element's text
  ]
end
#=> ["7491", "Ignatius Morgan"]
#=> ["9433", "Marian"]
#=> ["9502", "Ever"]

Instead of requiring the exact text value, you might also be interested in the XPath functions contains() or starts-with().


Q: Copy 12MB folder with 2500 files from assets to sd card quickly I'm trying to copy a large number of folders and subfolders from my apk asset folder to my sd card quickly. the folders contain 12mb of small files, probably 2500 total. The code example from this SO question works but it takes over 5 minutes on my device. Is there a faster way to do this?
I originally tried adding the folder to a zip archive and unzipping it after it was moved onto the device but it created to many problems on different devices and was failing a lot throughout the process.

A: 12mb should save a bit faster that, if you are using the methods from the other SO question, try increasing the buffer size in copyFile like so,
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[8192]; // 1024 is kind small,..try 8192 or 4096!!
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

A: I've had very good, consistent results with creating a zip file, putting it in raw or assets in my app, and unzipping it when the user first opens the app. I'd recommend you give it another shot, as I've been impressed that I've seen zero issues with hundreds of installs.
The tutorials I based the helper methods to zip and unzip files are here:
Unzipping Files w/ Android, and
Zipping Files w/ Android
It should be noted that I used the Java API to create the zip that I include with the install of my app. That might be why I had such consistent results unzipping them as well, using the Java API in Android.
Hope this helps! Best of luck!


Q: Using Emacs server and emacsclient on other machines as other users I know that after I call (start-server) inside an existing Emacs session I can then use emacsclient -c (on the same computer) to create new frames that connect into that server, so that each new frame created by emacsclient has access to the same set of shared state (e.g. buffers).
Most of the documentation I've found focuses on the "give me fast access to my local Emacs" use case, and so there are two things that I haven't seen any details of yet:

*

*Can emacsclient -c access Emacs servers started by other users, or is it hard-wired to detect only sessions started by my own user?

*Does Emacs server (directly or indirectly) support remote connections?  That is, is there some way to set up Emacs (possibly involving SSH) that allows calls to emacsclient -c on remote machines to have access to the local state of my Emacs server?
(In case you haven't already guessed, what I'd ultimately like to do is combine the two techniques above to provide rudimentary collaborative editing support.)

This is a real-world problem, so here's what I'm working with:

*

*The necessary functionality should be built into Emacs already (23.3.1, 64-bit).  I can stretch to Emacs extensions from the standard Ubuntu repositories, but I'd prefer not to.  (Which I believe rules out Rudel, sadly.)

*No new users or user spoofing.  Solutions should work with the existing set of user accounts, and users must not pretend to be other users (e.g. via su or ssh).

If it makes any difference, the machines are on a private LAN, have OpenSSH clients and servers installed (and running), and all users can connect to (their own account on) all machines, but they have no shared filesystem.

So, does anybody know whether Emacs server can

*

*grant access to other users, or

*provide remote access?

EDIT
As commented in rwb's answer, it's clear that the new windows being opened locally by running emacsclient -c are actually being created by the remote Emacs server process.  That is, emacsclient is simply triggering the relevant behaviour in the server.  This causes some issues with incorrect display settings, since the server does not normally have access to the local desktop (see below).  However, I can now connect in to a remote Emacs session if I use the following sequence of commands:
In one terminal, where 1.22.333.44 is the IP address of remotehost:
ssh -t -X remotehost \
  "emacs -nw --eval
   '(progn (setq server-host \"1.22.333.44\" server-use-tcp t) (server-start))'"

Then in another (on the same machine):
scp remotehost:.emacs.d/server/server /tmp/server-file
DISPLAY=localhost:10 emacsclient -c -f /tmp/server-file

The emacsclient command causes the remote Emacs server (which it finds details of in /tmp/server-file) to open up a graphical Emacs window (on the local display) that shares state with the Emacs session on the remote host.
Since the remote Emacs server was started via ssh -X, SSH provides it with access to my local display via a "fake" :10 display.  The DISPLAY=:10 passed to it (via emacsclient) thus causes a window to be opened on my local desktop.

Although the approach above does tick the "Run Emacs server on remote machine, connect to it using emacsclient locally" box, it's very limited.  In fact, it's not much different to running the server and clients all locally as a single user: the only difference is that the server is now remote, so has access to different system resources.
Unfortunately, launching via ssh -X is the only way I've been able to successfully open a window on a different machine's X server:

*

*Specifying a basic DISPLAY=remote:0 gets nowhere (since Ubuntu X servers are started with the -nolisten tcp option).

*Connecting via SSH and then using DISPLAY=:0 also fails, but this time only due to lack of suitable authentication credentials.  (I believe that's the case, anyway: the error message cryptically says No protocol specified / Can't open display.)
I think that finding a way around the second problem would probably get me a good deal closer to a solution.

Having read the posts at http://comments.gmane.org/gmane.emacs.devel/103350 (starting at the '25 Oct 14:50' post, about half way down) I'm starting to wonder if this might be one of the rare things that Emacs cannot do (i.e. is impossible ;-) ).
However, if anyone does have a way to provide access to remote X displays without the permissions error above, I'm still open to persuasion....
TL;DR
As pointed out by rwb's answer, my questions above about whether Emacs can grant remote access have got things backwards.  There's no real problem with Emacs granting access to other users (server-use-tcp and a suitable server-file take care of this): rather the problem is how to allow a process on one machine to open new X windows on other users' X displays (specifically, the Emacs running (start-server) needs to open windows for users who ask it to via emacsclient -c).  That answer's beyond the scope of this question.
Alternative solution
As a workaround, we use the following:

*

*machine0: tmux -S /tmp/shared-tmux-socket new-session

*machine1..machineN: ssh -t machine0 tmux -S /tmp/shared-tmux-socket attach
with suitable file permissions on /tmp/shared-tmux-socket.
Then we run a text-mode Emacs in the shared terminal. :-)  This does raise some user-spoofing questions, but at least the host can see everything that the guests are doing.

A: Aaron Gallagher implemented a solution: http://blog.habnab.it/blog/2013/06/25/emacsclient-and-tramp/
It works (AFAIU) like:

*

*emacs server is started with tcp

*He opens a connection to a remote system with tramp-sh, opening a forward port ("back channel")

*tramp-sh is advised to copy an extended auth cookie file to the remote system

*On the remote system he calls a special emacsclient.sh shell script that emulates emacsclient but prefixes the file names with the corresponding tramp prefix that is found in the extended auth cookie

I've added a comment to his blog post proposing this idea to be discussed and enhanced on emacs-devel.

A: If you are doing this to enable people to remotely edit files you may want to look at 'tramp mode'
http://emacswiki.org/emacs/TrampMode

A: This should provide a starting point for what you want.
From the info node (emacs) emacsclient Options
`--server-file=SERVER-FILE'
     Specify a "server file" for connecting to an Emacs server via TCP.

     An Emacs server usually uses an operating system feature called a
     "local socket" to listen for connections.  Some operating systems,
     such as Microsoft Windows, do not support local sockets; in that
     case, Emacs uses TCP instead.  When you start the Emacs server,
     Emacs creates a server file containing some TCP information that
     `emacsclient' needs for making the connection.  By default, the
     server file is in `~/.emacs.d/server/'.  On Microsoft Windows, if
     `emacsclient' does not find the server file there, it looks in the
     `.emacs.d/server/' subdirectory of the directory pointed to by the
     `APPDATA' environment variable.  You can tell `emacsclient' to use
     a specific server file with the `-f' or `--server-file' option, or
     by setting the `EMACS_SERVER_FILE' environment variable.

     Even if local sockets are available, you can tell Emacs to use TCP
     by setting the variable `server-use-tcp' to `t'.  One advantage of
     TCP is that the server can accept connections from remote machines.
     For this to work, you must (i) set the variable `server-host' to
     the hostname or IP address of the machine on which the Emacs server
     runs, and (ii) provide `emacsclient' with the server file.  (One
     convenient way to do the latter is to put the server file on a
     networked file system such as NFS.)

You also may want to look at variables server-auth-dir, server-auth-key and server-port

A: I think what you're asking for is impossible by definition, because if you give a remote user unrestricted access to your Emacs, this is just as much "user spoofing" as letting that remote user access a shell via ssh.  To spell it out, from a security point of view this is probably a bad idea.
Also, the results of letting two users access one Emacs aren't as good as you might hope.  It isn't designed with simultaneous access in mind.  It's years since I tried it, so things might have moved on a bit, but when I did it was quirky to say the least.
Still, I'll try to answer your question.
It sounds like you're thinking about this back-to-front, because, counter-intuitively, in network terms, the X11 display is the server, and the X11 application is the client.  This is surprising because typically the display is local to the user and the application is running on some remote server.
You can instruct a running emacs to connect to a remote display and open a new window with M-x make-frame-on-display.  For this to work, the owner of that display will need to grant you access to it.
We will assume host-l is the computer that is running Emacs, and that you want to make it accessible to a user of display 0 on host-r.  Be aware that you've said you don't want to use SSH forwarding, so following this method will cause all traffic will go across the network unencrypted.
First, make sure that display host-r:0 is accepting TCP connections.  You don't mention your operating system, but this is probably the default on Unix and probably isn't on Linux (for security reasons).  If, for example, the following mentions -nolisten tcp then you'll need to change this configuration.
host-r$ ps -ef | grep X

Next, get the user of host-r to run the following, and send you the output.  Be sure to warn them that this will allow you to take complete control of their current desktop session, should you choose.
host-r$ xauth list $DISPLAY
host-r/unix:0  MIT-MAGIC-COOKIE-1  01234567890abcdef0123456789abcd

This is, effectively, the "password" for the display.  On host-l, put it where Emacs will be able to find it with:
host-l$ xauth add host-r:0 MIT-MAGIC-COOKIE-1  01234567890abcdef0123456789abcd

Now enter M-x make-frame-on-display host-r:0 and an Emacs window should pop up on the remote display.


Q: SAP UI5: Re-align simple form label and fields to left side I need to move all these highlighted elements to left side of the page(Screen attached). Below is the code for simple form in my xml view:
<---XML View--->

<f:SimpleForm id="SimpleFormDisplay354" minWidth="1024" maxContainerCols="3" editable="false" layout="ResponsiveGridLayout"
    title="{i18n>searchFormTitle}" labelSpanL="3" labelSpanM="3" emptySpanL="4" emptySpanM="4" columnsL="1" columnsM="1">
    <f:content>
     <Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" >
      <layoutData>
       <l:GridData span="L2 M3 S6"/>
      </layoutData>
     </Label>
     <DatePicker id="datePickerId" visible="true" displayFormat="MMM dd,yyyy" valueFormat="dd-MM-yyyy" placeholder="{i18n>dateInput}"
      change="handleChange">
      <layoutData>
       <l:GridData span="L2 M3 S6"/>
      </layoutData>
     </DatePicker>
     <Button text="{i18n>search}" id="searchButton" width="50%" type="Emphasized" class="Button" press="OnDateSearch">
      <layoutData>
       <l:GridData span="L2 M3 S6"/>
      </layoutData>
     </Button>
    </f:content>
   </f:SimpleForm>

Can anyone help me with what GridData span setting I should make in order to move these elements to left most corner?
enter image description here

A: If you want to use the existing properties for the Grid Data, you can use indentL property.
<Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" >
    <layoutData>
        <l:GridData span="L1 M3 S6" indentL="0"/>
    </layoutData>
</Label>

Give one column (out of 12) to your label and then indent it to 0 (span value=0 for the Large screen), similarly, you can do it for different screen sizes.

A: You have to set labelSpanL/labelSpanM to 1 or 2 to decrease left space, but SimpleForm always align the label to right and put colon ":" between Label and Control.
If labelSpan 1 or 2 dont resolve. The only way i know is trying use CSS.


Q: OpenShift - no awt in java.library.path I use Openshift for a small app.
In this app, I upload images and resize them and stores them in a database.
I use: BufferedImage bufferedImage = ImageIO.read(inputStream);
But today when I run this part of code I got this exception:
java.lang.UnsatisfiedLinkError: no awt in java.library.path
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)
java.lang.Runtime.loadLibrary0(Runtime.java:849)
java.lang.System.loadLibrary(System.java:1088)
sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:67)
sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:47)
java.security.AccessController.doPrivileged(Native Method)
java.awt.Toolkit.loadLibraries(Toolkit.java:1657)

...
I do not know if the OpenShift team has done any upgrade lately. Last time I run that code was perhaps 6 months ago.
Do you guys have any solution?
Best regards
Fredrik

A: A rebuild, a redeploy and a restart solved the problem.
Really strange.
To me this sounds like a system thing and would not have to do with the app itself.
Best regards
Fredrik


Q: Splitting one table into multiple tables based on columns using velocity Ok below is the code that i have. Here we read a map from a JAVA object and populate columns based on the key and values of the map. The Java object map is of the form
HashMap<HashMap<String, Object>>.
The required table will have columns equal to number of outer hashmap. The row count will be equal to number of Sting/Objects in the inner hashmap.
Following is the code which generates table. As described above, the number of columns in the table will depend on the values in the java object. The problem we are facing is, if the value in hashmap is above 10 then PDH generation resuls in loss of data.

     #set ($allLegs = $ConfirmationObject.getAllLegs())
     #set ($i = 1)

           #foreach($legSzie in $allLegs.keySet())
               Leg $i
               #set ($i=$i+1)
           #end

             #set ($map = $ConfirmationObject.getLegMap(1))
             #foreach($key in $map.keySet())

                     $key

             #end

     #foreach($legString in $allLegs.keySet())

                #set ($legMap = $allLegs.get($legString))
                #foreach($legKey in $legMap.keySet())

                       $legMap.get($legKey)

                #end

     #end

Expectation:
Is it possible to have the data split into different tables when ever the column value reaches more than 3?
so for example consider a scenario where the table looks like
            LEG 1        LEG 2       LEG 3        LEG 4       LEG 5
A           12           13          14           15          16
B           12           13          14           15          16
C           12           13          14           15          16
D           12           13          14           15          16
E           12           13          14           15          16

How can we split this like
            LEG 1        LEG 2       LEG 3
A           12           13          14
B           12           13          14
C           12           13          14
D           12           13          14
E           12           13          14

            LEG 4        LEG 5
A           15           16
B           15           16
C           15           16
D           15           16
E           15           16

A: You could try something like that:
#set ($columns = $allLegs.keySet().toArray())
#set ($maxCols = 3)
#set ($groups = ($columns.size() + $maxCols - 1)/$maxCols)
#set ($lastGroup = $groups - 1)
#foreach ($group in [0..$lastGroup])

    #set ($firstCol = $maxCols*$group )
    #set ($lastCol = $firstCol + $maxCols - 1)
    #if ($lastCol >= $columns.size())
       #set ($lastCol = $columns.size() - 1)
    #end

    #foreach ($col in [$firstCol..$lastCol])
            $columns[$col]
    #end

    #set ($rows = $allLegs.get($columns[$firstCol]).keySet())
    #foreach($row in $rows)

            $row
    #foreach ($col in [$firstCol..$lastCol])
        #set ($legMap = $allLegs.get($columns[$col]))
            $legMap.get($row)
    #end

     #end

#end

A:     #set ($allLegs = $ConfirmationObject.getAllLegs())
    #set ($columns = $allLegs.keySet())
    #set ($maxCols = 3)
    #set ($groups = ($columns.size() + $maxCols - 1)/$maxCols)
    #set ($lastGroup = $groups - 1)

    #foreach ($group in [0..$lastGroup])
    #if($group >0 )

    #end

     #set ($allLegs = $ConfirmationObject.getAllLegs())
     #set ($i = (($group*$maxCols)+1))
     #set ($groupLegs = $ConfirmationObject.getGrouplLegSet($group, $maxCols))

       #foreach($legSzie in $groupLegs.keySet())
        Leg $i
         #set ($i=$i+1)
       #end

       #set ($map = $ConfirmationObject.getLegMap(1))
       #foreach($key in $map.keySet())

         $key

       #end

     #foreach($legString in $groupLegs.keySet())

       #set ($legMap = $allLegs.get($legString))
       #foreach($legKey in $legMap.keySet())

         $legMap.get($legKey)

       #end

   #end

 #end

Here we wrote a java method getGrouplLegSet($group, $maxCols). The method would just return sub-set of hashmap based on the group and maxCols. So for example if the group is 0 then values from 0 till 2 will be returned, if group value is 1 then sub map from 3 till 5 will be returned and so on..


Q: log4j2 filePattern doesn't interpolate I've tried to add the following RollingFile appender;
    <RollingFile name="appFile" fileName="${sys:catalina.base}${sys:file.separator}logs${sys:file.separator}${web:contextPath}${sys:file.separator}app.log" filePattern="app-%d{dd-MM-yyyy}.log">
        <PatternLayout pattern="%d{dd/MM/yyyy HH:mm:ss} %c{2} - %m%n" />
        <Policies>
            <TimeBasedTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="250 MB" />
        </Policies>
        <DefaultRolloverStrategy max="20" />
    </RollingFile>

The file is created in the correct path but the name is always the same (app.log) instead of app-xx-xx-xxxx.log.
What do I miss?

A: The filePattern attribute is the pattern of the file name to use on rollover. But if you want the date pattern in the name of the file that is actively written tom, you can use Date Lookup in the filename attribute, i.e:
fileName="${sys:catalina.base}${sys:file.separator}logs${sys:file.separator}${web:contextPath}${sys:file.separator}app-${date:dd-MM-yyyy}.log"


Q: Identityserver4/OpenId Connect, Hybrid mode, Token Refresh Fails I have as ASP.net Core MVC site, that uses OpenId connect to authenticate with another ASP.net Core site, that uses IdentityServer4, that uses another IdentityServer4 site as identity provider.
On the client, there is a very few pages, that in theory could be used for a long time with only AJAX-calls. I wan't the site to refresh the access token, so that the user won't be forced to log in, let's say the next day.
I've set up a timer, that calls a WebAPI method on the MVC-site, that refreshes the token.
It works with the two first refreshes, but always fails on the third.
The method returns a JWT to be used on external API-calls. I can see this updates on the fist call as expected, and that it gets a new expiration timestamp.
In the third call, the tokenClient.RequestRefreshTokenAsync fails, because the refreshToken is null.
    public async Task<IActionResult> RefreshToken()
    {
        var disco = await DiscoveryClient.GetAsync(_authenticationOptions.Value.Authority);

        if (disco.IsError)
            return BadRequest(disco.Error);

        var tokenClient = new TokenClient(disco.TokenEndpoint, _authenticationOptions.Value.ClientId, _authenticationOptions.Value.ClientSecret);
        var refreshToken = await HttpContext.Authentication.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);
        var tokenResult = await tokenClient.RequestRefreshTokenAsync(refreshToken);

        if (tokenResult.IsError)
            return BadRequest(disco.Error);

        var old_id_token = await HttpContext.Authentication.GetTokenAsync(OpenIdConnectParameterNames.IdToken);
        var new_access_token = tokenResult.AccessToken;
        var new_refresh_token = tokenResult.RefreshToken;

        var tokens = new List<AuthenticationToken>();
        tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token });
        tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token });
        tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token });

        var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
        tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });

        var info = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies");
        info.Properties.StoreTokens(tokens);

        await HttpContext.Authentication.SignOutAsync("Cookies");
        await HttpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties);

        return Ok(HttpContext.Authentication.GetTokenAsync("access_token").Result);
    }

I can see, that Chrome is notifying in the console, that a set-cookie header is ignored, because it exceeds 4kb.
Any tips?

A: Got it.
The clients IdentityToken expired, and since that api method wasn't protected by [Authorize] attribute, it didn't renew + changed the script to use an iframe instead of AJAX-calls!
Case closed.


Q: Flutter: disable dropdownbutton option I have this widget:
DropdownButton<String>(
        value: rentPeriod,
        items: rentPeriods.map((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(translate("expense.$value")),
          );
        }).toList(),
        onChanged: (value) async {
          setState(() {
            rentPeriod = value;
          });
        },
      ),

How can I disable, let's say, the first option of the list?

A: i dont think there is any straight forward way of disabling a DropdownMenuItem
but you can have a list of the DropdownMenuItems you want to disable and then when you run setState you can check if that DropdownMenuItem is contained in that list and if it is then do nothing, also check by the DropdownMenuItem text if its contained in that list and if it is then change the color to be greyed out.
Like this
class MyWidget extends StatefulWidget {
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }

    class _MyWidgetState extends State<MyWidget> {
      var rentPeriods = <String>['one', 'two'];
      final disabledItems = ['one'];
      var rentPeriod;
      @override
      Widget build(BuildContext context) {
       return DropdownButton<String>(
          value: rentPeriod,
          items: rentPeriods.map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(
                translate("expense.$value"),
                style: TextStyle(
                  color: disabledItems.contains(value) ? Colors.grey : null,
                ),
              ),
            );
          }).toList(),
          onChanged: (value) async {
            if (!disabledItems.contains(value)) {
              setState(() {
                rentPeriod = value;
              });
            }
          },
        );
      }
    }

A: You can create your own disable customization, changing the color and the callback of onChangedfunction in the DropdownButton, like this example:
https://dartpad.dev/587b44d2f1b06e056197fcf705021699?null_safety=true


Q: How to find the file associated with a memory mapped address in C Is there an existing example of how, in C, to take a memory address and get which, if any, file is mapped to that address?
Specifically, I am modifying how msync works and I want to know what file is associated with the address being synced.
I can see how in the proc man page such a thing could be found by looking at the contents of the /proc/self/map_files directory, but I am hoping there is an already existing helper function for doing this.