text:
Q: php 5, for loop not displaying correctly series of numbers that starts with 0 I'm trying to get the results of the for loop like: 00001, 00002, 00003, etc. but the result is not displaying 0's: instead I get: 1, 2, 3, etc.
This is the code:
$min = 00001;
$max = 00005;

for ($x = $min; $x <= $max; $x++) {
    echo "$x ";
}

A: Just change your echo statement to this:
echo sprintf('%05d', $x);

Also i would recommend you to change your $min and $max variables to this:
$min = 1;
$max = 5;

Because if you have leading zeros then number gets interpreted as an octal number! So 00012 would not be 12  it would be 10.

A: <?php
$min = 00001;
$max = 00005;
for ($x = $min; $x <= $max; $x++) {
printf("%5d",$x);
}
?>

this is new code
<?php
$min = 00001;
$max = 00005;
for ($x = $min; $x <= $max; $x++) {
printf("%05d",$x);
echo '<br>';
}
?>

A: Thanks a lot for the help. Doing the trick via MySQL got everything done. Just had to change the value to decimal and assign the field size (7) with the corresponding zerofill attribute.
Now i can insert the count of the for loop without zeros but the db inserts them for me. Thanks


text:
Q: C# HttpWebRequest POST strange response Good morning, I am writing a program that makes a POST webrequest to a website (websta.me). The request works, but the problem is the response.
I analyzed the http requests using Charles and this is the normal response:
{"meta":{"code":200},"data":{"created_time":"xs","text":"xxxx <3","from":{"username":"xxxx","profile_picture":"xxxx","id":"xxxx","full_name":"xxxx"},"id":"xxxx"},"status":"OK","called_count":x}

My program is returning this:

Any ideas on how to solve this? Thanks in advance for any help :)
This is my code if it can help:
byte[] bytes = ASCIIEncoding.UTF8.GetBytes("comment=+xxx&media_id=xxx");
HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("http://websta.me/api/comments/xxx);
WebHeaderCollection postHeaders = postReq.Headers;
postReq.Method = "POST";
postReq.Timeout = 10000;
postReq.Host = "websta.me";
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/35.0";
postReq.Accept = "application/json, text/javascript, */*; q=0.01";
postHeaders.Add("Accept-Language", "it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3");
postHeaders.Add("Accept-Encoding", "gzip, deflate");
postReq.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
postHeaders.Add("X-Requested-With", "XMLHttpRequest");
postReq.Referer = "http://websta.me/feed";
postReq.ContentLength = bytes.Length;

postReq.CookieContainer = cookies;

postReq.KeepAlive = true;

postHeaders.Add("Pragma", "no-cache");
postHeaders.Add("Cache-Control", "no-cache");
Stream postStream = postReq.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Close();
HttpWebResponse postResponse;
postResponse = (HttpWebResponse)postReq.GetResponse();
StreamReader reader = new StreamReader(postResponse.GetResponseStream());
MessageBox.Show(reader.ReadToEnd());

A: The result you are receiving from your request is GZip compressed data (the first three bytes are 0x1f8b08).
To get the text from it, just decompress it using GZipStream.  Something like this:
private byte[] Decompress(byte[] data)
{
    using (GZipStream stream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))
    {
        const int size = 4096;
        byte[] buffer = new byte[size];
        using (MemoryStream memory = new MemoryStream())
        {
            int count = 0;
            do
            {
                count = stream.Read(buffer, 0, size);
                if (count > 0)
                {
                    memory.Write(buffer, 0, count);
                }
            }
            while (count > 0);
            return memory.ToArray();
        }
    }
}

Then modify the end of your code (from where you get your response) to:
postResponse = (HttpWebResponse)postReq.GetResponse();
Stream Reader = postResponse.GetResponseStream();
byte[] Data = new byte[postResponse.ContentLength];
Reader.Read(Data, 0, Data.Length);
Data = Decompress(Data);
string Result = System.Text.Encoding.UTF8.GetString(Data);
MessageBox.Show(Result);

This reads the response data (which is compressed) into a byte array, then decompresses it before converting it to the appropriate text (which I believe is utf-8 from the content-type description).
Please note that the GZip decompression routine is taken from http://www.dotnetperls.com/decompress (it is not mine).

redpajama_set_name: RedPajamaStackExchange


text:
Q: DSRC and WIFI (LTE/Cellular) in vehicular communication Can NS -2.35 simulate both DSRC and WIFI vehicular communication in the same environement?
If not, is there any software simulation capable of ?

A: Veins 5.0 can be used to model wirelessly-networked road traffic (cars, trucks, bikes, trains, pedestrians). By default, Veins 5.0 includes models of DSRC, but it can be used together with projects like INET (for WiFi), SimuLTE (for 4G+ mobile broadband networking), or Veins VLC (for visible light communication). See http://veins.car2x.org/ for more information.


text:
Q: Retrieve files from Windows 7 backup, and save them to Windows 10 I have a USB with a backup of an old Windows7 pc, and I want to see what files are in it. I do not want to change anything in my Windows 10 system inadvertently. In addition to my local Drive C, I have an empty Drive D on my pc, with almost 100 Gb available..(see pic), can I restore the files to their, and delete what I dont want? Without making any changes to my local disk?
Thanks for your patience with my probably dumb question, but I haven't done this before.
Pic 1 - The backup files on my USB

Pic 2 - The drive I want to save the files to


text:
Q: IE 7 crashes when calling javascript function I have a jqGrid in my asp.net mvc 4 view and in this view I define a type that will be used for the jqGrid. The jqGrid is within a jQuery Tab (I have a jQuery tab component).
The jqGrid in the tab is inserted as follows:

      @Html.Partial("../Grids/_MyGrid")

this is called from an ajax call in the same view as follows:
@using (Ajax.BeginForm("Search", "Item",
   new AjaxOptions
   {
       HttpMethod = "GET",
       InsertionMode = InsertionMode.Replace,
       UpdateTargetId = "jqGrid",
       OnSuccess = "showGridItems()"
   }))
{
    // My Stuff
}

in the same view i have defined a type that will be used for the jqGrid as follows:

The partial view _MyGrid above indicated looks like the following also in the same view:

When the ajax call is executed (see above ajax code) and the result is success, below javascript function is called onsuccess:
function showGridItems() {
    $('#_itemGrid').jqGrid({
        caption: paramFromView.Caption,
        colNames: ['ID', paramFromView.ItemName, paramFromView.ItemAddress, paramFromView.ItemType, paramFromView.Actions],
        colModel: (...)
}

This function is defined in a js file and it is included in the same view as below:
@section scripts
{
    @Content.Script("/Grids/ItemGrid.js", Url)
}

It is working perfectly in IE8, IE9 and IE10 but in IE7 it crashes in the showGridItems. The error is saying that paramFromView is not defined! I do not know why because from IE8 to IE10 is working perfectly but not for IE7. What's happening?
UPDATED
It was caused by the comma after the pageSize. I have removed and now works.

A: Remove the last comma (,) from the script.


text:
Q: Mentions Auto Suggesting da jquery a php Hi I'm making a change to a text area and thanks to this plugin I can mention users from a db after entering @ in a textarea you place the complete code.

<!doctype html>

<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link href="bootstrap-suggest.css" rel="stylesheet" type="text/css">

<textarea class="form-control" rows="8" id="example-1"></textarea>

in the user variable there are the search fields by default, I ask you for help, which instead of the defaul fields in the variable, the search is done in a php page, the data to search from my database sql, how can I change the code? how do I change defaul fields with dynamic fields taken from the database? Thanks I hope you help me

A: So I pretty much just followed the documentation on http://lodev09.github.io/bootstrap-suggest/#api
I wanted to include Axios as that's a more preferred way to fetch data in large scale applications.
and in their example return $.getJSON("users/data.json", { q: q }); using q by default will look up all the keys in the array. You can specify if you only want to search say for username with { username: q }
Here's my working db example you can use from {} myjson
Now the part that'd you change for getting this to work with your php backend is the api and api endpoint you've setup.

<!DOCTYPE html>

  <meta charset="utf-8" />
  <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
  <link href="bootstrap-suggest.css" rel="stylesheet" type="text/css" />

  <textarea class="form-control" rows="8" id="example-1">type after ->  @</textarea>

anyways hopes this helps,
-Brendan


text:
Q: Makefile error :make: *** [main] Error 1 I am executing a makefile with 3 parts for my project is about overloading opertions for big numbers:
BigNum.h
#include <vector>
#ifndef BIGNUM_H
#define BIGNUM_H
class impossible_number_exception{};
class BigNum{
public:
//some functions
private:
   //
};
#endif

the second part is BigNum.cpp that I include libraries and functions and the third part is main.cpp that I write it for testing my library:
int main(){
BigNum f("8913.67811");
BigNum r(-5453.578);
d=-1.02+f;
if(d>r){
cout<<f<<endl;
}
cout<<d[3];
return 0;
}

and my makefile is this:
all:main.o BigNum.o
   g++ -o a.out BigNum.o
main.o:main.cpp BigNum.o
   g++ -c main.cpp
BigNum.o:BigNum.h BigNum.cpp
   g++ -c BigNum.cpp
clean:
   rm -rf*.o

and I place all the tabs and spaces correctly but I got this error that some of its line is:
g++ -c main.cpp
cc   main.o   -o main
main.o: In function `main':
main.cpp:(.text+0x23): undefined reference   std::allocator<char>::allocator()
...
main.cpp:(.text+0xb6): undefined reference to `BigNum::BigNum(double)'
main.cpp:(.text+0x2d9): undefined reference to `std::ios_base::Init::~Init()'
main.o:(.eh_frame+0x13): undefined reference to `__gxx_personality_v0'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'main' failed
make: *** [main] Error 1

what should I do about this?

A: well now I change my makefile to this
CXX=g++
CXXFLAGS=-g
main: main.o BigNum.o
$(CXX) $(CXXFLAGS) -o main main.o BigNum.o
main.o: main.cpp BigNum.h
$(CXX) $(CXXFLAGS) -c main.cpp
BigNum.o:BigNum.cpp BigNum.h
$(CXX) $(CXXFLAGS) -c bignum.cpp

and it  works!!!!!!!!
but I can not found out about the problem of my first makefile!


text:
Q: JQuery - how do I make the cells in my table one set width and height? Every time I run the program the cells in the table vary in size depending on what letter is in it. I have fiddled around with the CSS but no luck, can anyone help?
 var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", "pin", "gag", "sat", "pat", "tap", "sap", "tag", "gig", "gap", "nag", "sag", "gas", "pig", "dig", "got", "not", "top", "pop", "god", "mog", "cot", "cop", "cap", "cod", "kid", "kit", "get", "pet", "ten", "net", "pen", "peg", "met", "men", "mum", "run", "mug", "cup", "sun", "mud", "rim", "ram", "rat", "rip", "rag", "rug", "rot", "dad", "sad", "dim", "dip", "did", "mam", "map", "nip", "tin", "tan", "nap", "sit", "tip", "pip", "sip", "had", "him", "his", "hot", "hut", "hop", "hum", "hit", "hat", "has", "hug", "but", "big", "bet", "bad", "bad", "bed", "bud", "beg", "bug", "bun", "bus", "bat", "bit", "fit", "fin", "fun", "fig", "fan", "fat", "lap", "lot", "let", "leg", "lit"];

 var shuffledWords = listOfWords.slice(0).sort(function () {
   return 0.5 - Math.random();
   }).slice(0, 12);

var tbl = document.createElement('table');
   tbl.className='tablestyle';
   var wordsPerRow = 2;

for (var i = 0; i < shuffledWords.length; i += wordsPerRow) {
   var row = document.createElement('tr');

for (var j=i; j < i + wordsPerRow; ++ j) {
    var word = shuffledWords[j];

    for (var k = 0; k < word.length; k++){
        var cell = document.createElement('td');

        cell.textContent = word[k];
        // IF FIREFOX USE cell.textContent = word[j]; INSTEAD
        row.appendChild(cell);
       }
   }
   tbl.appendChild(row);
}

document.body.appendChild(tbl);

A: Have you messed with the min-width, max-width, and letter-spacing settings?  Here I set it to 42px (just arbitary) and it sets all the columns the same.  i believe you might be able to use a combination of this to acheive what you want.  (I'm not sure if the width's should be dynamic either)  so that's something you can play with.  Here's just the modified demo.
DEMO

A:
I have fiddled around with the CSS but no luck...

This is exactly what CSS is for. Here's an example: Live copy | source
CSS:
#target td {
  width: 3em;
}

HTML:

      one
      two
      three

      four
      five
      six

(The fact you're generating your content dynamically doesn't matter.)


text:
Q: How to convert integer timestamp to DateTime in c# I have a database file containing timestamp like "388740254860721408". Unfortunately, I don't have a lot of documentation for the format. So I'm not sure how the timestamp is formatted.
How do I convert this number to a datetime?

A: Is this timestamp an actual value you found in the file? The first thing that came to mind is UNIX timestamp. Either in milliseconds or in seconds. For that big of a number I'd go with milliseconds, but It's invalid.
If in fact the UNIX milliseconds format is used to display this, the proper code for this is:
var time = DateTimeOffset.FromUnixTimeMilliseconds(yourValue);


text:
Q: Joomla 3.0 Hide logo if site on mobile device Been tasked with the above title, found the logo, and how to create a custom html module. How should I proceed?

*

*I cant edit the index of the site directly, unless theres a way to do it in joomla.

A: I'm not the most knowledgeable on front-end design standards, but I'd think some sort of CSS media query would do the trick.

A: Joomla 3 is based on Twitter Bootstrap. There are CSS helper classes such as ".hidden-phone" - try adding that to you module CSS (without the dot). If the template was developed by someone else, ask them to tell you what is the exact CSS class you should use.Check documentation

A: Not knowing which template you're using (some templates simply don't load bootstrap) but assuming you've bootstrap loaded, you need to edit the css file in your template directory - templates/your_template/css/your_css_templatename.css
Here, you should use the media queries and find the @media that you would like to change. Bellow the examples. Then, inside the one(s) that you may figure out will suit your needs, set the logo id selector and the attribute to display: none; (example below)
/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) {
     #your_logo {
        display: none;
    }
}

