text:
Q: saving a TCP audio stream to .wav I´m trying to capture an audiostream that is send over TCP.
It kind of works but I have a lot of noise and gaps inside the audiofile. I don't really know what is going wrong so maybe you can help me:
import socket,os, sys
import threading, wave, pyaudio

host_name = socket.gethostname()
host_ip = '192.168.1.4'#  socket.gethostbyname(host_name)
print(host_ip)
port = 2013

filename="test.wav"
CHANNELS=2
RATE=24000
frames = []
sample_format=pyaudio.paInt16
p = pyaudio.PyAudio()

def audio_stream():
    with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as client_socket:
        socket_address = (host_ip,port-1)
        print('server listening at',socket_address)
        client_socket.connect(socket_address)
        print("CLIENT CONNECTED TO",socket_address)
        data_start=b'\x01\x00\xfe\xff\x01\x00\x00\x00\x08\x00\x06\x00\xfd\x74\xfa\x03\x00\x01\x05\x00\x00\x00\x00\x00'
        client_socket.sendall(data_start)
        print("Sent:     {}".format(data_start))
        i=0
        while True:
            try:
                data= client_socket.recv(1024*2)
                frames.append(data)

                i=i+1
                if i==1500:
                    data_stop=b'\x01\x00\xfe\xff\x03\x00\x00\x00\x04\x00\x08\x00\xce\xa7\x8a\x49\x00\x01\x05\x00'
                    client_socket.sendall(data_stop)
                    print("Sent:     {}".format(data_stop))
                    print(frames)
                    client_socket.close()
                    print('Audio closed')
            except socket.error as error_message:
                break

    with wave.open(filename,"wb") as sf:
                sf.setnchannels(CHANNELS)
                sf.setsampwidth(3)
                sf.setframerate(RATE)
                sf.writeframes(b"".join(frames))
                sf.close()
                print("data saved")

    os._exit(1)

t1 = threading.Thread(target=audio_stream, args=())
t1.start()

I'm sending a  message "data_start" to start the audiostream on a testrack. I capture the tcp frame I get and stop the audiostream with the "data_stop" message. After that the captured frames will be saved into an wavefile.
Wavefile of the captured tcp stream:

As you can see there is a lot of noise, left and right of the burst there should be anything near silence. There are also a lot of gaps inside the signal that aren't in the expected signal. For better comparison I show you the expected signal:

Am I missing frames or anything else?


text:
Q: Shape image like bubble with arrow (Android) What I wanted is to turn my imageview to shape like this
I was using this library
https://github.com/siyamed/android-shape-imageview

I was able to add a border radius on it but my problem is
I don't know how to add an arrow while adding border radius on it

A: use this app:siArrowPosition="right":-> siArrowPosition where to point the arrow, currently left|right
use this app:siRadius="6dp" :-> corner radius in dp
and
app:siBorderWidth="6dp" border width in dpfor border
<com.github.siyamed.shapeimageview.BubbleImageView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:src="@drawable/neo"
  app:siRadius="6dp"
  app:siBorderWidth="6dp"
  app:siArrowPosition="right"
  app:siSquare="true"/>

A: check it to get this kind of bubble view https://github.com/florent37/ShapeOfView
<com.github.florent37.shapeofview.shapes.BubbleView
    android:layout_width="150dp"
    android:layout_height="150dp"
    app:shape_bubble_arrowHeight="10dp"
    app:shape_bubble_arrowWidth="10dp"
    app:shape_bubble_arrowPosition="bottom"
    app:shape_bubble_borderRadius="20dp"
    app:arrow_posititon_percent="0.5"
    >

     <!-- YOUR CONTENT -->

</com.github.florent37.shapeofview.shapes.BubbleView>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do distinct count in a VBA generated pivot table is there a way to do disticnt count in a VBA generated pivot table?
The code below is used to create a pivot table, however it does not have an option to do distinct count. Is there a way to improve it? Thanks.
Dim wsData3 As Worksheet
Set wsData3 = Worksheets("ProcessIT GE")

Dim PvtTblCache3 As PivotCache
Set PvtTblCache3 = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
        SourceData:="GE")
    PvtTblCache3.CreatePivotTable TableDestination:=wsPvtTbl.Range("B" & LastRow_p + 8), _
        TableName:="PivotTable3"

Dim PvtTb3 As PivotTable
Set PvtTb3 = wsPvtTbl.PivotTables("PivotTable3")

PvtTbl.ManualUpdate = True

Set pvtFld = PvtTb3.PivotFields("Period")
pvtFld.Orientation = xlPageField

With wsPvtTbl.PivotTables("PivotTable3").PivotFields("Period")
        On Error Resume Next
        .PivotItems("Y").Visible = True
        .PivotItems("N").Visible = False
        On Error GoTo 0
    End With

Set pvtFld = PvtTb3.PivotFields("INVOICE_TYPE")
pvtFld.Orientation = xlPageField

With wsPvtTbl.PivotTables("PivotTable3").PivotFields("INVOICE_TYPE")
        On Error Resume Next
        .PivotItems("GE").Visible = True
        .PivotItems("PO Matched").Visible = False
        On Error GoTo 0
    End With

    For Each pivot_item In PvtTb3.PivotFields("Period").PivotItems
        If pivot_item.name = "Y" Then
            Set pvtFld = PvtTb3.PivotFields("Submission Date 1")
                pvtFld.Orientation = xlColumnField

            '.AddDataField PvtTb3.PivotFields("THEMIS_INV_ID"), "Distinct Count of ID", xlDistinctCount

            With PvtTb3.PivotFields("THEMIS_INV_ID")
               .Orientation = xlDataField
                .Function = xlCount
                .NumberFormat = "#,##0"
                .Position = 1
            End With
        End If
    Next pivot_item


text:
Q: why the photo does not appear although I have written the complete path in database? enter image description here
is there any wrong in the path? if there is .. so how to write valid image path in mysql database ? note that i am using php..The image above contains the colume of image which contains the paths of my images like C:/wamp/www/phpT/images/products/man.png
first of all I store the image by the complete path of it like this :
$uploadName=md5(microtime()).'.'.$mimeExten;
    $uploadPath='C:/wamp/www/phpT/images/products/'.$uploadName;
    $dbPath='C:/wamp/www/phpT/images/products/'.$uploadName;
    move_uploaded_file($fileTempLoc,$uploadPath);

    $insertSql="INSERT INTO products (title,price,list_price,brand,categories,image,description,sizes)
    VALUES ('$title','$price','$list_price','$brand','$category','$dbPath','$description','$sizes')";
    $db->query($insertSql);

Then I get it from the data base but it does not appear

A: Those are local file paths, not URLs.  The file paths aren't going to work as image sources in a web page.
You'll need to replace C:/wamp/www/ with something that points at your web server instead of your file system, like http://localhost/ for your local dev environment.
The exact URL depends on your web server configuration, whether you're using a framework or otherwise rewriting URLs, and other various info we don't have about your specific installation.
If you store just the filename, and fill in the rest of the URL and path in your application, it will give you more flexibility with those resources in the future. As it is, you won't be able to change the directory structure at all without breaking your images again.


text:
Q: Facebook channel shows as "Error" Under my channels, the Facebook one's status is "Error". But I can't see what it is in that state. I have removed the channel and re-added it but it is still the same.
What could be causing this?

A: If you hover over the "Error" text in the status list it will provide a more detailed messages.


text:
Q: Get count by unique values in a column I have a schema like: (parent, child, item, frequency)
The same parent can have multiple child and different child can have repeating item with the repeating frequency. e.g.
PA    CA   IA  FA
PA    CB   IA  FA
PA    CB   IB  FB

Note that CA and CB both have one common item.
So, now I want all distinct parents along with sum of frequencies. e.g. for the above table the answer is PA,(FA+FB). (NOTE: not 2*FA+FB).
I tried with the following SQL query but that is giving me 2*FA+FB.
SELECT distinct [parent], sum(frequency) as freq
FROM [sampleDB].[dbo].[sampleTable]
group by [parent]
order by freq DESC

That makes sense as distinct is over parent and not on query. Noting the mistake, then I tried with
SELECT distinct [parent], sum(frequency from (Select distinct [item], [frequency])) as freq
FROM [sampleDB].[dbo].[sampleTable]
group by [parent]
order by freq DESC

But that is giving syntactical errors. What should be the correct query?

A: Probably you need this:
SELECT parent, SUM(frequency) AS freq
FROM (SELECT DISTINCT parent, item, frequency FROM sampleTable) AS t
GROUP BY parent
ORDER BY freq DESC

A: try this:
SELECT parent, sum(frequency) FROM (SELECT DISTINCT parent, frequency FROM table_name) GROUP BY parent

A: If I understand correctly, you want to first summarize at the parent/item level, then sum the frequencies:
select parent, sum(frequency)
from (select distinct parent, item, frequency
      from sampletable st
     ) st
group by parent;


text:
Q: Changing theme color from grey to blue I am trying to change the default GREY color of the placeholder in md-input-container to Material Blue color. I have tried to change the default theme like mentioned in the documentation and I have tried making my own theme to theme a specific view/ui item. However none of the below code works to modify the color of the md-input-container placeholder. What am I missing?
mainApp.config(function($mdThemingProvider) {
    $mdThemingProvider.theme('alt')
        .backgroundPalette('blue-grey')
        .primaryPalette('orange')
        .accentPalette('green');
});

<md-input-container class="md-block" flex="30" md-theme="alt">
    <input required type="text" placeholder="Week"
           />

This is required.

</md-input-container>

A: Haven't found an official way to do this.
You can either use the selector (note that the theme name is part of it):
md-input-container.md-alt-theme label,
md-input-container.md-alt-theme .md-placeholder {
  color: rgb(96, 125, 139);
}

Or you can modify the foregroundPalette, seems the input label uses the third one:
$mdThemingProvider.theme('alt').foregroundPalette[3] = 'rgb(96, 125, 139)';


text:
Q: How to exclude wwwroot folder from an ASP.NET 5 project? How to exclude the wwwroot folder from an ASP.NET 5 project, so the Visual Studio wont track this folder?

A: To exclude this folder, go into the project.json file and make sure it is listed in the exclude section as listed below:
  "exclude": [
    "wwwroot",
    "node_modules"
  ]

In a newly created ASP.NET 5 web project, this file will be added for you automatically and should already have this setting configured.


text:
Q: Why my Revit view are blank? We are working on a project using workset. Recently we start to find our views blank when we start our Revit project, we need to zoom all to see the view content. It was not like that befor a new member come to our team. The same thing start happning in other project when she started working with it. What is the possible reason to that?

A: There is likely an element floating in space that is stretching your view extents. It could also be an element in a linked file, revit or cad.


