text:
Q: Backbone.js route interceptor I have main app with subapps:
main_app
 |-mainRouter.js
|-sub_app
    |-subAppRouter.js
subAppRouter.js extends mainRouter.js. subAppRouter.js has handler for route (e.g. /app1/item/). I have no access to subAppRouter.
Here is what I need:
In mainRouter I want to create routing that will handle all URL's from all apps.
It should handle route , make some check and in one case it should continue firing handler from subAppRouter for that url, else it should make redirect (e.g. /app2/somepage).
Could someone helps me with finding the best solution how to do it?
In other words: how to realize interceptor pattern via router in backbone?
Thanks

A: i will rephrase your question in points
1- you have a main router for common routes
2- you have a specialized router for some app routes
3- you need your main router to choose weather to handle the route of just forward it to sub router
to achieve this i suggest the following
1- create the main router , extending Backbone.Router
var mainRouter = Backbone.Router.extend({
    routes:{
        'index':'loadIndex',
        //other common app routes......
    },
    loadIndex: function(){
        //code to load index
    }
});

2- then define the sub router for app,extending the main router, but notice how routes is defined
var subAppRouter = mainRouter.extend({
    initialize: function(){
        // here we will extend the base routes to not lose default routing, and add app special routing
        _.extend(this.routes, {
           'subApp/index': 'subAppIndex'
       });
    },
    subAppIndex: function(){
         // code to load sub app index
    },
});

then you can use the sub router which will contains the base routing also

A: Here is a good article about subrouting. This works perfect for me.
Include subroute js lib in your project:

HTML body example:
App1
App2