The options above will work even if bootstrap not loaded. If you have bootstrap loaded and you're able to set the class attribute in the logo, you can use the .hidden-phone utility class.


text:
Q: Use Discord API to send a private message given a user ID I have been attempting to use Discord's API to send a new private message to a user, given their user ID.
I am aware this is possible using libraries such as Discord.JS and Discord.py - please do not recommend me to use those, I am quite aware of what I am wanting to do. I've tried looking at the source for libraries like Discord.js but can't seem to find the endpoint needed to create a new DM with the specific user.
In addition, Discord's documentation are unclear on the topic and research online is broad.
Here is my current code(which obviously won't work as the endpoint isn't correct):
const discordToken = "some-token";
const discordID = "some-user-id";
const userURL = `https://discordapp.com/api/users/${discordID}`;
    fetch(userURL, {
        method: 'POST',
        body: JSON.stringify({
            recipent_id: discordID,
            embed: {
              title: `Testing - Title `,
              description: `Testing - Description`
            }
        }),
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bot ' + discordToken
          },
    })

If anyone knows the proper endpoint or another way to achieve this(using purely POST requests, no external libraries), please let me know, thanks.

A: Note I have not used discord api directly, but from what I know, I believe this will work.
I think you send a dm like sending a message in a channel.
You first need to create the dm using https://discord.com/developers/docs/resources/user#create-dm
And then send to it like any normal channel
https://discord.com/developers/docs/resources/channel#create-message


text:
Q: OpenCL On ubuntu 16.04, Intel Sandy Bridge CPU Is it possible to install openCL on 16.04 (CPU-Only)?
I tried many guides, but still do not get a working box.
I have a sandy-bridge second gen CPU, if this matters.

A: install packets
Generic ubuntu packages for OpenCL
Basic installation

sudo apt install ocl-icd-libopencl1
sudo apt install opencl-headers
sudo apt install clinfo

Package that allows to compile OpenCL code (1.2 I think)
Needed to link and compile

sudo apt install ocl-icd-opencl-dev

For Intel GT core
Package that enables runnig openCL on Intel GT, IvyBridge and up

sudo apt install beignet

For SandyBridge Intel CPU and possible others
Download this file
OpenCL™ Runtime 16.1.1 for Intel® Core™ and Intel® Xeon® Processors for Ubuntu* (64-bit)
On https://software.intel.com/en-us/articles/opencl-drivers#latest_linux_SDK_release
Install packages for turning rpm to deb

sudo apt-get install -y rpm alien libnuma1

Untar downloaded file

tar -xvf opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25.tgz
cd opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25/rpm/

Turn rpm files to deb

fakeroot alien --to-deb opencl-1.2-base-6.4.0.25-1.x86_64.rpm
fakeroot alien --to-deb opencl-1.2-intel-cpu-6.4.0.25-1.x86_64.rpm

Install .deb packages

sudo dpkg -i opencl-1.2-base_6.4.0.25-2_amd64.deb
sudo dpkg -i opencl-1.2-intel-cpu_6.4.0.25-2_amd64.deb

Touch local config file

sudo touch /etc/ld.so.conf.d/intelOpenCL.conf

Open the file

sudo vim /etc/ld.so.conf.d/intelOpenCL.conf

and add the line

/opt/intel/opencl-1.2-6.4.0.25/lib64/clinfo

Create a vendors dir and add intel.icd

sudo mkdir -p /etc/OpenCL/vendors
sudo ln /opt/intel/opencl-1.2-6.4.0.25/etc/intel64.icd /etc/OpenCL/vendors/intel64.icd
sudo ldconfig

test if this worked
Command to list your devices

clinfo

Dowload this file

https://codeload.github.com/hpc12/tools/tar.gz/master

Run this code to make sure everything works

tar xzvf tools-master.tar.gz
cd tools-master
make
./print-devices
./cl-demo 1000 10

This should print out GOOD in the end
For Nvidia
install nvidia drivers (I used 370), this should include all the runtime dirvers
Usefull linkes I have used to put this together
https://wiki.tiker.net/OpenCLHowTo
http://korniychuk.org.ua/instruction/how-to-use-opencl-on-ubuntu-16-04/
https://laanwj.github.io/2016/05/06/opencl-ubuntu1604.html
https://software.intel.com/en-us/articles/opencl-drivers#latest_linux_SDK_release
https://software.intel.com/en-us/forums/opencl/topic/285869
https://streamcomputing.eu/blog/2011-06-24/install-opencl-on-debianubuntu-orderly/
https://software.intel.com/en-us/forums/opencl/topic/390630
https://stackoverflow.com/questions/16977216/opencl-compile-on-linux

A: As per Intel's support site, OpenCL is not supported on 2nd gen (Sandy Bridge) Core processors.
You will need a 3rd gen (Ivy Bridge) or newer CPU to use OpenCL 1.2, or a 7th gen (Kaby Lake) to have the option to use OpenCL 2.0 with the Intel GPU (I am not sure what is currently supported in the drivers available for Linux).

A: OpenCL is packaged in Ubuntu/Debian, so rather than manually installing, one could try installing the following packages:
sudo apt-get install beignet-opencl-icd ocl-icd-libopencl1 clinfo

Then run clinfo to make sure that it detects your OpenCL platforms and devices.
$ clinfo

Number of platforms                               1
  Platform Name                                   Intel Gen OCL Driver
  Platform Vendor                                 Intel
  Platform Version                                OpenCL 2.0 beignet 1.3


text:
Q: Disable textInput based on radio button selection on Shiny Say I have the following Shiny App:
library(shiny)
ui <- fluidPage(
  column(3,
         radioButtons("radios", "",
                      c("Enabled" = "enabled",
                        "Disabled" = "disabled"),
                      inline = TRUE)
  ),
  column(4, textInput("text", "", value = "Disable me"))
)
server <- function(input, output) {

}
shinyApp(ui=ui, server=server)

What's the easiest way to disable the textInput based on the selected radio button? I know I just have to add ... disabled /> to the input tag, but I have no idea on how to do that in Shiny.
I tried building the full tag "manually" by pasting the HTML as a string, the selected radio value and the rest of the HTML, using uiOutput and renderUI (based on this), but that didn't work.
The textInputgenerates this:
<input id="text" type="text" class="form-control" value="Disable me"/>

and I need to be able to switch between the above and this:
<input id="text" type="text" class="form-control" value="Disable me" disabled />

