text:
Q: Launch shiny application on server I am trying to launch shiny application on server. I just followed instruction from Administering guide:
mkdir ~/ShinyApps
sudo cp -R /opt/shiny-server/samples/sample-apps/hello ~/ShinyApps/

Then tried to access the hello application through http://<server-address>:3838/<your_username>/hello But it shows this page can't be displayed error. Anyone has any idea about what can cause this problem? Thanks!
Cont.
Thanks Jeff, I used the exact same part in guide.
Here is the shiny-server.conf file:
server {
  listen 3838;

  # Define a location at the base URL

  location /users {
      #this is set up so that I can run apps sithout sudo
      run_as :HOME_USER:
      user_dirs;
  }
  location /apps {
    run_as shiny;
    # Host the directory of Shiny Apps stored in this directory
    site_dir /srv/shiny-server;

    # Log all Shiny output to files in this directory
    log_dir /var/log/shiny-server;

    # When a user visits the base URL rather than a particular application,
    # an index of the applications available in this directory will be shown.
    directory_index on;
  }
}

shiny-server.log shows lots of error:
[32m[2014-04-28 11:04:42.871] [INFO] shiny-server - [39mShiny Server v1.1.0.10000 (Node.js v0.10.21)
[32m[2014-04-28 11:04:42.875] [INFO] shiny-server - [39mUsing pidfile /var/run/shiny-server.pid
[32m[2014-04-28 11:04:42.877] [INFO] shiny-server - [39mUsing config file "/etc/shiny-server/shiny-server.conf"
[33m[2014-04-28 11:04:42.973] [WARN] shiny-server - [39mRunning as root unnecessarily is a security risk! You could be running more securely as non-root.
[31m[2014-04-28 11:04:42.217] [ERROR] shiny-server - [39mError loading config: location directive must contain (or inherit) one of site_dir, user_apps, app_dir, or redirect (/etc/shiny-server/shiny-server.conf:10:3)
[32m[2014-04-28 11:04:42.218] [INFO] shiny-server - [39mShutting down worker processes

How can I fix those those error?

A: I assume you got that command from this portion of the guide? If so, did you also use the deploy-example script to change your configuration file? Did you get any errors when you ran that script?
Alternatively, edit your question to include your configuration file at /etc/shiny-server/shiny-server.conf and we'll be able to see if your server is properly configured to use user_dirs which would be needed for users to be able to host their own applications.
Also check for (and/or edit your question to include) any recent entries in the server's log at /var/log/shiny-server.log.

A: Try the URL http://<server-address>:4949/sample-apps/.
If not 4949, try 3838.

A: The reason is whether the port 3838 is open. If it's not open, maybe you should run the following directives in your server:
iptables -I INPUT -p tcp --dport 3838 -j ACCEPT
iptables -I INPUT -p gre -j ACCEPT


text:
Q: Installing runtime for business network undefined. ...Error: Error trying install composer runtime I'm facing this problem to when I try to deploy my network
$ composer network deploy -a tutorial-network@0.0.1.bna  -A admin -S adminpw -c PeerAdmin@hlfv1 -f networkadmin.card
Deploying business network from archive: tutorial-network@0.0.1.bna
Business network definition:
        Identifier: tutorial-network
        Description: Blockchain network for practicing purposes.
Installing runtime for business network undefined. This may take a minute...
Error: Error trying install composer runtime. Error: The Composer runtime is already installed on all the peers
Command failed
I've these images running
peer0.org1.example.com
couchdb
ca.org1.example.com
orderer.example.com

Then if I do as in the Developer Tutorial
This is what I have.
$ composer network start --card PeerAdmin@hlfv1 --networkAdmin admin --networkAdminEnrollSecret adminpw --archiveFile tutorial-network@0.0.1.bna --file networkadmin.card
Starting business network from archive: tutorial-network@0.0.1.bna
Business network definition:
        Identifier: tutorial-network@0.0.1
        Description: Blockchain network for practiving purposes.
Processing these Network Admins:
        userName: admin
â Starting business network definition. This may take a minute...
Error: Error trying to instantiate composer runtime. Error: No valid responses from any peers.
Response from attempted peer comms was an error: Error: Error starting container: Get https://registry-1.docker.io/v2/: net/http: TLS handshake timeout
I don't know why is getting this error Error: Error starting container: Get https://registry-1.docker.io/v2/
I have all images running or I think they are.
Any idea? Pleasee I'm almost frustrated.

A: Solution was to use Bootstrap script from Hyperledger Fabric at github in my case bootstrap-1.0.4.sh fixed the problem, that is the version I'm running.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Short story from many years ago where the two main characters merge into one The only thing I remember is that the two main characters are lovers (perhaps one is an alien?) and they merge into one entity at the end of the tale.  "It" pours itself a cup of coffee at/near the end.  I read it in the 1960's/1970's, but it may have been written before then. Anyone know this piece?  Thanks.

A: The Compleat Consummators by Alan E Nourse.
It is about a dating agency who promise a perfect match.

"One hundred per cent compatibility on all levels, or your money is
refunded and the alliance annulled."

Something happens to the couple that are matched:

"Something's happening!"
"Something's happening!"
"HELP..."
There was silence then, with only the echos of a strangled scream.
   After It had jelled for a while, It got up from the sofa and went into
the kitchen to make a pot of coffee.


text:
Q: bootstrap checkbox button did not triggered in react I want to re-write https://v4-alpha.getbootstrap.com/components/buttons/#checkbox-and-radio-buttons in react. Kindly review https://codepen.io/gamesover/pen/MoExWo?editors=1111 . There are two issues

*

*Clicking checkbox1, handleChange is not triggered

*Given checkbox1 initial status is on, click the checkbox1, its status becomes off. However, the background color is still dark, you have to click somewhere else to make the button background color become light(off status)

A: Answer is in reference to your codepen example.
The background color is depending on the 'active' class. In case of changing the checked status the active class is not getting change I guess.
I have created a simple github repository with react setup. And is working as expected. Please check this once and let me know if this solves your issue.
Attaching a screenshot of console message that you wanted to print.
 Hope it helps.

A: I have tried your example locally with a react setup and the console prints the message of handleChange.However, in codepen its not getting printed probably a codepen issue. Have you tried this on a local react setup? If not please do check once probably a codepen issue.


text:
Q: kable_styling with full_width = T in a tint document I have the following tint PDF document:
---
title: "Title"
subtitle: "Subtitle"
author: "Author"
date: "`r Sys.Date()`"
output: tint::tintPdf
---

```{r echo = FALSE, message = FALSE}
# Load library
library(dplyr)

# Create data frame
df <- data.frame(A = runif(10),
                 B = runif(10),
                 C = runif(10),
                 D = runif(10),
                 E = runif(10),
                 F = runif(10),
                 G = runif(10),
                 H = runif(10))

# Print as a table
knitr::kable(df, booktabs = TRUE, format = "latex",
             caption = "This is a caption in the margin.")
```

This produces a PDF with the following table:

The table is wide and spills out over the caption. To avoid this, I can specify it's a full width table using full_width = TRUE in the kable_styling function of kableExtra.
---
title: "Title"
subtitle: "Subtitle"
author: "Author"
date: "`r Sys.Date()`"
output: tint::tintPdf
---

```{r echo = FALSE, message = FALSE}
# Load library
library(dplyr)

# Create data frame
df <- data.frame(A = runif(10),
                 B = runif(10),
                 C = runif(10),
                 D = runif(10),
                 E = runif(10),
                 F = runif(10),
                 G = runif(10),
                 H = runif(10))

# Print as a table
knitr::kable(df, booktabs = TRUE, format = "latex",
             caption = "This is a caption in the margin.") %>%
  kableExtra::kable_styling(full_width = TRUE)
```

This gives the following error:

! LaTeX Error: Environment tabu undefined.
Error: Failed to compile Test.tex. See Test.log for more info.
  Execution halted

It seems to be upset about the tabu package (or lack thereof). So, I add in this package in my YAML, like so:
---
title: "Title"
subtitle: "Subtitle"
author: "Author"
date: "`r Sys.Date()`"
output: tint::tintPdf
header-includes:
  - \usepackage{tabu}
---

This runs, but produces the following:

Now, the contents of the table overlaps. Humpf. Even if I include fig.fullwidth = TRUE in the chunk options I have no luck.
How do I produce a full width table in this situation?

A: Here's a workaround. By specifying longtable = TRUE in kable, the caption is bumped to the top. Also, in the YAML: tables: yes. Counterintuitively, using kable_styling with full_width = TRUE will squish the table into the full width of the main body and not the main body + margin.
---
title: "Title"
subtitle: "Subtitle"
author: "Author"
date: "`r Sys.Date()`"
output: tint::tintPdf
tables: yes
---

```{r echo = FALSE, message = FALSE}
# Load library
library(dplyr)

# Create data frame
df <- data.frame(A = runif(10),
                 B = runif(10),
                 C = runif(10),
                 D = runif(10),
                 E = runif(10),
                 F = runif(10),
                 G = runif(10),
                 H = runif(10))

# Print as a table
knitr::kable(df, booktabs = TRUE, format = "latex", longtable = TRUE,
             caption = "This is a caption in the margin.")
```


text:
Q: Json4s: Trouble while trying to convert Json attribute to java.sql.Date I am using Json4s to deserialize json messages. I have a case class like
case class A(id: Int, b: Option[java.sql.Date])

Whenever I try to convert a json message to case class A, I get none as the value of b
scala> read[A]("""{"id":1,"b":12345}""")
res2: A = A(1,None)

scala> read[A]("""{"id":1,"b":"12345"}""")
res3: A = A(1,None)

scala> read[A]("""{"id":1,"b":"12/12/2014"}""")
res4: A = A(1,None)

How can I fix this issue

A: Something along these lines (you might want to be more specific with formats). And then mix this trait in the classes which need to have access to this custom serializer.
import org.json4s.DefaultJsonFormats._

trait JsonFormats {

  case object DateSerializer extends CustomSerializer[java.sql.Date](format => (
    {
      case JString(s) => Date.valueOf(s)
      case JNull => null
    },
    {
      case d: Date => JString(d.toString())
    }
    )
  )

  implicit val json4sFormats =  native.Serialization.formats(NoTypeHints) + DateSerializer
}


text:
Q: Error: Could not find or load main class Running Hadoop I am using Hadoop 2.9.1 standalone (the folder I am using is after successful compilation of the source code) and whenever I run a Hadoop command such as
(where $HADOOP_HOME= /usr/local/hadoop, the directory of hadoop)
$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.9.1.jar grep input output 'dfs[a-z.]+'

I get this error :

Error: Could not find or load main class org.apache.hadoop.util.RunJar

At first, I was thinking that I am missing some environment variables but are they necessary for the standalone case? Why did I get this error? (I even replaced with another example, I believe it is not a jar problem)

A: The problem was with the compilation folder I got using maven command :
mvn clean package -Pdist -Psrc -DskipTests -Dtar

The right one is:
mvn clean install -Pdist -Dtar -DskipTests


text:
Q: Laravel 5.2, why does 'npm install' NOT install laravel-elixir? I have to manually run npm install laravel-elixir with every new project.
Laravel project created by running composer create-project laravel/laravel
package.json contains:
{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "laravel-elixir": "^5.0.0",
    "bootstrap-sass": "^3.0.0"
  }
}


text:
Q: cloud fire store android X incompatibility problem in flutter I'm using flutter version 1.22.6 to run my flutter app .. and have  some packages including
  cloud_firestore: 0.16.0+1

everything runs fine and flutter pub get completed successfully, but when I try to run the app I get this error :
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':firebase_auth:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 49s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin cloud_firestore...
Running Gradle task 'assembleAarRelease'...
Exception: The plugin cloud_firestore could not be built due to the issue above.

A: Found this question in StackOverflow having a similar issue which can help in resolving the issue you're facing.
Found another stackoverflow thread in which it is suggested to look into the following github issue and update the below line in the [Project Directory]/android/build.gradle as:
classpath 'com.android.tools.build:gradle:3.5.4'

And after that it's suggested to run the below commands in your project directory:
flutter clean && flutter pub get

Then as a final step build the project again.


text:
Q: Проверка на наличие записи MySQL & PHP Имеется php файл который выводит название городов. Нужно сделать так, что бы перед выводом информации шла проверка на наличие записи в БД. Т.Е. файл стучится в БД, проверяет, существует ли такая запись:
$mysqli->query("SELECT * FROM Key WHERE Name LIKE '%".$Name."%'");
Если запись есть, то вытянуть из БД "соответствующую информацию".
Если записи нет, то запустить один скрипт, с генерировать "соответствующую информацию" добавить в БД. И при следующей загрузке страницы после проверки на существование, она там была.

A: Для проверки существования данных по запросу предназначена функция EXISTS
SELECT EXISTS(SELECT * FROM Key WHERE Name LIKE ?)

Она специальным образом оптимизирована для таких случаев. Выполнение подзапроса останавливается, когда найдена первая совпадающая строка.
Примерно таким же(зависит от деталей реализации) эффектом обладает запрос
SELECT 1 FROM Key WHERE Name LIKE ? LIMIT 1

Однако, утверждение

Если запись есть, то вытянуть из БД "соответствующую информацию".

говорит о том, что данные, если они есть вы всё равно планируете получать полностью.
Поэтому, всё, что вам нужно - проверить mysqli_result::$num_rows

A: $result = $mysqli->query("SELECT * FROM Key WHERE Name LIKE '%".$Name."%'");
if ($result->num_rows > 0) {
//do Something
}


text:
Q: how b3dm and pnts files are generated I am checking 3d tiles branch. I could successfully build this branch on my local environment and now I am trying to analyze how custom tiles can be written.
I tried viewing b3dm and pnts files but my editor shows junk characters in this file.
How can these files be written for my requirement? Or what is the way these files can be generated? Can I write a program to generate this kind of file?

A: To create b3dm, you can use the software in the "tools" directory of the 3d-tiles-tools repository, which contains a converter to go from glb to b3dm and also i3dm.
You see "junk characters" in your text editor because this is a packed binary file format; your data is not stored in characters. b3dm is glTF with a header added, but glTF comes in two versions -- a binary and a text version and b3dm uses the binary version. The exact description of the 3d Tiles formats are given at https://github.com/AnalyticalGraphicsInc/3d-tiles -- click the links under "spec status." If you want to see the actual coordinate numbers in those files you can do it with a hex editor.


text:
Q: Subscript out of range error in VBScript script I'm trying to move my entire User folder in Windows Vista to a non-system partition. To do so with a minimum hassle I'm following the directions provided at Ben's Blog, specifically the VBScript he provides.
However executing the script throws up an error which I can't resolve myself. Here's the VBScript code followed by the text file it works from, and finally my error message. How do I correct the problem?
VBScript Code:
'# Perform dir /a c:\users > c:\dir.txt
'# place this script file in c:\ too
'# double click to run it
'# run resulting script.bat from recovery mode
repprefix = " Directory of..." ' Modify to your language
sourcedrive = "C:\"
targetdrive = "D:\"
altsourcedrive = "C:\" 'leave same as target drive unless otherwise indicated
alttargetdrive = "E:\" 'leave same as target drive unless otherwise indicated

inname = "dir.txt"
outname = "script.bat"
userroot = "Users"

set fso = CreateObject("Scripting.FileSystemObject")

' construct batch commands for saving rights, then link, the recreating rights
Function GetCommand(curroot, line, typ, keyword)
 ' first need to get source and target
 pos = Instr(line, keyword) + Len(keyword)

 tuple = Trim(Mid(line, pos))
 arr = Split(tuple, "[")

 oldtarget = Replace(arr(1), "]", "")
 oldlink = curroot & "\" & Trim(arr(0))

 ' need to determine if we are pointing back to old disk
 newlink = replace(oldlink, sourcedrive, targetdrive)
 if(Instr(oldtarget, sourcedrive & userroot)) then
     newtarget = Replace(oldtarget, sourcedrive, targetdrive)
 else
 newtarget = oldtarget ' still pointing to original target
 end if

 ' comment
 out = "echo " & newlink & " --- " & newtarget & vbCrLf
 ' save permissions
 out = out & "icacls """ & replace(oldlink, sourcedrive, altsourcedrive) & """ /L /save " & altsourcedrive & "permissions.txt" & vbCrLf

 ' create link
 newlink = replace(newlink, targetdrive, alttargetdrive)
 if typ = "junction" then
     out = out & "mklink /j """ & newlink & """ """ & newtarget & """" & vbCrLf
 else ' typ = "symlink"
     out = out & "mklink /d """ & newlink & """ """ & newtarget & """" & vbCrLf
 end if

 'set hidden attribute
 out = out & "attrib +h """ & newlink & """ /L" & vbCrLf

 ' apply permissions
 shortlink = Left(newlink, InstrRev(newlink, "\") - 1) 'icacls works strangely - non-orthogonal for restore
 out = out & "icacls """ & shortlink & """ /L /restore " & altsourcedrive & "permissions.txt" & vbCrLf

 GetCommand = out & vbCrLf
End Function

Sub WriteToFile(file, text)
 ForWriting = 2
 Create = true
 set outfile = fso.OpenTextFile(file, ForWriting, Create)
 Call outfile.Write(text)
 Call outfile.Close()
End Sub

outtext = "ROBOCOPY " & altsourcedrive & userroot & " " & alttargetdrive & userroot & " /E /COPYALL /XJ" & vbCrLf & vbCrLf

set intext = fso.OpenTextFile(inname)
while not intext.AtEndOfStream
 line = intext.ReadLine()
 if Instr(line, repprefix) then
     curroot = Replace(line, repprefix, "")
 elseif Instr(line, juncname) then
 outtext = outtext & GetCommand(curroot, line, "junction", juncname)
 elseif Instr(line, linkname) then
 outtext = outtext & GetCommand(curroot, line, "symlink", linkname)
 end if
Wend

outtext = outtext & "icacls " & altsourcedrive & userroot & " /L /save " & altsourcedrive & "permissions.txt" & vbCrLf
outtext = outtext & "ren " & altsourcedrive & userroot & " _" & userroot & vbCrLf
outtext = outtext & "mklink /j " & altsourcedrive & userroot & " " & targetdrive & userroot & vbCrLf
outtext = outtext & "icacls " & altsourcedrive & " /L /restore " & altsourcedrive & "permissions.txt"

Call intext.Close()

Call WriteToFile(outname, outtext)

MsgBox("Done writing to " & outname)

dir.txt:

Volume in drive C is ACER
Volume Serial Number is 08D7-C0CC

Directory of c:\users

07/16/2009 12:29 PM {DIR} .
07/16/2009 12:29 PM {DIR} ..
11/02/2006 09:02 AM {SYMLINKD} All Users [C:\ProgramData]
11/02/2006 09:02 AM {DIR} Default
11/02/2006 09:02 AM {JUNCTION} Default User [C:\Users\Default]
08/21/2008 08:37 AM 174 desktop.ini
11/02/2006 08:50 AM {DIR} Public
07/19/2009 08:54 PM {DIR} Steve
1 File(s) 174 bytes
7 Dir(s) 5,679,947,776 bytes free

Error Message:

Windows Script Host
Script: C:\user location.vbs
  Line: 25
  Char: 2
  Error: Subscript out of range: '[number: 1]'
  Code: 800A0009
  Source: Microsoft VBScript runtime error

(In the VBScript script that I'm using on my system, I believe that 'Line 25' corresponds to the line beginning with oldtarget = Replace(arr(1), "]", "").

A: Make sure that when you copy script from another page that line breaks are copied over as they should be. For example, in the script you printed above, it appears the the line that starts
pos = Instr(line, keyword) + Len(keyword)

is actually appended to the remark on the previous line (everything after the ' in that line). That could cause the problem you're having in that pos would never be set appropriately and so nothing would be copied into arr.
Just go line by line in the script you have on your computer and compare it to the version you copied from at Ben's Blog. Every line that is on it's own line MUST be on it's own line in your script file as well.
EDIT: As for what the error message means, it looks like oldTarget is trying to grab a string between two brackets. The error occurs because there's not enough text in the string to start at array position 1 (and this is zero-based, meaning that it's actually trying to get the second character in the string), i.e. it is at most a one-character string which is not possible considering that even a blank string 'element' would have two characters (the open bracket and the close bracket). So, you need to figure out why you're not getting a valid string at that point in the code to fix this problem.

A: First off, this is a very poorly written script.  I would recommend rewriting it properly.  It's kind of a hack job and that's where most of your problems are coming from.
Specifically, your problem occurs in the second line here:
arr = Split(tuple, "[")

oldtarget = Replace(arr(1), "]", "")

It means the that split in the line before did not return an array, meaning that the [ was not found in tuple and thus arr(1) is out of range.  Try checking that arr is an array before trying to access it.

A: Except for the Jab at a beginner, I agree with Nilpo. Your issue is the 'arr(1)' is failing because the script is expecting this the second position in the array and it isn't there, which 99% of the time is an 'out of bounds' error. It may not always be in your control but that is typically a reference to an array bounds issue. Array positions start with zero. Ex. Array(0, 1, 2, 3, ...). So (1) is the second position. He is also right, it could be a lot cleaner but you wouldn't know if just starting with VBScript.
I think this is what you are looking for and it is cleaner. This will pull out the path between the brackets []. You never want to assume both brackets are there, even if it is a generated file, so I have an If/Then check for both before executing, otherwise it will skip to the next line and the end.
I did run this and it worked in capturing between the brackets. You may need to tweak some since I'm not sure exactly what you may want to see in the output. :)
Option Explicit

Dim fso : set fso = CreateObject("Scripting.FileSystemObject")
Dim fileIn : set fileIn = fso.OpenTextFile("c:\users\MyFolder\desktop\input.txt")
Dim fileOut : set fileOut = fso.OpenTextFile("c:\users\MyFolder\desktop\output.txt", 2, true) ' for writing/create
Dim line
Dim arr

Do Until fileIn.AtEndOfStream
    line = fileIn.ReadLine
    if InStr(line, "[") > 0 And InStr(line, "]") > 0 then
        arr = Split(Split(line, "[")(1), "]")

        fileOut.WriteLine arr(0) & "\"
    end if
Loop

fileIn.Close
fileOut.Close

Set fso     = Nothing
Set fileIn  = Nothing
Set fileOut = Nothing
Set line    = Nothing
Set arr     = Nothing


text:
Q: The '=' character, hexadecimal value 0x3D, cannot be included in a name  xmlnode = xmldoc.CreateElement(dRow.ItemArray.GetValue(0).ToString());
 xmlroot.AppendChild(xmlnode);
 xmlnode.InnerText = sub;

A: You can use:
string name = XmlConvert.EncodeName(dRow.ItemArray.GetValue(0).ToString());

to get a safe encoded name, then
xmlnode = xmldoc.CreateElement(name);

however; as Jon notes, this is highly unusual - and an encoded name is not pretty; for example a=b becomes a_x003D_b.

A: Look at the value of dRow.ItemArray.GetValue(0).ToString(). It sounds like it isn't a valid element name, due to including an = sign.
It's relatively rare to create an element with a name given dynamically from data. It's more common to specify the content of an element that way.
What exactly are you trying to achieve? What's in your row?

A: When you try to export a Microsoft  catalog to XML, the resulting file cannot be imported, and you receive the following error message
"The XML file path/filename contains an error at line. " "A Name contained an invalid character."
If you validate the XML catalog by using Microsoft Visual Studio .NET  you receive the following error message:
"The '(' character, hexadecimal value 0x28, cannot begin a name. Line #, Position #"
This problem occurs because the Commerce Server export was not encoding the following special characters:
The range 0x0021 – 0x002F includes ! " # $ % & ' ( ) * + , - . /
The range 0x03A – 0x0040 includes : ; < = > ? @
The range 0x007B – 0x007E includes { | } ~
The range 0x005B – 0x005E [ \ ] ^**

A: The title is your answer. You can't use '=' in a name.


text:
Q: Powershell Script To Get Timestamps of Nested files We have a situation with with our SQL Server database backups.
Data:

*

*Actually our DBA has set backups of website databases to every 4 hours

*The backup of each website database is created every 4 hours and it contains 4 files (with .bak) extension.

*Folder hierarchy of these backup files are as follows:
\\folder\sub-folder\(4 X Files).bak

PROBLEM we have is that we have to check in each "sub-folder" if the 4 (four) .bak files are created after every four 4 hours manually.
Can somebody help with the creation of the powershell script which can :

*

*Generate the list of the web sites (subfolder name) in which 4 new files are not created for the latest timestamp.

*Email us the list

Thanks in advance.
Saeed


text:
Q: Excel VBA ADO SQL connection error - Could not find the object I got a brilliant answer to my previous question from @Ryan Wildry but I thought I'd ask a different question regarding the same code: here goes.
Background Info
I have a shared (network/server) Excel template file which is both the input file and the data source (although on different sheets). Let's call that Input.xltm.
The code basically picks up a input in a range on Input Sheet, takes the first two letters and finds the closest code from Code Sheet, then populates a UserForm ListBox with the top five results.
The problem
The problem comes when users set off the UserForm and the error usually returns:
Run-time error '-2147467259'
The Microsoft Access database engine could not find the object 'C:\Users\user.name\Documents\Input1'. Make sure the object exists and that you spell its name and the path name correctly.......etc
I think it may have something to do with the fact Excel puts a number after the filename because it's a template file although I don't actually know!
The code
And here's the code:
Public MyConnection As New ADODB.Connection
Public MyRecordset  As New ADODB.Recordset

Private Sub UserForm_Initialize()
Dim ColumnName As String: ColumnName = "[Variant code]"
Dim SearchStr  As String: SearchStr = Left(Sheets("Input Sheet").Range("B4").Value2, 2)
Dim dbstring As String

dbstring = ThisWorkbook.FullName

Application.ScreenUpdating = False

If MyConnection.State <> adStateOpen Then
    With MyConnection
        .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbstring & _
                            ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';"
        .Open
    End With
End If

If MyRecordset.State = adStateOpen Then MyRecordset.Close
MyRecordset.Open "Select top 5 " & ColumnName & " from [Code Sheet$] where " & ColumnName & _
                 " like '%" & SearchStr & "%'", MyConnection, adOpenForwardOnly, adLockReadOnly

Me.ListBox1.Clear
If Not MyRecordset.EOF Then MyRecordset.MoveFirst

Application.ScreenUpdating = True

Do Until MyRecordset.EOF
    Me.ListBox1.AddItem MyRecordset.Fields(0).Value
    MyRecordset.MoveNext
Loop

End Sub

I just need everyone who accesses the file through the server to be able to pick up the correct data source (which is only in the next sheet) and populate the ListBox.
I'd be thankful for any suggestions! Thanks
#UPDATE
I have checked, now if you open (and then save) the actual template file so there's no '1' after the file name, then the code works as expected. It's only when the template is opened normally and the number automatically appended that it stops working.

A: It seems that you do not make early-binding for MyConnection and MyRecordset first.
You can make a late-binding by
step 1.
Change
Public MyConnection As New ADODB.Connection
Public MyRecordset  As New ADODB.Recordset

to
Public MyConnection As object
Public MyRecordset  As object

.
step 2.
Add
Set MyConnection = createobject("adodb.connection")
Set MyRecordset = createobject("adodb.recordset")

before If MyConnection.State <> adStateOpen Then


text:
Q: How to create custom range slider widget in flutter? The slider has to take n number of thumb based on user input. Need to select the percentage range.
I have just started using Flutter. I've been able to follow some tutorials well enough. Any help is much appreciated!
class _SliderScreenState extends State<SliderScreen> {
  RangeValues values = RangeValues(1, 100);
  RangeLabels labels = RangeLabels('1', "100");
  double _currentSliderValue = 20;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter RangeSlider Demo'),
      ),

      body: SliderTheme(
        data: SliderThemeData(
          trackHeight: 10,
        ),
        child: RangeSlider(
            divisions: 5,
            activeColor: Colors.red[700],
            inactiveColor: Colors.red[300],
            min: 1,
            max: 100,
            values: values,
            labels: labels,
            onChanged: (value) {
              print("START: ${value.start}, End: ${value.end}");

              setState(() {
                values = value;
                labels = RangeLabels("${value.start.toInt().toString()}\$",
                    "${value.start.toInt().toString()}\$");
              });
            }),
      ),
    );
  }
}

A: One package I would recommend is to use the https://pub.dev/packages/syncfusion_flutter_sliders which comes with versatile customization options with a robust performance.
PS: Their API documentation is outstanding as well which makes it easier to use.

A: Here you go, modify like you want
class _SliderScreenState extends State<SliderScreen> {
  RangeValues values = RangeValues(1, 100);
  RangeLabels labels = RangeLabels('1', "100");
  int divisions = 5;
  List strLabels = [];

  @override
  void initState() {
    super.initState();

    strLabels = [for (var i = 0; i <= values.end; i += (values.end ~/ divisions)) i];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter RangeSlider Demo'),
      ),

      body: ListView(
         shrinkWrap: true,
         children: [
         Container(
                width: MediaQuery.of(context).size.width * .95,
                child: Column(
                  children: [
                    SliderTheme(
                      data: SliderThemeData(
                        trackHeight: 10,
                      ),
                      child: RangeSlider(
                        divisions: divisions,
                        activeColor: Colors.red[700],
                        inactiveColor: Colors.red[300],
                        min: 1,
                        max: 100,
                        values: values,
                        labels: labels,
                        onChanged: (value) {
                          print("START: ${value.start}, End: ${value.end}");

                          setState(() {
                            values = value;
                            labels = RangeLabels(
                                "${value.start.toInt().toString()}\$", "${value.start.toInt().toString()}\$");
                          });
                        },
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: MediaQuery.of(context).size.width * .05),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: strLabels.map((i) {
                          print(i);
                          return Text('$i%');
                        }).toList(),
                      ),
                    ),
                  ],
                ),
              ),
       ],
      ),
    );
  }
}


text:
Q: Is it a good practice to make most of the methods of a class return instance of the class? Is there any performance or design issues if we make all the methods of a class (methods that would normally return void) return the instance of the class (or a subclass)?
Edit: I wasn't thinking about the builder pattern, actually. I was just exploring fluent api design.

A: This is actually a good practice called the "Builder Pattern". Here is a JavaWorld article that discusses it.

A: I agree with cybersam it's a good practice (for the right circumstances), but I don't think this is the original Builder Pattern. I believe it's called the Fluent Interface. Builder patterns aren't required to return an instance of the class after every call.

A: This also goes by the name " Fluent API". See https://en.m.wikipedia.org/wiki/Fluent_interface


text:
Q: Android stop loader from reloading after back navigation In my newest android app I'm using Loaders to load data from the internet.
I have a RecyclerView and when I click on an item a new Activity is started. But every time I navigate back the Loader reloads the data and therefore updates the RecyclerView which leads to a jump to the top of the list.
How can I stop that behaviour?
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null) {
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        pagerAdapter = new PagerAdapter(getApplicationContext(), getSupportFragmentManager());
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}

ListFragment
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getLoaderManager().initLoader(0, null, this);
}

@Override
public Loader onCreateLoader(int id, Bundle args) {
    return new DataLoader(getActivity());
}

@Override
public void onLoadFinished(Loader<Object> loader, Object data) {
    adapter.data = data;
    adapter.notifyDataSetChanged();
}

Code to start new Activity
Intent intent = new Intent(view.getContext(), DetailActivity.class);
intent.putExtra(DetailFragment.ARG_DATA, data);
view.getContext().startActivity(intent);

Back navigation
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

EDIT: Added the RecyclerView Code
public class ListItemRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public List<Data> data;

    public ListItemRecyclerViewAdapter(List<Data> data) {
        data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ListItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
         ((ListItemViewHolder) holder).setData(data.get(position));
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}

A: Have the same problem ... seems like the Loader calls onLoadFinished in onResume. To fix just call destroyLoader in onLoadFinished.
More details here:
Why is onLoadFinished called again after fragment resumed?

A: override the deliverResult and cached the data of previous loader and store that now onStartLoading check if stored variable contains data or not if not forceload else use the cached data this way it will prevent the data to reload
im new to android btw


text:
Q: PubSub acknowledge deadline I have a cloud function which publishes a message to PubSub and that triggers a cloud run to perform an archive file process. When there are large files, my cloud run python code takes some time to process the data it looks like PubSub is retrying the message after 20 seconds (default acknowledge deadline time) which is triggering another instance from my Cloud Run. I've increased the acknowledge deadline to 600s and redeployed everything but it's still retrying the message after 20 seconds. I am missing anything?
Cloud Function publishing the message code:
# Publishes a message
   try:
      publish_future = publisher.publish(topic_path, data=message_bytes)
      publish_future.result()  # Verify the publish succeeded
      return 'Message published.'
   except Exception as e:
      print(e)
      return (e, 500)

Here is the PubSub subscription config:

Logging showing a second instance being triggered after 20s:

Cloud Run code:
@app.route("/", methods=["POST"])
def index():
    envelope = request.get_json()
    if not envelope:
        msg = "no Pub/Sub message received"
        print(f"error: {msg}")
        return f"Bad Request: {msg}", 400

    if not isinstance(envelope, dict) or "message" not in envelope:
        msg = "invalid Pub/Sub message format"
        print(f"error: {msg}")
        return f"Bad Request: {msg}", 400

    pubsub_message = envelope["message"]

    if isinstance(pubsub_message, dict) and "data" in pubsub_message:
        #Decode base64 event['data']
        event_data = base64.b64decode(pubsub_message['data']).decode('utf-8')
        message = json.loads(event_data)

        #logic to process data/archive
        return ("", 204)

A: You should be able to control the retries by setting the minimumBackoff retrypolicy. You can set the minimumBackoff time to the max of 600 seconds, like your ack deadline, so that redelivered messages will be more than 600 seconds old. This should lower the number of occurrences you see.
To handle duplicates, making your subscriber idempotent is recommended. You need to apply some kind of code check to see if the messageId was processed before.
You can find below in the documentation at-least-once-delivery :
Typically, Pub/Sub delivers each message once and in the order in which it was published. However, messages may sometimes be delivered out of order or more than once. In general, accommodating more-than-once delivery requires your subscriber to be idempotent when processing messages. You can achieve exactly once processing of Pub/Sub message streams using the Apache Beam programming model. The Apache Beam I/O connectors let you interact with Cloud Dataflow via controlled sources and sinks. You can use the Apache Beam PubSubIO connector (for Java and Python) to read from Cloud Pub/Sub. You can also achieve ordered processing with Cloud Dataflow by using the standard sorting APIs of the service. Alternatively, to achieve ordering, the publisher of the topic to which you subscribe can include a sequence token in the message.


text:
Q: Is it better to add two numbers to a new variable or adding them together while displaying? Which is better:
int sum = a + b;
std::cout << sum;

std::cout << a + b;

In terms of performance and efficiency?

A:
Is it better two add two numbers to a new variable

No, it's not better in general.

or adding them together while displaying?

No, it's not better in general.
Either is usually fine. The intermediate local variable has advantages such as ability to give an understandable name, and it reduces the complexity of individual expressions. But adding a variable increases the total number of names which is another form of complexity. It's a matter of finding a good balance, and the "bestness" is subjective.

In terms of performance and efficiency?

Not using a local variable is pretty much never more efficient than using a variable. But there is no difference in the shown example. Furthermore, there is no difference in most simple cases.
The difference - if any - is primarily in readability.
Consider another example where you use the result of the operation multiple times. In that case, it would be rare for a program that repeats an operation to be more efficient than another program that stores the result in a variable. But there's still no difference if the case is simple.


text:
Q: Unable to update hikari datasource configuration in spring boot app Hikari datasource configurations always taking as default values. even though i provide the actual configurations in application.yml file.
MainApp.java
@SpringBootApplication
public class MainApp {

public static void main(String[] args) {
    SpringApplication.run(MainApp.class, args);
}

@Bean
@Primary
public DataSourceProperties dataSourceProperties() {
    return new DataSourceProperties();
}

//I use below method to set password from different approach instead of taking from app.yml
@Bean
public DataSource dataSource(DataSourceProperties properties) {
    DataSource ds = properties.initializeDataSourceBuilder()
     .password("setting a password from vault")
     .build();
    return ds;
}
}

application.yml
spring:
  application:
    name: demo
  datasource:
    hikari:
      connection-timeout: 20000
      minimum-idle: 5
      maximum-pool-size: 12
      idle-timeout: 300000
      max-lifetime: 1200000
      auto-commit: true
    driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
    url: jdbc:sqlserver://ip:port;databaseName=sample
    username: username

Using Spring 2.1.1.RELEASE and when i start the application i logged the Hikari logs and it says all default values. So i did debugged on the second bean datasource and its actually HikariDatasource and except default values rest of them are empty and not reflecting the given values from the application.yml. Please recommend or comment if i misconfigured anything or done any mistake!


text:
Q: Create logon token using BI Platform RESTful SDK I'm attempting to create a logon token using the BOE BI Platform RESTful SDK v4.1 (using RESTClient).
A GET request to http://server:6405/biprws/logon/long/ returns:
<attrs xmlns="http://www.sap.com/rws/bip">
  <attr name="userName" type="string" />
  <attr name="password" type="string" />
  <attr name="auth" type="string" possibilities="secEnterprise,secLDAP,secWinAD,secSAPR3">secEnterprise</attr>
</attrs>

A POST to http://server:6405/biprws/logon/long/ with a single header of Content-Type: application/xml and a payload of
<attrs xmlns="http://www.sap.com/rws/bip">
  <attr name="userName" type="string">myAccount</attr>
  <attr name="password" type="string">myPassword</attr>
  <attr name="auth" type="string" possibilities="secEnterprise,secLDAP,secWinAD,secSAPR3">secWinAD</attr>
</attrs>

returns:
<error>
    <error_code>FWM 00006</error_code>
    <message>Active Directory Authentication failed to log you on. Please contact your system administrator to make sure you are a member of a valid mapped group and try again. If you are not a member of the default domain, enter your user name as UserName@DNS_DomainName, and then try again. (FWM 00006)</message>
</error>

I've also tried attr name="userName" type="string">myAccount@mycompany.org</attr>, but with the same results.
A POST to http://server:6405/biprws/logon/adsso returns:
<error>
  <error_code>RWS 00057</error_code>
  <message>Method not allowed (RWS 00057)</message>
</error>

The credentials work with BI Launchpad and the CMC.
What am I missing?

A: First, a disclaimer -- I've only done REST WinAD with SSO, not manual logon.  So I can't be absolutely sure that my suggestions below will fix your problem.
The call to /biprws/logon/adsso requires a GET not a POST, but that will likely not work until you have SSO working.
There are a few settings that are required for WACS to use WinAD, with or without SSO.  The file is here:
SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\java\pjs\services\RestWebService\biprws\WEB-INF\web.xml
You will see a section commented out, starting with:
<!--  Kerberos filter section starts

Uncomment this section.  Then set the following parameters:

*

*idm.realm

*idm.princ

*idm.keytab

*idm.kdc

*idm.allowUnsecured

The values for these parameters should equal what was set in your system for BI launch pad.  This is in:
SAP BusinessObjects\tomcat\webapps\BOE\WEB-INF\config\custom\global.properties

The format of the file is different (global.properties is a simple properties file, but web.xml is xml).  So you can't just copy/paste the section, but you can copy the individual values.  For example, in global.properties, you might see:
idm.keytab=C:/WINDOWS/bosso.keytab

This would be done in web.xml as:
<init-param>
  <param-name>idm.keytab</param-name>
  <param-value>C:/WINDOWS/bosso.keytab</param-value>
  <description>
      The file containing the keytab that Kerberos will use for
      user-to-service authentication. If unspecified, SSO will default
      to using an in-memory keytab with a password specified in the
      com.wedgetail.idm.sso.password environment variable.
  </description>
</init-param>

Couple of references:
http://myinsightbi.blogspot.com/
https://techwriter79.wikispaces.com/file/view/sbo41sp5_bip_rest_ws_en.pdf


text:
Q: Setting up CMake with gfortran in Windows to run CACTUS My ultimate goal is to run CACTUS. It requires CMake, so I have downloaded both. I think CMake needs a compiler, so I downloaded MinGW (or gfortran or GNU, I'm not really sure the distinction).
Using the MinGW Installation Manager, I've installed mingw32-base, mingw32-gcc-fortran, and also all the MinGW libraries because at one point I thought it would help. I have navigated through
control panel>system>advanced system settings>advanced>environment

variables and in user variables I have added the variables CMake and FC with the values C:\ProgramFiles\CMake\bin and C:\MinGW\bin, respectively.
I also edited the path in system variables to include both of those as well as C:\MinGW\mingw32\bin. I've also downloaded and installed Microsoft Visual Studio 2019 because I read somewhere that it was necessary for gfortran to work, though I have not done anything directly with it so far. At this point, I open Windows command prompt (this is all in Windows 10), navigate to the build folder that I have created in the top CACTUS folder and type
cmake ../

It returns this:
-- Could NOT find BLAS (missing: BLAS_LIBRARIES)
-- LAPACK requires BLAS
-- A library with LAPACK API not found. Please specify library location.
-- Could NOT find OpenMP_Fortran (missing: OpenMP_Fortran_FLAGS OpenMP_Fortran_LIB_NAMES)
CMake Warning (dev) at C:/Program Files/CMake/share/cmake-3.17/Modules/FindPackageHandleStandardArgs.cmake:272 (message):
    The package name passed to `find_package_handle_standard_args` (OpenMP)
    does not match the name of the calling package (OPENMP). This can lead to
    problems in calling code that expects `find_package` result variables
    (e.g., `_FOUND`) to follow a certain pattern.
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.17/Modules/FindOpenMP.cmake:579 (find_package_handle_standard_args)
  CMakeLists.txt:30 (find_package)

This warning is for project developers.  Use -Wno-dev to suppress it.

-- Could NOT find OpenMP (missing: OpenMP_Fortran_FOUND)
CMake Error at CMakeLists.txt:32 (message):
  OPENMP option was set to true (default), but no OpenMP was found. Install
  OpenMP, or try again with -DOPENMP=OFF.  Exiting.

-- Configuring incomplete, errors occurred!

Starting at the top of that error, I did some googling and found these instructions starting at "Build Instructions to create LAPACK and LAPACKE 3.5.0 dlls for Windows with MinGW". I followed those instructions for Win32. After running C:/MinGW/bin/mingw32-make.exe from command prompt, it gets to 36% and errs with the following message:
c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot find -lFALSE
collect2.exe: error: ld returned 1 exit status
SRC\CMakeFiles\lapack.dir\build.make:28574: recipe for target 'bin/liblapack.dll' failed
mingw32-make.exe[2]: *** [bin/liblapack.dll] Error 1
CMakeFiles\Makefile2:2077: recipe for target 'SRC/CMakeFiles/lapack.dir/all' failed
mingw32-make.exe[1]: *** [SRC/CMakeFiles/lapack.dir/all] Error 2
Makefile:181: recipe for target 'all' failed
mingw32-make.exe: *** [all] Error 2

I have also tried directions here and here and have either had no luck or, frankly, don't understand them. I am not a programmer. I have lived a life spoiled by GUIs and single install programs with everything included. I don't know what to try anymore. I don't really understand what's wrong or, honestly, why I've taken most of the steps I've taken except that someone in another help forum suggested them. I guarantee that I will have follow up questions to your answers, but please help.
EDIT
As requested below, here is the config file for lapack after cmake:
# Load the LAPACK package with which we were built.
set(LAPACK_DIR "C:/Users/x/Downloads/lapack/lapack-3.9.0/build")
find_package(LAPACK NO_MODULE)

# Load lapack targets from the build tree, including lapacke targets.
if(NOT TARGET lapacke)
  include("C:/Users/x/Downloads/lapack/lapack-3.9.0/build/lapack-targets.cmake")
endif()

# Hint for project building against lapack
set(LAPACKE_Fortran_COMPILER_ID ${LAPACK_Fortran_COMPILER_ID})

# Report lapacke header search locations from build tree.
set(LAPACKE_INCLUDE_DIRS "C:/Users/x/Downloads/lapack/lapack-3.9.0/build/include")

# Report lapacke libraries.
set(LAPACKE_LIBRARIES lapacke ${LAPACK_LIBRARIES})

And, yes, I did choose to build the LAPACKE Library in CMake.


text:
Q: How to re-render screen on click in React Native Navigation? I have a rectangle inside React Native Navigation screen that I want to animate every time user clicks on that specific screen. Now it only plays animation once, when application renders for the first time. I saw multiple solutions that worked for other people for this kind of a problem, but none of them worked for me - the application doesn't re-render on click. What am I doing wrong?
SettingsScreen.js (animation which needs to rerender on screen switch)
const { width } = Dimensions.get("screen");

const SettingsScreen = ({navigation}) => {
  const isFocused = useIsFocused();
  return (
    <FlatList
      contentContainerStyle={style.barContainer}
      data={[1, 2, 3, 4, 5]}
      keyExtractor={(_, index) => index.toString()}
      renderItem={() => (
        <ProgressBar isFocused={isFocused} navigation={navigation} />
      )}
    ></FlatList>
  );
};

const ProgressBar = ({ navigation, isFocused }) => {
  const barWidth = React.useRef(new Animated.Value(0)).current;

  console.log(barWidth);

  const finalWidth = width / 2;

  React.useEffect(() => {
    const listener = navigation.addListener("focus", () => {
      Animated.spring(barWidth, {
        toValue: finalWidth,
        bounciness: 10,
        speed: 2,
        useNativeDriver: false,
      }).start();
    });

    return listener;
  }, [navigation]);

  return (
    <View style={style.contentContainer}>
      <Animated.View style={[style.progressBar, { width: barWidth }]} />
    </View>
  );
};

MainContainer.js (where all the navigation is set up)
const profileName = "Profile";
const detailsName = "Details";
const settingsName = "Settings";
const profileNameFR = "P";
const detailsNameFR = "D";
const settingsNameFR = "S";

const Tab = createBottomTabNavigator();

export default function MainContainer() {
  const { locale } = useContext(LanguageContext);

  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;

            let rn = route.name;

            if (rn === profileName || rn === profileNameFR) {
              iconName = focused ? "person" : "person-outline";
            } else if (rn === detailsName || rn === detailsNameFR) {
              iconName = focused ? "list" : "list-outline";
            } else if (rn === settingsName || settingsNameFR) {
              iconName = focused ? "settings" : "settings-outline";
            }

            return <Ionicons name={iconName} size={size} color={color} />;
          },
          tabBarActiveTintColor: "tomato",
          inactiveTintColor: "grey",
          tabBarStyle: { padding: 10, height: 60 },
          tabBarLabelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10 },
        })}
      >

A: This is happening because FlatList is a PureComponent, meaning that it will not re-render if props remain the same. So in this case try to use useIsFocused hook inside the SettingsScreen component and pass it to ProgressBar as a prop.
Inside SettingsScreen:
const isFocused = useIsFocused();

...

<FlatList
 ...
 renderItem={() => <ProgressBar isFocused={isFocused} />}

Also it's not recommended to use useIsFocused hook because this will unnecessary re-render your component many times. Instead you can use an event listener to listen to 'focus' event, like this:
React.useEffect(() => {
 const listener = navigation.addListener('focus', () => {
    Animated.spring(barWidth, {
      toValue: finalWidth,
      bounciness: 10,
      speed: 2,
      useNativeDriver: false,
    }).start();
 });

 return listener;
}, [navigation])


text:
Q: How can I constrain search result? I'm trying to constrain the result by genre_id which is the column in Communities table.
But the end of the line in communities_controller says error.
Why? How can I fix this?
communities_controller.rb
        @search = Community.search do
            fulltext params[:search]
            paginate :page => params[:page], :per_page => 5
        end

        @communities = @search.results

        @communities = @communities.find_by_genre_id(params[:genre])

A: You should watch this video: http://railscasts.com/episodes/278-search-with-sunspot
It will help you.
Here is the sample code he uses:
Model: article.rb
searchable do
  text :name, :boost => 5
  text :content, :publish_month
  text :comments do
    comments.map(&:content)
  end
  time :published_at
  string :publish_month
end

def publish_month
  published_at.strftime("%B %Y")
end

Search algorithm:
@search = Article.search do
    fulltext params[:search]
    with(:published_at).less_than(Time.zone.now)
    facet(:publish_month)
    with(:publish_month, params[:month]) if params[:month].present?
  end
  @articles = @search.results

I am not familiar with sunspot, but it looks like your error (unrecognized field) might be resolved by including :genre_id in your model, like this:
searchable do
  integer :genre_id
  ...
end

So your new search would look something like:
@search = Community.search do
  fulltext params[:search]
  with(:genre_id, params[:genre_id])
  paginate :page => params[:page], :per_page => 5
 end


text:
Q: Calling an overridden method from base constructor We have a class like this:
class LogAnalyzer
    {
        protected IExtensionManager manager;

        public  LogAnalyzer()
        {
            GetManager();
        }

        protected virtual void GetManager()
        {
            manager = new FileExtensionManager();
        }
    }

And we derive another class like this:
class TestableLogAnalyzer:LogAnalyzer
    {
        protected override void GetManager()
        {
            this.manager = new StubExtensionManager();
        }
    }

When we instantiate the child class what's supposed to happen in OOP rules? Does the virtual or the overridden method gets called and why? I tested it in C# and overridden method worked but I suspect it may be the other way around in an interpreted language. Is that true?

A: It's not simple to provide a language agnostic answer to this, because "what happens" depends on the language itself. In Java, for instance, the overridden (virtual) method will be called, but this can present its own problems, and is thus not recommended.
You need to consult the documentation or language specification you're interested in, and then read around to see if anyone's published an opinion on why you should or shouldn't do it, and what might go wrong, such as the Scott Meyers piece that AraK links to in his/her comment.

A: Since it's language agnostic, I'll use C++ as a base and will hope that the advice can be extrapolated.
Constructor of LogAnalyser is called before constructor of TestableAnalyser. This means that during its work TestableAnalyser is not constructed yet, thus calling virtual methods can be dangerous (they may use uninitialized data).
In your case derived class wants to affect initialization of its base class. Virtual methods overriding is not the only way to do this. You can create one more constructor which accepts manager, derived classes will pass "new StubExtensionManager();".


text:
Q: can't download android sdk on fresh installation of android studio bumblebee 2021.1.1 Patch 2 I can not download new sdk! My latest sdk is Android version 11!

This is a problem. I tried every proxy and VPN but still could not download the new sdk. Where is the problem?

A:
Open your SDK update sites and see if you're missing any.Then add as needed


text:
Q: Remove all html tags from string by list, except the first one I have string of html tags and a list of forbidden tags:
Any tag that is found in forbiddenTags should be removed from str, except the first one.
Maybe it can be done by one loop of the string
I tried the next thing:
var forbiddenTags = ["div", "city"];

var str = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<ADDUMP>' +
            '    ' +
            '

' +
            '
Help Wanted Line
' +
            '    ' +
            '    <ADINFO>' +
            '        <CUSTOMER>' +
            '            <CITY></CITY>' +
            '

' +
            '            <STATE></STATE>' +
            '       </CUSTOMER>' +
            '   </ADINFO>' +
            '</ADDUMP>' +
            '</xml>';

var arrayLength = forbiddenTags.length;

for (var i = 0; i < arrayLength; i++) {
    // remove all forbiddenTags (upper and lower case)
    var re = new RegExp("</? *" + forbiddenTags[i] + "[^>]*>","gi");
    str = str.replace(re, "");
}

console.log(str);

Unfortunately, there are two problems:
1) It removes also the first tag of the string that is found in forbiddenTags.
2) It doesn't remove the content of the tags.
example:

hi

how

should be:

hi

This is my jsfiddle:
http://jsfiddle.net/Ht6Ym/3469/
Any help appreciated!

A: Use str.match to get all matches and discard all except for the first one.

A: To match the content of the tag as well as the tag itself, you need to change your regex to look for both the opening and closing tag at the same time. Currently, it only checks for one or the other, which is why the tag content is being left.
This regex looks for an opening tag (and any associated attributes) the matching closing tag, and any intervening text:
new RegExp("<(" + forbiddenTags[i] + ")[^>]*>(.*?)</\\1>", "gi")

Your other issue (not wanting to remove the first match) can be solved by passing an anonymous function as a parameter to str.replace. In that function, make use of a counter variable to determine when to remove a match.
To do that, you'll need to add a counter variable somewhere. If you want to leave the first match of each type of forbidden tag, put it inside your for loop. If you only want to keep the first forbidden tag found overall, initialize it outside your for loop (it's unclear which you want from your question). Then replace str = str.replace(re, ""); with this:
str = str.replace(re, function(matchedText){
    if (++counter>1){
        return "";
    } else {
        return matchedText;
    }
});

This function runs against every match. If it's the first match, it simply returns that match (in effect, leaving it alone). Otherwise, it removes it.
Now, all together this makes your loop look like this:
for (var i = 0; i < forbiddenTags.length; i++) {
    var counter=0
    var re = new RegExp("<(" + forbiddenTags[i] + ")[^>]*>(.*?)</\\1>", "gi");
    str = str.replace(re, function(matchedText){
        if (++counter>1){
            return "";
        } else {
            return matchedText;
        }
    });
}

If using jQuery is an option, you can make things look a bit cleaner (namely, removing that obnoxious regex) using the function found in this answer:
var removeElements = function(text, selector) {
    var wrapped = $("
" + text + "
");
    wrapped.find(selector+":not(:first)").remove();
    return wrapped.html();
}

for (var i = 0; i < forbiddenTags.length; i++) {
    str = removeElements(str, forbiddenTags[i]);
}

A: It seems like the answer by Rob W on this post is what you are looking for.
All you need to change is the first = true to first = {} and check
if (!first[tag]) {
    first[tag] = true;
} else {
    return '';
}


text:
Q: Using WITH(NOLOCK) Together with FREETEXTTABLE I'm confused about how to use WITH (NOLOCK) along with full-text search.
From SQL Server NOLOCK and joins I got an important information that we should use WITH (NOLOCK) in each table in a SQL join. However, it doesn't work with this query:
SELECT *
FROM myTable AS FT_TBL WITH (NOLOCK)
FULL OUTER JOIN
    FREETEXTTABLE (myTable, fieldName,  'SRI') AS KEY_TBL WITH (NOLOCK)
ON FT_TBL.id = KEY_TBL.[KEY]

The error message is:

Msg 156, Level 15, State 1, Line 7
  Incorrect syntax near the keyword 'WITH'.
  Msg 319, Level 15, State 1, Line 7
  Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.'

The problem is in the 'AS KEY_TBL WITH (NOLOCK)', because it works without the 'WITH (NOLOCK)' on it. What should I do? I want that every similar record appears in the search result although somebody else updating those records. Please help and thanks in advance.

A: FREETEXTTABLE doesn't support table hints. If you want uncommitted reads throughout (which is what NOLOCK achieves for a single table), set the transaction isolation level before, either in T-SQL:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SELECT *
FROM myTable AS FT_TBL
FULL OUTER JOIN
    FREETEXTTABLE (myTable, fieldName,  'SRI') AS KEY_TBL
ON FT_TBL.id = KEY_TBL.[KEY]

Or in your client code using IsolationLevel.ReadUncommitted.
But you should be fully aware of the consequences of this: READ UNCOMMITTED will indeed issue fewer locks, but it can give back inconsistent results. If all you're after is reads that don't block, a worthwhile alternative to explore is snapshot isolation and the READ_COMMITTED_SNAPSHOT database option. The problems with NOLOCK as well as the alternatives are eloquently summed up in this article.


text:
Q: Storing Game Player Progress ID's in database - Comma-delimited data in MySQL vs Normalized MySQL Records (regarding server performance) I'm developing an online game which will save the player's progress to a MySQL database, and i'm trying to optimize for performance.  This data would be in the form of an ID which corresponds to a specific progress achievement.  These 'achievements' would consist of speaking to NPCs, initiating quests, completing quests etc, so the IDs would be added to the database in no specific order.  I am currently having trouble deciding on how to store the achievement data, out of these scenarios:
1) as a comma-delimited text field (for example 32,2,53,1,3,5) on the "Player" table.
Each time an achievement is triggered, the corresponding ID would be added to the end of the text field.  The PHP side would perform checks using strpos.
2) stored as records inside a Player_Progress table.  This could potentially mean a huge number (~100) of records per player, and I have no idea how this might affect performance.
I understand that delimited fields are frowned upon, but seeing as the data is only checked a few times, and only ever added to (not deleted), I was wondering if Normalization would be a little overkill in this situation?

A: If you were going to always read everything into a game client, persist state there (perhaps in a dictionary or hashtable), then just use the database as a flat persistence/serialization store, I could argue it doesn't matter. However this line caught me:

The PHP side would perform checks using strpos.

This sounds like you want to query on individual achievements, and using the database would most certainly be recommended here for two reasons:

*

*You do not want to read the entire string and deserialize it every time you make a request to the server. State is not persisted between requests without some effort. I read the above statement to mean this game is not run with a local client, but in a browser constantly making requests to the server.

*You can leverage the power of the database.

With a normalized database, you can simply check for a given player's achievement by the query:
SELECT 1
FROM achievements
WHERE playerId = @playerId
AND achievementId = @achievementId

And with the right indexes in place, this should be lightning-fast.
If you just had a string you'd have to first retrieve the serialized blob from the database, then either parse it into a useable data structure, or go through each character one-by-one to find the data you are looking for. This seems like a lot more overhead.
As an extra note 100 rows per player, even if you had 1,000,000 players, is not really "a lot" of rows.


text:
Q: Extending or adding action to a function Is it possible to extend a php function ?
if no how does WordPress add_action() works ?
can you guys suggest me add_action like function for non wordpress system ?
Thanks for help

A: I got what I was looking for,
https://github.com/bainternet/PHP-Hooks
This class works great, thanks to Bainternet


text:
Q: birt reports resources I have a folder containing lots of birt reports.
I have to open one report, modify it in an rcp application.
I want to copy from the original workspace all the resources related to the report i am working on.
All the resources , for all the reports and in a big folder ..how can i find out witch ones my report depends on, so i can copy them.
After i make the changes, i will deploy on jboss, the modified report, so that is why i need all the  reports resources, so my reports show all in jboss.
Is it the way to do it ? Is there a simpler way ?
Thanks

A:
Is it the way to do it ?

Depending on what kind of relation is between report design and resources, you could try to find them in rptdesign xml source.
For example I have a report with some images - their locations are referenced by <expression name="uri" type="constant">my_image.png</expression> tags, so i probably will find them manually using expression like <expression name="uri". I would try also simple .png, .jpg patterns to find them, if I knew what kind of files they are.
Next, libraries are listed in Outline view. They are also searchable in rptdesign xml.
Next, some resouces are defined as report properties: Property Editor -> Resources -> Properties files, Jar files, Javascript files. Also listed in rptdesign xml.

Is there a simpler way ?

I'm afraid, it isn't. If it is repetitive work, some script or xsl transformation on xml would do the job.
And be carefull with libraries - they can have their own dependencies.


text:
Q: How do I configure this database.json file so that my app's api connects to a database I'm banging my head against a wall right now trying to get this app I cloned up and running. Here is the database.json file I'm working with:
{
  "development": {
    "username": "root",
    "password": null,
    "database": "crate",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "seederStorage": "sequelize"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "crate",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "seederStorage": "sequelize"
  }
}

here's the config.json file
{
  "url": {
    "api": "http://my-ip-address:8000"
  },
  "message": {
    "error": {
      "timers": {
        "short": 1000,
        "default": 2000,
        "long": 4000
      }
    }
  },
  "product": {
    "types": {
      "cloth": {
        "id": 1,
        "name": "Cloth"
      },
      "accessory": {
        "id": 2,
        "name": "Accessories"
      }
    }
  },
  "user": {
    "gender": {
      "male": {
        "id": 1,
        "name": "Male"
      },
      "female": {
        "id": 2,
        "name": "Female"
      }
    }
  }
}

The problem is that when I run npm run setup:api, like the readme says to do, it crashes when it starts running the Sequelize CLI
Sequelize CLI [Node: 12.18.3, CLI: 5.5.1, ORM: 5.21.6]

Loaded configuration file "src\config\database.json".
Using environment "development".

ERROR: connect ECONNREFUSED 127.0.0.1:3306

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! api@1.0.0 db:migrate: `sequelize db:migrate`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the api@1.0.0 db:migrate script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\usr\AppData\Roaming\npm-cache\_logs\2020-08-08T00_45_25_767Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! api@1.0.0 setup:db: `npm run db:migrate && npm run db:seed`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the api@1.0.0 setup:db script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\usr\AppData\Roaming\npm-cache\_logs\2020-08-08T00_45_25_808Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! api@1.0.0 setup: `npm run setup:install && npm run setup:db`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the api@1.0.0 setup script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\usr\AppData\Roaming\npm-cache\_logs\2020-08-08T00_45_25_857Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! crate@1.0.0 setup:api: `npm run setup --prefix api`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the crate@1.0.0 setup:api script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I'm running Windows 10, Node v12.18.3, through Visual Studio v1.47.3
If anyone can help I'd be extremely grateful!

A: You'll have to setup a mysql database on your device. There are multiple applications you can use for this. Personally I use the database that comes with XAMPP. After you setup XAMPP or any other database application, you'll have to create a database named crate.


text:
Q: How can we force google maps to match the city component We are using the google Maps API to search to geocode an address.
The problem is that there is no way to break the API request address field to its components.
{
  address: string,
  location: LatLng,
  placeId: string,
  bounds: LatLngBounds,
  componentRestrictions: GeocoderComponentRestrictions,
  region: string
}

Since we can't break it to
{
  city: city
  street: street
  ...
}

we are getting strange results like e.g. "XX MyStreet st., MyCity"
Returns result where MyCity is the county and the city is a complete different city.
Is there a way to mark Google Maps that "MyCity" is a city and not a county.

A: I've had a look at your sample address 'Lilach 27, Beer Sheva, Israel'. Let's check it in Geocoder tool:
https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3DLilach%252027%252C%2520Beer%2520Sheva%252C%2520Israel
As you can see this address is clearly located inside the locality Omer. So address component locality = Omer seems to be correct here.
http://maps.google.com/maps?cid=0x1502676f35a89239:0xd3092fa77576ecf6

Referring to administrative_area_level_2 = Be'er Sheva, please note that Google has admin area with this name and you can see it here
http://maps.google.com/maps?cid=0x1501934b23af369b:0x31b08b946bdd4342

So, at this point it looks like the response is correct.
If you believe that administrative area should have another name or address should be located at different place, please send feedback to Google. Also, note that the result type in geocoder is RANGE_INTERPOLATED and place ID is EiHXnNeZ15zXmiAyNywg16LXldee16gsINeZ16nXqNeQ15w. Typically these place IDs that start with E mean that address doesn't exist in database and was interpolated. You can report missing place to Google following the Help center:
https://support.google.com/maps/answer/6320846
I hope my answer clarifies your doubts!


text:
Q: Cannot instantiate subclass due to compile-time exception I'm new to java and am running into the error

An enclosing instance that contains ... is required

when creating a new object from a subclass defined in the same source file as its parent, but not when the subclass has its own source file, and I'd like to understand why.
The main file:
package tessty
public class Tessty {
    public static void main(String[] args) {
        Person me = new Person();
        me.addtoitems();
    }
}

Another source file for the "Person" class:
package tessty;
import tessty.Item.*; // I included this import as per NetBeans' suggestions

public class Person {

    Item[] items;

    public Person() {
        items = new Item[3];
    }

    public void addtoitems() {
        items[0] = new Apple(); // Compile error thrown here
        items[1] = new Shoe(); // and here
        items[2] = new Hat(); // but not here
    }
}

The "Item" class source file with two sub-classes defined in the same file:
package tessty;

public class Item {

    int weight;

    public class Apple extends Item {
        public Apple() {
            weight = 2;
        }
    }

    public class Shoe extends Item {
        public Shoe() {
            weight = 3;
        }
    }

}

And finally, another child of Item, but defined in its own source file:
package tessty;

public class Hat extends Item {

    public Hat() {
        weight = 1;
    }

}

I'd really like to be able to define sub-classes in the same file as the parent class for organizational purposes (the application I'm working on will have many "small" sub-classes). Could someone please explain why I'm getting this error only for the sub-classes that are in the same source file as their parents? Is it related to the fact I have to use an import for the sub-classes in the same file as their parent and not for the sub-class with its own file?

A: First, your Testty class doesn't compile. You've missed a ; after the package statement:
package tessty;

Then, you can define super and subclass in one source file, but one of them has to be public and you need the package statement just once (because it's shared for both of the classes). For example:
package something;

public class SuperClass {

}

class SubClass extends SuperClass {

}

The source-file they will be stored, will have to be named SuperClass.java.
Alternatively, you can make the sub-class(es) nested and static, as answered by @AndyBrown.

A: You need to make your subclasses static member classes for this to work. As it is they are inner classes, but there is no point in using those in your case. You could also make Item abstract as you don't intend to create any instance of it.
If you were to create non-nested classes in a single file, only one can be public (as per the JLS 7 at the bottom of section 7.6). Therefore if you want multiple public non-nested subclasses, they must all be in separate files.
package tessty;

public abstract class Item {

    int weight;

    public static class Apple extends Item {
        public Apple() {
            weight = 2;
        }
    }

    public static class Shoe extends Item {
        public Shoe() {
            weight = 3;
        }
    }

}

In summary, classes are:

*

*top level if they are not enclosed in any other class

*nested if they are enclosed in another class (nested can mean static or not, and declared as a member, local or anonymous class)

Within the nested set they are:

*

*member if they are declared immediately within the class definition block

*local if they are declared inside a method

*anonymous if they are declared with an instance creation expression

And nested classes are either:

*

*static member if they are static (therefore they must only be member)

*inner if they are not static (these can be member, local or anonymous)

Inner classes receive an implicit reference to the instance of the parent that created it. Static member classes have no implicit knowledge of any parent instance.


text:
Q: Dapper.net decimal Output parameters not returning the Precision value I am Using Dapper for some time now and its a great ORM mapper. but recently i found an issue with decimals being passed as an Output parameter for the Stored procedures would cut off the precision and only returns the whole number.
var dynamicParam = new DynmaicParam();

dynamicParam.Add("decimalOut",11.25,dbtype.decimal,ParameterDirection.OutPut);
connection.execute("sp1",dynamicParam,commandType.StoredProcedures);
decimal val = dynamicParam.Get<decimal>("decimalOut");

in this case val will be 11 its not returning 11.25 as it is meant to when the procedure just returns the exact out put parameter as it was passed.
we have used a work around as following where it returns the precision as well,
var dynamicParam = new DynmaicParam();
dynamicParam.Add("decimalOut",11.25,dbtype.double,ParameterDirection.OutPut);
connection.execute("sp1",dynamicParam,commandType.StoredProcedures);
decimal val = dynamicParam.Get<dynamic>("decimalOut");

but i still think there must be a better way to handle these decimal precision problem in dapper given the fact it's an amazing ORM mapper where it supports in many data types. appreciate a better work around and thanks in Advance

A: You need to use precision and scale.
Example:
dynamicParam.Add("decimalOut",11.25,dbtype.decimal,ParameterDirection.OutPut, precision: 18, scale: 2);


text:
Q: wso2 esb file processing example smooks csv parser first line includes payload namespace Dabbling with WSO2 ESB example http://wso2.org/library/articles/2011/01/wso2-esb-example-file-processing but encountering a problem where when a simple csv file
name0,value0
name1,value1
name2,value2
name3,value3

is parsed by smooks using this configuration
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:csv="http://www.milyn.org/xsd/smooks/csv-1.1.xsd">
<csv:reader fields="name,value" />
</smooks-resource-list>

results in largely the correct output but the first line includes the payload namespace which is incorrect
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
    <text xmlns="http://ws.apache.org/commons/ns/payload">name0,value0
name1,value1
name2,value2
name3,value3</text>
</soapenv:Body>
</soapenv:Envelope>

so when the first name0 value is read it includes the  which is also incorrect.
Smooks then converts this into
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
    <csv-set>
        <csv-record number="1">
            <name><?xml version='1.0' encoding='utf-8'?><text xmlns="http://ws.apache.org/commons/ns/payload">name0</name>
            <value>value0</value>
        </csv-record>
        <csv-record number="2">
            <name>name1</name>
            <value>value1</value>
        </csv-record>
        <csv-record number="3">
            <name>name2</name>
            <value>value2</value>
        </csv-record>
        <csv-record number="4">
            <name>name3</name>
            <value>value3</text></value>
        </csv-record>
    </csv-set>
</soapenv:Body>
</soapenv:Envelope>

So is Smooks doing all it is asked as the input includes the the  as last? However, the number of elements it understands are counted as 4 so it isn't as if the csv is supposed to have a header row. I can resolve (to a certain extent) by including a header row but then the element count is incorrect. I can resolve the end closing  by just including a carriage return on the last line of csv.
How can I resolve this? I have found one other thread a year ago asking the same question but no answers.

A: I have sorted this now. In my smooks tag
<smooks xmlns="http://ws.apache.org/ns/synapse" config-key="conf:/smooks-config.xml">
   <input type="text"/>
   <output type="xml"/>
</smooks>

I had the first input element set to xml. Changing to text solved the issue. (in the GUI editor in WSO2 it defaults to having these elements whereas the tutorial doesn't have these at all).


text:
Q: Vectorising numpys roll I'm doing some sampling from an array at the moment, and I'm using a boolean mask to count the number of values that lay within a certain radius from a given centroid. I was wondering if someone could show me how to vectorise my approach instead of using a python loop to loop over elements of a list.
I have a 1d numpy array called centres, where each element of centres is a centroid given as a 1d numpy array. I have also created a boolean mask which is centered in the middle of the array ('centre_Y', 'centre_X' in the code below), which I am rolling from the middle of the array to the centroid position. I am then making the mask be sparse because my actual array that I am sampling from ('item' in the code below) is sparse. I then count the number of nonzero elements under the mask. Below is my code
for item in data:

    ### Do stuff

    for radius in radii:

        ### Do stuff

        # roll mask to centroid and count the number of elements within radius
        for centroid in centres:

            # roll in the vertical direction to centroid y coordinate
            mask_roll_y = np.roll(mask,centroid[0]-centre_Y,axis=0)

            # roll in the horizontal direction to centroid x coordinate and make sparse
            roll_mask = sparse.csr_matrix(np.roll(mask_roll_y,centroid[1]-centre_X,axis=1))

            # apply sparse mask to sparse data and count number of nonzero elements below
            number_count.append(np.count_nonzero(item[roll_mask]))

Now, the code above works perfectly fine and gives the results I want. My issue is, after doing some timings, the 'for centroid in centres' loop takes about .4 seconds to compute (for one array in data while using 50 radii and taking 100 samples for each radii), which is far and away the most time consuming part of my code. I need to do this for about 100 data sets with roughly 1000 arrays in each data set and I would like to take far more radii and samples than I did previously. So, I was wondering how I could eliminate the 'for centroid in centres' loop? I tried the following horrible piece of code
number_count.append(np.count_nonzero(item[sparse.csr_matrix(np.roll(np.roll(mask,centres[:][0]-centre_Y,axis=0),centres[:][1]-centre_X,axis=1))]))

where I tried to vectorise centres, but this just gave me a list of zeros in number count of length len(centres). Could anyone help please?
EDIT:
I forgot to specify that I need to roll my mask from the center to certain positions to maintain periodicity of the mask. Applying the mask straight away near the edges of the boolean array doesn't wrap the mask around to the parallel edge, and I don't want the mask to have a cutoff. This is because the data I am applying the mask to comes from a simulation with periodic boundary conditions.
UPDATE:
So I managed to write a piece of code using Numba that eliminated the need for masks and is quite fast. It takes in a 2d numpy array, a list of positions (centroids) to sample from and a radius to sample out to. The code iterates through the positions and searches for the nonzero elements within radius distance from each position. The boundaries are handled periodically. Some aspects of the code are redundant and I'm sure it can be made better and more general, but it works for what I need. Thanks to those who gave their input into the problem.
@nb.njit(fastmath=True)
def nonzero_count(array,positions,radius):

    stored_values = list()
    y,x = array.shape

    for k in range(len(positions)):

        pos_y,pos_x = positions[k][0],positions[k][1]
        nonzero = 0

        # this section handles the periodic boundary conditions
        if pos_y+radius+1>y:
            # recenter pos_y so it is given a negative value
            aa = y-(pos_y+radius+1)
            # iterate around new pos_y, from -'ve to +'ve
            yy = (aa-radius,aa+radius+1)
        else:
            aa = pos_y
            yy = (pos_y-radius,pos_y+radius+1)

        if pos_x+radius+1>x:
            # recenter pos_x so it is given a negative value
            bb = x-(pos_x+radius+1)
            # iterate around new pos_x, from -'ve to +'ve
            xx = (bb-radius,bb+radius+1)
        else:
            bb = pos_x
            xx = (pos_x-radius,pos_x+radius+1)

        # this section handles the count
        for i in range(yy[0],yy[1]):
            for j in range(xx[0],xx[1]):
                # check nonzero elements lie within radius
                if array[i,j] != 0 and (bb-j)**2+(aa-i)**2<=radius**2:
                    nonzero += 1

        stored_values.append(nonzero)

    return stored_values

A: I would suggest using the numba package to speed up these loops, it seems it would be perfect for your use case. Just do something like the following, and some refactoring will most likely be required:
import numba as nb

@nb.njit(nopython=True)
def slow_code():
    # roll in the vertical direction to centroid y coordinate
    mask_roll_y = np.roll(mask,centroid[0]-centre_Y,axis=0)

    # roll in the horizontal direction to centroid x coordinate and make sparse
    roll_mask = sparse.csr_matrix(np.roll(mask_roll_y,centroid[1]-centre_X,axis=1))

    # apply sparse mask to sparse data and count number of nonzero elements below
    number_count.append(np.count_nonzero(item[roll_mask]))

for item in data:

    ### Do stuff

    for radius in radii:

        ### Do stuff

        # roll mask to centroid and count the number of elements within radius

        for centroid in centres:
            slow_code()

A: If your mask is sparse, it is better to first convert it to sparse and then roll it; this will give you significant speedups.  As you are doing it now, you are converting the matrix to sparse in the loop, which is both expensive and negates the advantages.
Observe:
import numpy as np
import scipy.sparse as sparse

zero_matrix = np.zeros((1024, 1024))
%timeit np.roll(zero_matrix, (10, 10))
>>1000 loops, best of 3: 1.36 ms per loop

sparse_matrix = sparse.random(1024, 1024, density = 0.001)
%timeit np.roll(sparse_matrix, (10, 10))
>>100000 loops, best of 3: 15.4 µs per loop


text:
Q: Given an entity that can have a parent, or can stand on its own, what is the best way to represent it in a relational database Lets assume we have to model the following entities:

*

*Application :  Application submitted by users

*Application Study: the study to determine if the Application  should be accepted

*Consultation : A consultation with an external party as part of the Application Study.  Consultations with external parties could also be initiated independent of an Application Study.

So we have entity Consultation that can have parent Application Study or stand on its own. What is the best way to model this in a relational database?
I see 2 options:

*

*have a nullable foreign key in Consultation  table referencing  Application Study

*have 2 tables: Application Study Consultation with a non nullable application_study_id and another Consultation  table without any reference to application study.

Which is the best practice way?
EDITED:
There is a ONE-TO-MANY relationship between Application Studies and Consultations.  In other words, an application study can have multiple Consultations. Hense the foreign key.  In addition, an Application Study may or may not have a consulation.

A: *

*Option 2 is ruled out because you don't need a join table for 1:M relationships.

*The relationship between APPLICATION_STUDY and CONSULTATION is 0:M, not 1:M.

*Option 1 is the correct one. That's the usual way of modeling 0:M relationships: a nullable FK on the MANY side.
EDIT : Note that the 0 in 0:M mean 0 or 1, which is why you have a nullable FK on the many side.


text:
Q: using TypeScript for partial application I like using object literals as a function argument because it allows me to label the argument names. I thought there would be a type-safe generic way to do partial function application on these types of functions. Suppose a function takes an argument of type X. And then I run that function through another function called "partial" where I supply a Partial of X, it could return a new function that expects just the missing values. Easiest to see with an example below. The nice thing here is that with my "partial" function I can supply any number or combination of arguments and get a result function that clearly indicates what is still needed.
function partial<Args, Fixed extends Partial<Args>, Result>(fn: (args: Args) => Result, fixed: Fixed) {
    type Unspecified = { [P in Exclude<keyof Args, keyof Fixed>]: Args[P] };
    const result = (args: Unspecified) => {
        const combined = {};
        Object.assign(combined, fixed, args);
        return fn(combined as Args);
    };
    return result as ({} extends Unspecified ? () => Result : (args: Unspecified) => Result);
}

interface AddThreeNumbersArgs {
    a: number;
    b: number;
    c: number;
    caption: string;
}

function addThreeNumbers(args: AddThreeNumbersArgs) {
    return `${args.caption} ${args.a + args.b + args.c}`;
}

test("fix one number and the caption", () => {
    const f = partial(addThreeNumbers, { b: 10, caption: "The answer is:" });
    const result = f({ a: 1, c: 25 });
    expect(result).toBe("The answer is: 36");
});

This all works nicely for the AddThreeNumbers example above. But it does NOT work when the function argument is a generic - see below - and I don't know why. Instead the result of partial is a function that takes NO arguments rather than the missing pieces. Do any TypeScript gurus know why?
interface ConcatenateArrayArgs<TItem> {
    first: TItem[],
    second: TItem[]
}

function concatenate<T>(args: ConcatenateArrayArgs<T>) {
    return [...args.first, ...args.second];
}

test("concatenate", () => {
    const result = concatenate({ first: [1, 2, 3], second: [4, 5, 6] });
    expect(result).toEqual(expect.arrayContaining([1, 2, 3, 4, 5, 6]));
});

test("fix first array in concatenate to array of numbers", () => {
    const f = partial(concatenate, { first: [1, 2, 3] });
    // expect f to take a { second: [4,5,6] } here but instead
    // f is a function with no arguments
});

A: I think you have run into the issue in Microsoft/TypeScript#9366; TypeScript doesn't have great support for type inference involving higher-rank function types.  UPDATE: The support added in TS3.4 for inferring higher order function types isn't general enough to help you here, unfortunately; the compiler can now propagate some generic type parameters from an input function to an output function (e.g., if concatenate is generic, then partial(concatenate, ...) will also be generic), but it can't arbitrarily specify a generic type parameter in the input function (e.g., plug number in for the type parameter in concatenate to make the output function non-generic).  So, for example, microsoft/TypeScript#25256 is still a design limitation.
The only workaround I can think of is for you to explicitly specify types somewhere.  You could, for instance, lower the rank of your callback function to a non-generic one, as in:
const f = partial(
  concatenate as (x: ConcatenateArrayArgs<number>)=>number,
  { first: [1, 2, 3] }
);

And then inference works as you expect.  Or you could explicitly specify the type parameters in the call to partial() so that it is essentially non-generic and there is no inference for the compiler to get wrong:
const r = partial<
  ConcatenateArrayArgs<number>,
  { first: number[] },
  number[]
>(concatenate, { first: [1, 2, 3] });

Those both work, but are not particularly satisfying.  Hope that at least points you in the right direction.  Good luck!


text:
Q: What is a good percentage value for SMOTE in Weka I am using the oversampling technique named as SMOTE to balance my dataset in Weka. To balance my dataset I needed to use 1300 as my -p (percentage) value. The default -p (percentage) value is 100.
I am interested in knowing whether the -p (percentage) value I am using bad because it is a very big number compared with the default value? Does this unnecessarily affect the performance of the classification models constructed (I am using 10-fold cross validation to construct my models)?
I am happy to provide more details of my classification if needed :)


text:
Q: Software for computing geometirc data of parametric surfaces Is there any (possibly free) software suitable for computing geometric quantities of parametric surfaces?
Any suggestion will be very appreciated.

A: Sage is a free piece of software similar to Mathematica. Check it out here.
For example, to compute the Gaussian and mean curvatures of the sphere,
sage: sphere = surfaces.Sphere(); sphere
sage: K = sphere.gauss_curvature();
sage: H = sphere.mean_curvature();

See here for more functions.
This MO answer also contains many other software links.
This link is particularly useful to find software oriented to a particular field.


text:
Q: What's the difference between "chomp" and "munch"? What is the difference between "chomp" and "munch"? As far as I know both mean: To eat something noisily.
1) I chomped on popcorn during the movie.
2) He was munching on an apple.

A: They mean the same thing. Really, it's not so much the noisy aspect I think of with these words. If there's any difference, I'd say "munch" doesn't necessarily imply eating noisily.

Sally: Whatcha looking for?
Bob: We got anything to munch on?

Here it just really means "eat" or "snack." On the other hand, with "chomp" I think more of eating ravenously - very hungrily and quickly, choking down your food.
I wouldn't probably use "chomp" personally, as it reminds me of a Pac-Man game. But it's a perfectly good word.

A: Both are onomatopoeia "Chomp" starts with the grinding "ch" sound but has the "p" sound of your mouth closing and is the sound of bite: closing the mouth on food.
Munch has the closed mouth "m" and the "ch" to evoke grinding.  It is more about chewing than biting.
But really this is splitting hairs. In many, or most, casual situations, chomp or munch are close to meaning the same.


text:
Q: Xamarin forms Android Icon doesn't show in App Center We have a Xamarin.Forms apps with Android and iOS apps which get built using Azure DevOps pipeline and published to App Center.
The iOS app shows in App Center with the correct icon, however the android app just shows a default icon.
I found this issue on GitHub https://github.com/microsoft/appcenter/issues/958, but it seems to have just been closed.
We use a png icon in the mipmap-hdpi folder in our Android project and it doesn't show in App Center. Does the icon need to go in a specific place to show in App Center?
Does anyone know how to get the Android icon to display in App Center?


text:
Q: Move all values of array into one variable in PHP I have a very simple question.
Imagine I have this array :
$array = array("one","two","three");

I want to merge all values into one variable :
$array = "one,two,three";

How to do it ?

A: By using this :
$variable = implode(",",$array);


text:
Q: R apply cannot get multiple mins when rows exceed certain numbers I am trying to get a random variable when there are 2 minimal values, using a line of code like
sliced_coor$option<-apply(sliced_coor[1:312], 1, function(t) sample(names(t)[which(t==min(t[c('intuitive','reflective')]))],1))

I intend to apply for all rows, [1:312] is just where I found the abnormality. It is very strange that the function fails to get 2 minimal values once the rows exceed 312, and the limit is not constant when I tested with other data..
Although I managed to fix the issue with moving the specification of columns [c('intuitive','reflective')] to data parameter - sliced_coor , but I am still don't understand the problem of the early method.