JS Code example:
var MyApp = {};
MyApp.App1 = {
    Router: Backbone.SubRoute.extend({
        routes: {
            "": "init",
            "sub1": "sub1"
        },
        init: function  () {
            console.log("app1");
            $(".app").html($("
", {text: "App1"}));
            $(".app").append($("", {href: "#app1/sub1", text: "sub1"}));
        },
        sub1: function  () {
            console.log("sub1");
            $(".app").append($("
", {text: "sub1"}));
        }
    })
};
MyApp.Router = Backbone.Router.extend({
    initialize: function  () {
        if(!MyApp.Routers){
            MyApp.Routers = {};
        }
    },
    routes: {
        "app1/*subroute": "invokeApp1Router",
        "app2": "app2"
    },
    invokeApp1Router: function  (subroute) {
        if(!MyApp.Routers.App1){
            MyApp.Routers.App1 = new MyApp.App1.Router("app1/");
        }
    },

    app2: function  () {
        console.log("app2");
        $(".app").html($("
", {text: "App2"}));
    }
});

$(document).ready(function  () {
    new MyApp.Router();
    Backbone.history.start();
})


text:
Q: How can I dynamically assign an url to an image map? I'm trying to dynamically insert an URL in an imagemap using PHP.

*

*I check if the current URL contains a substring.
If yes the url will be ...
If no the url will be..

*In case there is a problem with PHP I do a check if the variable $myurl exists.
If not assign a default value to $myurl

*Then I insert the variable $myurl in the imagemap.

However it doesn't work.
When I move the mouse over my image map I see this as URL: <?= $myurl ?>
What did I wrong?
The code:
[1]
if (strpos($_SERVER['REQUEST_URI'], "/nl/") !== false){
   $myurl = "url2"
} else {
   $myurl = "url1"
}

[2]
if (!isset($myurl)) {
    $myurl = "url1"
}

[3]
<img src="../imagemap_blue.png" usemap="#imagemap2">
<map name="imagemap2">
<area shape="rect" alt="" coords="15,5,302,55" href="<?= $myurl ?>">
</map>

A: Does your server support the short tags? If not (perhaps you're using a version of PHP earlier than 5.4), maybe try replacing
 <?= $myurl ?>

with
<?php echo $myurl; ?>

Or try setting short_open_tag to "1" if you can:
https://www.php.net/manual/en/ini.core.php
If that doesn't work either, the standard php open/close tags aren't working correctly, and you need to figure out why that is. Make sure your file has a .php extension on the end. Make sure you have an actual server (localhost or an external one) you're opening your page on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read binary data from a MDB-file running under LAMP I need to be able to connect to an MDB-file in a LAMP-environment (running on Linux) and ultimately insert converted data into a Mysql db.

*

*The data I need to access is stored
as a BLOB (Long Binary Data according
to Access) in the MDB file. I have
not yet been able to actually have a
look at the data but I have been told
that the BLOB consists of byte
strings. Something along the lines
of:
0x1c 0x10 0x27 0x00 0x00

*I need to parse the byte strings and
convert these to a format that is
human readable. I do have access to
the documentation that explains the
various byte strings.
So this is really two questions:

*

*How do a get access to the MDB file
via PHP* (running under LAMP) and read the BLOB (I do not
have access to a Windows-platform)?

*What would be the best way to parse
the binary data (in PHP*) once I am
able to connect to the MDB-file?

*Or are there other methods/languages that are more appropriate?

A: There is a PECL library that connects to a Linux based MDB parsing tool.
Reading Access Databases with PHP and PECL

In this article, I'll introduce you to PHP's MDBTools extension, which provides an API to programmatically read data from Microsoft Access database files. If your project involves working with such files, extracting database records either for calculations or for conversion to other formats, you'll find this extension invaluable. Come on in, and see how it works!

You will probably need administrator access on the server to install the necessary libraries.
If you can use a Windows server, you should be able to connect to the file directly using ODBC using ADODb or through the windows COM as shown in this blog entry.


text:
Q: Question about the altering the multinomial theorem So as I understand it the multinomial coefficient helps us make a deduction about a problem of the following type:
In how many ways can the letters of POODLE be rearranged. And so the idea is that all the letters can be rearranged in 6! ways, but then since the two Os are indistinguishable they can be interchanged, and what we have is $\frac{6!}{2!}$.
Now what I am thinking is that if we consider the two Os to be as one box, we can think of the whole word to be changed to P[OO]DLE. And we can then consider how many different ways this can be rearranged which is 5!. This is obviously wrong, since the textbook mentions that the correct answer is what I have written above. But what is the flaw in my reasoning?

A: Consider this:
1. POODLE
2. PODOLE
3. PODLOE
4. PODLEO

If you had only one O how would you count the above result?
If you had PODLE then yes - you have 5! possibilities. In other words, don't confuse 2 O that are indistinguishable (POODLE and POODLE are the same since O1 and O2 are the same o) with 2 Os that are next to each other.
So yes, the result would be  $\frac{6!}{2!}$ and not $5!$.


text:
Q: Polynomial and spectrum of a Operator . I need help with the following question :
Let us consider $X$ to be a $\mathbb C  $ Banach space . Let $T \in B(X)$ ie. $T$ is a continuous linear map from $X$ to $X$ . define $$P(T)=\sum_{k=o}^{n}a_kT^k$$ with $T^0=id_X$ (identity) .
The claim is that the spectrum of $T : \sigma(T) \subset\{\lambda \in \mathbb C : P(\lambda)= 0\}$
Here $P$ is a polynomial such that $P(T) =0$  .
Thanks.

A: Let me expand on the setting. Let $\text{Hol}(T)$ be the set of all the functions holomorphic in a neighborhood of $\sigma(T)$. The Riesz functional calculus now says that indeed if I have the polynomials $p$, that $p(T)$ is as expected - of course, for polynomials this is trivial.
Additionally, we have the Banach algebra of bounded operators on $X$, and:
Spectral mapping theorem: If $T$ is an element of a Banach algebra $\mathcal A$ and $f$ is holomorphic in a neighborhood of $\sigma(T)$, then
$$\sigma(f(T)) = f(\sigma(T)).$$
If we thus select such a polynomial $p$ such that $p(T) = 0$, we get $p(\sigma(T)) = 0$.

A: It is enough to show the contrapositive, namely, that if $P(\lambda) \neq 0$, then $T - \lambda \operatorname{id}_X$ is invertible. Now, since $P(\lambda) \neq 0$, $x-\lambda$ does not divide the polynomial $P(x)$, so that we may write $P(x) = Q(x)(x-\lambda) + R$ for some polynomial $Q(x)$ and a non-zero remainder $R \in \mathbb{C}$ — since $x-\lambda$ is of degree one, the remainder must be of strictly lower degree, and thus constant. But then, this means that $0 = P(T) = Q(T)(T-\lambda \operatorname{id}_X) + R\operatorname{id}_X$, so that since $T-\lambda \operatorname{id}_X$ and $Q(T)$ commute, we find that $T-\lambda \operatorname{id}_X$ is invertible with bounded inverse $(T-\lambda \operatorname{id}_X)^{-1} = -\tfrac{1}{R}Q(T)$, as required.


text:
Q: Flutter: How can i tap on item(product) and go to detail? I'm using a socket io. I could listed all the items and made them clickable but when I try to go to detail it returns null. How can I go to detail of the item that I clicked?
I tr
return Padding(
                                  padding: EdgeInsets.symmetric(horizontal:
                                                                       5),
                                  child: Column(
                                    children: <Widget>[
                                      InkWell( onTap: (){

                                          MyNavigator.goToDetail(context);

                                        },
                                       child: Row(
                                          children: <Widget>[
                                            Expanded(
                                              flex: 40,
                                              child: Container(
                                                padding: EdgeInsets.only(top:
                                                                 2, left: 3,),
                                                child: Column(
                                                  crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    Text(

                                          x["symbols"].elementAt(index).name,
                                                      style: TextStyle(
                                                          color:
                                                        Colors.black54,
                                                          fontSize: 18,
                                                          fontWeight:
                                                          FontWeight.bold),
                                                    ),
                                                    Padding(
                                                      padding:
                                                      EdgeInsets.all(1),
                                                    ),
                                                    Text(
                                                      x["symbols"]
                                                          .elementAt(index)
                                                          .lastUpdate,
                                                      style: TextStyle(
                                                          color:
                                                          Color(0xFF96979A),
                                                          fontSize: 13),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),


text:
Q: My Bootstrap TableTools are not working as expected My TableTools are not working, I get this error in the console:

Uncaught TypeError: Cannot read property 'aDataSort' of undefined

in jquery.datatables.min.js file
I have included these two files
<script src=" <?php echo base_url('assets/js/TableTools/js/dataTables.tableTools.min.js'); ?>"></script>
<link href="<?php echo base_url('assets/js/TableTools/css/dataTables.tableTools.min.css'); ?>" rel="stylesheet" media="screen">

and my jQuery is:
$('#datatable_examplesss').dataTable( {
                    "dom": 'T<"clear">lfrtip',
                    "tableTools": {
                        "sSwfPath": "/swf/copy_csv_xls_pdf.swf"
                    }
                } );

but it does not showing me anything on table please help me

A: can you post the full code on jsfiddle or something like that?
If i had to guess it could be your load order of the libs.
Try this order:
script type="text/javascript" src="dataTables.tableTools.min.js"
script type="text/javascript" src="jquery.dataTables.min.js"

If this does not help u could try to set ur jQuery in the noConflict Mode.
But a full example would help as well.
Cheers


text:
Q: jQuery addClass some problems I wanted to pass in a function to .addClass() to add the "green" class to a div that already has a "red" class.
here is my code
Fiddle
$( "two" ).addClass(function( index, currentClass ) {
  var addedClass;

  if ( currentClass === "red" ) {
    addedClass = "green";
  }

  return addedClass;
});

And this is my html

Hi there

Hello

And this is my css
 .red {
    background: red;
 }
 .green {
    background: green;
 }

A: You can do something like this:

Hi there

Hello

$('.black').removeClass('black').addClass('red');

Fiddle

A: because value of b is two black and you comparing it with black which return always false, so try:
var one = $('.one');
var two = $('.two');
two.addClass(function (a, b) {
    var s;
    if (b.indexOf('black')>0) {
        s = 'red';
    }
    return s;
});

Here is demo
But you should know that it will add class to your element so after this you class will be two black red if you dont want black there than remove it using:
$(this).removeClass('black')

Here is demo

A: This will also work.
var one = $('.one');
var two = $('.two');
two.addClass(function( index, currentClass ) {
    var addedClass;
    var $class = currentClass.split(' ')
    for(i in $class){
        if ( $class[i] === "black") {
            addedClass = "red";
        }
    }
    return addedClass;
});


text:
Q: do we need to protect single assignment or if statement for threadsafety Suppose I have like :
static int write_log = 0;

void *logger__run(void *arg){
    // logger thread execution.
    while(1){
         // get log message from shared queue.
         if(write_log){
             // just checking write_log value.
             // write logs till write_log is true.
         }
         // destroy log message.
    }
}

void logger__set_logging(int p_write_log){
    // other threads can start / stop logging by logger thread.
    // just assigning value.
    write_log = p_write_log;
}

int logger__is_logging(void){
    // other threads can check whether logger thread is logging or not.
    // just returning value.
    return write_log;
}

The function logger__run() will be executed by logger thread. Other threads can start / stop logging by logger thread by setting write_log shared variable. Other threads can also check if logger is logging or not.
As you can see, there are only single statements like: assignment or returning value or checking in while loop. So, do we need this write_log access to be protected with locks?

A: I would say yes. logger__run may read an incorrect value for write_log because the assignment in logger__set_logging is not atomic (thus, some bytes of the int value may have been written and others may have yet to come within this single assignment).


text:
Q: Closing workbook destroys variable? I defined a class called "cSettings".  Then I created a cSettings object called "info".  The info object has a method to read data from a user selected workbook, then store them in its member variables.  The member variables are object type.  More specifically, "nested Dictionary" type.
What I've observed was - before closing the workbook, all data in the info object was good.  After closing the workbook, I'm "object required" message when accessing one of the member variables.  So it seems like closing the workbook has somehow destroy part of the data.  But how?  Here's my code:
' Class module cSettings

Option Explicit
Public obj1 As Object
Public obj2 As Object

' ----------

Public Sub ReadFrom(wb As Workbook)
    Set obj1 = CreateObject("Scripting.Dictionary")
    Set obj2 = CreateObject("Scripting.Dictionary")

    Set obj1 = Get1(wb, "sheet1")
    Set obj2 = Get2(wb, "sheet2")
End Sub

Private Function Get1(wb As Workbook, sh As String) As Dictionary
    Dim a_obj as object
    Set a_obj = CreateObject("Scripting.Dictionary")

    ' Read from workbook

    ' Add data to outer dictionary, creating inner dictionary
    a_obj.add "key1", CreateObject("Scripting.Dictionary")

    ' Add data to inner dictionary
    a_obj("key1").add "key11", "Value11"

    Set Get1 = a_obj
End Function

Private Function Get2(wb As Workbook, sh As String) As Dictionary
    Dim a_obj as object
    Set a_obj = CreateObject("Scripting.Dictionary")

    ' Read from workbook

    ' Add data to outer dictionary, creating inner dictionary
    a_obj.add "key2", CreateObject("Scripting.Dictionary")

    ' Add data to inner dictionary
    a_obj("key2").add "key21", "Value21"

    Set Get2 = a_obj
End Function

Here's the main program:
Sub Main()
    Dim myFile As Variant
    Dim wb As Workbook
    Dim info As New cSettings

    myFile = Application.GetOpenFilename()
    Set wb = Workbooks.Open(myFile, False, True)

    info.ReadFrom wb

    Debug.Print info.Items("key1")("key11").count '<-- OK
    Debug.Print info.Items("key2")("key21").count '<-- OK

    wb.Close

    Debug.Print info.Items("key1")("key11").count '<-- OK
    Debug.Print info.Items("key2")("key21").count '<-- Error "Object Required"
End Sub

Note: The above is not the original code because the original code is two long to paste.  But I was trying to understand why closing a workbook will have impact on a variable.  Would it be possible that the variable somehow is a 'pointer' to the workbook?  Thus when the workbook was closed, the actual data in the variable was also gone?  Thank you!

A: Your code as posted did not compile. With some modifications to get it to run, I'm unable to reproduce the errors:
Sub Main()
    Dim myFile As Variant
    Dim wb As Workbook
    Dim info As New cSettings

    myFile = Application.GetOpenFilename()
    Set wb = Workbooks.Open(myFile, False, True)

    info.ReadFrom wb

    Debug.Print info.obj1("key1")("key11") '<-- OK
    Debug.Print info.obj2("key2")("key21") '<-- OK

    wb.Close

    Debug.Print info.obj1("key1")("key11") '<-- OK
    Debug.Print info.obj2("key2")("key21") '<-- OK
End Sub

Hope that helps.

A: OK, I figured it out.
In my code I use dictionary.Add method to add a cell's content.  The original code was like myDic.Add "key", ws.cells(r,c), where ws was referring to a worksheet of an opened workbook.  As a newbie, I thought it would take the value of the cell and simply add a key, value pair to the dictionary.
What it actually did was to add a pointer to that cell.  When the workbook is closed, of course that cell won't exist anymore.  Thus the content of the dictionary was corrupted.  I changed the code as below and it's working as expected:
val = ws.cells(r,c)
myDic.Add "key", val

Newbie question:  how do I tell VB use the value instead of reference?  Thanks!


text:
Q: Salesforce Marketing Cloud: How can I retrieve Automation Activities via SOAP API? Every time I try to grab an Automation Activity via the SOAP API, I'm told "AutomationTasks" does not exist as a property of object_type of "Automation". The documentation says otherwise (https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/automation.htm).

A: Not all properties of objects are "Retrievable". The easiest way to check which properties can be retrieved is by issuing a Describe request against the API for the object. "AutomationTasks" is marked as not retrievable:
Request
Method = "POST" and SoapAction = "Describe"
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsse:UsernameToken wsu:Id="UsernameToken-31606811" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsse:Username>{{Username}}</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">{{Password}}</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <DefinitionRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
         <DescribeRequests>
            <ObjectDefinitionRequest>
               <ObjectType>Automation</ObjectType>
            </ObjectDefinitionRequest>
         </DescribeRequests>
      </DefinitionRequestMsg>
   </soapenv:Body>
</soapenv:Envelope>

Response
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <soap:Header>
        <wsa:Action>DescribeResponse</wsa:Action>
        <wsa:MessageID>urn:uuid:bb1c8ace-f9d6-4983-a65c-b36c141d67fd</wsa:MessageID>
        <wsa:RelatesTo>urn:uuid:a44243bb-51cf-4686-ab56-c9bc8940dfd9</wsa:RelatesTo>
        <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
        <wsse:Security>
            <wsu:Timestamp wsu:Id="Timestamp-0bf2a344-7b36-4ed2-8c95-38f07eb0aaec">
                <wsu:Created>2017-06-09T01:05:17Z</wsu:Created>
                <wsu:Expires>2017-06-09T01:10:17Z</wsu:Expires>
            </wsu:Timestamp>
        </wsse:Security>
    </soap:Header>
    <soap:Body>
        <DefinitionResponseMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
            <ObjectDefinition>
                <ObjectType>Automation</ObjectType>
                <Properties>
                    <PartnerKey xsi:nil="true" />
                    <ObjectID xsi:nil="true" />
                    <Name>ObjectID</Name>
                    <DataType>String</DataType>
                    <IsUpdatable>true</IsUpdatable>
                    <IsRetrievable>true</IsRetrievable>
                    <IsRequired>true</IsRequired>
                </Properties>
...
                <Properties>
                    <PartnerKey xsi:nil="true" />
                    <ObjectID xsi:nil="true" />
                    <Name>AutomationTasks</Name>
                    <DataType>AutomationTask[]</DataType>
                    <IsUpdatable>true</IsUpdatable>
                    <IsRetrievable>false</IsRetrievable>
                </Properties>
...
                </Properties>
            </ObjectDefinition>
            <RequestID>74d36995-9e1c-4ed3-b502-34a91ad3dfbd</RequestID>
        </DefinitionResponseMsg>
    </soap:Body>
</soap:Envelope>


text:
Q: Angular 2 click event doesn't work My have a web project and using angular 2 my different pages used click event don't have any problem but new page created then click event give a error in new page.
This Error

TypeError: self.parentView.parentView.context.changedItem is not a
  function
      at View_SiteConfig3.handleEvent_0 (/AppModule/SiteConfig/component.ngfactory.js:137)
      at View_SiteConfig3.eval (core.umd.js:12399)
      at HTMLTextAreaElement.eval (platform-browser.umd.js:3223)
      at ZoneDelegate.invokeTask (zone.js:265)
      at Object.onInvokeTask (core.umd.js:3971)
      at ZoneDelegate.invokeTask (zone.js:264)
      at Zone.runTask (zone.js:154)
      at HTMLTextAreaElement.ZoneTask.invoke (zone.js:335)

site-config.html
<div *ngFor="let item of items1; let i = index;" class="col-sm-4">
    <button (click)="changedItem(item)">Test</button>
</div>

site-config.ts
import { Component, OnInit } from '@angular/core'
import { Http } from '@angular/http'

@Component({
    selector: 'site-config',
    moduleId: module.id,
    templateUrl: '/site-config.html'
})
export class SiteConfig implements OnInit {

    items1: number[] = [1,2,3]

    ngOnInit(): void {
    }

    public changedItem(item) {
        //My Codes This Here
    }

    constructor(private http: Http) {
    }
}

EDIT: Solved problem this method;

My project worked. Problem is ts file not compiled then give a "is not
  a function" error

A: Maybe it's an error from a piece of code you don't provide.
I reproduce your code :
The view:
<pre *ngIf="current">{{current}}</pre>
<div *ngFor="let item of items1; let i = index;" class="col-sm-4">
  <button (click)="changedItem(item)">Test</button>
</div>

The class content:
items1: number[] = [1,2,3]

current: number;

ngOnInit() {
}

public changedItem(item) {
    this.current = item;
}

constructor() {
}

Here's a working Plunkr : https://plnkr.co/edit/ZGI1FNB8RWN9BnnPnKgJ?p=preview
Can you provide more code ?

A: Try this:
site-config.html
<div *ngFor="let item of items1; let i = index;" class="col-sm-4">
    <button type="button" (click)="changedItem($event, item)">Test</button> <!-- add type="button" -->
</div>

site-config.ts
import { Component, OnInit } from '@angular/core'
import { Http } from '@angular/http'

@Component({
    selector: 'site-config',
    moduleId: module.id,
    templateUrl: '/site-config.html'
})
export class SiteConfig implements OnInit {

    items1: number[] = [1,2,3]

    ngOnInit(): void {
    }

    public changedItem(event: any, item: number) {
        event.preventDefault();
        //Your code...
    }

    constructor(private http: Http) {
    }
}


text:
Q: Disable flash in background when clicking CheckBox in Android I have noticed that when you click on a CheckBox or a RadioButton in Android, the layout of the widget becomes white for a few milliseconds. How do you disable that ?
Thanks.


text:
Q: RecyclerView onCreateViewHolder is not called For some reasons my recyclerview adapter's onCreateViewHolder is not called and I cant figure out why.
Initially, i was using a single adapter for all my recyclerview lists and i was experiencing the same thing so i made a separate adapter to find out why. I want to believe am configuring it correctly.
Here is my adapter
class BrowseMediaRecyclerAdapter(
    private val clickListener: (Upload) -> Unit,
    private val moreInfoListener: (Upload) -> Unit) : RecyclerView.Adapter<BrowseMediaRecyclerAdapter.ViewHolder>() {

    lateinit var binding: BrowseMediaItemListBinding

    /**
     *
     * Autonotify msee
     *
     */
    private var uploadList: List<Upload> by Delegates.observable(emptyList()) { _, oldList, newList ->
        autoNotify(oldList, newList) {old, new -> old.id == new.id}
    }

    fun updateList(items: List<Upload>?){
        uploadList = items!!
        Log.e("Items", "Item received: ${items.size}")
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)

        Log.e("Bind", "View holder created")
        binding = DataBindingUtil.inflate(inflater, R.layout.browse_media_item_list, parent, false)

        return ViewHolder(binding.root)

    }

    override fun getItemViewType(position: Int): Int = position

    override fun getItemCount(): Int = uploadList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val item = uploadList[position]

        Picasso.get()
            .load(item.thumbnailLink)
            .placeholder(R.drawable.ic_local_movies_black_24dp)
            .fit()
            .transform(TransformImage(16f))
            .into(holder.thumb)

        holder.bind(uploadList[position], binding, clickListener, moreInfoListener)
        Log.e("Bind", "Item binded: ${item.id}")
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val thumb: ImageView = itemView.media_thumb
        val authorThumb: ImageView = itemView.authorImage
        private val moreInfo : FrameLayout = itemView.moreDetail

        /**
         *
         * Bind data
         *
         *
         */

        fun bind(item: Upload, binding: BrowseMediaItemListBinding, clickListener: (Upload) -> Unit, moreInfoListener: (Upload) -> Unit) {

            binding.uploadItem = item

            thumb.setOnClickListener{clickListener(item)}

            moreInfo.setOnClickListener{moreInfoListener(item)}
        }

    }

}

And inside my Fragment i configure it this way
mediaRecyclerAdapter = BrowseMediaRecyclerAdapter(
            { upload: Upload -> onMediaItemClicked(upload) },
            { upload: Upload -> onMediaMoreInfoClicked(upload) })

        binding.subjectUploadsRecyclerView.apply {

            this.adapter = mediaRecyclerAdapter

            this.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)

            this.setHasFixedSize(true)

            this.setItemViewCacheSize(10)

        }

and later on update the list in my observer
private val loadUploadItemsObserver = Observer<SubjectUploads> { subject ->

        binding.selectedSubjectText.text = subject.subject_title
        mediaRecyclerAdapter.updateList(subject.uploads)

    }

My xml file
<androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/subjectsUploadsRecyclerView"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            app:layout_constraintEnd_toEndOf="parent"
                            app:layout_constraintStart_toStartOf="parent"
                            app:layout_constraintTop_toBottomOf="@id/selectedSubjectTextFrame"
                            tools:listitem="@layout/media_item_list" />

What could i be possibly doing wrong? Can some one help please


text:
Q: I have a list of customers, each customer has invoice dates, I am trying to average the dates between customer orders I am importing the data from QB, with headers Customer, Date - I am calculating the Days between last purchase and am trying to take the average of those dates. What I am left with is this - How do I take the average of each separate customer?

A: The way I would do it is to add another column to calculate which customer the value relates to, then work out the average.
To do this, insert a column between "Days Btwn Orders" and "Average Days Btwn Orders". We'll call this "Corresponding Customer". The rest assumes "Date" is column B, "Days Btwn orders" is column C and "Corresponding Customer" is column D.
Put this formula into that column, row 2: =IF(A2<>"",A2,D1)
Then, put this into row 2 of "Average Days Btwn Orders": =IF(AND(A2<>"",C2=""),averageifs(C:C,D:D,D2),"")
Then drag both formulas down as far as you need. There's probably a way to do this in an arrayformula so it doesn't need the extra column.


text:
Q: ¿Como dejar activa una clase aun cuando se haya dado reload la pagina? con jQuery o JS Tengo esta lista de titulos en la cual seleccionas uno y se depliega otra lista de subtitulos , mi pregunta es como puedo hacer para que cuando se seleccione un subtitulo dentro de la lista, al recargar la pagina se siga mostrando la lista desplegada y el subtitulo seleccionado marcado ya se de otro color o que resalte.
Importante: Que al recargar la pagina por darle clic a un subtitulo la lista desplegada se siga mostrando con el subtitulo seleccionado, en caso de que no se seleccione ningun subtitulo al recargar la pagina todas las listas se contraigan.
Espero puedan ayudarme, Gracias.

$("label.title-item").click(function() {
    // Obtener el elemento que se debe mostrar u ocultar
    let desplegable = $(this).next(".desplegable-1");
    // Saber si se tiene que mostar u ocultar
    let mostrar = !desplegable.hasClass('active-desp');
    // Ocultar todos los desplegables
    $(".desplegable-1").removeClass("active-desp");
    // Mostrar u ocultar el actual
    if(mostrar) {
        desplegable.addClass('active-desp');
    } else {
        desplegable.removeClass('active-desp');
    }
});

$("label.title-sub").click(function() {
    // Buscar el siguiente elemento por clase
    $(this).next(".desplegable-2").toggleClass("active-desp2");
});

const currentLocation = location.href;
        const menuItem= document.querySelectorAll("a.sub-title-item");
        const menuLength = menuItem.length
        for(let i=0; i<menuLength; i++){
            if(menuItem[i].href === currentLocation){
                menuItem[i].className="sub-title-item active"
            }
        }
.desplegable-1,.desplegable-2 {
    display:none;
}

.active-desp, .active-desp2{
    display:block;
}

input[type="checkbox"] {
    display: none;
}

.sub-title-item.active{
    color:#0AADFF;
    font-weight: 400;
}

.sub-title-item{
    color:black;
    font-weight: 200;
}

a{
text-decoration:none;
}

                    <input type="checkbox" id="A"/>
                    Titulo 3

Sub titulo 1

Sub titulo 2

                                <input type="checkbox" id="A-A"/>
                                Lista de Sub titulos

Lista 1

Lista 2

Lista 3

Lista 4

Sub titulo 3

                    <input type="checkbox" id="B"/>
                    Titulo 2

Sub titulo 1

Sub titulo 2

                                <input type="checkbox" id="B-A"/>
                                Lista de Sub titulos

Lista 1

Lista 2

Lista 3

Lista 4

Subtitulo3

                    <input type="checkbox" id="B"/>
                    Titulo 1

Sub titulo 1

Sub titulo 2

                                <input type="checkbox" id="B-A"/>
                                Lista de Sub titulos

Lista 1

Lista 2

Lista 3

Lista 4

Sub titulo 3

A: Hola lo que puedes hacer es guardar el label seleccionado en el localStorage
Primero ponerle un id a cada label (data-id) a los titulos y subtitulos

                    <input type="checkbox" id="A"/>
                    Titulo 3

Sub titulo 1

Sub titulo 2

                                <input type="checkbox" id="A-A"/>
                                Lista de Sub titulos

Lista 1

Lista 2

Lista 3

Lista 4

Sub titulo 3

                    <input type="checkbox" id="B"/>
                    Titulo 2

Sub titulo 1

Sub titulo 2

                                <input type="checkbox" id="B-A"/>
                                Lista de Sub titulos

Lista 1

Lista 2

Lista 3

Lista 4

Subtitulo3

                    <input type="checkbox" id="B"/>
                    Titulo 1

Sub titulo 1

Sub titulo 2

                                <input type="checkbox" id="B-A"/>
                                Lista de Sub titulos

Lista 1

Lista 2

Lista 3

Lista 4

Sub titulo 3

Luego en tu función donde le das la funcionalidad al click del label guardamos el id del label seleccionado
$("label.title-item").click(function() {
    // Obtener el elemento que se debe mostrar u ocultar
    let desplegable = $(this).next(".desplegable-1");

    //Eliminar
    if (!desplegable.hasClass('active-desp')) {
        localStorage.setItem("titleSelected", $(this).data("id"));
    }else{
         localStorage.removeItem("titleSelected");
    }

    // Saber si se tiene que mostar u ocultar
    let mostrar = !desplegable.hasClass('active-desp');
    // Ocultar todos los desplegables
    $(".desplegable-1").removeClass("active-desp");
    // Mostrar u ocultar el actual
    if(mostrar) {
        desplegable.addClass('active-desp');
    } else {
        desplegable.removeClass('active-desp');
    }

});

$("label.title-sub").click(function() {

    if ($(this).next(".desplegable-2").hasClass("active-desp2")) {
        localStorage.removeItem("subTitleSelected");
    }else{
        localStorage.setItem("subTitleSelected", $(this).data("id"));
    }

        // Buscar el siguiente elemento por clase
    $(this).next(".desplegable-2").toggleClass("active-desp2");
});

Y por ultimo cuando se carga la pagina si el localStarage tiene valor damos click al label seleccionado
$( document ).ready(function() {
   //Titulo
    if (localStorage.getItem("titleSelected") != null) {
        $("label[data-id='"+ localStorage.getItem("titleSelected") +"']").trigger("click");
        //Subtitulo
        if (localStorage.getItem("subTitleSelected") != null) {
                $("label[data-id='"+ localStorage.getItem("subTitleSelected") +"']").trigger("click");
        }
    }
});


text:
Q: OpenGL: How does perspective division work? After multiplication by the projection matrix If any clip coordinate is less than -wc, or greater than wc, then the vertex will be discarded.
Then perspective division is performed by W. But what happens if w = 0? OpenGL just doesn't do division?

A: Perspective division is done when converting coordinates from clip space to normalised device coordinates. Before this the x,y and z are compared to the w component and as you said if any of the components are greater than wc or smaller than -wc it will be clipped.
The w component in clip space will have the same value as the z coordinate in viewspace, so for it to be equal to zero, the z component in view space would also need to be zero. In view space the camera's z component is zero. In front of the camera is the near plane and anything with a z less than the near plane will be clipped. The z component in viewspace will be rescaled ,in this case since it is zero, to the negative of the nearplanes z component. This means that z will be smaller than the w component which is zero, the vertice will be clipped and there will be no perspective division.
Here is a youtube video that I think sums up the process of perspective projection quite well

A: if you got input position (x,y,z,w=1) or vector (x,y,z,w=0) then after multiplication with uniform homogenuous 3D transform matrix the resulting w is never zero if the input x,y,z is in the frustrum range ...
So in case your result has w=0 the point or vector is outside frustrum anyway so you can ignore such point/vector ...


text:
Q: OSM Map projection doesn't seem to change I have the following OpenLayers map:
Proj4js.defs["EPSG:31258"] = "+proj=tmerc +lat_0=0 +lon_0=13.33333333333333 +k=1 +x_0=450000 +y_0=-5000000 +ellps=bessel +towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.4232 +units=m +no_defs";
var googleProj = new OpenLayers.Projection("EPSG:900913");
var salzburgProj = new OpenLayers.Projection("EPSG:31258");
var bounds = new OpenLayers.Bounds(426249,294999,426251,295001);
var maxZoom = 19;
var minZoom = 15;
var res = [4.77731426696777,2.38865713348389,1.194328566741945,0.5971642833709725];

mapCOD = new OpenLayers.Map({
    div: "mapCODs",
    allOverlays: true,
    maxExtent: bounds,
    projection: salzburgProj,
    allowSelection: true,
    controls: [new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.Navigation()]
});

var layer = new OpenLayers.Layer.OSM(
        "layer1",
        "tiles/input/${z}/${x}/${y}.png",
        {zoomLevels: maxZoom, zoomOffset: minZoom, resolutions: res}
    );
mapCOD.addLayer(layer);

I have produced tiles with mapnik using EPSG:31258, so I would like to change the default projection of the map from 900913 to 31258.
The problem is that "projection" parameter is not taken into account and if I perform a console.log(mapCOD.getProjection()), I obtain "EPSG:900913".
Another proof that map projection remains 900913 is that I have to perform a coversion to get the correct map center:
var center = bounds.getCenterLonLat();
mapCOD.setCenter(center.transform(salzburgProj,googleProj), minZoom);

What am I missing?

A: try this:
map.projection = new OpenLayers.Projection("EPSG:31258");
map.displayProjection = new OpenLayers.Projection("EPSG:4326");

or write like this:
mapCOD = new OpenLayers.Map('map', {
    numZoomLevels: 20,
    projection: new OpenLayers.Projection("EPSG:31258"),
    displayProjection: new OpenLayers.Projection("EPSG: 4326")
});

i hope it helps you....


text:
Q: How do I create an answer for an equation using randomly generated numbers and operator? I'm wondering how to plus, subtract and multiply a randomly generated number from other random number with a random operator.
This is the code I've got so far:
ops = ['+','-','*']
op = random.choice(ops)
variable1 = random.randrange(1,10)
variable2 = random.randrange(1,10)
if op == '+':
    answer = sum(var1+var2)
elif op == '-':
      answer = sum(var1-var2)
elif op == '*':
      answer = sum(var1*var2)

I usually get an error message:
answer = sum(var1-var2)
TypeError: 'int' object is not iterable
Sorry if this is a simple answer, still fresh to the whole python coding! :)

A: sum is for summing up an iterable - meaning a list or something behaving as a list.
Just use answer = var1 + var2.
There is also a fun module named operators that allows you to supply an operator that mirrors the built-in operators, which would allow you to generalize this even further.
Something like this would probably be more pythonic :
import operators
ops = [operators.iadd, operators.imul, operators.isub]
# pick your op = ..
# pick your vars = ..

answer = op(var1, var2)

A: sum requires iterable. Here, you already know the answer but trying to give it to sum so no need, just remove it.
ops = ['+','-','*']
op = random.choice(ops)
var1 = random.randrange(1,10)
var2 = random.randrange(1,10)
if op == '+':
    answer = var1+var2
elif op == '-':
    answer = var1-var2
elif op == '*':
    answer = var1*var2


text:
Q: How to override BuildConfig from Android-Library? I have a Android Library and I am using it in app module. In library I use a BuildConfig.SPECIAL_VALUE.
I would like to override this BuildConfig in my app module build gradle.
I found similary question but It doesn't help me (Access buildConfigField from gradle in Android app)
I try this but is not working:
My app module build.gradle:
android {

publishNonDefault true
compileSdkVersion 28
flavorDimensions "default"
buildToolsVersion '28.0.3'

defaultConfig {
    applicationId "app....id"
    flavorDimensions "default"
    minSdkVersion 23
    targetSdkVersion 28
    versionCode 1
    versionName "1.0.0"
    multiDexEnabled true
    renderscriptTargetApi 18
    renderscriptSupportModeEnabled true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField 'boolean', 'DEBUG_LOG_ENABLED', 'false'
        signingConfig signingConfigs.productivity_mentor_release_config
        debuggable = false
        manifestPlaceholders = [crashlyticsEnabled: true]
    }
    debug {
        testCoverageEnabled = false
        buildConfigField 'boolean', 'DEBUG_LOG_ENABLED', 'true'
        debuggable = true
        manifestPlaceholders = [crashlyticsEnabled: false]
    }
    unitTest {
        testCoverageEnabled = false
        buildConfigField 'boolean', 'DEBUG_LOG_ENABLED', 'false'
        manifestPlaceholders = [crashlyticsEnabled: false]
    }
}

productFlavors {
    develop {
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'false'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'false'
        buildConfigField 'String', 'SPECIAL_VALUE', '"11"'
    }
    production {
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'true'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'true'
        buildConfigField 'String', 'SPECIAL_VALUE', '"22"'
    }
    beta {
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'true'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'true'
        buildConfigField 'String', 'SPECIAL_VALUE', '"33"'
    }
    roboTest {
        minSdkVersion 18
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'false'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'true'
        buildConfigField 'String', 'SPECIAL_VALUE', '"44"'
    }
}
testOptions {
    unitTests.returnDefaultValues = true
}
lintOptions {
    abortOnError false
}
compileOptions {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}

And my library build.gradle:
android {
compileSdkVersion 28
flavorDimensions "default"
buildToolsVersion '28.0.3'
publishNonDefault true
defaultConfig {
    minSdkVersion 22
    targetSdkVersion 28
    multiDexEnabled true
    renderscriptTargetApi 18
    renderscriptSupportModeEnabled true
    javaCompileOptions {
        annotationProcessorOptions {
            arguments = ["room.schemaLocation":
                                 "$projectDir/schemas".toString()]
        }
    }
}
buildTypes {
    release {}
    debug {}
    unitTest { }
}

productFlavors {
    develop {
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'false'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'false'
        buildConfigField 'String', 'SPECIAL_VALUE', '"1"'
    }
    production {
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'true'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'true'
        buildConfigField 'String', 'SPECIAL_VALUE', '"2"'
    }
    beta {
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'true'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'true'
        buildConfigField 'String', 'SPECIAL_VALUE', '"3"'
    }
    roboTest {
        minSdkVersion 18
        buildConfigField 'boolean', 'LOG_EVENTS_TO_REMOTE_ENABLED', 'false'
        buildConfigField 'boolean', 'FIREBASE_CRASH_ENABLED', 'true'
        buildConfigField 'String', 'SPECIAL_VALUE', '"4"'
    }
}
testOptions {
    unitTests.returnDefaultValues = true
}
lintOptions {
    abortOnError false
}
compileOptions {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}

}
ext {
    google_services_version = '16.0.7'
}


text:
Q: How to rotate x-labels in one subfig? When I use text() in the following way, the labels will not be shown.
layout(
  mat=rbind(
    1
    , 2
    , 3
  )
  , heights=c(5, 1, 1)
)
par(
  oma = c(5,4,0,5)
  , mar = c(0,0,1,0)
)
plot(1:10, 1:10, xaxt='n')
plot(1:10, 1:10, xaxt='n')
plot(1:10, 1:10, xaxt='n')
text(1:10, 0, srt = 60, adj = 1, xpd = T, labels = 1:10)

If I just use it alone, then the x labels can be rotated.
plot(1:10, 1:10, xaxt='n')
text(1:10, 0, srt = 60, adj = 1, xpd = T, labels = 1:10)

How to rotate labels in the first case?

A: You need to set xpd = NA to prevent the text being clipped to the plotting region in a multi-plot layout, as explained in the docs (emphasis added)

xpd    A logical value or NA. If FALSE, all plotting is clipped to the plot region, if TRUE, all plotting is clipped to the figure region, and if NA, all plotting is clipped to the device region. See also clip.

Which means you can do:
layout(
  mat=rbind(
    1
    , 2
    , 3
  )
  , heights=c(5, 1, 1)
)
par(
  oma = c(5,4,0,5)
  , mar = c(0,0,1,0)
)
plot(1:10, 1:10, xaxt='n')
plot(1:10, 1:10, xaxt='n')
plot(1:10, 1:10, xaxt='n')
text(1:10, 0, srt = 60, adj = 1, xpd = NA, labels = 1:10)


text:
Q: Конфигурация устройств (аналогично диспетчеру устройств) Добрый день.
Скажите, какой функционал предпочтительнее для изменения параметров устройства (конкретно ком-порта).
Пока копаю в сторону SetupApi. С его помощью можно перечислить устройства, отфильтровать искомое по имени и вроде как получить и задать набор параметров.
Однако получается адское нагромождение кода, может есть что-то попроще?

A: Установка параметров COM-порта делается через SetCommState(). Отображение окна настроек - через CommConfigDialog(), но меняет ли она настройки я не знаю.


text:
Q: How to use two svelte componenets on different pages with distinct ids? I'd like to use two unrelated svelte compoents on two distincpages of a website say  /cats and /dogs so in main.js I have
import App from './App.svelte'; //this is empty

import ListCats from './ListCats.svelte';

import ListDogs from './ListDogs.svelte';

new ListCats({
  target: document.querySelector('#list-cats'),
});

new ListDogs({
  target: document.querySelector('#list-dogs'),
});

const app = new App({
    target: document.body
});

export default app;

The prblem is that error:
Uncaught Error: 'target' is a required option
    at new SvelteComponentDev (index.mjs:1993:19)
    at new ListDogs (ListDogs.svelte:76:39)
    at main.js:9:1
    at main.js:24:2

This arises becasue /cats page does not have #list-dogs and /dogs does not have #list-cats and both pages import the same bundle.js of svelte.
How can I avoid this problem?

A: try
let target = document.querySelector('#list-cats');
if (target) new ListCats({ target });

target = document.querySelector('#list-dogs');
if (target) new ListDogs({ target });


text:
Q: add comma after thousand amount in javascript I am using slide input with following javascript,

                <input id="ex1" type="text" data-slider-min="0000" data-slider-max="8000" data-slider-step="1" data-slider-value="0"/>
                0

This is working properly. Only thing I want to add a comma after thousands.
like 2,000 80,000 170,000
Please help me add this.
Thank you+

A: in this way you can use @RokoC.Buljan usefull link for your code:

here i used .toLocaleString(); function that has been mentioned in that link.

A: How about this? just a little example

 var mynumber = document.getElementById("mynumber").innerHTML;
 mynumber = parseInt(mynumber);
 document.getElementById("mynumber-after").innerHTML = mynumber.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

80000

A: You can use Intl.NumberFormat
For example:

var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
});

$("button").on("click", function() {
  $("span").text(formatter.format(80000))
  //If you do not want to see the currenycy symbol
  // $("span").text(formatter.format(80000).substr(1))
})

<button>Calculate</button>


text:
Q: Z-Substitution of Integrals I'm busy studying for my Calculus exam and came across something that I'm not too sure about. The question asks to use z-substitution to determine an integral. The actual question is:
Use z=tan(x/2) to determine the integral:
Integral from 0 to pi/3 of dx/(3+2cosx)

Is Z-Substitution the same as normal substitution but they give you what to use? Or is there another method?
Any help would be appreciated. Thanks in advance!

A: This is a standard substitution for evaluating integrals of rational functions of trigonometric functions. A more common name is the Weierstrass substitution.
You will find full details in the Wikipedia article linked to above.


text:
Q: How to make complex array combination from user input? Javascript I'm pretty new to this field. So, currently, I want to make a simple feature for my website where if the user input like width and height value, the program will make an array that combines the two values but the other one is in alphabet form. So, for example, the user input weight = 4, and height = 2, I want the array to produce [A1, A2, B1, B2, C1, C2, D1, D2]. But, I got stuck in the part where combining those numbers and alphabet. As you can see from the snippet, I use for loop for most of the process. But, in the nested for loop, it will produce like [A1, A12, A1, A12] and so on. The alphabet is not changing and the number is stacking. I really need your help, Thank you!

var askW = prompt('Enter width value');
var askH = prompt('Enter height value');
mapGenerator(askW, askH);

function mapGenerator(askW, askH){
    var w = Number(askW);
    var h = Number(askH);
    var containerW = [];
    var containerH = [];
    var initialCharValue = 64;
    var i;

    for (i = 64 ; i <= w + initialCharValue; i++){
        containerW.push(String.fromCharCode(i));
    }

    for (i = 1 ; i <= h; i++){
        containerH.push(i);
    }

    console.log(containerW);
    console.log(containerH);

    mapGenerator2(containerW, containerH);

    function mapGenerator2(containerW, containerH){
        var temparray = [];
        var repeated = [];
        var testArr = [];
        var i,j,a,b,chunk = 1;
        for (i=1,a=containerW.length; i<=a; i++) {
            temparray[i] = containerW.slice(i,i+chunk);
            repeated[i] = new Array(containerH.length).fill(temparray[i]).flat();
        }
        for (i=1, a = containerW.length; i<a ; i++){
            testArr = repeated[i].map(function(item) {
              for(i=1, a = containerW.length; i<a ; i++){
                  console.log(item+= i);
              }
            console.log(testArr);
            });
        }
    }

}

P.S.: In the nested for loop, I use console.log because if I push the items into the array, it will like lagging and not logging console.

A: you need to create two loops that are nested the first loop will be in charge of the alphabet and the second will be in charge of the numbers like so:

function mapGenerator2(height, width) {
  const result = [];

  for(let i = 0; i < width; i++) {
    for(let j = 1; j <= height; j++) {
      result.push(`${String.fromCharCode(65 + i)}${j}`);
    }
  }

  return result;
}

console.log(mapGenerator2(2, 4));

A: I have updated your MapGenerator Function which shows the correct way of using nested for loops

var askW = prompt('Enter width value');
var askH = prompt('Enter height value');
mapGenerator(askW, askH);

function mapGenerator(askW, askH){
    var w = Number(askW);
    var h = Number(askH);
    var containerW = [];
    var containerH = [];
    var initialCharValue = 64;
    var i;

    for (i = 64 ; i <= w + initialCharValue; i++){
        containerW.push(String.fromCharCode(i));
    }

    for (i = 1 ; i <= h; i++){
        containerH.push(i);
    }

    result = mapGenerator2(containerW, containerH);
    console.log(result)

    function mapGenerator2(containerW, containerH){
        var resultarray = [];
        containerW.shift();
        containerW.forEach(function(itemW) {
           containerH.forEach(function(itemH) {
             resultarray.push(itemW + itemH.toString());
           })
        });

        return resultarray;
    }

}


text:
Q: Why can't I access the bin directory? Why can't I access the bin directory with the following command?
ls / this shows me the hidden bin folder
cd bin I get this error 'No such file or directory'

A: When you do cd bin you look for a bin directory in the current working directory (which apparently doesn't exist).
To access the root bin directory, /bin you need to do
cd /bin

with the leading /.

A: To further explain:
List the current directory's contents (either one):
ls .
ls

List the root directory's contents (wherever you are):
ls /

List the home directory's contents (wherever you are):
ls ~

So your first command listed the contents of a directory that was (likely) not the one you were in.  If you are wondering about your current directory, try
pwd

The prompt that you see does not always show the full path, since that would take up the entire screen.  You can modify this, but it's not desired.


text:
Q: Implementing NSText delegate methods in PyObjc and Cocoa In the project that I'm building, I'd like to have a method called when I paste some text into a specific text field. I can't seem to get this to work, but here's what I've tried
I implimented a custom class (based on NSObject) to be a delegate for my textfield, then gave it the method: textDidChange:
class textFieldDelegate(NSObject):
    def textDidChange_(self, notification):
        NSLog("textdidchange")

I then instantiated an object of this class in interface builder, and set it to be the delegate of the NSTextField. This however, doesn't seem to do anything. However, when I build the example code from http://www.programmish.com/?p=30, everything seems to work perfectly fine. How do I impliment this delegate code so that it actually works?

A: The reason this isn't working for you is that textDidChange_ isn't a delegate method. It's a method on the NSTextField that posts the notification of the change. If you have peek at the docs for textDidChange, you'll see that it mentions the actual name of the delegate method:

This method causes the receiver's delegate to receive a controlTextDidChange: message. See the NSControl class specification for more information on the text delegate method.

The delegate method is actually called controlTextDidChange_ and is declared on the NSTextField superclass, NSControl.
Change your delegate method to:
def controlTextDidChange_(self, notification):
    NSLog("textdidchange")

and it should work for you.


text:
Q: How to use np.where to find the index value of a certain element within an array? Here is my sample data:
# sample data
xdata = [3.33172, 3.33348, 3.33525, 3.33702, 3.33878, 3.34055, 3.34232,
3.34408, 3.34585, 3.34762, 3.34938, 3.35115, 3.35292 , 3.35468, 3.35645,
3.35822, 3.35998, 3.36175, 3.36352, 3.36529, 3.36705, 3.36882]
ydata = [-0.00437834, -0.00486735, -0.0118371, -0.00582171, 0.00339488,
-0.000369502, -0.000898799, -0.00797662, -0.00853566, -0.0123596,
-0.0162318, -0.0103355, -0.00445416, 0.00137920, -0.00251916, -0.00968244,
0.00260652, 0.00841350, 0.00445556, 0.00373271, 0.00621243, 0.00220983]

How could I use np.where to find the index value of 3.35115, for example?

A: You need to first turn your data into a numpy array so you can check where it is == to your target value:
>>> np.where(np.array(xdata) == 3.35115)
# (array([11]),)

This says that index 11 of xdata is 3.35115.


text:
Q: Terraform - Getting error: Your query returned no results. Please change your search criteria and try again Simply I'm trying to adopt some project tags to an existing internet gateway, by using data statements
data "aws_internet_gateway"    "internet_gateway"  {
   filter {
       name   = "attachment.vpc-id"
       values = [ aws_default_vpc.network[0].id ]
   }

   tags = var.tags
}

I've also checked with aws cli, here is the output
aws ec2 describe-internet-gateways
{
    "InternetGateways": [
        {
            "Attachments": [
                {
                    "State": "available",
                    "VpcId": "vpc-***"
                }
            ],
            "InternetGatewayId": "igw-***",
            "OwnerId": "***",
            "Tags": []
        }
    ]
}

The filter I've used were in the example of terraform official documentation web page
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/internet_gateway

A: You should remove the tags section from the Terraform data lookup. You are instructing Terraform to search for an internet gateway that has those tags, but as you can see in the CLI output the internet gateway doesn't have any tags assigned to it.
On a Terraform resource element, specifying tags would cause it to assign those tags to the resource, but on a data element specifying tags causes Terraform to use the tag values as part of the search it performs.

If it still doesn't work, you will need to verify that the value of aws_default_vpc.network[0].id  is what you are expecting, i.e. the same value as VpcId in the CLI output.


text:
Q: error while adding repo for kde plasma 5 in ubuntu 14.04 I was trying to install KDE plasma 5 in ubuntu 14.04 64 bit
when i am trying to add
sudo apt-add-repository ppa:neon/kf5

i am getting this error
Cannot add PPA: 'ppa:neon/kf5'.
Please check that the PPA name or format is correct.

I was following the tutorial here


text:
Q: Advice on how to create a view in Redshift based on the following: I have the following table structure
JUR SDATE       EDATE       DESC
NYC 2019-04-06  2019-04-22  Term 1  USA
NYC 2019-06-29  2019-07-14  Term 2  USA
NYC 2019-09-21  2019-10-07  Term 3  USA
NYC 2019-12-14  2020-01-27  Term 4  USA
CAL 2019-04-13  2019-04-29  Term 1  USA
CAL 2019-09-28  2019-10-13  Term 3  USA
CAL 2019-12-19  2020-01-28  Term 4  USA
DPR 2019-05-06  2019-05-29  Term 1  COL

I need to create a view to return the following Boolean values parsing a date between start and end?
isNYCtermdate
isCALtermdate
isDPRtermdate


text:
Q: How to create playstore like shapes
How to create these download, rating , Media & Video and similar kind of shapes in android ? Is there any library available to do that ?
Thanks in advance.

A: Have look at this library. Its very easy to use.
<com.github.siyamed.shapeimageview.{ClassName}
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    android:src="@drawable/neo"
    app:siBorderWidth="8dp"
    app:siBorderColor="@color/darkgray"/>

You can put following classes in place of {ClassName}
1. BubbleImageView
2. CircularImageView
3. DiamondImageView
4. HeartImageView
5. HexagonImageView
6. OctogonImageView
7. PentagonImageView
8. RoundedImageView
9. StarImageView
etc


text:
Q: Value Error: Specifying the columns using strings is only supported for pandataFrames from sklearn.compose import make_column_transformer
col_trans=make_column_transformer((OneHotEncoder(handle_unknown='ignore'),['State']),
remainder='passthrough')
x=col_trans.fit_transform(x)
ERROR:


text:
Q: How to deal with Singleton along with Serialization Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
 private static MySingleton myInstance;

 private MySingleton(){

 }
  static{
    myInstance =new MySingleton();
 }
 public static MySingleton getInstance(){
    return MySingleton.myInstance;
 }
}

The above definition according to me satisfies the requirements of a Singleton.The only additional behaviour added is that the class implements serializable interface.
If another class X get the instance of the single and writes it to a file and at a later point deserializes it to obtain another instance we would have two instances which is against the Singleton principle.
How can I avoid this or am I wrong in above definition itself.

A: The solution with enum won't work with Singletons managed by Spring, EJB, Guice or any other DI framework. It works only with enums, only because enum is treated specially by the serialization algorithm.
Firstly, singletons don't need serialization, because if you deserialized it, and then deserialized singleton != YourSingleton.getInstance(), it would mean that you have two instances of your singleton, which means that YourSingleton isn't singleton at all, which may lead to unpredictable bugs.
However sometimes you need to serialize non-singleton which contains a reference to singleton. The solution is easy:
class NonSingleton implements Serializable {
    private transient YourSingleton singleton = YourSingleton.getInstance();
    ...
}

With Spring:
@Configurable
class NonSingleton implements Serializable {
    @Autowired
    private transient YourSingleton singleton;
    ...
}

A: Here below is my Singleton class that implements Serializable interface. Mark that it contains readResolve() method also.
import java.io.Serializable;

public class Singleton implements Serializable {

    private static Singleton singleton = new Singleton( );

    public int i = 1;

    private Singleton() { }

    public static Singleton getInstance( ) {

       return singleton;
    }

    public Object readResolve() {
       return getInstance( );
    }

    public static void main(String[] args) {
        Singleton s1 = getInstance();
        System.out.println(s1.hashCode());

        Singleton s2 = getInstance();
        System.out.println(s2.hashCode());
    }
}

Below is the class that will first serialize and then deserialize the above class. Here deserialization takes place two times, but both time only one instance will be created because of readResolve() method.
public class SingletonSerializableDemo {

    static Singleton sing = Singleton.getInstance();
    static Singleton s1  = null;
    static Singleton s2 = null;
    public static void main(String[] args) {
        try {
             FileOutputStream fileOut =
             new FileOutputStream("E:/singleton.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
             out.writeObject(sing);
             out.close();
             fileOut.close();
             System.out.println("Serialized data is saved");

             FileInputStream fileIn1 = new FileInputStream("E:/singleton.ser");
             FileInputStream fileIn2 = new FileInputStream("E:/singleton.ser");
             ObjectInputStream in1 = new ObjectInputStream(fileIn1);
             ObjectInputStream in2 = new ObjectInputStream(fileIn2);
             s1 = (Singleton) in1.readObject();
             s2 = (Singleton) in2.readObject();
             System.out.println(s1.hashCode() + " "+ s1.i);
             s1.i = 10;
             System.out.println(s2.hashCode() + " "+ s2.i);
             in1.close();
             in2.close();
             fileIn1.close();
             fileIn2.close();
          }catch(Exception i) {
             i.printStackTrace();
          }
    }
}

And the output will be:
Serialized data is saved
21061094 1
21061094 10
Conclusion: Singleton class can also be serialized by keeping readResolve() method in the Singleton class.

A: The best way to do this is to use the enum singleton pattern:
public enum MySingleton {
  INSTANCE;
}

This guarantees the singleton-ness of the object and provides serializability for you in such a way that you always get the same instance.
More generally, you can provide a readResolve() method like so:
protected Object readResolve() {
  return myInstance;
}

A: @ColinD is kind of right, but his answer also illustrates why singletons don't really jell with serialization.
Here's what happens when you serialize an enum value (see here).

The rules for serializing an enum instance differ from those for serializing an "ordinary" serializable object: the serialized form of an enum instance consists only of its enum constant name, along with information identifying its base enum type. Deserialization behavior differs as well--the class information is used to find the appropriate enum class, and the Enum.valueOf method is called with that class and the received constant name in order to obtain the enum constant to return.

So any additional state that you attach to your enum values does not survive serialization and deserialization.
You could do the same thing yourself, by adding custom serialization / deserialization code to your singleton classes.  That code would need to either not record the singleton's state at all, or throw it away when the singleton is deserialized.  Either way, you'd put the logic into a readResolve() method as explained by @ColinD's answer.
Now, I presume that the reason you want to serialize singletons is that you want to persist their state.  Unfortunately, that presents a conceptual problem.  Suppose that your application has instantiated the singleton in the normal course of events, and then it deserializes some object graph that includes a copy of a previous instance of the singleton.  What can it do?

*

*If it deserializes the singleton normally, it violates "singleton-ness".

*If it doesn't then the application cannot access the singleton's previous state.

A: This may be a familiar solution but just in case for reference.
public class ConnectionFactory implements Serializable {

    //Static variable for holding singleton reference object
    private static ConnectionFactory INSTANCE;

    /**
     * Private constructor
     */
    private ConnectionFactory() {

    }

    /**
     * Static method for fetching the instance
     *
     * @return
     */
    public static ConnectionFactory getIntance() {
        //Check whether instance is null or not
        if (INSTANCE == null) {
            //Locking the class object
            synchronized (ConnectionFactory.class) {
                //Doing double check for the instance
                //This is required in case first time two threads simultaneously invoke
                //getInstance().So when another thread get the lock,it should not create the
                //object again as its already created by the previous thread.
                if (INSTANCE == null) {
                    INSTANCE = new ConnectionFactory();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * Special hook provided by serialization where developer can control what object needs to sent.
     * However this method is invoked on the new object instance created by de serialization process.
     *
     * @return
     * @throws ObjectStreamException
     */
    private Object readResolve() throws ObjectStreamException {
        return INSTANCE;
    }

}

Testing the code
public class SerializationTest {

    public static void main(String[] args) {
        ConnectionFactory INSTANCE = ConnectionFactory.getIntance();

        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("connectFactory.ser"));
            oos.writeObject(INSTANCE);
            oos.close();

            ObjectInputStream osi = new ObjectInputStream(new FileInputStream("connectFactory.ser"));
            ConnectionFactory factory1 = (ConnectionFactory) osi.readObject();
            osi.close();

            ObjectInputStream osi2 = new ObjectInputStream(new FileInputStream("connectFactory.ser"));
            ConnectionFactory factory2 = (ConnectionFactory) osi2.readObject();
            osi2.close();

            System.out.println("Instance reference check->" + factory1.getIntance());
            System.out.println("Instance reference check->" + factory2.getIntance());
            System.out.println("===================================================");
            System.out.println("Object reference check->" + factory1);
            System.out.println("Object reference check->" + factory2);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

}

Output
Instance reference check->com.javabrains.ConnectionFactory@6f94fa3e
Instance reference check->com.javabrains.ConnectionFactory@6f94fa3e
===================================================
Object reference check->com.javabrains.ConnectionFactory@6f94fa3e
Object reference check->com.javabrains.ConnectionFactory@6f94fa3e

A: Let say we have the following singleton class:
public class ConnectionFactory implements Serializable {
    private static ConnectionFactory INSTANCE;

    private ConnectionFactory() {  }

    public static ConnectionFactory getInstance() {
        if (INSTANCE == null) {
            synchronized(ConnectionFactory.class) {
                if(INSTANCE == null)
                    INSTANCE = new ConnectionFactory();
            }
        }
        return INSTANCE;
    }
}

Now we have the main class like below for serialising and deserializing objects:
 public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
     ConnectionFactory INSTANCE=ConnectionFactory.getInstance();
     ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("connFactory.ser"));
     oos.writeObject(INSTANCE);
     oos.close();

     // Here I am recreating the instance by reading the serialized object data store
     ObjectInputStream ois = new ObjectInputStream(new FileInputStream("connFactory.ser"));
     ConnectionFactory factory1 = (ConnectionFactory) ois.readObject();
     ois.close();

     // I am recreating the instance AGAIN by reading the serialized object data store
     ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("connFactory.ser"));
     ConnectionFactory factory2 = (ConnectionFactory) ois2.readObject();
     ois2.close();

     // Let's see how we have broken the singleton behavior
     System.out.println("Instance reference check->" +factory1.getInstance());
     System.out.println("Instance reference check->" +factory2.getInstance());
     System.out.println("=========================================================");
     System.out.println("Object reference check->" + factory1);
     System.out.println("Object reference check->" + factory2);
}

So if we execute above code we will get following behaviour:
"it has created two objects and one static reference for INSTANCE. That means if we read the serialized format of a singleton object multiple times, we will create multiple objects. This is not what a singleton object is supposed to do. So can we avoid i?, Yes, we can."
To avoid multiple instances of singleton class we will use following method provided by serialization:
private Object readResolve() throws ObjectStreamException {
    return INSTANCE;
}

This will prevent the creation of multiple instances of a singleton class.

A: I think Singletons can be serialized and here is the code on how to do it:

import java.io.Serializable;

public class MySingleton implements Serializable {

    private MySingleton(String name) {
        this.name = name;
    }

    private static MySingleton mySingleton;

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static MySingleton getInstance(String name) {
        if(mySingleton == null) {
            System.out.println("in if...");
            mySingleton = new MySingleton(name);
        }

        return mySingleton;
    }
}

and here is "main" method which gets the instance of the Singleton class above,  serializes and de-serializes it:

 public static void main (String[] args) {

        MySingleton m = MySingleton.getInstance("Akshay");

        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D://temp.ser"));
            oos.writeObject(m);

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D://temp.ser"));
            MySingleton m2 = (MySingleton) ois.readObject();
            System.out.println(m2.getName());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

and output is:-

in if...
Akshay

Thanks.

A: Here is the Answer for Breaking the Singleton  class and and how to prevent our class from creating different object by using readResolve() methood;
import java.io.Serializable;
public class Singleton implements Serializable {
private static final long serialVersionUID = 1L;

private Singleton() {
}

private static class SingletonHelper {

    private static final Singleton INSTANCE = new Singleton();

}

public static Singleton getInstance() {

    return SingletonHelper.INSTANCE;
}

private Object readResolve() {
    Singleton instance = getInstance();
    return instance;
}

}
public class BreakSIngletonUsingSerialization {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {

    Singleton demo1 =Singleton.getInstance();
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("C:/Eclipse/serial.ser"));
    out.writeObject(demo1);
    Singleton demo2 =null;
    ObjectInput in = new ObjectInputStream(new FileInputStream("C:/Eclipse/serial.ser"));

    demo2 = (Singleton)in.readObject();

    System.out.println("Hascode demo1 : " +demo1);
    System.out.println("Hascode demo2 : " +demo2);
}

}

A: Singleton classes is just like a manager or controller and in general we do not want to save the state of any controller instead of the entity. Generally we need to save the object state of any entity not the controller.
Singleton is singleton for a single class loader not for multiple class loader. If a class is loaded in a classes loader then the other class loader will not know about it so it behaves like this.


text:
Q: disable Postfix TLS support for specific destination server I am trying to configure postfix to disable TLS for a specific remote smtp server that serves for multiple recipient domains.
I have set up a policy map that already contains some entries for specific recipient domains that work fine. But ist there a way to configure postfix to disable TLS for a remote smtp server regardless of what domains are hosted there?
I have tried quite a few entries in my TLS policy map file but without any success. I tried:

*

*smtp.server.com           none

*[smtp.server.com]         none

*smtp.server.com:25        none

*[smtp.server.com]:25      none

*12.23.34.45               none

*[12.23.34.45]             none

*12.23.34.45:25            none

*[12.23.34.45]:25          none

btw: yes, I postmapped the modified policy file :)
Still postfix tries to relay to that host using a TLS connection. As soon as I configure a specific recipient domain delivered via this mx, things work fine and no TLS connection is established. But since there are hundreds of recipient domains on the remote host, I cannot configure all of them in my policy :)
Any suggestions? Thanks in advance!
Best regards

A: As documented in http://www.postfix.org/TLS_README.html#client_tls_policy, a hostname or IP enclosed in square brackets is not resolved to an MX; it is assumed to be the MX.
Please provide postmap -q output for this map, and log entries that show what goes wrong.


text:
Q: Django throws TemplateDoesNotExist for a template located it in the 'my_app/templates/my_app' subfolder I am studying Django and got stuck right at the first project.
I've got TemplateDoesNotExist exception when accessing index page of my application. I saw a lot of same looking questions here, but answers seem to be referring to slightly different cases or older Django versions.
Template-loader postmortem shows that Django looked for the index page (index.html) in the 'movies/templates' directory, while file is placed inside 'movies/templates/movies' as it is suggested by manuals.
Project info
Project structure
'movies' is added to the INSTALLED_APPS list in the settings.py
And movies/views.py refers to the index.html in following way:
def all_films(request):
    return render(request, 'index.html', {'movies': my_movies, 'director': settings.DIRECTOR})

What worked
Adding 'os.path.join(BASE_DIR, 'movies', 'templates', 'movies'),' to the TEMPLATES['DIRS'] values in the settings.py makes it work, but after reading manuals and answers to same questions I assume it shouldn't be required.
Also, if I change movies/views.py so that it refers to 'movies/index.html' instead of 'index.html' everything works. But is it a good practice to use app name in links like this? I mean, it could be hard to maintain in future etc.
Question
Basically, question is what am I doing/getting wrong.
Could you please suggest, what else should I check to make it work in default state without manual editing of TEMPLATES' DIRS property?
P.S. I am using Django 3.2.7, OS is Ubuntu.

A: Check if 'APP_DIRS': True in settings.py>TEMPLATES

A: This should work!
settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

views.py
def all_films(request):
    return render(request, 'movies/index.html', {'movies': my_movies, 'director': settings.DIRECTOR})


text:
Q: Powershell Balloon Notification Vanishes before showing Have another head scratcher here, simply put my balloon notification does not work when fired from inside of a function that is inside of a job, the icon shows up for a fraction of a second and then disappears, tried several compinations of -wait -sleep -sleep-start to see if i could delay its "completion" since i feel the function is not running it's full course before ending, it works outside of the job/function, but inside it does not, here is the snippet I am calling
function MakeToolTip
{
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory=$true)]
$Text,

[Parameter(Mandatory=$true)]
$Title,

[ValidateSet('None', 'Info', 'Warning', 'Error')]
$Icon = 'Info',    $Timeout = 10000
)

Add-Type -AssemblyName System.Windows.Forms

if ($script:balloon -eq $null)
{
$script:balloon = New-Object System.Windows.Forms.NotifyIcon
}

$path                    = Get-Process -id $pid | Select-Object -ExpandProperty Path
$balloon.Icon            = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balloon.BalloonTipIcon  = $Icon
$balloon.BalloonTipText  = $Text
$balloon.BalloonTipTitle = $Title
$balloon.Visible         = $true

$balloon.ShowBalloonTip($Timeout)
}

This is called with: MakeToolTip "Testing" "VNC Connections" Info
The full code of the script is here, lines 239-269: https://pastebin.com/7Q4gwLJe
I'm considering running the balloon in a separate job? Maybe the pipeline is completing it too quickly because there too much other stuff going on?
EDIT
Finding that when wrapped in a job a balloon notification does not work, very strange behavior
$MakeToolTip =
{

function Makeit {
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory=$true)]
$Text,

[Parameter(Mandatory=$true)]
$Title,

[ValidateSet('None', 'Info', 'Warning', 'Error')]
$Icon = 'Info',    $Timeout = 10000
)

Add-Type -AssemblyName System.Windows.Forms

if ($balloon -eq $null)
{
$balloon = New-Object System.Windows.Forms.NotifyIcon
}

$path                    = Get-Process -id $pid | Select-Object -ExpandProperty Path
$balloon.Icon            = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balloon.BalloonTipIcon  = $Icon
$balloon.BalloonTipText  = $Text
$balloon.BalloonTipTitle = $Title
$balloon.Visible         = $true

$balloon.ShowBalloonTip($Timeout)
write-host $Text, $Title
}
}

$balloonjob = Start-Job -ScriptBlock {MakeIt 'Hi' 'There'} -InitializationScript $MakeToolTip -Name "BalloonJob"
        Register-ObjectEvent $balloonjob -EventName StateChanged -Action {
            if ($eventArgs.JobStateInfo.State -eq [System.Management.Automation.JobState]::Failed)
            {
                Write-Host "Closing the Balloon"
                # This command removes the original job
                $sender | Remove-Job -Force

                # These commands remove the event registration
                $eventSubscriber | Unregister-Event -Force
                $eventSubscriber.Action | Remove-Job -Force
            }
        }


text:
Q: How to automatically update small letter characters to capital letter in Java JEditorPane? So I want to automatically convert all entered characters to uppercase.
Here is relevant part of the code :
editorPane = new JEditorPane();
editorPane.getCaret().setBlinkRate(0);
this.keyListener = new UIKeyListener(editorPane);
editorPane.addKeyListener(keyListener);

And the UIKeyListener Class I am only providing the keyReleased function as other part is just boilerplate code
@Override
public void keyReleased(KeyEvent e) {
    capitalizeCode();
}

private void capitalize() {
    int prevCarerPosition = editorPane.getCaretPosition();
    editorPane.setText(editorPane.getText().toUpperCase());
    editorPane.setCaretPosition(prevCarerPosition);
}

This is mostly OK but the problems are :-

*

*I cannot select text

*Every time I type the characters they first appear in small letters then become capital

Now The first problem is solved if I call the capitalize function from keyTyped function but there there is a new problem : the last typed letter remains small
And I also want to ask whether can we do this without listening to keyevents like by default the editorpane will only accept capital letters?

A: Don't use a KeyListener.
A better approach is to use a DocumentFilter.
This will work whether text is typed or pasted into the text component.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class UpperCaseFilter extends DocumentFilter
{
    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
        throws BadLocationException
    {
        replace(fb, offs, 0, str, a);
    }

    public void replace(FilterBypass fb, final int offs, final int length, final String text, final AttributeSet a)
        throws BadLocationException
    {
        if (text != null)
        {
            super.replace(fb, offs, length, text.toUpperCase(), a);
        }
    }

    private static void createAndShowGUI()
    {
        JTextField textField = new JTextField(10);
        AbstractDocument doc = (AbstractDocument) textField.getDocument();
        doc.setDocumentFilter( new UpperCaseFilter() );

        JFrame frame = new JFrame("Upper Case Filter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new java.awt.GridBagLayout() );
        frame.add( textField );
        frame.setSize(220, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

The filter can be used on any text component.
See the section from the Swing tutorial on Implementing a DocumentFilter for more information.


text:
Q: Puppeteer Sharp not able to take screenshot in server Puppeteer Sharp not able to take screenshot in server using dotnet core web api. Its working in local.
I have already put executable chrome.exe and local-chromium folder in bin folder.
This is the message from server.
The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail
Did I miss anything?


text:
Q: How to handle ORA-00028 "your session has been killed" in Oracle 12c (12.2.0.1.0)? The problem is that handling an error ORA-00028 is kinda tricky. Please, look at the code below.
If you run proc1 in session 1 and while it's still running you kill session 1 with ALTER SYSTEM KILL SESSION then you get ORA-00028 error message and no row in llog table.
If you run proc1 and let it finish (1 min) then error handling works as expected and you get no error message and 1 row in llog table. But the funny thing is if after that you run proc1 again and kill that session you get no error-message (ORA-00028 handled) and one more row in llog table.
So for ORA-00028 to be handled in exception clause you need to catch some other error first. It seems to be a bug. Has anyone faced this problem?
/* creating simple table with logs */

create table llog(time timestamp, error varchar2(4000));
/

/* creating package */

create or replace package my_pack
is
       procedure proc1;
end;
/
/* creating package body*/

create or replace package body my_pack
is

e_session_killed EXCEPTION;
PRAGMA EXCEPTION_INIT(e_session_killed, -00028);

procedure error_log (time llog.time%type, error llog.error%type) is
  pragma autonomous_transaction;
begin
  insert into llog values (time, error);
  commit;
end;

procedure proc1 is
begin

  dbms_lock.sleep(60);

  raise too_many_rows;

  exception
    when e_session_killed then
      error_log(systimestamp, sqlerrm);

    when others then
      error_log(systimestamp, sqlerrm);

end;

end;

A: You can't catch a kill session. It interrupts the current operation (as mush as it can - there might be some low level operations that cause issues), rolling back the open transaction(s). Once the rollback is complete the client is told that it is disconnected (assuming the client is still there) and the process goes away.
There's a couple of variants of kill session that affect the order of those but you're not going to be able to insert anything into any table from a killed session.
The only exception might be through a database link or similar, where you actually have two separate sessions/processes going on at the same time.


text:
Q: Python adding attachment to an e-mail from a function I am trying to automate sending attachments and e-mails from Python:
def Emailer(text, subject, recipient):
    import win32com.client as win32
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    mail.Display(True)
    attachment = 'C:/Users/.../file.pdf'
    mail.Attachments.Add(attachment)

Emailer('text', 'test', 'name@mail.com')

However, this does not add an attachment. The path should be correct, because when I try below, it works:
import win32com.client as win32
mail = win32.Dispatch('outlook.application').CreateItem(0)
mail.To = 'name@mail.com'
mail.Subject = 'test'
mail.HTMLBody = 'text'

attachment  = 'C:/Users/.../file.pdf'
mail.Attachments.Add(attachment)
mail.Display(True)

Anyone knows what I am doing wrong with my Emailer()

A: In Emailer you call MailItem.Display(True) before you add the attachment, whereas in the "working" snippet you do so after. According to the official documentation Display(True) creates a modal window, it might also be a blocking call meaning Emailer would stop running until you close the window.
I'd suggest moving the call to Display to after you've added the attachment, or maybe try opening a non-modal window.
Incidentally, according to the doc linked above Display is deprecated.


text:
Q: Proof that interval $]0,1[$ is an open set I have this question in my set of exercises of real analysis:

prove that the interval $]0,1[$ is an open set.

The definition says

the set $A\subset \mathbb{R}^m$ is open if for all $a \in A$, $\exists \delta \gt 0$ such that $B[a; \delta] \subset A$.

Although I get the intuition of this definition somehow, I don't really know how to prove the statement mathematically. In particular, I don't know how to choose my $\delta$.
Any tips are welcomed.
Thank you in advance.

A: If $a\in A$, take $\delta=\min\{a,1-a\}$ (that is, $\delta$ is the smallest between the distances from $a$ to $0$ and to $1$). Then $(a-\delta,a+\delta)\subset(0,1)$.

A: For $a \in (0,1)$ set $$\delta = \frac12(1-|2a-1|)$$
Then $B(a, \delta) = (a-\delta, a+\delta) \subseteq (0,1)$. Indeed,
$$a-\delta = a-\frac12(1-|2a-1|) = \left(a-\frac12\right) + \left|a-\frac12\right| \ge 0$$
$$a+\delta = a+\frac12(1-|2a-1|) = \left(a+\frac12\right) - \left|a-\frac12\right| \le \left(a+\frac12\right) - \left(a-\frac12\right) =1 $$


text:
Q: React material-ui: centering items on Toolbar I am trying to implement a toolbar on a page in which I have three ToolbarGroup components:
            <Toolbar>
                <ToolbarGroup firstChild={true} float="left">
                    {prevButton}
                </ToolbarGroup>

                <ToolbarGroup>
                    {releaseBtn}
                </ToolbarGroup>

                <ToolbarGroup lastChild={true} float="right">
                    {nextButton}
                </ToolbarGroup>
            </Toolbar>

The general idea is that prevButton should render all the way to the left of the toolbar (it does), nextButton should render all the way to the right (it does)... and that releaseBtn should be centered on the toolbar (not currently happening).
Per the material-ui docs there doesn't appear to be some easy setting for centered={true}-- how can I accomplish this?
I've tried manually setting the style on the middle ToolbarGroup to margin: 0px auto but that doesn't seem to help.

A: If anyone runs into this in 2021 or later like I did, material-ui's Toolbar uses Flexbox under the hood, so all you have to do is apply a custom class (or override the default one in the theme):
.myToolbar {
  justify-content: space-between;
}

space-between will distribute the children alongside the main horizontal axis:

(picture from https://css-tricks.com/snippets/css/a-guide-to-flexbox/)

A: The final solution for me was to do this:
            <Toolbar>
                <ToolbarGroup firstChild={true} float="left">
                    {prevButton}
                </ToolbarGroup>

                <ToolbarGroup style={{
                    float       : 'none',
                    width       : '200px',
                    marginLeft  : 'auto',
                    marginRight : 'auto'
                }}>
                    {releaseBtn}
                </ToolbarGroup>

                <ToolbarGroup lastChild={true} float="right">
                    {nextButton}
                </ToolbarGroup>
            </Toolbar>

I first had to set the middle ToolbarGroup with no float (not an option through the material-ui props) and then play with the width/margins. I imagine your mileage may vary depending on what you shove inside the ToolbarGroup.

A: In new versions of Material UI you can just use the sx prop:
https://mui.com/system/the-sx-prop/#main-content

<Toolbar sx={{ justifyContent: "space-between" }}> // or "center" for a single element
...
</Toolbar>