A: You could do this with session$sendCustomMessage on the server (which generates javascript that disables or enables the text box) and Shiny.addCustomMessageHandler in the UI (which executes the javascript).
library(shiny)
ui <- fluidPage(
  tags$head(tags$script(HTML('
      Shiny.addCustomMessageHandler("jsCode",
        function(message) {
          eval(message.code);
        }
      );
    '))),
  column(3,
         radioButtons("radios", "",
                      c("Enabled" = "enabled",
                        "Disabled" = "disabled"),
                      inline = TRUE)
  ),
  column(4, textInput("text", "", value = "Disable me"))
)
server <- function(input, output, session) {
  observe({
    if(input$radios == "disabled") {
      session$sendCustomMessage(type="jsCode",
                                list(code= "$('#text').prop('disabled',true)"))
    } else {
      session$sendCustomMessage(type="jsCode",
                                list(code= "$('#text').prop('disabled',false)"))
    }
  })
}
shinyApp(ui=ui, server=server)

A: This kind of stuff is actually very trivial if you use the shinyjs package - it was built exactly because these questions popped up so often.  There are are functions called disable and enable that you can call in your server to disable/enable an input, or you can use the toggleState function to enable/disable based on a condition. Here is how to achieve what you want with minimal code without having to use JavaScript:
library(shiny)
ui <- fluidPage(
  shinyjs::useShinyjs(),
  column(3,
         radioButtons("radios", "",
                      c("Enabled" = "enabled",
                        "Disabled" = "disabled"),
                      inline = TRUE)
  ),
  column(4, textInput("text", "", value = "Disable me"))
)
server <- function(input, output, session) {
  observe({
    shinyjs::toggleState("text", input$radios == "enabled")
  })
}
shinyApp(ui=ui, server=server)

All I had to do to modify your original code was to add a call to shinyjs::useShinyjs(), add the session parameter to the server, and add the call to shinyjs::toggleState().
Disclaimer: I wrote the shinyjs package


text:
Q: Orbeon XPath getting checked values from checkboxes list to dropdown list I got a scrollable list of checkboxes from which I want to extract the checked values and insert them into a dropdown menu.
The list of checkboxes besides the static values it also receives dynamic content based on how the user interacts with the form.
I saw that the list of checkboxes saves the checkboxed items dynamically into the instance('form-name')/control-name but they are separated with space.
I thought that I make a xxf:script that splits them and then adds them to the dropdown menu but I think I over think it.
Is there a better way and also can someone provide some example code?


text:
Q: checkbox work as radio button in lwc datatable? I have created a data table with Multiple table by iterating it. I have to select only one row per data table using checkbox by checking one the other one automatically remove just like radio button.
Please help me
<template for:each={oppList} for:item="table">

    <lightning-card key={table.category} icon-name="custom:custom11">

{table.category}

        </lightning-card>
    <lightning-datatable
      data-id={table.category}
      key-field="Id"
      selected-rows={preSelectedRows}
      onsave={handleSave}
      onrowselection={handleRowSelection}
      suppress-bottom-bar="true"
      draft-values={draftValues}
      data={table.data}
      columns={column}

    >
    </lightning-datatable>

</template>

JS code:
handleRowSelection = event => {
        var selectedRows=event.detail.selectedRows;
        if(selectedRows.length>1)
        {
            var el = this.template.querySelector('lightning-datatable');
            selectedRows=el.selectedRows=el.selectedRows.slice(1);
            event.preventDefault();
            return;
        }
}

How to achieve this ?
[![enter image description here][1]][1]

A: I have something already implemented like this as an example for your use case:
<template if:true={contact}>
<lightning-datatable key-field="Id"
    data={contact}
    onrowselection={handleRowSelection}
    columns={columns}>
</lightning-datatable>
</template>

JS Code:
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

const columns = [
{ label: 'First Name', fieldName: 'FirstName' },
{ label: 'Last Name', fieldName: 'LastName' },
{ label: 'Title', fieldName: 'Title' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Email', fieldName: 'Email', type: 'email' }
];
export default class SingleSelectDatatable extends LightningElement {
error;
columns = columns;
contact=[];
connectedCallback()
{
    getContactList()
    .then((result,error) => {
        if (result) {
           this.contact=result;
        } else if (error) {
            console.error(error);
        }
    })
}
handleRowSelection = event => {
    var selectedRows=event.detail.selectedRows;
    if(selectedRows.length>1)
    {
        var el = this.template.querySelector('lightning-datatable');
        selectedRows=el.selectedRows=el.selectedRows.slice(1);
        this.showNotification();
        event.preventDefault();
        return;
    }
}
showNotification() {
    const event = new ShowToastEvent({
        title: 'Error',
        message: 'Only one row can be selected',
        variant: 'warning',
        mode: 'pester'
    });
    this.dispatchEvent(event);
  }
}

You can make it work for Opportunity record list in the same way..
lighting-datatable has property max-row-selection will restrict maximum number of records can be selected. If we set 1 as value then instead of checkbox it will be show radio.


text:
Q: Making Bootstrap button with an image I need to make a button that is an image so that when you click on it, it will do what the button is supposed to do. I'm making a carousel and trying to change the left and right buttons if you were wondering what I needed it for. At the bottom is the code I am trying to change. Instead of glyphicons I need it to be my own images.

A: Within both the left and right controls, replace these lines of code:

with:

Without seeing the code in action, it's difficult to say, but you may need to resize your images—or the CSS that governs the size of the carousel controls—to make your switch display correctly. It shouldn't require too much tweaking, though.


text:
Q: How to force CMake to use a response file when linking CUDA on Windows? How to force CMake to use a response file when linking CUDA on Windows?
I have been trying to create a convenience library on Windows in a
project that has CUDA.  The goal is to wrap up several libraries into
one.  The first approach was the straightforward
  add_library(conv
    $<TARGET_OBJECTS:a>
    $<TARGET_OBJECTS:b>
    $<TARGET_OBJECTS:c>
    )

which tries to link with nvcc, but overruns the windows command line length limit.  I.e, it emits
The command line is too long.

There are no problems on Darwin or Linux.
Then I discovered in cmake-3.20.3 the code,
  NVIDIA-CUDA.cmake: set(CMAKE_CUDA_RESPONSE_FILE_FLAG "--options-file ")

which led me to wonder whether I could just override the defaults by
setting
  set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_LIBRARIES TRUE)

but upon doing so, I saw no change in behavior.  It still links with nvcc, it still does not use a response file, and it still results in command line too long.
So then I tried setting the linker to be the Windows linker with
  set_property(TARGET conv PROPERTY LINKER_LANGUAGE CXX)

and making sure to have
--   CMAKE_CXX_USE_RESPONSE_FILE_FOR_LIBRARIES= TRUE

But the linker remained nvcc, and no response file was used.
Any ideas on how to fix this?

A: Looks like the option to use a response or options file in CUDA is not yet available in CMake. In current master (line 129):
# FIXME: investigate use of --options-file.
# Tell Makefile generator that nvcc does not support @<rspfile> syntax.
set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_INCLUDES 0)
set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_LIBRARIES 0)
set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_OBJECTS 0)


text:
Q: Memoization Function taking more time than non memoized one I am trying to implement memoization technique in javascript. But my memoized function is taking more time than the non memoized function. I think I have implemented memoized function correctly (I am a newbie to programming).
Can anybody help and let me know the reason.
Memoized function code :
function fiboeven(n){
    var cache =[]
    if (n in cache)  return cache[n]
    else if (n === 1) return cache[0] = 2
    else if (n === 2) return cache[1] = 8
    else return cache[n] = 4*fiboeven(n-1) + fiboeven(n-2)
}

Non memoized  function:
function fiboeven(n){
    if (n === 1)
        return 2
    else if (n === 2)
        return 8
    else
        return 4*fiboeven(n-1) + fiboeven(n-2)
}

A: No your cache will be recycled after every call. And youre not really using it:
var cache=[0,2,8];
function fiboeven(n){
        if (cache[n])  return cache[n];
        return cache[n] = 4*(cache[n-1] || fiboeven(n-1)) + (cache[n-2] || fiboeven(n-2));
}

http://jsbin.com/fatoxivola/edit?console
The or operator ( || ) tries to take a cached value first, if it does not exist it generates it recursively.


text:
Q: How to avoid generating empty .deflate files for a Hive query? When I run a Hive query, a large number of empty .deflate files are generated (they are actually about 8 bytes, which I think is the minimum size for a .deflate file).  I suspect this is happening because the query requires a large number of reducers.  I am wondering if there is a way to avoid generating these empty .deflate files?
Thanks in advance,
Lin

A: .deflate is the default compression codec
There are compression settings for Hive that can be used to reduce the amount of disk space that Hive uses for its queries.
When the property hive.exec.compress.output=true, Hive will use the codec configured by the mapred.map.output.compression.codec property to compress the storage in HDFS.  These properties can be set in the hive.site.xml or in the Hive-CLI.
To enable output compression from Hive-CLI.:
hive> set hive.exec.compress.output=true;
To enable output compression using hive.site.xml
<property>
 <name>hive.exec.compress.output</name>
 <value>true</value>
</property>

So to disable the .deflate file:
set hive.exec.compress.output=false;


text:
Q: jQuery remove class from UL hierarchy except for See fiddle: http://jsfiddle.net/3mpire/yTzGA/1/
Using jQuery how can I remove the "active" class from all LIs except for the one furthest (deepest) from the root?

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

This is the desired result:

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

A: Sort them by number of parents and exclude the last one as that will be the one nested the furthest regardless of markup, and remove the class on the rest of them
$('.active').sort(function(a,b) {
    return $(a).parents().length > $(b).parents().length;
}).not(':last').removeClass('active');

FIDDLE
To do it for each navpole, just wrap it in a each()
$('.navpole').each(function() {
    $('.active', this).sort(function(a,b) {
        return $(a).parents().length > $(b).parents().length;
    }).not(':last').removeClass('active');
});

FIDDLE

A: Note: This assumes that there is only a single path from the root to the deepest .active element, which contains all .active  Elements under that root (i.e. no branching). If that cannot be guaranteed, then this solution won't work.
$('.navpole .active').slice(0, -1).removeClass('active');

Since the order of the selected elements is the order in which their appear in the document, the "deepest" element is inevitably the last one, so we have to remove the class from every selected element, but the last one.
DEMO

A: You could use each() to loop through the .active elements and remove the class if its sibling elements have a ul child:
UPDATED EXAMPLE HERE
$('.navpole .active').each(function(){
    if($(this).siblings().children('ul').length > 0 ){
        $(this).removeClass('active');
    }
});

A: If you want to keep just the last .active item into each .navpole you can do something like this:
$(document).ready(function () {
    //For each navpole
    $('.navpole').each(function(){
    //Find number of active elements
        var len = $('.active',this).length;
    //Filter that elements and remove class for all elements except the last one
        $('.active',this).filter(function(index){
        return index != len-1;
        }).removeClass('active');
    })
});

Check this Demo Fiddle

A: Try this out. The previous example by adeneo is great, but has issues if you have two active nodes at the same level at the lowest level of the hierarchy and want all of their active states preserved. This version will keep all lowest nodes selected if they're at the same level in the hierarchy.
$(document).ready(function () {
    $('.navpole').each(function () {
        var active = $(this).find(".active").map(function () {
            return $(this).parents().length;
        });
        var maxParents = Math.max.apply(Math, active);
        $(this).find(".active").each(function () {
            if ($(this).parents().length != maxParents) $(this).removeClass("active");
        });
    });
});

here is a fiddle to illustrate:
http://jsfiddle.net/CGcr9/1/


text:
Q: Getting quotation marks to the bottom of a line Quotation marks go to the top of the line in MS Word, like "this".
However, official EU text as well as some Dutch publications use quotation marks as follows:
Van Slingelandt: "We vinden het belangrijk dat gemaakte afspraken nagekomen worden."
The opening quotation marks are at the bottom of the line. How do I get MS Word to do the same? Is there a setting in MS Word, or do I need to do something in the Apple/Mac environment?

A: On my (german) mac keyboard

*

*I get " when i press ALT + SHIFT + w

*I get " when I press ALT + SHIFT + 2

*and I get " when I press ALT + 2

On your keyboard this can be different depending depending on the language and/or setup. Another option I recently saw here could be as follows:

*

*get " when you press ALT + .

*get " when you press ALT + [

In order to find the right key combination it can be useful to turn on the keyboard viewer from "preferences > languages and text > input sources ..."  as described here.

A: There is a setting in Word (which I thought was enabled by default) which is called "Smart Quotes" in the auto-correction part.  Since I am not with the Mac at the moment, I do not know the exact location or wording, however.
NOTE: Smart Quotes depend on the spelling language you use at the cursor location.  So, if the set language of the part of your document you are currently working on is set to US, it will use the upper quotes.  If it is set to Dutch, it will use the correct ones for that language.
To make sure that the entire document is set to the correct language, highlight all text (Cmd+A), then choose the spelling language.