text:
Q: QML access to ListView custom property from header component I have code like this (reusable LisView):
//ListViewEx.qml

ListView {
    id: root
    property string headerText

    header: Pane {
        id: headerComponent
        ...
        Label {
            text: root.headerText
        }
        ...
    }
    ...
}

and use it, like this:
//sample.qml

Item {
    ...
    Pane {
        ...
        GridLayout {
            ...
            ListViewEx {
                headerText: qsTr('sample header')
                ...
            }
        }
    }
}

This works, but qmllint reports "Unqualified access". I'm new to QML and I'm not sure if it's a problem with qmllint or should I use different formule.
I tried some modification. For example text binding like this:
    text: headerComponent.ListView.view.headerText

This works too, but qmllint reports "Property headerText not found on type QQuickItemView".
Interestingly, in the first case, if I change the ListView property declaration to this (which is obviously a bug - required properties with initializer do not make sense):
    required property string headerText: ""

then qllint will stop reporting the warning.
========

*

*Python 3.11

*PySide6 (Qt 6.4.1)

*VSCode

A: Perhaps you can consider using the ListView.view attached property to gain access to the parent ListView. Typically, in a delegate, I assigned the attached property to a new property so that the entire delegate has a convenient way of accessing the property:
property ListView listView: ListView.view

The following is an example usage where both the item delegate and header delegate are using the ListView.view attached property to discover its width as well as read the custom headerText property:
import QtQuick
import QtQuick.Controls
Page {
    background: Rectangle { color: "#848895" }
    MyListView {
        width: 200
        height: parent.height
        headerText: qsTr('sample header')
        model: MyModel { }
        delegate: MyDelegate { }
    }
}

// MyListView.qml
import QtQuick
import QtQuick.Controls
ListView {
    model: 20
    width: 200
    height: parent.height
    property string headerText: "Header"
    ScrollBar.vertical: ScrollBar {
        width: 20
        policy: ScrollBar.AlwaysOn
    }
    header: MyHeader { }
}

// MyHeader.qml
import QtQuick
import QtQuick.Controls
Frame {
    property ListView listView: ListView.view
    width: listView.width - 20
    background: Rectangle {
        color: index & 1 ? "#eee" : "#ddd"
        border.color: "#ccc"
    }
    Text {
        text: listView.headerText
    }
}

// MyDelegate.qml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Frame {
    property ListView listView: ListView.view
    width: listView.width - 20
    background: Rectangle {
        color: index & 1 ? "#eee" : "#ddd"
        border.color: "#ccc"
    }
    RowLayout {
        width: parent.width
        Text {
            text: index + 1
            color: "grey"
        }
        Text {
            text: n
        }
    }
}

// MyModel.qml
import QtQuick
import QtQuick.Controls
ListModel {
    ListElement { n: "Bill Gates" }
    ListElement { n: "Jeff Bezos" }
    ListElement { n: "Steve Jobs" }
}

You can Try it Online!


text:
Q: How get WEB-INF folder path in java JAX-WS app I have a java webservice application with java bean's.
How i can determine full path to file in WEB-INF directory.

A: Why do you need this for ?
One way to do this is from your jsp/servlet through getServletContext().getResourceAsStream("web-app/WEB-INF/...")
Also, if you are trying to use a .wsdl file on a client, you are better off specifying the uri of your server rather than the physical address.


text: Q: Get Linux Executable Signing Certificate Information I wanted to know if there was a way (some sort of library that I'm unaware of) that gets the signing certificate details of an executable. I know it's possible to sign a binary using openssl but how can I retrieve this details? In mac there is a command called codesign that allows getting details of signed packages/executables.  Is there something similar to this on linux?


text:
Q: Replace content present in the nested brackets Input = ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))
Expected Output = ABCDEF,GHIJKLMN,OPQRSTUVW
Tried so far
Output = Input.replace(/ *\([^)]*\)*/g, "");

A: Using a regex here probably won't work, or scale, because you expect nested parentheses in your input string.  Regex works well when there is a known and fixed structure to the input.  Instead, I would recommend that you approach this using a parser.  In the code below, I iterate over the input string, one character at at time, and I use a counter to keep track of how many open parentheses there are.  If we are inside a parenthesis term, then we don't record those characters.  I also have one simple replacement at the end to remove whitespace, which is an additional step which your output implies, but you never explicitly mentioned.

var pCount = 0;
var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = "";
for (var i=0; i < Input.length; i++) {
    if (Input[i] === '(') {
        pCount++;
    }
    else if (Input[i] === ')') {
        pCount--;
    }
    else if (pCount == 0) {
        Output += Input[i];
    }
}

Output = Output.replace(/ /g,'');
console.log(Output);

A: If you need to remove nested parentheses, you may use a trick from Remove Nested Patterns with One Line of JavaScript.

var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = Input;
while (Output != (Output = Output.replace(/\s*\([^()]*\)/g, "")));
console.log(Output);

Or, you could use a recursive function:

function remove_nested_parens(s) {
    let new_s = s.replace(/\s*\([^()]*\)/g, "");
    return new_s == s ? s : remove_nested_parens(new_s);
}
console.log(remove_nested_parens("ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))"));

Here, \s*\([^()]*\) matches 0+ whitespaces, (, 0+ chars other than ( and ) and then a ), and the replace operation is repeated until the string does not change.


text:
Q: How to create 3 unique values from an array of characters can you please take a look at this demo and let me know how I can  create 3 unique values from an array of numbers?

var num = [];
var chances = "0123456789";
for (var i = 0; i < 3; i++) {
  num.push(chances.charAt(Math.floor(Math.random() * chances.length)));
}

console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: You can do something like this

var num = [];
for (var i = 0; i < 3;) {
  var ran = Math.floor(Math.random() * 10);
  //  You can generate random number between 0-9 using this , suggested by @Tushar
  if (num.indexOf(ran) == -1)
  // check number is already in array
    num[i++] = ran;
    // if not then push the value and increment i
}