text:
Q: Need with Help Invalid outside source error I am trying to process information with a dead mans program. Every time I try to run it I get Compile error Invalid outside procedure. I've never messed with VB6 before. I've been searching for a solution but I only get help saying it needs to be in sub or something but the threads are closed and I haven't been able to get their solutions to work for me. http://pastebin.com/vR7A7iN5
I think the problem is in this specific section of the code but I am unsure how to place it into a sub or get it to work otherwise.
End Type

Dim recout As statrec

Open "\STAT\PP\QM1409\MGA013A\" For Random As #1 Len = 150

num.recs = LOF(1) / 150
Print num.recs

For Count = 1 To num.recs

  Get #1, Count, recout

   If recout.mga = "013" Then

A: It is a big reach to assume this is the only incompatibility, but start by wrapping the code you're talking about now inside a method as Plutonix mentioned. That IS definitely an error. However I would not be surprised if there are more problems.
Example:
Public Sub GetStatRecs()
    Dim recout As statrec

    Open "\STAT\PP\QM1409\MGA013A\" For Random As #1 Len = 150

    num.recs = LOF(1) / 150
    Print num.recs

    For Count = 1 To num.recs
        Get #1, Count, recout
        ....
    Next Count

    ....

End Sub


text:
Q: can you get more than one download URL at once in firestore storage? I have a path in my bucket that has 10 images can I get the downlead URL of all those 10 images at once in a similar way when you for each doc fields in getDoc() ? or it it stricted to only one at time and to only a specific file name refrence?
const storage = getStorage();
getDownloadURL(ref(storage, 'images/1.jpg'))
  .then((url) => {
  }

const storage = getStorage();
getDownloadURL(ref(storage, 'images/'))
  .then((url) => {
  // all the images inside path images/
  }


text:
Q: Julia: Why ridge regression not working (optim) I am trying to implement ridge-regression from scratch in Julia but something is going wrong.
# Imports
using DataFrames
using LinearAlgebra: norm, I
using Optim: optimize, LBFGS, minimizer

# Read Data
out = CSV.read(download("https://raw.githubusercontent.com/jbrownlee/Datasets/master/housing.csv"), DataFrame, header=0)

# Separate features and response
y = Vector(out[:, end])
X = Matrix(out[:, 1:(end-1)])
λ = 0.1

# Functions
loss(beta) = norm(y - X * beta)^2 + λ*norm(beta)^2
function grad!(G, beta)
    G = -2*transpose(X) * (y - X * beta) + 2*λ*beta
end
function hessian!(H, beta)
   H =  X'X + λ*I
end

# Optimization
start = randn(13)
out = optimize(loss, grad!, hessian!, start, LBFGS())

However, the result of this is terrible and we essentially get back start since it is not moving. Of course, I know I could simply use (X'X + λ*I) \ X'y or IterativeSolvers.lmsr(X, y) but I would like to implement this myself.

A: The problem is with the implementation of the grad! and hessian! functions: you should use dot assignment to change the content of the G and H matrices:
G .= -2*transpose(X) * (y - X * beta) + 2*λ*beta
H .= X'X + λ*I

Without the dot you replace the matrix the function parameter refers to, but the matrix passed to the function (which will then be used by the optimizer) remains unchanged (presumably a zero matrix, that's why you got back the start vector).


text:
Q: How to convert a string with numbers and spaces into an int I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!

A: intval(preg_replace('/[^0-9]/', '', $input))

A: Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);

A: $str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234

A: This is how I would handle it...
<?php

$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";

$new_string = preg_replace("/[^0-9]/", "", $string);

echo $new_string // Returns 12345

?>

A: I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
    $numericValues = $matches = $result = array();
    $regExp = null;
    $decimalSeparator = preg_quote($decimalSeparator);
    $regExp = "/[^0-9$decimalSeparator]/";
    preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
    if(!empty($matches))
        $matches = $matches[0];

    foreach($matches as $match):
        $numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
    endforeach;
    $result = $numericValues;
    if(count($numericValues) === 1)
        $result = $numericValues[0];

    return $result;
}

So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.

A: Use this code for removing any other characters like .,:"'\/, !@#$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !@# then the output will be just an integer number!";

$output = intval(preg_replace('/[^0-9]/', '', $string));

var_dump($output);


text:
Q: How to append something in list which is in another python file? Suppose,
Content in fileA.py
# Content in fileA
import fileB

Content in fileB.py
# Content in fileB
fruits = ["Apple", "Orange", "Watermelon"]

So suppose I want to append something to the fruits list which is in the fileB from fileA how can I do that?

A: In this case you should import the other file as a module
So in your manage.py where the list lives, you would have
SOME_LIST=[1, 2, 3]

And you should create an __init__.py file in that folder to ensure you can use it as a module.
Then in the file you want to use that list:
from manage import SOME_LIST

[your code]

Do note that if the manage.py file is in another directory, you need to specify the full path to where it is
from path.manage import SOME_LIST

You can use the list from that file as a constant, but modifying it permanently is another matter. If you want to read and write data, you would need to use some sort of file instead of a Python module. Maybe a JSON or a YAML. If the list is simple, maybe even a txt file where each line is one element of the list.


text:
Q: Minimize $\mathrm{tr}(AX^{-1}A'X)$ such that $X\succ0$ Given $A\in\mathbb{R}^{n\times n}$
\begin{array}{ll} \underset{X\in\mathbb{R}^{n\times n}}{\text{min}} & \mathrm{tr}(AX^{-1}A'X).\\ \text{s.t.} & X\succ0\end{array}
("$X\succ0$" means that $X$ is symmetric positive definite matrix)

Special case when $A=\begin{bmatrix}
a_1 &  & \\
 & a_2 & \\
&&a_2
\end{bmatrix}$ was discussed here: Find $\mathrm{tr}(AX^{-1}A'X).$
Is it possible to linearize/convexify such problem? Or is there any good approximation methods?


text:
Q: Footer will not stay at bottom of page My footer will not stay at the bottom of the page. Now when I use position: fixed; or position: absolute;, It says at the bottom of the browser and not the page. So I want it to make it stay at the bottom of the webpage, but also stays below the content.
I tried adding height: 100%; to my wrapper (my footer is outside my wrapper) and it didn't work. I also just tried adding the sticky footer and it didn't work, but I left that part in my jsfiddle also.
Here's my jsfiddle: http://jsfiddle.net/PfVFd/
Now it seems to work with a small screen (like the result window on jsfiddle), but on a 1080 resolution, it doesn't work so here's my website also: http: http://erraticfox.com/about.html

A: you should read Ryan documentation about the sticky footer, everything is on: http://ryanfait.com/resources/footer-stick-to-bottom-of-page/
To complete my previous answer:
http://jsfiddle.net/PfVFd/1/
You should have position: fixed
footer {
line-height: 100px;
position: fixed;
background: rgba(28, 32, 36, 1);
bottom:0px;
width: 100%;
margin-left: 0;
margin-right: 0;
height: 100px;
text-align: center; }

A: Make position:absolute and bottom:0px

*,
*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing:    border-box;
  box-sizing:         border-box;
}

html {
  height: 100%;
}

body {
  position: relative;
  margin: 0;
  padding-bottom: 4rem;
  min-height: 100%;
  font-family: "Helvetica Neue", Arial, sans-serif;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}
This footer will always be positioned at the bottom of the page, but not fixed.


text:
Q: Different fonts in the same Style in a Plot I have a plot, not important what it is and I have a linelegend as below:
PlotLegends ->
Placed[LineLegend[{Style["K=3", FontSize -> 23],
Style["K=5", FontSize -> 23], Style["K=7", FontSize -> 23],
Style["K=9", FontSize -> 23]},

Here all "K" s must be italic but not "=" and the following numbers. In the usual case all are roman. How can I deal with this problem?

A: Plot[{3 x, 5 x, 7 x, 9 x}, {x, -1, 1},
 PlotLegends ->  Placed[LineLegend[Row[{Style["K", 23, Italic],
        Style["=" <> ToString@#, 23]}] & /@ {3, 5, 7,   9}], {After, Top}]]

Or, use
PlotLegends -> Placed[LineLegend[
   Style[ToString[Style[K, Italic], StandardForm] <> "=" <> ToString[#], 23] & /@
     {3, 5, 7, 9}], {After, Top}]


text:
Q: Usage of different headings with fancyhdr in a thesis I have been trying to insert different headings to my thesis.
The requirement is to show the frontmatter with Roman letters and the name of the section or chapter. The heading of the main part shall show the number of the chapter, the chapter title and the page number. The backmatter again shall show the same as the main part, thus the number of the chapter, title and page number. Sounds pretty easy. However, I have my difficulties.
I have tried the following code. It works fine for the frontmatter. The main and backmatter do not show the expected result. In the main matter, the number of the chapter is not shown and on the "rightmark" page, the section is shown instead of the chapter details.
Same for the backmatter. It shows the title twice in the header, but not the chapter number or the page number.
Attached you will find the equivalent code.
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancypagestyle{main}{%
\fancyhf{}
%\fancyhead[EL,OR]{\textsl{\rightmark}}
%\fancyhead[OL,ER]{\textsl{\rightmark}}
\fancyhead[EL]{\thepage}
\fancyhead[ER]{\leftmark}
\fancyhead[OL]{\leftmark}
\fancyhead[OR]{\thepage}
\renewcommand{\chaptermark}[1]{%
     \markboth{\thechapter{} #1}{\thechapter{}#1}}
}
\fancypagestyle{plain}{%
\fancyhf{}
\fancyhead[L]{\nouppercase{\rightmark}}
\fancyhead[R]{\nouppercase{\leftmark}}
\fancyhead[EL]{\thepage}
\fancyhead[OR]{\thepage}

\renewcommand{\chaptermark}[1]{%
    \markboth{#1}{#1}}
}
\fancypagestyle{back}{%
\fancyhf{}
\fancyhead[EL]{\thepage}
\fancyhead[ER]{\leftmark}
\fancyhead[OL]{\leftmark}
\fancyhead[OR]{\thepage}

\renewcommand{\chaptermark}[1]{
    \markboth{\thechapter{} #1}{\thechapter{}#1}}
}
\appto\frontmatter{\pagestyle{plain}}
\appto\mainmatter{\pagestyle{main}}
\appto\backmatter{\pagestyle{back}}

%**Another way of doing it is the following:**
\documentclass[12pt,twoside]{book}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage[a4paper,width=150mm, top=25mm, bottom=25mm, bindingoffset=6mm]{geometry}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage{fontspec}
%\usepackage[scaled]{uarial}
\setsansfont{Arial}
%\usepackage{lmodern}
\usepackage{amsmath}
\usepackage{siunitx}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[]{unicode-math}
\setmainfont[Mapping=tex-text,Numbers={OldStyle,Proportional},Ligatures={TeX, Common}]{TeX Gyre Termes}
\setmonofont[Mapping=tex-text,Scale=0.8]{TeX Gyre Cursor}
\setsansfont[Mapping=tex-text,Numbers=OldStyle,Ligatures=Common]{TeX Gyre Heros}
\setmathfont[math-style=ISO,bold-style=ISO,vargreek-shape=TeX]{TeX Gyre Pagella Math}
\usepackage{makeidx}
\usepackage{multirow}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{fancyhdr}
\setlength{\headheight}{15pt}
\fancypagestyle{plain}{%
\fancyhf{}
\fancyhead[L]{\nouppercase{\leftmark}}
\fancyhead[R]{\nouppercase{\leftmark}}
\fancyhead[EL]{\thepage}
\fancyhead[OR]{\thepage}
\renewcommand{\chaptermark}[1]{%

    \markboth{#1}{#1}}
}
%\fancypagestyle{main}
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\chaptermark}[1]{
    \markboth{\thechapter{} #1} {} }

\fancyhead[LE,RO]{\thepage}
\fancyhead[RE]{\nouppercase{\leftmark} }
\fancyhead[LO]{\nouppercase{\leftmark}
}

\graphicspath{images/}
\usepackage[style=alphabetic]{biblatex}
\addbibresource[style=alphabetic]{references.bib}
\usepackage{setspace}
\setstretch{1.1}
\usepackage{acronym}

\parindent0cm
\renewcommand*{\familydefault}{\sfdefault}

\makeatletter
% Define frontmatter, mainmatter and backmatter if not defined
\@ifundefined{frontmatter}{%
    \newcommand{\frontmatter}{%
       %In Roemischen Buchstaben nummerieren (i, ii, iii)
       \pagenumbering{roman}
    }
}{}
\@ifundefined{mainmatter}{%
    % scrpage2 benoetigt den folgenden switch
    % wenn \mainmatter definiert ist.
%    \newif\if@mainmatter\@mainmattertrue
    \newcommand{\mainmatter}{%
       % -- Seitennummerierung auf Arabische Zahlen zuruecksetzen (1,2,3)
       \pagenumbering{arabic}%
       \setcounter{page}{1}%
    }
}{}
\@ifundefined{backmatter}{%
%    \newif\if@backmatter\@backmattertrue
    \newcommand{\backmatter}{ %
       %In Roemischen Buchstaben nummerieren (i, ii, iii)
       \pagenumbering{roman}
    }
}{}
\makeatother

\begin{document}
{\sffamily
%\maketitle
\begin{titlepage}
   \begin{center}
       \vspace*{2cm}

\begin{Huge}
{xx}
\end{Huge}

       \vspace{0.5cm}
        {\Large xx}

       \vspace{1cm}
\textbf{xx}\\
        \vspace{1cm}
zxx

        \vspace{1cm}
\textbf{xx}

        \vspace{0.5cm}
\textbf{(xx)}

\vspace{1cm}

       von xx\\
       \vspace{0.5cm}
xx \\
        \vspace{0.5cm}
xx\\
        \vspace{0.5cm}
xx\\
        \vspace{1.5cm}
xx: \\
        \vspace{0.5cm}
xx\\
        \vspace{0.5cm}
xx\\
        \vspace{1cm}
xx
%       \includegraphics[width=0.4\textwidth]{university}

   \end{center}
\end{titlepage}
\thispagestyle{empty}
\frontmatter
\pagestyle{plain}

\chapter{Vorwort}
\chapter{Danksagung}
xx
\chapter{Abstrakt}
xx
\chapter{Abstract}
xx
\chapter{Abkürzungsverzeichnis}
\begin{acronym}[SEPSEP]
\acro{abb}[Abb.]{Abbildung}
\end{acronym}
\newpage
\tableofcontents
\listoffigures
\listoftables
\mainmatter
\pagestyle{fancy}
\chapter{Einleitung}
xx

\chapter{ssssssssss}
xx

\chapter{eeeeeeeeee}
cccc

\backmatter

\appendix
\chapter{Anhang}
ffffffffff
}

\end{document}

A: Since I had to create an MWE anyway, here it is.
\documentclass{book}
\usepackage{etoolbox}
\usepackage{lipsum}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancypagestyle{main}{%
\fancyhf{}
%\fancyhead[EL,OR]{\textsl{\rightmark}}
%\fancyhead[OL,ER]{\textsl{\rightmark}}
\fancyhead[EL]{\thepage}
\fancyhead[ER]{\leftmark}
\fancyhead[OL]{\leftmark}
\fancyhead[OR]{\thepage}
\def\chaptermark##1{\markboth{\thechapter{} ##1}{\thechapter{}##1}}%
}
\fancypagestyle{plain}{%
\fancyhf{}
\fancyhead[L]{\nouppercase{\rightmark}}
\fancyhead[R]{\nouppercase{\leftmark}}
\fancyhead[EL]{\thepage}
\fancyhead[OR]{\thepage}
\renewcommand{\chaptermark}[1]{%
    \markboth{##1}{##1}}
}
\fancypagestyle{back}{%
\fancyhf{}
\fancyhead[EL]{\thepage}
\fancyhead[ER]{\leftmark}
\fancyhead[OL]{\leftmark}
\fancyhead[OR]{\thepage}
\renewcommand{\chaptermark}[1]{
    \markboth{\thechapter{} ##1}{\thechapter{}##1}}
}
\appto\frontmatter{\pagestyle{plain}}
\appto\mainmatter{\pagestyle{main}}
\appto\backmatter{\pagestyle{back}}

\begin{document}
\frontmatter
\chapter{chapter}
\section{section}
\lipsum[1-10]
\mainmatter
\chapter{chapter}
\section{section}
\lipsum[1-10]
\backmatter
\chapter{chapter}
\section{section}
\lipsum[1-10]
\end{document}

A: Chapters in backmatter are unnumbered. So, I think they should be unnumbered in the page header, too. Therefore I would use \if@mainmatter in a global redefinition of \chaptermark:
\makeatletter
\renewcommand{\chaptermark}[1]{\markboth{\if@mainmatter\thechapter{}\ \fi#1}{}}
\makeatother

Example:
\documentclass[12pt]{book}
\usepackage[a4paper,width=150mm, top=25mm, bottom=25mm, bindingoffset=6mm]{geometry}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage{fontspec}
\usepackage{}
\usepackage{fancyhdr}
\setlength{\headheight}{15pt}
\pagestyle{fancy}% before the redefinition of \chaptermark

\makeatletter
\renewcommand{\chaptermark}[1]{\markboth{\if@mainmatter\thechapter{}\ \fi#1}{}}
\makeatother

\fancyhf{}
\fancyhead[LE,RO]{\thepage}
\fancyhead[LO,RE]{\nouppercase{\leftmark}}

\renewcommand*{\familydefault}{\sfdefault}

\usepackage{lipsum}% nur für Fülltext
\begin{document}
\begin{titlepage}
\begin{center}
  \Huge Titelseite\par
  \normalsize
  Weiterer Text auf der Titelseite
\end{center}
\end{titlepage}
\thispagestyle{empty}
\frontmatter
\chapter{Vorwort}
  \lipsum[1]
\chapter{Danksagung}
  \lipsum[2]
\chapter{Abstrakt}
  \lipsum[3]
\chapter{Abstract}
  \lipsum
\tableofcontents
\listoffigures
\listoftables
\mainmatter

\chapter{Einleitung}
\lipsum
\chapter{ssssssssss}
\lipsum
\chapter{eeeeeeeeee}
\lipsum
\backmatter
\appendix
\chapter{Anhang}
\lipsum
\end{document}

Note, that first page of each chapter uses pagestyle plain. If they should get the same layout, define fancypagestyle plain in the preamble:
\fancypagestyle{plain}{%
  \fancyhf{}%
  \fancyhead[LE,RO]{\thepage}%
  \fancyhead[LO,RE]{\nouppercase{\leftmark}}%
}

or
\fancypagestyle{plain}{}% change plain pagestyle to fancy


text:
Q: How to check if given string can be formed from another string in Java? I need to check if a given string can be formed from main string or not in Java .
Example :
Input
Main String - lhLoe
HELLO
eel
eL,$H.
Ouput:
HELLO : YES
eel : NO
eL,$H. : YES
I can try with permutation , but if the first string is long , it will take much time . Any other way to do this ?
Note: we can ignore special characters.

A: You could use regex and define your String as a character group.
Something like this:
    String search="lhLoe";
    String input="HELLO";
    input=input.replaceAll("^[a-zA-Z1-9]","");
    Pattern p = Pattern.compile("^["+search+"]+$",Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(input);
    boolean b = m.matches();

A: First, lowercase both strings, so that:
lowerCasedMainString = "hello"
lowerCasedTargetString = "el,$h"

Next remove special characters, since you say they can be ignored:
lowerCasedTargetStringStripped = "elh"

There are various ways you can tackle the rest of the problem, but I would do a loop like this (pseudocode):
while(length of target > 0) {
    char c = target.charAt(1);

    if(main contains c) {
       main = main with that instance of c removed
    } else {
       return false
    }

    target = target.substring(1);
}
return true;

Each individual step of this should be easily achievable. If you're tackling a problem like this, you've probably already seen the methods that will do it. Otherwise, there will be existing answers on Stack Overflow.

A: You could store the occurrences of each character in the given main string in an array. (Let's call it array a.)
Repeat the same procedure for the given test strings. (Let's call it array b)
If the occurrence of each character in test string (array b) is less than equal to the occurrence of that corresponding character in the main string(array a), then, the test string can be formed using main string.
Runtime complexity will be linear.
Take care of case sensitivity and special symbols.


text:
Q: How to get IP of my site, exactly? I've contacted some website administrators for their API, in return, they have asked for source IP, in order to whitelist it, so that only requests from that IP will be considered as legit (it is ok even if it is a shared IP).
So, now the problem is how do i get the ip of  the site. Being a PHP developer, I've tried gethostbyname() which gives random ip's & also $_SERVER['REMOTE_ADDR'] (called from other server) which always gives the single IP. I'm totally confused with this, also I've very less time to give them my source IP.
I don't have paid hosting. I always use, free tiers of appfog (*.aws.af.cm) & openshift (*-name.rhcloud.com). It would be great if someone can tell me the process for finding any of those IP addresses or show me a way to get a static IP (which i could share with them) for free or another host. Also, they have given permission to use this API only for 10days.
UPDATE: I've also tried ping mysite.aws.af.cm (which is same as gethostbyname()) gives different IPs for different calls.

A: Web hosts usually have static IP addresses but I'm surprised they require an IP for a web-based API instead of a domain/some kind of secret key.
Have you considered just pinging your domain, as the ping command will convert your domain into the IP address it correspondes to?
EDIT: Another solution.
Considering your API is being contacted by the server, I have created a file on my own website that returns $_SERVER['REMOTE_ADDR'], BUT you should access the file using a script on your site!
Upload the following to your website and run it:
<?php
    echo file_get_contents("http://barathesh.com/server.php");
?>

A: From command-line
Ping it from your terminal (works in Windows & Linux based OS)
ping youhostname.com

will print something like
64 bytes from 74.125.206.100: icmp_seq=0 ttl=44 time=3.151 ms
64 bytes from 74.125.206.100: icmp_seq=1 ttl=44 time=3.116 ms

Pure PHP
Take a look to the gethostbyname function
echo gethostbyname('yourdomain.com');

will output the ip adress of yourdomain.com

A: Use this php function and echo out the result like so:
$myip = ($_SERVER['REMOTE_ADDR']);
echo $myip


text:
Q: Word Break Problem: Not getting the expected O/P for the negative cases I have written a code using java on word break problem. This idea is to return the list of words from the dictionary which when combined give the entered string. I have used  TRIE data structure in my approach. It is working fine for positive cases, however, it is not working as expected for negative cases.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WordBreakProblem {

    public class Node{

        String prefix;
        Map<Character, Node> children;
        boolean isWord;

        public Node(String prefix){
            this.prefix = prefix;
            children = new HashMap<Character, Node>();
            isWord = false;
        }
    }

    Node trie;
    public WordBreakProblem(String[] words){
        trie = new Node("");
        for(String s : words){
            insertIntoTrie(s);
        }

    }

    private void insertIntoTrie(String s) {
        Node curr = trie;
        for(int i=0; i<s.length(); i++){
            if(!curr.children.containsKey(s.charAt(i)))
                curr.children.put(s.charAt(i), new Node(s.substring(0, i+1)));
            curr = curr.children.get(s.charAt(i));
            if(i == s.length()-1)
                curr.isWord = true;
        }

    }

    public ArrayList<String> searchForPair(String str, ArrayList<String> list){
        Node curr = trie;
        int i;
        for(i = 0; i<str.length(); i++){
            if(curr.children.containsKey(str.charAt(i))){
                curr = curr.children.get(str.charAt(i));
            }
            else
                break;
        }
        if(curr.isWord){
            list.add(curr.prefix);
            searchForPair(str.substring(i), list);
        }
        else
            return null;

        return list;
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        WordBreakProblem w = new WordBreakProblem(new String[]{"news", "abcd", "tree", "geeks", "paper"});
        List<String> al = w.searchForPair("newsgeeksabc", list);
        for(String s : al){
            System.out.println(s);
        }
    }
}

Expected: null
Output:
news

geeks

Since "abc" is not present in the dictionary, it should return null.
The problem seems to be somewhere here:
if(curr.isWord){
            list.add(curr.prefix);
            searchForPair(str.substring(i), list);
        }
        else
                   return null;

A: It's a little hard to follow your code, as I am not entirely sure why you expect it to return null. From what I can glean, you expect it to return null because you come across something that isn't a word - so, despite finding words previously, you want to throw those away and return null.
It's because you ignore the return value in your recursive call:
    if(curr.isWord){
        list.add(curr.prefix);
        searchForPair(str.substring(i), list);  // HERE
    }
    else
               return null;

    return list;

Even if that recursive call returns null, you ignore it and still return list.
Handle the case of receiving null:
if (curr.isWords) {
  list.add(curr.prefix);
  List<String> result = searchForPair(str.substring(i), list);
  if (result == null) {
    return null;
  }
} else {
  return null;
}
return list;

If I may offer a couple of observations on the code:

*

*return/break in an else is a sign that your code code be made clearer (you may find it clearer) if you invert the condition, and remove the else, for example:
if(!curr.isWord){
  return null;
}
list.add(curr.prefix);
searchForPair(str.substring(i), list);  // HERE
return list;

*Returning null is awkward in the case of not finding any words, because calling code then has to handle the case that it's null. The API may be easier to use if you return some non-null value to represent "no words found", such as an empty list.


text:
Q: Two containers one compose file network not working This should be something simple. I have a docker compose file that starts a DB2 container and another Java application container that does work against the database. The purpose of this stack is for solely to verify testing, the values in the database should not persist. But, I need the Java container to be able to make a JDBC connection to DB2. Right now, it's refusing, but I'm not sure why. I created a common network for both of them (I thought).
My docker-compose.yml
version: "3.2"
services:
  ssc-file-generator-db2-test:
    container_name: "ssc-file-generator-db2-test"
    image: ibmcom/db2:latest
    hostname: db2server
    privileged: true
    ports:
      - 50100:50000
      - 55100:55000
    networks:
      - back-tier
    restart: "no"
    volumes:
      - setup-sql:/setup-sql
      - db2-shell-scripts:/var/custom
      - host-dirs:/host-dirs
    env_file:
      - acceptance-run.environment
  ssc-file-generator:
    container_name: "ssc-file-generator_testing"
    image: "ssc-file-generator:latest"
    depends_on: ["ssc-file-generator-db2-test"]
    entrypoint: ["sh", "/ssc-file-generator/bin/wait-for-db2.sh"]
    env_file: ["acceptance-run.environment"]
    networks:
      - back-tier
    restart: "no"
    volumes:
      - setup-sql:/setup-sql
      - db2-shell-scripts:/var/custom
      - host-dirs:/host-dirs

networks:
  back-tier: {}
volumes:
  setup-sql:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ./setup-sql
  db2-shell-scripts:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ./db2-shell-scripts
  host-dirs:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ./host-dirs

A: try to add healthcheck to db service. To start ssc-file-generator after ssc-file-generator-db2-test successfully started and ready for connections.
https://docs.docker.com/compose/compose-file/compose-file-v2/#depends_on
ssc-file-generator-db2-test:
  ...
  healthcheck:
    test: some command that checks db2 is working

ssc-file-generator:
  ...
  depends_on:
    ssc-file-generator-db2-test:
      condition: service_healthy

A: The db in docker compose context should be available at the host:
ssc-file-generator-db2-test:50000
ssc-file-generator-db2-test:55000


text:
Q: setDrawingCacheQuality doesn't work in Android? I tried to get View's caching bitmap, the code is as follows:
View cachingView = getActivity().getWindow().getDecorView().getRootView();
cachingView.setDrawingCacheEnabled(true);
cachingView.setLayerType(View.LAYER_TYPE_NONE,null);
cachingView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
 Bitmap bitmap = Bitmap.createBitmap(cachingView.getDrawingCache());
LogHelper.i("bitmap size: "+bitmap.getByteCount());
LogHelper.i("bitmap size: "+ BitmapCompat.getAllocationByteCount(bitmap));

The print result is :
bitmap size: 14745600
bitmap size: 14745600
Obviously,it is too big. I changed different parameters of setDrawingCacheQuality , but the result is the same.
How can I get a smaller bitmap?
Thanks

A: The quality here isn't the quality of the compression like when writing a JPEG.  Its the quality of the alpha blending for transparencies.  So it does work, it just doesn't do what you thought it did.
(As an aside-  Bitmaps in memory are uncompressed, so it doesn't matter what compression quality you use to write them to disk-  in memory they take up the same amount of memory based if they're the same size).


text:
Q: Solutions to the functional equation $f(f(x))=f(x+1)$ I am trying to find all solutions to $f(f(x))=f(x+1)$ with $f:\mathbb{R}\rightarrow \mathbb{R}$.
I have found that $f(x)=x+1$ is a solution and $f(x)=c$ for any $c \in \mathbb{R}$ and
I think that there are no other rational (polynomial) solutions.
Are there any other (perhaps non-continuous) solutions?

A: There are no other polynomial solutions - if $f$ has degree $n$, then $f(f(x))$ has degree $n^2$, which is greater than $n$ if $n > 1$. And if $f$ has degree of at most $1$, then $f(x) = ax + b$, and we can find that solutions are only $a = 0$ and $a = 1, b = 1$ - which corresponds to $f(x) = c$ and $f(x) = x + 1$.
There are many discontinuous solutions even without AC. For example, $$f(x) = \begin{cases}0,\ x \in \mathbb{Z}\\ \frac{1}{2}, x \notin \mathbb{Z} \end{cases}$$.
There are also some other continuous solution. For example, $f(x + n) = |x|$ where $n \in \mathbb{Z}$ and $-\frac{1}{2} \leq x < \frac{1}{2}$ (any number has unique such representation): $f(f(x + n)) = f(x) = x$ and $f(x + n + 1) = x$. Alternative form of the same function: $f(x) = \rho(x, \mathbb Z) = \min\limits_{n \in \mathbb Z} |x - n|$.

A: There are an infinite number of non-continuous solutions which can be created by combining the two solutions you gave. For example, define $A_k$ as the set of algebraic numbers of degree $k$ or less. That is, $A_k$ is the set of algebraic numbers whose minimal polynomial has degree $k$ or less. Now, if $\alpha\in A_k$ then $\alpha+1\in A_k$ and if $\alpha\not\in A_k$ then $\alpha+1\not\in A_k$. Now, define
$$f(x)=\begin{cases}
      x+1 & x\in A_k \\
      c & x \in \mathbb{R}/A_k
   \end{cases}$$
(for any constant $c$). For any particular $x$ we have
$$f(x)\in A_k \Leftrightarrow x\in A_k$$
Thus, $f(x)$ satisfies the functional equation.

A: There are in fact uncountably many non-continuous solutions:
You can take $f: \mathbb{R} \rightarrow \mathbb{R}$ with $f(x)=0$, if $x \in \mathbb{Q}$, and $f(x)=y$, if $x \notin \mathbb{Q}$, for every irrational number $y \in \mathbb{R}$.
This works since there are uncountably many irrational numbers and the sum of an irrational number with a rational number is irrational.


text:
Q: Private betas, launches, relaunches, rules for promotion, and community partnerships The second private beta launch of EmbeddedSystems has been killed after about a week and a half.
Having had one disappointing experience with the maiden beta, and now a second (though with less personal buy-in, because of my experience with the first), the engineer in me feels compelled to start running a DFMA on this process. Here's where this exercise leads me.
In professional practice, I would never sign on the dotted line until the rules are made clear to me. I would put the work in up front to make sure I understood the needs, the timetable, the review steps, and the tools available to me to do the work.
In the Area51 process, I have very little of that. I don't know the rules, the metrics for success, and the timetable for review is simply unrealistic for the endeavor given those conditions.
I get that SE needs to somehow monetize our expertise to make this endeavor worth their bandwidth. I don't mind that. What I do mind is that in the Area51 process, SE feels like the executioner, not a partner. There are community coordinators like @JonEricson and @RobertCartaino who are generally encouraging, but certainly aren't playing the role of coaches who help move us through the process -- they just tell us when its over, and encourage us to start again.
Having been through two private betas (with the first the more successful of the two, in terms of engaging questions, IMO), and getting the feeling that critical mass in this area will be hard to come by, I'll say up front that I'd be very reticent to participate in a third without a clear review plan, some metrics, and an engaged community partner who can help move us to graduation to public beta.
This is a repost of a meta ES.SE post, but I'm reposting it here as a general discussion on private beta launches and graduations to public beta.
EDIT:  Discussion has led me to request a feature to reinvite committers from previous launch attempts to new attempts.  I added a reference to here at a feature request at  the Area51 discussion area.

A: After reading all the wonderful discussion, I can see one very powerful way for Community to help advocate relaunches.  I have a data point of N=1 for ES.SE, but the 10% level of first launch committers who participated in the relaunch seems low.  I can think of two possible reasons for it.

*

*Dissatisfaction with the first launch

*They simply didn't know about the second launch

It seems like an absolute no-brainer to me that sending private beta announcements to the committers from all previous launches (without, of course, changing any commitment phase rules) might substantially increase private beta participation.
So, is this something the Community can make happen?  Not just for ES.SE, but for relaunches in general?

A: I'm with you on just about… all of this.
A few months ago, I wrote a promising proposal called "An Objective Site Life Cycle" which accomplished about 90% of what you described above. It was ultimately pushed out in favor of splitting up the graduation process (baby steps), but the main tenet of this proposal was to present a completely objective and transparent process which listed exactly what communities would need to get to that next level (including things like starting an election, removing the 'beta' label, getting a custom design, etc, etc). It was a way to clearly convey:

You are ⇒here⇐ and here is what's
                                                      ⇓
                                                 coming
                                                      ⇓
                                                     up
                                                      ⇓
                                                   next

A set of completely objective criteria would all but remove the Community Team from that adversarial role of judge and executioner. There would likely have to remain a thin editorial layer to account for process-gaming and other crazy sh—, but challenging communities to work towards very specific goals puts us back in that role of counselor and community advocate.
That doesn't guarantee that all sites will work — you can never really take 100% of that sting out of losing an experiment that just didn't work out — but when you know up front, "If you can do {this} by {x} date, you move on", communities are remarkably resilient and understanding when the "agreement" is known up front.

A: I closed both Embedded Systems private betas. In terms of the negative feelings closing a site causes, both were difficult decisions. In objective terms, however, I'm entirely comfortable. As I wrote the first time around:

Have you ever run across an awesome blog post and went to read the rest of the site only to discover the author gave it up after a week or two? That's how I feel about this site. To my (admitted unexpert) eye, the questions and answers so far are just what I'd hoped to see on this site. There's a lot to like. But the initial activity suggests a site that didn't gather the critical mass that Area 51 is supposed to build.

(I had to dig this up out of the data dump. One feature of private betas that we take seriously is making sure content is freely available even if the site gets closed.)
Building a site's user base is best done during the Area 51 process. Over the years, we've set up a handful private betas with the Field of Dreams approach. Instead of forcing proposals to complete each Area 51 phase, we've simply allowed the site to start with the promise that an audience will materialize. (Most of these cases were the result of an organization approaching us directly asking either for a site to be built or for one of the restrictions to pass to the next phase be lifted.) I'm not aware of any "Field of Dreams" sites (including our own) reaching graduation; most languish in beta if they ever go public at all.
The first week of a private beta is particularly critical since it sets the course of a site for months, if not years. Paradoxically, site activity usually decreases after going public. The exceptions are sites that start strong right out of the gate and never really slow down: Emacs, CiviCRM, Stack Overflow itself, etc. Much of the initial surge seems to be the result of the novelty effect; people put in more effort into using a thing while it's still new. Sites that don't benefit from a fast start tend to remain slow.
I am somewhat reluctant to publish objective numbers for private betas to hit because of the Hawthorne Effect. In addition, as Robert points out, we haven't done the work to figure out what level of activity has worked well and what level hasn't. However, setting objective numeric criteria (as described in Thinking, Fast and Slow) will reduce the subjective judgements we make, which are really likely to be wrong.
There are hidden risks of keeping a slow site around and those risks are heightened for a topic that's already being served by an existing site. Stack Exchange sites are community curated, which means ordinary users earn the right to edit, vote to close, review posts, and so on. Building up an invested community takes time so beta sites have lower reputation requirements for these actions. Instead of building a new site for embedded systems questions from scratch, most askers would be better off asking on an existing site that fields those questions. And of course, experts will find more questions to answer on more active sites.
Finally, I apologize for appearing to be more an executioner than an advocate. One way I can improve in the future, I suspect, would be to not assume that everyone was already familiar with the entire process. It's likely I overestimated the number of people who had experienced the first Embedded Systems closure.

A: When announcing site closure, Jon Ericson cited 74 questions in the first 9 days. On the other hand, Arabic Language was given green light with 63 questions in the first 9 days. Even now, the nearly month-old Arabic Language has only 89 questions, trailing the condemned Embedded Systems which has 109.
We can deduce that the decision is not a direct function of the question volume. Another factor likely to be in play is whether the site brings new participants and new audience to the Stack Exchange network, as opposed to moving them from one part of the network to another. This is a major handicap of the Embedded Systems proposal; I imagine it would need to demonstrate a high level of activity not only in general, but from users who are not already active on the network.

A: I've participated in several private betas, and my impression is very different. In the cases where the sites were closed, most of the community generally agreed that it didn't work out. Those were the easy cases, but this one looks more difficult as the community doesn't seem to agree with the decision.
From what I read just now, question volume seems to have been the deciding factor this time. Usually the problem is either question volume or quality, and while the latter is pretty much impossible to quantify, I think a general guideline could be created for the required volume.
Initial post volume in a private beta is a really useful indicator for several issues. It tells us something about the number of actually interested users that the A51 process managed to attract, and something about whether the scope and topic of the site are a reasonable fit for an SE Q&A site. Starting a site without enough active users is bound to fail, it's really hard to attract new users if a site looks very inactive.
Just to add some statistics, the two sites I'm a moderator on had 64 and 120 questions in the first two days. The initial volume of ES.SE with 20 questions on the first day and around 10 on the second looks low to me.
What could be useful is a statistic about all the private betas that a new site could compare themselves to. This would give the users of the new private beta a better idea on what kind of volume is expected. I wouldn't tie down SE to a specific value, it wouldn't be much use as there are several other more subjective factors aside from the question volume. But simply showing what other sites looked like when they started could be helpful.


text:
Q: Chrome cast using Wi-Fi HotSpot of Android Smartphone Can chrome cast be used using Wi-Fi Hotspot of my Android Smartphone ?
Model Number: Galaxy Nexus (Nexus 3)
Android Version: 4.1.1

I do not want to introduce third external device (i.e. External WiFi router) to stream YouTube  videos from Smartphone to TV having Chrome-cast. Is that possible?
Is it technically feasible ?
[ Unfortunately I cannot test this scenario , as i didn't have chrome cast device yet]

A: It should work just fine BUT you will have to setup your chromecast from a different device than the one being used as a router(i.e. your android phone).  The reason being(This is how I believe it works):
1) Start with setup device connected to internet Wi-Fi device
2) Setup device finds chromecast listed as a Wi-Fi hotspot and connects to it for setup, at which point it is disconnected from the internet Wi-Fi device and connected to chromecast's Wifi
3) You configure chromecast to connect to your internet Wi-Fi device
4) Both devices then connect back to your internet Wi-Fi and communicate that way
As you can see, if your setup device was the same as your internet Wi-Fi device, there would be conflicts with how the Wi-Fi chip is used, and you wouldn't be able to complete setup. Once you got to the step of connecting the chromecast to Wi-Fi you wouldn't have the Wi-Fi on your phone broadcasting because it's being used to connect to the chromecast.

A: Tried this with my Galaxy Nexus as the hotspot and it gave me the AP isolation error.  Does not appear that the OS hotspot app supports peer to peer connections.  Not sure if it may be because I'm using Foxfi to enable the hotspot or if the phone doesn't support it.


text:
Q: Mysql query to select if a user's friends list is the logged in user's friend I am trying to get the friend list of a user profile. That's easy because of the schema I did.
Here is the table I did and demo data http://sqlfiddle.com/#!9/f78cf7/2

If I want to get the friend of user id 1, I would run select * from friends where user_id = 1 and I will get friends of this user. This is will return only first row with friend_id = 21.
Now how can I know if user id 30 is also a friend with id 21 in same query? How can I get the status column in same query?
Thank you.

A: You can try the below way -
DEMO
select f.user_id,f.friend_id,f.status
from friends f join friends f1 on f.id=f1.id+1
where f.status='Friend' and f1.status='Friend'

A: You can search both sides. For example:
select *
from friends where user_id = 30 and friend_id = 21 and status = 'Friend'
                or user_id = 21 and friend_id = 30 and status = 'Friend'


text:
Q: Pandas How To Pivot Without Losing Data I'm trying to assess Power Query/M with Pandas for some repeatable transformations. So far so good, but I've hit a brick wall with the following scenario in Pandas and would be very grateful for pointers as to what (I presume) I am doing wrong.
I have a DataFrame which looks like:
    sales rep   quarter result  value
0   adam        q1      target  3000
1   ben         q1      target  3200
2   cal         q1      target  2900
3   dan         q1      target  3400
4   adam        q1      actual  2900
5   ben         q1      actual  2100
6   cal         q1      actual  2100
7   dan         q1      actual  3500
8   adam        q2      target  4000
9   ben         q2      target  3200
10  cal         q2      target  7200
11  dan         q2      target  5200
12  adam        q2      actual  3400
13  ben         q2      actual  3900
14  cal         q2      actual  9000
15  dan         q2      actual  6000
16  adam        q3      target  4000
17  ben         q3      target  4000
18  cal         q3      target  7200
19  dan         q3      target  6400
20  adam        q3      actual  4500
21  ben         q3      actual  4000
22  cal         q3      actual  6500
23  dan         q3      actual  6500
24  adam        q4      target  5200
25  ben         q4      target  4300
26  cal         q4      target  7000
27  dan         q4      target  6500
28  adam        q4      actual  5100
29  ben         q4      actual  4300
30  cal         q4      actual  6900
31  dan         q4      actual  7200

And I am trying to pivot the data on the 'result' column using the 'value' column for the values. I need to retain the 'sales rep' and the 'quarter' columns. Essentially I am trying to get to (and I get by default on the unpivot operation in Power Query) is:
sales rep   quarter target  actual
adam        q1      3000    2900
adam        q2      4000    3400
adam        q3      4000    4500
adam        q4      5200    5100
ben         q1      3200    2100
ben         q2      3200    3900
ben         q3      4000    4000
ben         q4      4300    4300
cal         q1      2900    2100
cal         q2      7200    9000
cal         q3      7200    6500
cal         q4      7000    6900
dan         q1      3400    3500
dan         q2      5200    6000
dan         q3      6400    6500
dan         q4      6500    7200

Using the pivot_table method in Pandas I get:

Which is, obviously, a pivot table which makes it much harder to then do any further manipulations on the table. Is there any way to get there in Pandas?
Thanks!

A: DataFrame.pivot() is a specialized or second level function designed to mix .groupby() and .unstack() into one method. Pivot and reset_index will work fine in this example.
However, .groupby() is a more generalized method that offers the main benefit of being able to group by any Indexer other than a column :

*

*an series not in the DataFrame

*a level of the MultiIndex

*the df single-level Index containing duplicates

*a function applied to a column (e.g. df.col1 > 100 or np.sign(df.col1))

*any combination of the above

*basically any Indexer that has THE SAME LENGTH as the DataFrame being grouped

On top of that big advantage, groupby's ability to combine with apply and transform makes virtually every data analysis possible.
You might want to get familiar Pandas Groupby user guide


text:
Q: Making \includeonlylecture{} only ignore frames but not global structure elements such as sections I am presently preparing lecture notes in beamer. I have the lecture course structured into parts, sections etc and I would like use the numbering scheme consistently throughout the course. Without doing a lot of manual copy-and-paste stuff this implies for me that a single .tex file (maybe with includes here and there) for the entire course is the best solution. But of course this means that LaTeX always has to process a lot of stuff and I always get a PDF with the entire course, which is not really practical.
To solve this, beamer class has the \lecture command and the accompanying \includeonlylecture command. However, if I use this, my structure will be broken, because Latex will ignore all structural elements (parts, sections, etc.) outside of the current lecture, producing new numberings for each lecture. Andrew's answer to Entire course with beamer provides an even more rigorous approach to the \lecture mechanism, but it will also ignore everything.
Therefore my question: How can I make \includeonlylecture{} to only ignore \frame commands and frame environments?
Here is a try of a MWE:
\documentclass[11pt, t, xcolor=dvipsnames, utf8x]{beamer}
\includeonlylecture{day2}

\begin{document}
\lecture{27. April 2014}{day1}
\part{one}
  \frame{Ignore this....}
  \section{one-one}
\lecture{24. April 2014}{day2}
  \section{one-two}
  \frame{Use this frame and let it be in section one-two}
\part{two}
\end{document}

A: I found a solution myself. Basically it redefines beamer's \beamer@section etc. macros such that most of the stuff performed at the start of a section (or part or subsection) is done, even, when it's not in the current lecture.
Here's the code for sections (the other two are very similar):
\long\def\beamer@section[#1]#2{%
  \beamer@savemode%
  \mode<all>%
    \refstepcounter{section}%
    \beamer@ifempty{#2}%
    {\long\def\secname{#1}\long\def\lastsection{#1}}%
    {\global\advance\beamer@tocsectionnumber by 1\relax%
      \long\def\secname{#2}%
      \long\def\lastsection{#1}%
      \addtocontents{toc}{\protect\beamer@sectionintoc{\the\c@section}{#2}{\the\c@page}{\the\c@part}%
        {\the\beamer@tocsectionnumber}}}%
    {\let\\=\relax\xdef\sectionlink{{Navigation\the\c@page}{\noexpand\secname}}}%
    \beamer@tempcount=\c@page\advance\beamer@tempcount by -1%
    \beamer@ifempty{#1}{}{%
      \addtocontents{nav}{\protect\headcommand{\protect\sectionentry{\the\c@section}{#1}{\the\c@page}{\secname}{\the\c@part}}}%
      \addtocontents{nav}{\protect\headcommand{\protect\beamer@sectionpages{\the\beamer@sectionstartpage}{\the\beamer@tempcount}}}%
      \addtocontents{nav}{\protect\headcommand{\protect\beamer@subsectionpages{\the\beamer@subsectionstartpage}{\the\beamer@tempcount}}}%
    }%
    \beamer@sectionstartpage=\c@page%
    \beamer@subsectionstartpage=\c@page%
    \def\insertsection{\expandafter\hyperlink\sectionlink}%
    \def\insertsubsection{}%
    \def\insertsubsubsection{}%
    \def\insertsectionhead{\hyperlink{Navigation\the\c@page}{#1}}%
    \def\insertsubsectionhead{}%
    \def\insertsubsubsectionhead{}%
    \def\lastsubsection{}%
    \Hy@writebookmark{\the\c@section}{\secname}{Outline\the\c@part.\the\c@section}{2}{toc}%
    \hyper@anchorstart{Outline\the\c@part.\the\c@section}\hyper@anchorend%
  \ifbeamer@inlecture
    \beamer@ifempty{#2}{\beamer@atbeginsections}{\beamer@atbeginsection}%
  \fi%
  \beamer@resumemode}%

The only thing that is omitted when we are not in the current lecture is the execution of the \AtBeginSection-type macros.
The solution works well in the way that all parts, sections and subsections prior to the current lecture are added to the table-of-contents. So I can maintain a consistent section numbering scheme throughout the lecture. However, it seems a bit weird to me that all the global structure elements after the current lecture are not added. This is not really painful butI remember that it was once their, but now it is gone.


text:
Q: Add a button and a webbrowser in a scrollviewer I have a scrollviewer that contain a webbrowser, I need to add a button  <Button Grid.Row="1">
                            <Button.Background>
                                <ImageBrush ImageSource="../Images/cont_banner.png" />
                            </Button.Background>
                            <Button.Content>
                                <HyperlinkButton Content="" NavigateUri="callto:3950" />
                            </Button.Content>
                        </Button>
 also inside the scrollview but i can't.
This my code with the button outside the scroolviewer, how can i move it inside?

            <DataTemplate>

                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="100"/>
                    </Grid.RowDefinitions>

                    <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" Margin="25, 0, 0, 0" Grid.Row="0">
                        <!--<TextBlock Text="{Binding Path=Descrption}" Style="{StaticResource servicesText}" TextWrapping="Wrap" />-->

                        <phone:WebBrowser DataContext="{Binding Path=Descrption}" x:Name="webBrowserHTML" Foreground="Black" Loaded="webBrowserHTML_Loaded" />

                    </ScrollViewer>
                        <!--<Image Source="../Images/cont_banner.png" Width="270"  Grid.Row="1"/>-->

                    <Button Grid.Row="1">
                        <Button.Background>
                            <ImageBrush ImageSource="../Images/cont_banner.png" />
                        </Button.Background>
                        <Button.Content>
                            <HyperlinkButton Content="" NavigateUri="callto:3950" />
                        </Button.Content>
                    </Button>

                </Grid>

            </DataTemplate>
        </controls:Pivot.ItemTemplate>

A: You could do it like this:
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
              VerticalScrollBarVisibility="Auto"
              Margin="25, 0, 0, 0">
    <StackPanel>
        <phone:WebBrowser DataContext="{Binding Path=Descrption}"
                          x:Name="webBrowserHTML"
                          Height="400"
                          Foreground="Black"
                          Loaded="webBrowserHTML_Loaded" />

        <Button>
            <Button.Background>
                <ImageBrush ImageSource="../Images/cont_banner.png" />
            </Button.Background>
            <Button.Content>
                <HyperlinkButton Content="" NavigateUri="callto:3950" />
            </Button.Content>
        </Button>
    </StackPanel>
</ScrollViewer>

Note that you'll need to set the height of the web Browser control explicitly to something appropriate.
You probably also want to set that left margin to be 24 pixels (not 25) to be consistent with the rest of the platform.
Update
You MUST set the height of the WebBrowser for this to work.


text:
Q: Why would my Swagger.JSON related to a DTO not update based upon the definition in the API.XML file being update? I have an ASP.NET Core app and using Swashbuckle.ASP.NECore 5.5.1.
My DTO class is (I removed the XML Comments):
public class ArticleBankDTO : BaseDTO
{
    public int ID { get; set; }

    public List<ArticleTagDTO> ArticleTags;

    public List<ArticleDTO> Articles;

    public List<ArticleSourceDTO> Sources;

    private ArticleBankDTO() { }

    public ArticleBankDTO(int id, List<ArticleTagDTO> articleTags, List<ArticleDTO> articles, List<ArticleSourceDTO> sources)
    {
        if (id <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(id));
        }

        ID = id;
        ArticleTags = articleTags ?? throw new ArgumentNullException(nameof(articleTags));
        Articles = articles ?? throw new ArgumentNullException(nameof(articles));
        Sources = sources ?? throw new ArgumentNullException(nameof(sources));
    }

Inside the Get on my Controller I have:
            var result = await ControllerRepository.GetArticleBankAsync(articleBankdID);

            if (result == null)
            {
                return NotFound();
            }

            return Ok(Mapper.Map<ArticleBankDTO>(result));

I look at my API.XML file generated for the ArticleBankDTO and it is:

In the Swagger.JSON it is reflected as:

And my Swagger UI is:

I have cleaned the solution and rebuilt the solution and the changes do not make it through to the SWagger.JSON.  I am using Visual Studio 2019 Community Edition.
In my startup.cs I have in ConfigureServices:
        services.AddSwaggerGen(setupAction =>
        {
            setupAction.SwaggerDoc(
                $"JobAssistOpenAPISpecification",
                new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title = "ArticleBank API",
                    Version = "1",
                    Description = "Through this API you can access ArticleBank.",
                });

            var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);

            setupAction.IncludeXmlComments(xmlCommentsFullPath);
        });

A:   public async Task<List<ArticleBankDTO>> GetListAsync(EntityDto<int> input)
    {
        try
        {
            var result = await ControllerRepository.GetArticleBankAsync(articleBankdID);
            return new List<ArticleBankDTO>(result.MapTo<List<ArticleBankDTO>>());
        }
        catch (Exception ex)
        {
           // throw new UserFriendlyException(ex.Message.ToString());
        }
    }

A: I found out the issue.  You need {get; set;} for all properties.  Once I did:
public List<ArticleTagDTO> ArticleTags {get; set;}

public List<ArticleDTO> Articles {get; set;}

public List<ArticleSourceDTO> Sources {get; set;}

Everything worked.


text:
Q: Identify individual organization that visits my website - PHP There are a few services (at least here in Sweden) which let you identify a company that has visited a particular website. By checking an IP address, I know that you can get information such as the ISP and an organization, but the organization isn't necessairily the one that visited.
So my question is: How does this work?
(PS. I recently received a call from one of these companies after I visited their website, even though my IP here at the office isn't connected to my company in any way.)

A: Have a look at this:
DNSStuff - Whois
And aside from that you just need to use Curl to get the contents of the website and sort out the data you need.
Unless they provide an API.


text:
Q: Plugin architecture in Spring web application I'm designing Spring web application (I use Spring MVC) follow plugin architecture. Each plugin (plugin is a jar file) with its components (Controller, Service, POJO,..) will be contained in each ApplicationContext, whenever I disable that plugin (by closing its ApplicationContext) then user will receive an message say that "The feature or function is not available". When I refresh again plugin's ApplicationContext that plugin will be available again and user can access the feature of that plugin. Plugins don't depend with each other, it just depends on the Core module. But in Spring only child context can see the parent context not vice-versa. Because of this limitation of Spring I have some other ideas to implement it as below:
1/ I create an annotation @Plugin to mark on package of that plugin and using AOP to intercept user access. Whenever plugin is disabled then user cannot access that plugin's service/controller and an exception will raise to notify to user on web page.
2/ Not support disable plugin at runtime. Server needs to stop and we have to remove that jar file to uninstall that plugin from web application
3/ Create a channing ApplicationContext that will lookup beans or components in many ApplicationContext and using this one for DispatcherServlet.
Could anyone give me some advices about this? Which above idea should I use or none of them? I want to develop a web application that we can install/uninstall plugin at runtime without restart the server.
Thanks

A: maybe you should try to use spring osgi with gemini? http://www.eclipse.org/gemini/blueprint/documentation/reference/1.0.2.RELEASE/html/app-deploy.html


text:
Q: Merging multiple GeoJSON files into one file with layers What is the best way to merge several GeoJSON files of different types into a single GeoJSON but where each original GeoJSON is its own data layer within the final output?
Been playing with QGIS and can't figure out a way to get this result without combining all the data together into one layer (which when I have polygons and points I can not do).
Can most likely write a script to read in and convert all the JSONs and then write out to a single file, but just wondering if there is a better/built in way of doing this.