document.write(num.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

For getting unique alphabets

var res = [],
  alp = 'abcdefghijklmnopqrstuvwxyz'.split('');
  // creating an array of alphabets for picking alphabers
for (var i = 0; i < 3;) {
  var ran = Math.floor(Math.random() * 26);
  //  You can generate random number between 0-25 using this
  if (res.indexOf(alp[ran]) == -1)
  // check alphabet is already in array
    res[i++] = alp[ran];
  // if not then push the value and increment i
}

document.write(res.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or

var res = [],
  alp = 'abcdefghijklmnopqrstuvwxyz'.split('');
  // creating an array of alphabets for picking alphabers
for (var i = 0; i < 3;) {
  var ran = Math.floor(Math.random() * 10000) % 26;
  //  You can generate random number between 0-25 using this
  if (res.indexOf(alp[ran]) == -1)
  // check alphabet is already in array
    res[i++] = alp[ran];
  // if not then push the value and increment i
}

document.write(res.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: You may also try this code:

var num = [];
var chances = "0123456789";
var len = chances.length;
var str;
while (num.length < 3) {
  str = "";
  while (str.length < len)
    str += chances[Math.floor((Math.random() * len) % len)];
  if (-1 === num.indexOf(str))
    num.push(str);
}
document.write(JSON.stringify(num));


text:
Q: is css for pair tags only? i'm trying to understand css and first thing i tried was this:

and

can anybody please explain what's happening? i thought there should be no difference.. until now i was experiencing just pure xml so this is kinda frustrating for me..
and one more side question.. how does it work with displaying the whole thing? I assume first thing is the browser builds the DOM tree which would normally be displayed dependent from order of elements. Is it the same with css with only that little change defined by styles? i mean the rule from stylesheet is first applied when some concrete element is being displayed, no other tricks in it..right?

A: You are, no doubt, serving your XHTML with a text/html content-type.
This is a hack designed to ease the transition from HTML to XHTML, so people can start using XHTML before browsers support it. After a decade, Internet Explorer still doesn't support it and I've gone back to HTML.
Since you are using this hack, you must write your XHTML to be compatible with HTML parsers as well as XML parsers. This means following the HTML Compatibility Guidelines which include:

If an element permits content (e.g., the div  element) but an instance of that element has no content (e.g., an empty section), DO NOT use the "minimized" tag syntax (e.g.,
).

Elements which do not permit content are defined as "EMPTY" and can be easily spotted on the HTML list of elements.

A: CSS can be applied to any "tag" but you use of
 is just not correct. A div tag always needs a closing tag:

And what is happening is that you give the div a width and height of 100 pixels and a black border which is 1 pixel wide.
Maybe you want to read some CSS tutorials.
You can also try

to see that it works with self-closing tags ;)
A list of valid self-closing tags in XHTML.

A:
s are supposed to have content, so they are not self closing tags. Your CSS properties are fine, but your markup is incorrect.

A: As mentioned, a div element needs start and end tags… Unless you do what you did in some of your examples:

Or…

This is a self-closing (empty) div.
So, for your CSS tests, you probably don't wanna use
 — use
Foo
 instead.

A: If you really want self-closing DIVs:

*

*Serve your content as XHTML. This includes using the correct mime-type (application/xhtml+xml), but be aware that you'll need to handle browsers that still don't understand XHTML.

*Use a valid XHTML doctype and namespace,
e.g.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

This will then display your DIVs as you expect but, in my experience, serving good old HTML 4 strict is a lot less hassle.

A: I'm not sure that your DIV problem is based on CSS, I think it's more a case of browser interpretation. Browsers expect DIVs to have content and maybe don't render those correctly. XHTML is XML compatible, but isn't itself (meaning it doesn't abide by ALL the rules of), XML.
CSS does work for self-closing tags - e.g. IMG or HR.
Your second question seems right. The browser effectively caches the stylesheet and applies the styles whenever it sees a relevant tag within the DOM. You never really see all this happening because it's generally done before any drawing is done to the page. If you dynamically add a DOM Tag, with a CSS reference, it would automatically take on that style defined in your stylesheet.


text:
Q: Creating the equivalent Action in Java from C# I have code in C# that looks like:
 Action<Guid, QueryResult> onData = (guid, data) =>
 {
      total += data.NumberOfRows;
      Console.WriteLine("Guid: {0} Number of rows: {1}", guid, data.NumberOfRows);
 };

I would like to replicate this in Java, but Im unsure of the equivalent Java that would replace the Action code
Could anyone advise?

A: Here it is:
 BiConsumer<String, Integer> resultBiConsumer = new BiConsumer<Guid, QueryResult>() {
     @Override
     public void accept(Guid s, QueryResult data) {
         total += data.numberOfRows;
         System.out.printf("Guid: %s  Number of rows: %d%n", s, data.numberOfRows);
     }
 };


text:
Q: Qt Signal calling from second thread works -> no effect on connected slot I have a Qt-Application. One of my class ViewSimulation has a static-Methode loggingHandler which calls (emit) a class-signal logging. The methode loggingHandlerwill be passed as function-pointer to a c-file publisher.c. publisher.c calls his function-pointer (*logger) in a seperate thread.
At the debugging I'm seeing publisher.c calls ViewSimulation::loggingHandler and the signals logging is emited, but the connected slot does not react. But if a call/emit logging in the main thread, the slot of &ViewGooseList::logging) react.
Why the slot is not reacting by "calling" from the other c-thread in publisher.c?

ViewSimulation.cpp/h
class ViewSimulation : public QGroupBox
{
...
    signals:
          void logging(int id, uint64_t timestamp);
    private:
          static void loggingHandler(int id, uint64_t timestamp);
    ViewSimulation* ViewSimulation::m_current;
...
    void ViewSimulation::loggingHandler(int id, uint64_t timestamp)
    {
          emit ViewSimulation::m_current->logging(id, timestamp);
    }
...
    connect(m_gooseSimulation, &ViewSimulation::logging, m_gooseList, &ViewGooseList::logging);
    setLogging(loggingHandler);

publisher.c/h
/*Header*/
void setLogging(void (*logging)(int, uint64_t));
static void (*logger)(int gooseId, uint64_t timestamp);

/*C-File*/
void setLogging(void (*logging)(int, uint64_t))
{
    logger = logging;
}
...
/*This methode will be called from main-thread **AND** from second thread */
logger(gooseMessage->id, gooseMessage->lastTimeStamp);
...

A: For signal/slot connections across threads, you should create queued connections:
connect(m_gooseSimulation, &ViewSimulation::logging, m_gooseList,
        &ViewGooseList::logging, Qt::QueuedConnection);


text:
Q: Systemjs configuration Error in javascript and html I want to use modules in my javascript and html. When i use systemjs with version 5, i am getting error, in github i cant see the steps to configuration. If i removed System.config from below code, at that time i getting CORS issue.

*

*What are the package i have to use to run modules in javascript and html

*How to set the configurations for latest version
        <!-- <script src="node_modules/traceur/bin/traceur.js"></script>
        <script src="node_modules/systemjs/dist//system.js"></script> -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/5.0.0/system.js"></script>
    </head>

    <body>
        <script>
//Configuration
            System.config({
                'meta': {
                    './js/*.js': {
                        format: 'esm'
                    }
                }
            });
            System.import('./js/app.js');
        </script>

    I am getting Error : index.html:18 Uncaught TypeError: System.config is not a function. if I removed system.config i am getting Error : Unable to resolve bare specifier "js/app.js" from file:///C:/Train/ES6/systemjss/ at throwBare (system.js:184)     at resolveImportMap (system.js:180)     at system.js:734


text:
Q: How can I return the last element number from a tuple that satisfies a condition? How can I return the largest number in a sorted tuple an that is still smaller than a given number (ratio)?
Here is my code:
def returnPrevious(width, height):
    an = (2,3,4,6,8,9,12)
    z = -1
    for i in an:
        if (width//height) >= i:
         z += 1
        else: break
    return an[z]

A: If you reverse the order of the numbers then you can just return the first match:
def returnPrevious(width, height):
    an = (12,9,8,6,4,3,2)
    for i in an:
        if width//height >= i:
            return i
    return None

You could even do it in a single statement by using next(), which returns the first element from an iterable, or a default value of our choice (None) if the iterable is empty.
def returnPrevious(width, height):
    return next((i for i in (12,9,8,6,4,3,2) if width//height >= i), None)

A: You could use something like this instead, you wouldn't get rid of the z, but it's cleaner
def returnPrevius(width, height):
    an = (2,3,4,6,8,9,12)
    z = None
    for i in an:
        if (width//height) >= i:
         z = i
        else: break
    return z

A: You can do this
import itertools
def findLast(w,h):
   r = w//h
   return list(itertools.takewhile(lambda e: e < r, an))[-1]

or
def findLast(w,h):
   r = w//h
   return [e for e in an if e < r][-1]

But it builds a list that you don't need only to take last elem from it.
What you can do is reverse the list and find the first elem that matches your condition, then you don't need to remember prev elem. But you still need to handle the case that there is no such elem. Or add 0 to the reversed list as last elem.


text:
Q: Cocoa get main window I want to create 3 windows like this:
NSWindow *win1 = [[NSWindow alloc] initWithContentRect:rect1
                                             styleMask:uiStyle
                                               backing:backingStoreStyle
                                                 defer:NO];

and make one of them the main window, then get the main window, but I always get nil.
[win1 makeKeyAndOrderFront:win1];
[win2 makeKeyAndOrderFront:win2];
[win3 makeKeyAndOrderFront:win3];
[win2 makeMainWindow];

And all of these are nil:
NSLog(@"%@", [app mainWindow]);
NSLog(@"%@", [win1 isMainWindow]);
NSLog(@"%@", [win2 isMainWindow]);
NSLog(@"%@", [win3 isMainWindow]);

A: I tried your code. It does return an instantiated NSWindow object. I didn't get nil at all. Can you please post more context to code snippet?
Secondly, it is far easier and manageable to create window in IB. Thirdly, check - (BOOL)canBecomeMainWindow before passing it the message makeMainWindow.
If you want to create custom windows programaticaly, I would suggest create a Window in MainMenu.xib. Get it's IBOutlet, for example window. Then create your windows win1, win2 etc and add then as child windows to your window using addChildWindow.


text:
Q: How to configure System Restore to restore "everything"? Given that I can browse a restore point and see the deleted files, how to restore this point completely? When I try to, Windows says everything's fine, but the files I was looking for weren't restored (D:\1\willbedeleted.txt) and the files created after the restore point didn't vanish (D:\1\createdafter.txt).
I never used this feature before and I thought that setting "Restore system settings and previous versions of files" would do the thing.
Also, after restore and reboot there's a message box saying "your documents have not been affected". But I wanted them to be affected! I don't care if files created after creating the point are deleted or overwritten.
Is there a way to do what I want?
Update:
I tried vshadow -revert={SnapID} on Windows 7 (see Windows VSS/vshadow), but it fails with: ShouldBlockRevert() ... Not implemented. I hope someone tries that on a later version of Windows. Possible solution for Windows 7 can be rebuilding vshadow from sources and handling the error in ShouldBlockRevert()

A: In a word, no.
The Restore Previous Versions capability that allows you to recover an earlier version of your personal files works separately from a System Restore. Although they both rely upon the Volume Shadow Copy service and are configured in the System Protection interface, dropping back to a previous System Restore point only affects the operating system itself and the installed applications.
Here is a good article that elaborates a bit more on the Restore Previous Versions process:
Use Windows 7's Previous Versions to Go Back in Time and Save Your Files

A: You seem to be under the impression that System Restore backs up files in, for example, your user's Documents directory. This is not the case. It only saves copies of system files (such as drivers and registry files). To create a backup of personal documents there is a built-in backup utility in Windows or several third-party options that backup files either locally or to the cloud.


text:
Q: Sql Join , updating one table and generating output from another table CREATE TABLE LeadCustomer
(
  CustomerID INTEGER NOT NULL, FirstName VARCHAR(20) NOT NULL,
  Surname VARCHAR(40) NOT NULL, BillingAddress VARCHAR(200) NOT NULL,
  email VARCHAR(30) NOT NULL
)

CREATE TABLE Flight
(
 FlightID INTEGER NOT NULL, FlightDate TIMESTAMP NOT NULL,
 Origin VARCHAR(30) NOT NULL, Destination VARCHAR(30) NOT NULL,
 MaxCapacity INTEGER NOT NULL, PricePerSeat DECIMAL NOT NULL
)

CREATE TABLE FlightBooking
(
 BookingID INTEGER NOT NULL, CustomerID INTEGER NOT NULL, FlightID INTEGER NOT NULL,
 NumSeats INTEGER NOT NULL, Status CHAR(1) NOT NULL, BookingTime TIMESTAMP NOT NULL,
 TotalCost DECIMAL
)

If the flight is rescheduled, how can we generate a list of customers who needs to be contacted ?
So far I have completed up to:
SELECT
LeadCustomer.CustomerID,Flight.FlightID
FROM LeadCustomer
inner join FlightBooking
ON LeadCustomer.CustomerID = FlightBooking.CustomerID
inner join
Flight ON FlightBooking.FlightID = Flight.FlightID;

but don't know how to update the flight time

A: I understand that Flight.FlightDate is equal to FlightBooking.BookingTime. When you update the first column you can search where one became different from the other, like:
SELECT
LeadCustomer.CustomerID,Flight.FlightID
FROM LeadCustomer
inner join FlightBooking
ON LeadCustomer.CustomerID = FlightBooking.CustomerID
inner join
Flight ON FlightBooking.FlightID = Flight.FlightID
WHERE Flight.FlightDate <> FlightBooking.BookingTime

If I´m wrong could you explain it better


text:
Q: Can't bind to port 80 I'm using Windows 10 and Visual Studio 2016. I can't bind to port 80. I can bind to all other ports. The error printed is: "Bind of IP address 0.0.0.0 returned an error, port 80: No error"
Here is my code:
/*  bind this socket to the server's Internet address */
if( bind(fd,(struct sockaddr *)server_addr,sizeof(struct sockaddr_in))<0 )
{
    printf("Bind of IP address %s returned an error, port %d: %s\n",
        inet_ntoa(server_addr->sin_addr), ntohs(server_addr->sin_port),
        strerror(errno));
    //close(fd);
    return -1;
}

A: Well, you can use netstat to see if anyone else is listening, see this article:
https://technet.microsoft.com/en-us/library/bb490947.aspx
Find which process is already using port 80 and stop it.
You also need to be an admin or explicitly grant access to the user you're running as if you're binding port < 1024.  See here
HttpListener Access Denied

A: Use "netstat -o -q -a -n". Then use task manager and look at the Details tab. Click to sort the PID as low to high. Find the PID and notice the name of the program that has the port open. In my case System is listening on port 80 and since you can't kill System then you basically can't bind to port 80.


text:
Q: Generate a range of special characters with ruby I'm very new to ruby at the moment but I came from a PHP background and must say that I enjoy doing ruby, alot. It's a really nice language and the community is strict but helpful.
Today I was looking at stackoverflow and checked one of my answers to a question to generate a random string using PHP. I had actually written a script for this so I thought, why not share it!
This script has some modifiers which allow you to choose wether you want to include the following sets

*

*lowercase a-z

*[1] + uppercase a-z

*[1, 2] + numbers

*[1, 2, 3] + special characters

*[1, 2, 3, 4] + some crazy voodooh characters

So in this PHP script I physically typed each set into an array e.g.:
$charSubSets = array(
    'abcdefghijklmnopqrstuvwxyz',
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    '0123456789',
    '!@#$%^&*()_+{}|:">?<[]\\\';,.`~',
    'µñ©æáßðøäåé®þüúíóö'
);

and this was basically my way of being able to define complexity right there.
Now this looks alright, even in the code but ruby has ranges and ranges are something new and shiny for me to play with so I was thinking of building a random string generator later today just to get some more experience with it.
Now for my question, I know that you can do the following things with a range including:

*

*'a'..'z'

*'A'..'Z'

*0..9
etc.. But I was thinking, could you also make a range with special characters? as in, only special characters? and if that is possible, would you also be able to do the same for the crazy voodooh?
The reason I'm asking is because there is no example in the docs or anything on SO explaining this.

A: *

*Check out Range#to_a which is gotten from Enumerable.  Note that on the left hand side of the docs it says that Range includes Enumerable, which means that the methods in Enumerable can be called on Ranges.  If you can't find a method in a class, see what modules the docs say are included and click on the link to the included module.

*Check out Array#shuffle.

*Check out Array#join

*Check out Array#[], which will take a range as a subscript, so you can take a slice of an array of random characters.

*A two dot Range includes the end.  A three dot Range doesn't include the end:
p (1...5).to_a  #=> [1, 2, 3, 4]
Putting it all together:
chars = (0..9).to_a + ('A'..'z').to_a + ('!'..'?').to_a

10.times do
  puts chars.shuffle[0..5].join
end

--output:--
I(m,E.
%_;i(3
rb=_ef
kJrA9n
YA`e.K
89qCji
Ba1x3D
acp)=8
2paq3I
U0>Znm

(Shakespeare will appear there eventually.)

A: Yes - this is certainly possible.
Fire up your console e.g. irb or pry.
1. for the special characters:
('!'..'?').to_a
# => [
#     "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-",
#     ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":",
#     ";", "<", "=", ">", "?"
# ]

2. for the 'voodooh' characters:
('µ'..'ö').to_a
# => [
#     "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á",
#     "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î",
#     "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö"
# ]

This is trivial to just try tho, the position (and kb index of the key) on your keyboard for the end special character defines what characters come inbetween, if I'd pick a ~ instead of a ? for the end it would look like this:
('!'..'~').to_a
# => [
#     "`", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",",
#     "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
#     ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F",
#     "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
#     "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "a",
#     "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
#     "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{",
#     "|", "}", "~"
# ]

basically if character a is 65 and z is 90 then all characters inbetween like b which is 66 will be included, it works like that for anything you put in a range and since in ruby everything is an object, you can use anything in a range as long as it implements certain methods as explained by the docs!
EDIT (13-11-2015)
After doing some playing around in my console I came to this solution which "mimics" the given PHP example and perhaps even completes it.
def rng(length = 10, complexity = 4)
    subsets = [("a".."z"), ("A".."Z"), (0..9), ("!".."?"), ("µ".."ö")]
    chars = subsets[0..complexity].map { |subset| subset.to_a }.flatten
    # => [
    #     "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
    #     "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
    #     "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
    #     "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
    #     "W", "X", "Y", "Z", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "!", "\"",
    #     "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".",
    #     "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":",
    #     ";", "<", "=", ">", "?", "µ", "¶", "·", "¸", "¹", "º", "»",
    #     "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç",
    #     "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó",
    #     "Ô", "Õ", "Ö"
    #  ]
    chars.sample(length).join
end

Now calling rng will produce results like this:
rng         # => "·boÇE»Ñ¼Á¸"
rng(10, 2)  # => "nyLYAsxJi9"
rng(20, 2)  # => "EOcQdjZa0t36xCN8TkoX"

EDIT#2 (14-05-2020)
As pointed out below in the comments, I did not even provide a documentation link to the relevant concept, in Ruby this is called a Range and can be found here (2.5.0).
If you need docs for your specific version, try googling for ruby range [your ruby version]. You can find out what your version is by running ruby -v in the terminal. Happy rubying :D
all dates are in dd-mm-yyyy format


text:
Q: NPM command config is broken I edited npm config set <key> <value> and messed up.
Now whenever I try running anything that remotely starts with npm config, I'm getting an issue that looks like that:

Error: Failed parsing JSON config key

How can I reset my npm config or find the file to manually delete my changes?
I have tried reinstalling npm and nvm several times.
Accepted answer
Was technically correct, I also realized that I was missing a second question (ie how to find invisible files athe mac). I'm on a mac and .npmrc is a hidden file (which can be toggled with cmd+shift+.) But all in all, it worked out, thanks yall!

A: Try editing the config file directly: ~/.npmrc
https://npm.github.io/installation-setup-docs/customizing/the-npmrc-file.html


text:
Q: semantic Versioning for plugins I have an application that support plugins. both use semantic Versioning. I want to see which way is better to manage the plugin version compatibility.  The goal is that application should  not load any plugins that are not compatible with current version. Keep in mind that  plugins could be developed by somebody else.
The approach I took now works like this:
The plugins will define SupportedVersions.  For example, the Application version is 1.10.34.    the SupportedVersions could be 1.09,1.10.   So the application will only load the plugin if the SupportedVersions includes the application's current version.
The problem for this approach is, every time the application has a new version, need to add that to the plugin's SupportedVersions.  We could say if the Major version is the same, we can load the plugin, but the Majar version of the application changes does not mean it break up the compatibility with the plugin, right?
So, any better approach than that?


text:
Q: Capitalization issue with Workbooks.Open using VBA in Excel 2016 I am trying to write code that will prompt the user for a .xlsx file path and then open that workbook. Eventually, I will want VBA to copy data from the workbook it is opening. But, I am not able to get VBA to open a workbook.
Here is my code:
    Sub Select_File_Or_Files_Mac()
Dim MyPath As String
Dim MyScript As String
Dim MyFiles As String
Dim MySplit As Variant
Dim N As Long
Dim Fname As String
Dim mybook As Workbook

On Error Resume Next
MyPath = MacScript("return (path to documents folder) as String")
'Or use MyPath = "Macintosh HD:Users:Ron:Desktop:TestFolder:"

' In the following statement, change true to false in the line "multiple
' selections allowed true" if you do not want to be able to select more
' than one file. Additionally, if you want to filter for multiple files, change
' {""com.microsoft.Excel.xls""} to
' {""com.microsoft.excel.xls"",""public.comma-separated-values-text""}
' if you want to filter on xls and csv files, for example.
MyScript = _
"set applescript's text item delimiters to "","" " & vbNewLine & _
           "set theFiles to (choose file of type " & _
         " {""org.openxmlformats.spreadsheetml.sheet""} " & _
           "with prompt ""Please select a file or files"" default location alias """ & _
           MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
           "set applescript's text item delimiters to """" " & vbNewLine & _
           "return theFiles"

MyFiles = MacScript(MyScript)
On Error GoTo 0

If MyFiles <> "" Then
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    MySplit = Split(MyFiles, ",")
    For N = LBound(MySplit) To UBound(MySplit)

        ' Get the file name only and test to see if it is open.
        Fname = Right(MySplit(N), Len(MySplit(N)) - InStrRev(MySplit(N), Application.PathSeparator, , 1))
        If bIsBookOpen(Fname) = False Then

            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MySplit(N))
            On Error GoTo 0

            If Not mybook Is Nothing Then
                MsgBox "You open this file : " & MySplit(N) & vbNewLine & _
                       "And after you press OK it will be closed" & vbNewLine & _
                       "without saving, replace this line with your own code."
                mybook.Close SaveChanges:=False
            End If
        Else
            MsgBox "We skipped this file : " & MySplit(N) & " because it Is already open."
        End If
    Next N
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End If

    Cells(1, 1) = MyFiles

    Set mybook = Workbooks.Open(MyFiles)

    End Sub

    Function bIsBookOpen(ByRef szBookName As String) As Boolean
    ' Contributed by Rob Bovey
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
    End Function

When I run the code, I get a 1004 run-time error saying the file could not be found with the file path in all caps. This is odd as the user has to select the file in a pop up window so the file HAS to be there. I also have the code write the file path to cell 1,1 in the spreadsheet. Whats weird is the file path the program prints has the proper casing as the actual file path, but the error is in all caps. I think the issue is that unix is case sensitive and I am running this on OSX. why is Excel putting the file path in all caps? This also happens if I hard code the file path to Workbooks.Open(direct file path here)
I am using code I found at https://msdn.microsoft.com/en-us/library/office/hh710200(v=office.14).aspx

A: this seems to be missing
' Change drive/directory to MyPath.
ChDrive MyPath
ChDir MyPath


text:
Q: Maximo REST API does not return results in node.js I downloaded the GIT code for Maximo with node.js from the link: https://github.com/ibm-maximo-dev/maximo-nodejs-sample
I am able to connect to the Maximo server and authenticate fine. But when I perform a read operation, I get the below error.
I am accessing the below Maximo REST API, which works OK in the browser.
https://domain/maximo/oslc/os/CDUISRMINCIDENT?lean=1&oslc.select=*&oslc.pageSize=1
The same thing, I try in node.js:
router.get("/incidents", function (req, res) {

  var maximo = new Maximo(options);
  maximo.resourceobject("CDUISRMINCIDENT")
      .select(["*"])
      .pagesize(2)
      .fetch()
      .then(function(resourceset)
          {
             jsondata = resourceset.thisResourceSet();
           res.json(jsondata);
          })
      .fail(function (error)
      {
            console.log('****** Error Code = '+error);
      });
});

when I access the above route in browser: localhost:3000/api/v1/incidents I get the below error:
Maximo Node API server is running on port 3000
API version is v1
Request received by node middleware ...
### islean 1
Auth header type = maxauth
Request received by node middleware ...
### islean 1
this.islean ****** 1
***** RESPONSE 302
undefined:1

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

Any inputs would be greatly helpful.
Thanks
R


text:
Q: What does ?DataType mean in Vb.NET I have the following line of code:
CType(IIf(CBool(product.IsDiscontinued Is Nothing Or product.IsDiscontinued = True), False, True), Boolean?)

What does the Boolean? mean at the end. I have seen it used on other data types as well.

A: That's a Nullable(Of Boolean).
It allows value types to be Nothing.

A: The ? at the end is a shortcut for Nullable<T>, in this case Nullable<Boolean>.
Using Nullable allows you to store null inside of a value type that you wouldn't otherwise be able to.

A: Nullable... It's a nullable boolean...
As a quick aside, in the back end, these can create boxing/unboxing fun if you're not careful...
Here's a nice article explaining it (though it's written for c#)
http://msmvps.com/blogs/luisabreu/archive/2008/04/26/c-and-nullable-value-types.aspx


text:
Q: Create & burn an ISO Image from a source Blu-Ray under Linux My aim is to create an accurate, bit-for-bit identical copy of a Blu-Ray disc while leaving all the original content, DRM etc. untouched. How would I manage to do so using dd command to rip to .iso and to burn back to a blank BD?
I succeeded in creating accurate DVD copies by following this particular approach.
My basic steps according to the above instructions were:

*

*Running dd with the parameters for block size and volume size which results in an accurate, ready-to-burn ISO image.

*Burning the ISO image to a blank DVD using dd

*Verifying the DVD copy by re-ripping it to .iso (see step 1.) and comparing the resulting ISO image to the ISO image I used to burn the DVD (file size, MD5 checksum were identical)

As far as I know, I cannot read the block size and the volume size of a retail BD using the isoinfo -d -i /dev/cdrom command because of the fact that BDs are generally not in ISO 9960 format. Therefore, I followed my basic steps as usual but I just used the dd if=/dev/cdrom of=test.iso command without any bs and count arguments. As one might expect, my final comparison (step 3.) leaves me with two different ISO files (one larger file, different MD5 sums).
Does anybody have a solution to this? I assume some obligatory bs and count arguments are missing in my ripping routine - but how do I obtain the necessary information (Logical block size, volume size of BD) in the first place?
Thank you very much in advance for your help.

A: You can get the block size by using blockdev --getbsz /dev/sr0 where "/dev/sr0" may change, depending on the amount of drives you have and the block count by using blockdev --getsz /dev/sr0, multiplied by 512 and then divided by the block size.
You can test this using isoinfo -d -i /dev/sr0 on a normal DVD.
From my understanding dd will work just fine, creating a perfect copy of your blue-ray, even with no size or count variables set.
These variables are only used when skipping unwritten parts of the disc, parts that physically exist but do not store information, as is common when the data isn't as large as the disk.
I tested creating an ISO of a blue-ray without the size and count variables and using bit wise comparison cmp to compare it with the disc, and it didn't give me any error.
I assume that the reason it didn't work for you was that you burned it to yet another disc, which (as @JonasCz said) won't work due to copy-protection.
The ISO will play just fine, though.
I successfully opened and watched a blue-ray ISO using leawo on windows.
For example:

*

*blockdev --getsz /dev/sr0 shows me 16142856.

*blockdev --getbsz /dev/sr0 shows me 2048.

*16142856 * 512 = 8265142272,

*8265142272 / 2048 = 4035714.

This equals the output of isoinfo -d -i /dev/sr0
when used on a DVD:

*

*Logical block size is: 2048

*Volume size is: 4035714


text:
Q: Change icon in childlist of Expandabllistview when onClick icon in android Now i am working with ExpandableListview in android.
In ExpabdableListview GroupHeader contain one textview.
and Child contain one Textview and one Button.
In Button i have setbackground white star.
I have also use BaseExpandableListAdapter class to set the data in expandablelistview.
My Question
when click in particular child list button that time that button background change. White to Yellow.
Please any one have idea to change the color of specific button ?
Thank you in Advance.

A: It's difficult to respond without any code presented in your question, but idea can be the following:

*

*In your adapter, maintain list of 'clicked' child;

*In getChildView() check if items is clicked and set proper background image;

Example code would look the following:
// for ViewHolder pattern
private static class ViewHolder {
    // Child item views
    public Button button;

    public long combinedId;
}

private static class ExpandableAdapter extends BaseExpandableListAdapter implements View.OnClickListener {

    private LongSparseArray<Boolean> mClickedItems = new LongSparseArray<Boolean>();

    @Override
    public View getChildView(final int groupPosition, final int childPosition, final boolean isLastChild, final View convertView, final ViewGroup parent) {
        View view = convertView;
        ViewHolder holder = null;

        if (view == null) {
            // Inflate child view

            holder = new ViewHolder();
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        holder.combinedId = getCombinedChildId(groupPosition, childPosition);
        holder.button.setOnClickListener(this);

        if (mClickedItems.get(holder.combinedId, false)) {
            holder.button.setBackgroundResource(R.drawable.not_clicked_background);
        } else {
            holder.button.setBackgroundResource(R.drawable.clicked_background);
        }

        return null;
    }

    @Override
    public void onClick(final View v) {
        final long id = ((ViewHolder)v.getTag()).combinedId;
        Boolean clicked = mClickedItems.get(id);

        if (clicked == null) {
            clicked = true;
        } else {
            clicked = !clicked;
        }

        mClickedItems.append(id, clicked);
    }

    // Rest of adapter
}

Also, it might be better to use ToogleButton instead of normal button.


text:
Q: Trove hash maps not implementing hashCode I stumbled across the issue with TObjectDoubleHashMap of trove. The version 2.0.2 doesn't override the hashCode method.
More recent versions of trove (3.0.0) include the hashCode.
Note, that the equals method is overriden in both versions.
Why wasn't the hashCode method overriden in the version 2?  Maybe the contract for overriding hashCode/equals was introduced after the trove maps were written originally? Or is it simply a violation of the contract and a bug that was fixed later? I'd be very surprised if it's a bug and not a feature, because how come the class that mostly deals with hashing not override hashCode when it has equals

A:
Maybe the contract for overriding hashCode/equals was introduced after the trove maps were written originally?

No.  That was present way back.  I believe at least as early as 1.1, but I can't find anything earlier than 1.3 docs.

Or is it simply a violation of the contract and a bug?

Yes.  It is a violation of the contract.  Note that java.util.Map has its own extra equality/hashCode contract above and beyond java.lang.Object, which is knowingly violated by IdentityHashMap and a few others.
From the javadoc:

public boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two Maps represent the same mappings. More formally, two maps t1 and t2 represent the same mappings if t1.entrySet().equals(t2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.


text:
Q: How to remove \n and \t from webpack compiled template literal? I am developing a javascript plugin, which uses es6 template literals to generate a template, I am attaching a piece of code in my plugin.
"use strict";
(function () {
window.project = {
    template: {
        generateHtmlTemplate: function(data) {
        var template = `

                    <input type="text" value="${data.val}" />

`;
       return template;
      }
   }
}

When i tried to get build via webpack babel transpiles it to es5 so the template literals like the following. This is the webpack minified babel transpiled version of the plugin. This minified transpiled file is used by users. This production build minified file contains \n \t, this is what i want to remove.
(Just think like jQuery development version written with es6 and using babel and webpack to transpile and minify it to form jquery.min.js)
"use strict";
(function () {
window.project = {
    template: {
        generateHtmlTemplate: function(data) {
        var template = '
\n\t\t\t
\n\t\t\t\t<input type="text" value="${data.val}" />\n\t\t\t\t\t
\n\t\t\t\t\t
';
       return template;
      }
   }
}

It is filled with \n and \t. I have tried some the solutions in stackoverflow. But it doesn't work for me. What this common-tags package does is it injects the code to remove \n and \t along with the plugin code.
What I want
Just remove \n and \t from the output file.
What I tried

*

*I have tried webpack string replace plugin to replace \t and \n. But it doesn't worked. It take source code and tried to replace before transpiler works.

*I got a hack to solve new line problem by adding \ to the end of each line (also code becomes messy). But even though \t is there.

*If i try to regEx all \n and \t after build and replacing it is not a good method, it is error prone.

Webpack production build config
const TerserPlugin = require('terser-webpack-plugin');
const ReplacePlugin = require('webpack-plugin-replace');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtactPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const BrotliPlugin = require('brotli-webpack-plugin');

const config = {
    mode: 'production',
    entry: ['./src/source.js', './src/ufe.css'],
    output: {
        path: __dirname + '/dist/',
        filename: 'source.min.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /\.css$/,
                use: [MiniCssExtactPlugin.loader, 'css-loader']
            },
            {
                test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
                use: 'url-loader?limit=100000'
            }
        ]
    },

    plugins: [
        // new uglifyJsPlugin(),
        // new ReplacePlugin({
        //     values: {
        //         "\n": '',
        //         "\t": ''
        //     }
        // })
        }),
        // Brotli compression output for files
        new CompressionPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.js$|\.css$|\.html$|\.svg$/,
            threshold: 1024,
            minRatio: 0.8
        }),
        new BrotliPlugin({
            asset: '[path].br[query]',
            test: /\.js$|\.css$|\.html$|\.svg$/,
            threshold: 1024,
            minRatio: 0.8
        })
        // new HTMLWebpackPlugin({
        //  template: path.resolve(__dirname, 'index.html')
        // }),
        // new webpack.HotModuleReplacementPlugin()
    ],
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    ecma: undefined,
                    warnings: false,
                    parse: {},
                    compress: {},
                    mangle: true, // Note `mangle.properties` is `false` by default.
                    module: false,
                    output: null,
                    toplevel: false,
                    nameCache: null,
                    ie8: false,
                    keep_classnames: undefined,
                    keep_fnames: false,
                    safari10: false,
                }
            }),
            new OptimizeCssAssetsPlugin({})
        ],
    },
    resolve: {
        extensions: ['.js', '.svg']
    },
    devServer: {
        port: 3000,
        contentBase: __dirname + '/build',
        inline: false
    }
};
module.exports = config;

Any suggestions to solve this will be much appreciated.
Thanks in advance.

A: I have got solution for what I want exactly.
Create a babel plugin to remove it.
var pattern = new RegExp("[\n\t ]+", "g");

function transfrom (quasis) {
  ["raw", "cooked"].forEach(function (type) {
    quasis.forEach(function (element) {
      element.value[type] = element.value[type].replace(pattern, " ");
    });
  });
}

module.exports = function (babel) {
  var t = babel.types;

  return {
    visitor: {
      TaggedTemplateExpression: function (path) {
        let node = path.node;

        if (t.isIdentifier(node.tag, { name: "nowhitespace" })) {
          transfrom(node.quasi.quasis);
          return path.replaceWith(node.quasi);
        }
      }
    }
  };
};

It's bit old, but still works.
https://github.com/WebEngage/babel-plugin-template-string-transform
https://engineering.webengage.com/2016/07/15/babel/

A: That's not how template literals work: they preserve whitespace. This feature is very much on purpose as it allows you to preserve formatting much like formatted strings in other languages (e.g. heredocs in PHP and triple-quoted strings in python). If you don't want that behavior, then you can just concatenate plain strings as we did in ye old days prior to ES 6:
window.project = {
    template: {
        generateHtmlTemplate: function(data) {
        var template = '' +
             '
' +
                '
' +
                    '<input type="text" value="' + data.val + '" />' +
                '
' +
             '
';
        return template;
      }
   }
}

Note that this is harder to read in the source. Whether or not it's worth it to save a handful of bytes in your payload is subjective but FWIW I'd stick with the template string.
Edit
If you really want to use a template but strip the whitespace just do this instead:
function(data) {
    var template = `

                <input type="text" value="${data.val}" />

`.replace(/[\t\n]+/g, ''); // remove all tabs and returns
    return template;
}


text:
Q: Merge specific fields of array indexes with duplicate values I am working with a JSON dataset provided via CSV file from my client. I have processed the CSV into a JSON format.
I have the following result (dataset reduced from 1304 to 2 for readability)
"1": {
    "title": "Abercarn RFC",
    "address": "High Street, Abercarn, Newport, Gwent",
    "postcode": "NP11 5GQ",
    "category": "Club",
    "website": "http://abercarn.rfc.wales",
},

"2": {
    "title": "Abercarn RFC",
    "address": "High Street, Abercarn, Newport, Gwent",
    "postcode": "NP11 5GQ",
    "category": "Seniors",
    "website": "http://abercarn.rfc.wales",
}

I want to be able to loop through my array (pre-json_encode($array)) and merge these objects but preserve both the category values into a CSV list, so the ideal output in this case will be
"category": "Club, Seniors"

I am happy to simply merge all the other fields as they are consistently the same across the data set.

A: You can do it with simple loop (I used the title to define similarity between element but you can change that):
$arr = array(["title" => "Abercarn RFC", "category"=> "Club"], ["title" => "other title", "category"=> "BlaBla"], ["title" => "Abercarn RFC", "category"=> "Seniors"]);

$res = array();
foreach($arr as $e) {
    if (isset($res[$e["title"]]))
        $res[$e["title"]]["category"] .=   ", " . $e["category"];
    else $res[$e["title"]] = $e;
}

If you want to remove the array key you can use array_values.
$res will be your desire output.


text:
Q: Why are we able to see air bubbles under water? Title is self explanatory.
I'm assuming both water and air are transparent.
So, if they are true, how can I clearly distinguish an air bubble under water?

A: Air and water are both transparent to a good enough approximation. However, light travels more slowly in water: the speed of light in air is about 33% faster than in water. As a result, when light passes from one medium to the other, it is partly reflected and partly refracted (bent). For the refracted part, the general rule for determining the bending angle is called Snell's law, which can be expressed like this:
$$
   \frac{\sin\theta_\text{w}}{\sin\theta_\text{a}}=\frac{v_\text{w}}{v_\text{a}}
 \approx \frac{1}{1.33}
\tag{1}
$$
where $v_\text{w}$ and $v_\text{a}$ are the speed of light in water and air, respectively, and where $\theta_\text{w}$ and $\theta_\text{a}$ are the angles of the light ray relative to a line perpendicular to the surface, on the water side and on the air side, respectively.
If the angle on the water side is $\theta_\text{w} \gtrsim 49^\circ$, then equation (1) does not have any solution: there is no air-side angle $\theta_\text{a}$ that satisfies the equation. In this case, as niels nielsen indicated, light propagating inside the water will be completely reflected at the water-air interface. So the rim of the bubble acts like a mirror: if you do a reverse ray-trace from your eye back to near the rim of an air bubble in the water, the angle between the ray and the line perpendicular to the surface of the bubble will be greater than $49^\circ$ (this defines what "near the rim" means), so that part of the bubble acts like a mirror for light coming from those angles, as illustrated here:

A: You can see light reflected off of the surface of a submerged bubble because the index of refraction of the air inside the bubble is different from that of the water that surrounds the bubble.
That difference, if great enough, will turn a bubble surface into a mirror for light rays that approach it from certain directions, thereby making it easy to see.
This condition is easily met for the combination of air and water.
A google search on "refraction" and "total internal reflection" will furnish more examples of this, and explain the math behind it.

A: The inside of the bubble is not dark because only the light making a more glancing intersection than 49 degrees is completely reflected.  Light that hits near the center of the bubble with respect to the direction it is traveling will be mostly transmitted into the bubble, illuminating the interior.

A: For the exact same reason why you can see rain. Light waves hit it and the direction of propagation(travel) of the wave changes because it goes from one medium to another. Its movement causes the refraction to happen differently making it different from it's surroundings and visible to you.


text:
Q: FFT differential equations Given a generical differential equation what is the procedure to solve it using fft command. Can anyone explain me how to do it?
For example:
$$\frac{d^2y}{dt^2}+10\cdot \frac{d\:y}{dt}=-5\cdot t^2+t^4\cdot \cosh \left(t\right)$$
Should we use it as a discrete or as a continuous time transformation?
I think fft is for discrete time but that way we have not got the rule of differentiation.
Thanks


text:
Q: Python PIL doubling images I am trying to draw over 2 images, and I am getting this weird error. For most of the time the image drawing goes well.
     -or-
These are the two symbols as they normally would be. However here is what is being outputted randomly Most of the time this code works without a hitch but sometimes it does this:

So here is my code. This first one chooses ONE overlay image(not two)
   if 'Instant' in s.duration:
    durpic = Image.open('Dur-I.png')
elif 'round' in s.duration:
    durpic = Image.open('Dur-R.png')
    dnum = write_roman(int(re.search(r'\d+', s.duration).group()))
    draw = ImageDraw.Draw(durpic)
    w, h = draw.textsize(dnum)
    draw.text((0, 0), dnum, (0, 0, 0), font=font)
elif 'min' in s.duration:
    if 'Concentration' in s.duration:
        durpic = Image.open('Dur-CM.png')
    else:
        durpic = Image.open('Dur-M.png')
    dnum = write_roman(int(re.search(r'\d+', s.duration).group()))
    draw = ImageDraw.Draw(durpic)
    w, h = draw.textsize(dnum)
    draw.text((0, 0), dnum, (0, 0, 0), font=font)
elif 'hour' in s.duration:
    if 'Concentration' in s.duration:
        durpic = Image.open('Dur-CH.png')
    else:
        durpic = Image.open('Dur-H.png')
    dnum = write_roman(int(re.search(r'\d+', s.duration).group()))
    draw = ImageDraw.Draw(durpic)
    w, h = draw.textsize(dnum)
    draw.text((0, 0), dnum, (0, 0, 0), font=font)
elif 'day' in s.duration:
    if 'Concentration' in s.duration:
        durpic = Image.open('Dur-CD.png')
    else:
        durpic = Image.open('Dur-D.png')
    dnum = write_roman(int(re.search(r'\d+', s.duration).group()))
    draw = ImageDraw.Draw(durpic)
    w, h = draw.textsize(dnum)
    draw.text((0, 0), dnum, (0, 0, 0), font=font)
elif 'Until' in s.duration:
    durpic = Image.open('Dur-R.png')

Placing the image over the base image
image_copy = scho.image
image_copy.paste(durpic, scho.point3, durpic)
imgpath = 'output/' + s.name + '.png'
image_copy.save(imgpath)

So any advice on what is causing this error? I could paste more code if needed or more output examples.


text:
Q: Getting Python2 exec behaviour in python3: UnboundLocalError: local variable I am using some old code base that was initially written in python2. The devs say they have ported it to python3 however I found a all the code that uses exec is completely broken. Below you can find an example like the one I am trying to fix:
def function_with_exec(table):

    (sess, tgt) = 3, None
    try:
        exec("ec = some_object.{}_get_entry_count(sess_hdl=sess, dev_tgt=tgt)".
             format(table))
    except AttributeError:
        return []

    ec = some_function(ec)

When running this code, I get: `UnboundLocalError: local variable 'ec' referenced before assignment.
I have been reading that a way to modify the global ec variable from the exec function is to pass the globals() as second argument. However, when I do that, then the variables sess and tgt which are also used in the expression, become undefined too.
I really do not find a way to solve this.

A: Python thinks ec is a local variable, which hasn't yet been assigned to, and you can't reference it before first assigning to it. Use the global statement at the start of your function, like so:
def function_with_exec(table):
    # ec now refers to the global variable, which presumedly already been as
    global ec
    (sess, tgt) = 3, None
    try:
        exec("ec = some_object.{}_get_entry_count(sess_hdl=sess, dev_tgt=tgt)".
             format(table))
    except AttributeError:
        return []

    ec = some_function(ec)

See 7.12. The global statement

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

You could also remove the call to exec by using getattr instead:
def function_with_exec():
    global ec

    (sess, tgt) = 3, None
    try:
        ec = getattr(some_object, f"{table}_get_entry_count")(sess_hdl=sess,
                                                              dev_tgt=tgt)
    except AttributeError:
        return []

    ec = some_function(ec)


text:
Q: Order IEnumerable object based on Dictionary I have a IEnumerable<T> list. - T is a custom type, one of the members of that type is an int called Id.
I also have a Dictionary<int, int>object the first int is an Id (this id will be in the IEnumerable<T> list. The second Int is a rating number.
I want to order the IEnumerable<T> list based on the rating inside Dictionary<int, int> - Highest First
I can do this by if statements and looping, but I have a feeling this can be done using a linq/lambda statement.
Any one got any ideas how this can be done?
I'm guessing something like  list.OrderBy(x => x.id == Dictionaryname.  something something something

A: just use the OrderByDescending
var sorted = list.OrderByDescending(x => dictionary[x.id])

A: You can simply do:
list.OrderByDescending(x => dictionary[x.id])


text:
Q: Escape [ in grep I read strings from stdin and I want to display the users that match the strings. Problem is, if the user inputs the character '[', or a string containing it.
grep -F does not work because the line has to start with the string (^ - which is a simple character with -F). Also, getent $user won't be good because I need only the username not id as well.
if [[ "$user" == *"["* ]]; then
    echo -e "Invalid username.\n"
    continue
fi

if ! getent passwd | grep "^$user:"; then
    echo -e "Invalid username.\n"
    continue
fi

This is the workaround for '[', is there another way?
awk will do the job most probably, but I have no knowledge of it yet, I'm interested in grep.

A: [ is not the only character to escape for regexps. All the RE operators are including . which is common in user names (r.ot as a regexp matches root for instance).
Also, your approach (getent passwd | grep "^$user:") is also invalid in that it wouldn't flag root:0 as invalid for instance.
Here, it would be better to use awk:
user_valid() {
  getent passwd |
    U="$1" awk -F: '$1 == ENVIRON["U"] {found = 1; exit}
                    END {exit(1 - found)}'
}

Now, not all user databases allow enumeration like that.
$ getent passwd | grep stephane
$ id -u stephane
10631
$ getent passwd stephane
stephane:*:10631:10631:Stephane Chazelas:/export/./home/stephane:/bin/zsh

In my case, that user is in a LDAP database. enumeration is disabled (there could be thousands of users), but I can still query/resolve users individually.
So here, to validate users, it's better to query the user database directly for that user. For instance, using the id command (a standard command contrary to getent):
user_valid() {
  case $1 in
    (*[!0-9]*) id -u -- "$1" > /dev/null 2>&1;;
    (*) false;;
  esac
}

(we're taking care of all-digits users separately as some id implementations would give you information for the user id in that case. User names can't be numerical in most systems (that would break most commands that expect either user names or user ids as arguments (like those ids above, ps, find...))).

A: Escaping special characters is a bit of a chore. Instead you could just pick the username field from getent's output first, and then match against the full remaining line:
LC_ALL=C
if ! [[ $user =~ ^[A-Za-z0-9._][A-Za-z._-]*$ ]] ; then
    echo "Username is invalid"
    continue
fi
getent passwd | cut -d: -f1 | grep -xF -e "$user"

-F for fixed-strings, -x for full line match.
If you don't have users with usernames consisting only of digits, you could use getent:
LC_ALL=C
if ! [[ $user =~ ^[A-Za-z0-9._][A-Za-z._-]*$ ]] ; then
    echo "Username is invalid"
    continue
elif [[ $user =~ ^[0-9]+$ ]] ; then
    echo "Cannot handle username of digits only, sorry :("
    continue
fi
if ! getent -- passwd "$user" > /dev/null ; then
    echo "$user doesn't exist"
    continue
fi

Or, to avoid the problems with getent or others assuming a string of digits must be an UID instead of a user name we should call getpwnam() manually. This doesn't make other assumptions of what the usernames can be, other than what the underlying getpwnam() implementation does.
export user
if ! perl -e 'exit !defined getpwnam($ENV{user})' ; then
    echo "$user doesn't exist"
fi

I'll skip writing the corresponding C wrapper.

A: Either escape it or put it in a character class, something along these lines:
grep '\['

grep '[[]'

grep -e "${user//\[/\\\[}"

The syntax ${var//c/d} => in the shell variable $var we replace all the characters c with d. Now, in your case the c is [ but it so happens that [ is special in this syntax (it does globbing) and hence we need to escape it by prefixing it with a backslash, i.e., \[.
Now coming to the replacement part, what we need is a \[ in there. But again, both \ and [ are special in this syntax of ${var//...} parameter substitution and hence both need to be, yes you guessed it right, backslashed
leading to the expression: \\\[ :     "${var//\[/\\\[}"
HTH


text:
Q: How to set Separator style for UITableView how to change Separator Style for UITableView expandable cell. I am using Custom Tableview Class for that.

A: [tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];

A: Potentially add a UIView as a separator of your own that has an autoresizing mask set to keep it stuck to the bottom.
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
Then in your custom UITableViewCell subclass
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.backgroundColor = [UIColor myColour]; // do cell setup in here

        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, self.contentView.bounds.size.height - 1.0f, self.contentView.bounds.size.width, 1.0f)];
        lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        lineView.backgroundColor = [UIColor myOtherColour];

        [self.contentView addSubview:lineView];
}

return self;

}
If you really want to do it in cellForRowAtIndexPath you can, but I wouldn't recommend it
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      static NSString *CellIdentifier = @"Cell";

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];

      if (!cell)
      {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];

        cell.backgroundColor = [UIColor myColour]; // do cell setup in here

        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, cell.contentView.bounds.size.height - 1.0f, cell.contentView.bounds.size.width, 1.0f)];
        lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        lineView.backgroundColor = [UIColor myOtherColour];

        [cell.contentView addSubview:lineView];
      }

  // rest of your cell for row code here


text:
Q: Wrong data output on basic select condition i'm trying to get the values which Dates bigger then 2021-07-17 and Cities starting with 'G'. I have id in the PERSON table, id (references from PERSON(id)) and date in VACCDATA table, id (references from PERSON(id)) and city in ADDRESS table.
SELECT p.id, v.vac_date, a.city
FROM PERSON AS p
LEFT JOIN VACCDATA AS v
ON v.vac_date > '2021-07-17' AND v.id=p.id
LEFT JOIN ADDRESS AS a
ON a.city LIKE 'G%' AND a.id=v.id;

          ID       DATE        CITY

Row 1 --> 15 ; "2021-07-19" ; ""

Row 2 --> 18 ; "2021-07-18" ; "Giresun"

Row 3 --> 17 ; "" ; ""

While i only want the Row 2 (because it's city name is starts with 'G' and Date is bigger then 2021-07-17 at the same time), it gives the above output. What am i doing wrong?

A: You are using LEFT JOIN with the conditions on the join itself. So you get all persons from database no matter the criteria is matching.
You can use INNER JOIN with WHERE filter instead:
SELECT p.id, v.vac_date, a.city
FROM PERSON AS p
  INNER JOIN VACCDATA AS v ON v.id = p.id
  INNER JOIN ADDRESS AS a ON a.id = v.id
WHERE v.vac_date > '2021-07-17' AND a.city LIKE 'G%'

A: If you want to apply join with condition, then first make relationship between tables and the add condition.
First make relationship v.id = p.id and then add condition v.vac_date > '2021-07-17'
SELECT p.id, v.vac_date, a.city
FROM PERSON AS p
  INNER JOIN VACCDATA AS v ON v.id = p.id AND v.vac_date > '2021-07-17'
  INNER JOIN ADDRESS AS a ON a.id = v.id AND a.city LIKE 'G%'


text:
Q: use of Context menu in Expandable List View I have seen in some places that while using Expandable List View we register the list view for  context menu. I want to know that why it is done and what effect it will have on our application if we dont register our List View for context menu

A: What do you mean by we register the list view for context menu?
I am sure there is a call of registerForContextMenu(View) , which describes that whenever you perform any action on that particular view, this context menu will get displayed.
In the case of Expandable ListView, if you call registerForContextMenu then it will display context menu whenever you click on any item.


text:
Q: Having issues with a replace function in Javascript Okay, so I have some variables in javascript...
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;

As you can see, I have a link and a position. Using the position var I would like to replace some text in the link field. I would like to strip &pos2=1.teamsp00ky.chat from the link. Naturally, I have to do some basic regular expressions; the problem comes into when I try to use the position var in the regex. I just can't figure it out.
In PHP I could do the following:
preg_replace('/&pos'.$position.'=[^&]*/i', '', $link);

I tried the following in JS, but its not working:
link.replace(new RegExp('&pos'+position+'=[^&]*'), '');

Could someone help me out and tell me what I'm doing wrong? Also, how would I make it case-insensitive?

A: You need to set the value, not just call the method:
link = link.replace(new RegExp('&pos'+position+'=[^&]*'), '');

To make it case insensitive, use this regex:
new RegExp('&pos'+position+'=[^&]*', "i")

Although it might make it easier if you split the string on the "?", then split up the key/value pairs by "&", and then split them by "=".

A:
Could someone help me out and tell me what I'm doing wrong?

replace does not mutate the string, but returns a new one - you'd have to assign it somewhere.

Also, how would I make it case-insensitive?

Pass the i flag to the RegExp constructor.
link = link.replace(new RegExp('&pos'+position+'=[^&]*', 'i'), '');

A:

var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;

var start = link.indexOf("pos2");

var end = link.indexOf("&", start);

document.getElementById("result").textContent = link.slice(0, start) + link.slice(end + 1);

on jsfiddle


text:
Q: ArduinoJson DynamicJsonDocument Wish you all good weekend! Simple newbie question:
I'm trying to get some json data using ArduinoJson library. I have no idea how to get data from multidimension array.
Here is the json:
{"file":"1.png","time":"15000","data":[["test1","test2"],["test3","test4"],["test5","test6"]]}

here is the code:
// Allocate the JSON document
  // Use arduinojson.org/v6/assistant to compute the capacity.
  const size_t capacity = 3*JSON_ARRAY_SIZE(2) + JSON_ARRAY_SIZE(3) + JSON_OBJECT_SIZE(3)+63;
  DynamicJsonDocument doc(capacity);

  // Parse JSON object
  DeserializationError error = deserializeJson(doc, client);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }

  // Extract values
  Serial.println(F("Response:"));
  Serial.println(doc["file"].as<char*>());
  Serial.println(doc["time"].as<long>());
  Serial.println(doc["data"][0][0].as<char>());
  Serial.println(doc["data"][0][1].as<char>());
  Serial.println(doc["data"][1][0].as<char>());
  Serial.println(doc["data"][1][1].as<char>());
  Serial.println(doc["data"][2][0].as<char>());
  Serial.println(doc["data"][2][1].as<char>());

here is the result:
16:25:30.933 -> Response:
16:25:30.933 -> 1.png
16:25:30.933 -> 15000
16:25:30.933 ->
16:25:30.933 ->
16:25:30.933 ->
16:25:30.933 ->
16:25:30.933 ->
16:25:30.933 ->
16:25:30.933 -> *WM: freeing allocated params!

The question i how do I get to "data" subarrays ?

A: A bit late but still... There are missing asterisks. You have to pass the pointer the same way you do at the Serial.println(doc["file"].as<char*>()); row.
Replace the
Serial.println(doc["data"][0][0].as<char>());
Serial.println(doc["data"][0][1].as<char>());
Serial.println(doc["data"][1][0].as<char>());
Serial.println(doc["data"][1][1].as<char>());
Serial.println(doc["data"][2][0].as<char>());
Serial.println(doc["data"][2][1].as<char>());

with
Serial.println(doc["data"][0][0].as<char *>());
Serial.println(doc["data"][0][1].as<char *>());
Serial.println(doc["data"][1][0].as<char *>());
Serial.println(doc["data"][1][1].as<char *>());
Serial.println(doc["data"][2][0].as<char *>());
Serial.println(doc["data"][2][1].as<char *>());

I have tried to add it to your code and the result is
Response:
1.png
15000
test1
test2
test3
test4
test5
test6


text:
Q: While updating records in django check whether the newly entered data is already matching with the other records in database? forms.py
class RoleForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        if Group.objects.filter(name__iexact=name).exists():
            raise forms.ValidationError("Role name already exists")
        return name

views.py
def updateroles(request, id):
    roles = Group.objects.all()
    instance = get_object_or_404(Group, pk=id)
    if request.method == "POST":
        fm = RoleForm(request.POST, instance = instance)
        if fm.is_valid():
            fm.save()
            messages.success(request, 'Updated Successfully')
            return redirect('roles')
    else:
        fm = RoleForm(instance=instance)
    return render(request, 'crm/roles.html', {'form': fm, 'roles': roles})

While adding new records I want to check whether the records already exists in database.If it exist I need to raise a ValidationError which is working fine.But while updating records check whether the newly entered data is not matching with any other records,if it matches I need to raise a ValidationError like newly entered data matches with some other record.My current code is raising a validationerror even if I click on update without changing the existing data.Any help would be appreciated.

A: You should exclude the object:
class RoleForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        # exclude the current instance ↓
        if Group.objects.exclude(pk=self.instance.pk).filter(name__iexact=name).exists():
            raise forms.ValidationError("Role name already exists")
        return name


text:
Q: Should I compile with -mssse3 in the presence of ASM SSSE3 code? I have a question regarding compiling a build of x264 on GCC.
x264 has assembly code dealing with instruction sets such as SSE3 and SSSE3 and by default has auto-vectorization disabled in the makefile.
Should I compile it with the -mssse3 flag anyways or could that actually cause a loss in performance?
And does -mssse3 imply -msse3 or is SSE3 separate from SSSE3?

A: The -m<isa> flag tells the compiler what instructions to use in the code that it generates. It does not affect inline assembly that just gets further passed unmodified to the assembler not does it affect assembly (.s) files compiled separately. Compiling with SSSE3 and without automatic vectorisation is pointless as SSE is all about vectorisation, although it also can be used to perform scalar floating-point operations.


text:
Q: jQuery function filter with attribute name contains bracket is not working This is my code:

$(function() {
  console.log($('[name^=foo]').filter('[name=foo\\[front\\]]').length);
  console.log($('[name^=bar]').filter('[name=bar\\[front\\]]').length);
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" name="foo[front]" />
<input type="text" name="foo[front]" />
<input type="text" name="bar[front]" />

The first console.log return 2 as expected, but the second console.log return 0 which I supposed to be 1.  What's wrong with my filter selector?

A: Bug confirmed jQuery Bug Tracker #4170


text:
Q: Clear text from document body I have a javascript function that is checking if the text entered is a number or not. When the user clicks on the enter button, and the text is not a number it displays a message on the screen. If I keep pressing the enter the text keeps appearing but I want to clear the text each time the enter button is pressed so it doesn't keep repeating.

HMTL:

 Enter Distance: <input id="distance" type="text" name="txtDistance">

        <button id="enter" role="button">Enter</button>

JavaScript code:
document.getElementById('enter').addEventListener('click', function(event){

if(isNaN(document.getElementById('distance').value)){
    var docBod = document.body;
    var Error = document.createElement('h4');
    Error.textContent = "Please enter a number";
    docBod.appendChild(Error);
 }else{

 }

});

A: Use innerHTML to add the element to the body

document.getElementById('enter').addEventListener('click', function(event) {

  if (isNaN(document.getElementById('distance').value)) {
    var docBod = document.body;
    docBod.innerHTML += '
Please enter a number
'
  } else {

  }

});

  Enter Distance: <input id="distance" type="text" name="txtDistance">

    <button id="enter" role="button">Enter</button>

A: Not sure if I have read your question correctly, but the above answer doesn't clear the field like you've mentioned. I've created the below jsfiddle, let me know if this answers your question.
https://jsfiddle.net/pon962ke/3/
HTML:
<input type="text" name="textBox" id="textBox">
<button id="button">Click Me</button>

Please enter a number

A: Something like this should work:

 Enter Distance: <input id="distance" type="text" name="txtDistance">

    <button id="enter" role="button">Enter</button>

And then in the JavaScript:
var numError = document.querySelector('#num-error');
document.getElementById('enter').addEventListener('click', function(event){

if(isNaN(document.getElementById('distance').value)){
   numError.textContent = "Please enter a number";
}else{
   numError.textContent = "";
}

});

A: The obvious problem you're running into is the line:
var Error = document.createElement('h4');

This creates a new
 element every time the user attempts to submit a non-numeric character, and ultimately your function appends that to the page.
One option to avoid that problem is to find the existing
 element on the page, if it exists, and use that element; otherwise create a new one:
// here we use document.querySelector() to find the first, if any,
// element that matches the selector; if no such element is found
// document.querySelector() returns null, and we move on to creating
// a new
 element:
var Error = document.querySelector('h4') || document.createElement('h4');

This does, of course, mean that the same message is being added to the same element, which does nothing to draw the user's attention.
So, to draw the user's attention there are two obvious solutions:

*

*empty/remove the element when the <input> is focused, and add it back if a new error is made, or

*leave the error in place, but add a flash of colour with, for example, a CSS transition.

To that end, then:
// because we use the elements more than once, we cache them:
const button = document.getElementById('enter'),
  input = document.getElementById('distance');

button.addEventListener('click', function(event) {
  // other than the use of the 'input' variable, this function
  // is unchanged from your original:
  if (isNaN(input.value)) {

    // using the docBod element, retrieving by its id,
    // instead of the document.body:
    var docBod = document.getElementById('docBod'),
      Error = document.createElement('h4');

    Error.textContent = "Please enter a number";
    docBod.appendChild(Error);
  }
});

// here we bind the anonymous function as the event-handler
// for the focus event:
input.addEventListener('focus', function() {

  // we find the existing
 element in the document, if
  // one exists, and cache it:
  const temp = document.querySelector('h4');

  // if no element was found then temp will be null:
  if (temp) {
    // if temp was found, then we use ChildNode.remove()
    // to remove it from the document:
    temp.remove();
  }
  // for user convenience we could also select the <input>
  // value:
  // input.select();
});

const button = document.getElementById('enter'),
  input = document.getElementById('distance');

button.addEventListener('click', function(event) {
  if (isNaN(input.value)) {
    var docBod = document.getElementById('docBod'),
      Error = document.createElement('h4');

    Error.textContent = "Please enter a number";
    docBod.appendChild(Error);
  }
});

input.addEventListener('focus', function() {
  const temp = document.querySelector('h4');
  if (temp) {
    temp.remove();
  }
  //input.select()
});

  Enter Distance: <input id="distance" type="text" name="txtDistance">

    <button id="enter" role="button">Enter</button>

To add a flash of colour to grab attention:
// again, caching the relevant elements:
const button = document.getElementById('enter'),
  input = document.getElementById('distance');

button.addEventListener('click', function(event) {
  if (isNaN(input.value)) {

    // as above, I've chosen to use the element with the id of
    // docBod to assign to the variable of the same name:
    var docBod = document.getElementById('docBod'),

      // as in the first answer we here look for the existing
      // element, if it doesn't exist we create it:
      Error = document.querySelector('h4') || document.createElement('h4');

    Error.textContent = "Please enter a number";
    docBod.appendChild(Error);
  }
});

The above JavaScript relies on CSS to provide the animation:
// we create a CSS animation to animate the colour of the
// element to which the animation is bound from transparent
// (adjust to an appropriate colour of your choice) to
// #f90 (at the 75% point in the animation) and then back
// to transparent:
@keyframes attentionGrab {
  0% {
    background-color: transparent;
  }
  75% {
    background-color: #f90;
  }
  100% {
    background-color: transparent;
  }
}

h4 {
  /*
    'attentionGrab': the animation-name, the name of the
                     animation that we're using,
    '1.5s': the animation-duration, in seconds ('s'),
    'ease-in-out': the animation-timing-function,
    '1': the animation-iteration-count, here we play the
         animation once.
  */
  animation: attentionGrab 1.5s ease-in-out 1;
}

const button = document.getElementById('enter'),
  input = document.getElementById('distance');

button.addEventListener('click', function(event) {
  if (isNaN(input.value)) {
    var docBod = document.getElementById('docBod'),
      Error = document.querySelector('h4') || document.createElement('h4');

    Error.textContent = "Please enter a number";
    docBod.appendChild(Error);
  }
});
@keyframes attentionGrab {
  0% {
    background-color: transparent;
  }
  75% {
    background-color: #f90;
  }
  100% {
    background-color: transparent;
  }
}

h4 {
  animation: attentionGrab 1.5s ease-in-out 1;
}

  Enter Distance: <input id="distance" type="text" name="txtDistance">

    <button id="enter" role="button">Enter</button>

References:

*

*CSS:

*

*animation.

*animation-duration.

*animation-iteration-count

*animation-timing-function.

*JavaScript:

*

*childNode.remove()

*document.querySelector().

*Element.classList.

Bibliography:

*

*"Using CSS Animations," at Mozilla Developer Network.


text:
Q: Which one is default ODS destination in SAS - Listing or HTML? Which one is default ODS destination in SAS - Listing or HTML?
In SAS BASE Prep book, it says Listing but in Step by Step SAS programming it says HTML.

A: Depends on the version of SAS, and what you mean by default. There's the user default - which you get when you open SAS, and there's the factory installed default which is what it comes set as in the installation. This is an easily changed option so I wouldn't worry too much about which is default since you can change it in all of the latest versions. I prefer the listing default so I've set my SAS 9.3 to have a listing destination as the default.
I believe in SAS 9.3 the factory default was set to HTML. Prior to SAS 9.3 it was Listing.  So you're possibly looking at books that have refer to different SAS versions.


text:
Q: How to copy every repository/folder from one JFrog artifactory to another JFrog artifactory using Python? There is a package called "dohq-artifactory" in python which copies file from one to another artifactory but not folders/repositories. I have tried to copy folder with same package but It didn't work.
Please let me know how to accomplish this with python or suggest if there is any better way to accomplish this.

A: The mechanism to copy artifacts between 2 different Artifactory instances is replication (or repository import/export , however this will import the entire repository and will override existing content in the target which is not the case here).
You can configure push replication between the 2 repositories to replicate artifacts. As you want to replicate only a single specific file, you can configure the Path prefix with the path to that artifact.

With the Path Prefix configured, only artifacts under that path will be replicated to the target repository. After the replication has completed and the file was deployed to the target repository, you can delete the replication configured.


text:
Q: How to use a 2d array to declare an array_view or array object in c++ AMP I'm trying to use an array such as int myarray[2][3] to initialize an array_view object. I've tried array_view<int, 2> a(2,3, myarray); However that does not work. I would also like to be able to do the same thing with a vector. Any ideas?

A: Try array_view<int, 2> a(2, 3, *myarray);
EDIT :
A vector of (fixed-size) vectors can't be used directly to init an array_view object.
However you could do something like that:
vector< vector<int> > my_multi_vector; // Fill my_multi_vector with data
vector<int> my_composed_vector;
for(int i = 0, ie = my_multi_vector.size(); i != ie; ++i)
    my_composed_vector.insert(my_composed_vector.end(), my_multi_vector[i].begin(), my_multi_vector[i].end());
array_view<int, 2> a(2, 3, &my_composed_vector.front());

A: Baltram's method is correct.
And you can replace
array_view<int, 2> a(2, 3, &my_composed_vector.front());

by
array_view<int, 2> a(2, 3, my_composed_vector);

to make it simpler.
Here is an even more simpler way:
int myarray[2][3];
int *p = &myarray[0][0];
array_view<int, 2> a(2, 3, p);

Thanks,