text:
Q: python-pptx: change border width for pie chart Is it possible to set/edit a Pie chart's border width in python-pptx?

I'd image something like this would do the trick?
    for idx, point in enumerate(chart.series[0].points):
        point.format.width = Pt(7.25)

A: This feature is not yet supported by the python-pptx API, but you can accomplish it by adapting a workaround like this:
from pptx.dml.color import RGBColor
from pptx.dml.line import LineFormat
from pptx.oxml import parse_xml
from pptx.oxml.ns import nsdecls
from pptx.util import Pt

plotArea = chart._chartSpace.plotArea
# ---get-or-add spPr---
spPrs = plotArea.xpath("c:spPr")
if len(spPrs) > 0:
    spPr = spPrs[0]
else:
    # ---add spPr---
    spPr_xml = (
        "<c:spPr %s %s>\n"
        "  <a:noFill/>\n"
        "  <a:ln>\n"
        "    <a:solidFill>\n"
        "      <a:srgbClr val=\"DEDEDE\"/>\n"
        "    </a:solidFill>\n"
        "  </a:ln>\n"
        "  <a:effectLst/>\n"
        "</c:spPr>\n" % (nsdecls("c"), nsdecls("a"))
    )
    spPr = parse_xml(spPr_xml)
    plotArea.insert_element_before(spPr, "c:extLst")

line = LineFormat(spPr)
line.color.rgb = RGBColor.from_text("DEDEDE")
line.width = Pt(2)

The LineFormat object formed in this way has all the methods and properties described here:
https://python-pptx.readthedocs.io/en/latest/api/dml.html#lineformat-objects
It probably makes sense to extract most of that code into a method chart_border(chart) that returns the LineFormat object for the chart, after which you can manipulate it in the usual way.


text:
Q: The database structure to scale the table in MySQL I am writing a name card storage system. It works like this, first, a company register on my website, then they are given an account, and start saving name card on my server.
The database is like this:
Company
-id
-name
-address

Card
-id
-name
-title
-*company_id

The problem is, is this simple structure can fulfil the need when there are more than 100,000 company, if one company has 1000 cards then the card table will be very huge and the query time is long.
How to scale the table, given that I don't know the actual number of the company, should I create a new table once the company register? but I need to store the table name as well and make the situation more complex.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reading string and integer from file in C I have a file for marks of student as shown as below:
T1 T2 T3 HW1 HW2 HW3 HW4 PRJ
47 17 50 10  10  10  10  68
20 41 40 15  10  10  10  80

but I don't know how the number of students in the class. I try to write a code to read the data from the file but I get infinite loop.
  char header[10];
  int data;
  int a;
  int nos=0;

  //READ HEADINGS OF THE TABLE
  while(fscanf(f1, "%s", header) != '\n')
  {
      printf("%s \t", header);
  }
  printf("\n");

  //READ DATA OF THE TABLE
  while(fscanf(f1, "%d", data) != EOF)
  {
      for(a=0; a<=7; ++a)
      {
          printf("%d \t", data);
      }
      printf("\n");
  }
  printf("\n");
  printf("Number of students in class: %d", nos/8);
  system("pause");

A: An easier way is to read each line in full in a buffer and use sscanf to extract the names.
 #define N 100
 char buffer[N];
 fgets(buffer, N, f1);
 unsigned num_tasks = 0;
 while(sscanf(buffer, "%s", header) == 1) {
     printf("%s \t", header);
     num_tasks++;
 }

Do the same for each line of marks and count students along the way. Stop when fgets() returns EOF.

A: *

*fscanf returns the total number of arguments successfully matched so fscanf(f1, "%s", header) != '\n' will always be true as -1 < 10 (EOF), 0 < 10 (Matching failure but not end of file) and also 1 < 10 (matched successfully). Here 10 is ASCII of \n.

*Also in second fscanf instead of data, it should be &data.
Please read man -s3 fscanf.
Here correct solution will be:
#define HEADERS 8

char header[10];
int data, a, nos = 0;

for(a = 0; a < HEADERS; a++) //assuming there'll always be 8 headers
{
    fscanf(f1, "%s", header);
    printf("%s \t", header);
}
printf("\n");

while(fscanf(f1, "%d", &data) == 1)
{
    nos++;
    printf("%d \t", data);
    if(!(nos % HEADERS))
        printf("\n");
}

printf("Number of students in class: %d", nos/HEADERS);


text:
Q: Are there any special internal Ethernet connectors other than RJ45? I am working on the board that suppose to have 1 GbE port (10/100/1000BASE-T). Looking at connectors all I seem to find is standard RJ45 connector.
However in my design the board itself is not directly exposed to the outside, there is a backplane which will include some other ports as well.
Now, I could put the standard RJ45 on the board and and 2 of them on backplane and connect board to backplane with standard CAT5 cable. However the RJ45 connector is rather bulky comparing to everything else on board.
So my question is -- are there any alternatives to this approach, how do commercial products that do not expose main board ports directly work around that?
PS: I've seen this question which recommends micro USB 2.0 port as chip alternative, but that means only 4 wires per port (so 2 ports per board for single RJ45?) I foresee some impedance matching issues right there.

A: You need to use a different ethernet standard than 802.3ab, that doesn't need RJ45 jacks. Like IEEE 802.3ap "Backplane Ethernet", which supports gigabit speeds over a backplane type of connection. This standard was designed for your application in mind.
Also see On-Board connection of ethernet transceivers for 10/100 speed connections on the same board. The Micrel now Microchip app note AN-120 http://ww1.microchip.com/downloads/en/AppNotes/Capacitive%20Coupling%20Ethernet%20Transceivers%20without%20Using%20Transformers.pdf describes how non-transformer (and connector) ethernet connections are designed on board.


text:
Q: Webpart Page as Document Template (SP 2007) I am trying to create a custom content type where the Document Template is a webpart page with multiple webparts already on it.
My problem is, I created a page in a page library, saved a copy of that page and then set it as the Document Template. However, when I create a document library with this content type, clicking the "New" button opens the aspx file in designer.
Is there any way to accomplish this without code? It should function similar to the "link to a document" content type, in that when you click "New" you are taken to the metadata form and once that is filled in a new aspx is created in the library.
Any help would be appreciated.
EDIT:  This is a MOSS environment.

A: you can't have Web Parts Page with Web Parts as a Document template. Web Parts and all the personalization data (including position on the page, size, toolbars etc) are stored in Content DB. You can see that you need new data pushed to Content DB every time you creating new Document from your template. Thus only code. Good luck!
UPDATE (as answer to additional questions from the comments):
well, when you are clicking "New" button you always get your new document created from your template (WebPart Page) and opened for editing. Actual UX will depend on your settings for the document type - if your system configured to edit .aspx files in SPD you will have it opened in SPD and so on. Ways to change it: 1. Change "New" button behavior by Custom Action (kind of custom dev) 2. Change "New" button behavior for particular page by javascript (pure custom dev but could be done easily with CEWP) 3. Update your .aspx file extensions associacion 4. see @Laurie 's suggestion above (sounds good although I can't test it myself right now)

A: I believe you need a custom page layout as well and your site template must be of a publishing site to do this code-less. Checkout my article @ http://www.dotnetcurry.com/ShowArticle.aspx?ID=638
The above is in 2010 but I've done it in 2007 as well. Steps are pretty much the same, the UI elements look different in 2007.
The following seems to suggest you can enable Publishing in a team site and get it going in 2007
http://office.microsoft.com/en-us/sharepoint-designer-help/create-a-publishing-page-layout-HA010174128.aspx


text:
Q: Using batch script to automatically copy latest file to folder I would like to call for help on my attempt to create a script which will automatically check last modified file and transfer it to destination.
What I have is this:
@Echo Off
Set _Delay=1
for /f "tokens=1,2,3 delims==" %%a in (config.ini) do (
if %%a==source set _Monitor=%%b
if %%a==destination set _Dest=%%b
if %%a==timer set _Timer=%%b
)
Set _Base=%temp%\BaselineState.dir
Set _Chck=%temp%\ChkState.dir
Set _OS=6
Ver|Findstr /I /C:"Version 5">Nul
If %Errorlevel%==0 Set _OS=5 & Set /A _Delay=_Delay*1000
Goto :_Xfer
:_StartMon
@echo off
SET R1=Start /w Sync1.vbs
Call :_SetBaseline "%_Base%" "%_Monitor%"
:_MonLoop
If %_OS%==5 (Ping 1.0.0.0 -n 1 -w %_Delay%>Nul) Else Timeout %_Delay%>Nul
Call :_SetBaseline "%_Chck%" "%_Monitor%"
FC /A /L "%_Base%" "%_Chck%">Nul
If %ErrorLevel%==0 Goto _MonLoop
::
for /l %%a in (%_Timer%,-1,0) do (
@Echo::::::::::::::::::::::::::::::::::::::::::::::
@Echo:: SEC Auto Transfer ::
@Echo:: Aizal 16 June 2012 ::
@Echo::::::::::::::::::::::::::::::::::::::::::::::
@Echo This script will scan SEC Data Folder for
@Echo new files every 30 minutes and will copy
@Echo it to the Server. Make sure you set correct
@Echo folder before using this script.
ECHO.
ECHO Currently recording:
FOR /F %%a in ('xcopy "%_Monitor%\*.SEC" "%_Dest%" /L /Y') DO (
IF NOT EXIST "%_Dest%.\%%~nxa" ECHO %%~nxa
)
ECHO Refreshing...
ECHO Please wait %%a seconds...
%R1%
cls
)
::
:_Xfer
FOR /F %%a in ('xcopy "%_Monitor%\*.SEC" "%_Dest%" /L /Y') DO (
IF NOT EXIST "%_Dest%.\%%~nxa" xcopy "%%a" "%_Dest%" /Y
)
::
Echo.Change Detected
ECHO.
Goto :_StartMon
:::::::::::::::::::::::::::::::::::::::::::::::::::
:: Subroutine
:::::::::::::::::::::::::::::::::::::::::::::::::::
:_SetBaseline
If Exist "%temp%\tempfmstate.dir" Del "%temp%\tempfmstate.dir"
For /F "Tokens=* Delims=" %%I In ('Dir /S "%~2"') Do (
Set _Last=%%I
>>"%temp%\tempfmstate.dir" Echo.%%I
)
>"%~1" Findstr /V /C:"%_Last%" "%temp%\tempfmstate.dir"
Goto :EOF

Now, if you noticed the script will compare the content of source folder with the content of the destination folder and will copy the files from source if there is not already file in destination. I would like to know if someone can help me figuring out how to make the script to check the last modified file in source folder and ONLY copy it to the destination AND if the said file is currently in use/being write to then script will wait until it finished before trying to copy it again.
Also, right now I have to edit source.ini file to specify which folder I want to monitor and each time I have to change the subfolder path to watch for changes, is there a way to watch parent folder for any new files and take that file to the destination?
I found this script on the net but hoping to check the file not based on day but instead of time.
::Copy Files Made Or Modified Today
@echo off
setlocal
set source= <source directory>
set dest= <destination directory>
pushd "%source%"
set t=%date:~4%
::for /f %%a in ('dir /b /a-d /o-d') do call :PROCESS "%%a"
goto :eof
popd
:PROCESS
for /f %%j in ('echo %~t1') do set d=%%j
if "%d%"=="%t%" copy %1 "%dest%"
goto :eof

Hope to find the solution from here.
Many thanks

A: With this you'll get the last modified file:
for /f %%A in ('dir /b /tw /o-d not-mandatory-file-mask') do (
   set last_file=%%A
   goto :endloop
)
:endloop

With this you'll copy the file if it is possible. If not it will try again and again:
:tryagain
set /a errorlevel=0
copy some_dir\%last_file% %destination%
if %errorlevel% NEQ 0 (
   sleep 10
   goto :tryagain
) else (
   goto :end
)
:end


text:
Q: For every x, y ∈ IN = {1, . . . , N} define K(x, y) = min{x, y}. Prove that K is a valid kernel I need to prove K is a valid Kernel.
x and y are positive integers, and K is the minimum of x and y.
I know I should prove K positive definite. But May I see how.

A: Let $\mathcal X$ be any subset of $\{1...N\}$, and $|\mathcal X|=n,$ and $x_i,x_j$ be any two elements from this set.
We can write $\min(x_i,x_j)$ as below:
$$\min(x_i,x_j)=\int_0^N \mathbb 1(t\leq x_i)\mathbb 1(t\leq x_j)dt$$
The reason of this equality is straightforward. The first indicator function will be $1$ until $x_i$; and the second indicator function is $1$ until $x_j$. The multiplication will be $1$ if both are $1$, which means until the minimum of $x_i$ and $x_j$. The integral then can be written as
$$\begin{align}\int_0^N\mathbb 1(t\leq x_i)\mathbb 1(t\leq x_j)dt&=\int_0^{\min(x_i,x_j)}\mathbb 1(t\leq x_i)\mathbb 1(t\leq x_j)dt\\&=\int_0^{\min(x_i,x_j)}1\times 1\times dt\\&=\min(x_i,x_j)\end{align}$$
Then, we substitute in to the PSD requirement:
$$\begin{align}\sum_{i=1}^n\sum_{j=1}^n c_i c_j \min(x_i,x_j)&=\sum_{i=1}^n\sum_{j=1}^n c_i c_j \int_0^N \mathbb 1(t\leq x_i)\mathbb 1(t\leq x_j)dt \\&=\int_0^N \underbrace{\left(\sum_{i=1}^n c_i\mathbb 1(t\leq x_i)\right)}_{M(t)}\underbrace{\left(\sum_{j=1}^n c_j\mathbb 1(t\leq x_j)\right)}_{M(t)}dt\\&=\int_0^NM(t)M(t)dt=\int_0^NM(t)^2dt\geq 0\end{align}$$
Both multiplicands are equal because both summations range from $1$ to $n$. We can also change the order of summations and integrations according to Fubini's theorem (in short, the sums and integrals are finite).
This covers PSD property and you've already mentioned the symmetric property in your comment.

A: Let $B_1, B_2, \ldots, B_N, \ldots$ be a sequence of independent zero-mean unit variance random variables.  For instance, each $B_i$ could be a Rademacher variable that has a $1/2$ chance of being $+1$ and a $1/2$ chance of being $-1.$
Let $X_i = B_1 + B_2 + \cdots + B_i$ be the partial sum.  The sequence $(X_i)$ is an example of a random walk.  We are going to compute the covariance matrix of this walk.  The algebra is simple, but I will give all the details just to be perfectly clear.
Because each $X_i$ is a sum of independent (therefore uncorrelated) variables, its variance is the sum of the variances of its components, whence $$\operatorname{Var}(X_i) = \operatorname{Var}(B_1) + \operatorname{Var}(B_2) + \cdots + \operatorname{Var}(B_i)  = i.$$
Morever, when $j\gt i$ the additional terms in $X_j$ (namely, $B_{i+1} + \cdots + B_j$) are independent of $X_i$ and therefore uncorrelated with it, showing that
$$\begin{aligned}
\operatorname{Cov}(X_i, X_j) &= \operatorname{Cov}(X_i, X_i + (X_j-X_i))\\
& = \operatorname{Cov}(X_i,X_i) + \operatorname{Cov}(X_i, X_j-X_i) \\
&= \operatorname{Var}(X_i) + 0 \\
&= i.
\end{aligned}$$
Since covariance is symmetric, $$\operatorname{Cov}(X_j,X_i) = \operatorname{Cov}(X_i,X_j) = i.$$
A convenient way to express all these results is

$$\operatorname{Cov}(X_i,X_j) = \min(i,j) = K(i,j).$$

Because $K$ is a covariance matrix and all covariance matrices are positive semi-definite, it is a kernel, QED.


text:
Q: GCP Download/Get Service Account Key This is how am trying to create a key under a service account and when am trying to fetch privateKeyData which contain is a base64 representation of credentials file via serviceAccountKey.getPrivateKeyData, the method is returning empty, not sure what am I doing wrong here
Can anyone throw some light here,
public void createServiceAccountKey(String serviceAccountName)
      {
        ServiceAccountKey serviceAccountKey = null;
        try {
          initService();

          serviceAccountKey =
              service
                  .projects()
                  .serviceAccounts()
                  .keys()
                  .create(
                      "projects/-/serviceAccounts/"
                          + serviceAccountName
                          + "@"
                          + serviceAccountConfig.getProjectId()
                          + ".iam.gserviceaccount.com",
                      new CreateServiceAccountKeyRequest())
                  .execute();

          log.info("Created key under Service Account: {}", serviceAccountName);
          log.info("Service Account Private Data: ", serviceAccountKey.getPrivateKeyData());
          log.info("Service Account Key Type: ", serviceAccountKey.getKeyType());
          log.info("Service Account Key Type: ", serviceAccountKey.getKeyAlgorithm());

        } catch (IOException e) {
          log.error("Unable to create key under service account: {}", e.toString());
        }
      }

A: According to GCP documentation
The format of the key may differ depending on how it is generated.

Because the formatting differs between each method, it's easiest to generate a key using the same method you plan to use when making future API calls. For example, if you're using gcloud, also generate your key using gcloud. To use a key for one method that's been generated using a different method (such as using a REST-generated key with gcloud), you'll need to edit the key to match the appropriate format

This might be helpful, look for how you are using and generating the keys.


text:
Q: Can't disable Hyper-V in Windows 10 While developing Android apps with Xamarin in Visual Studio 2019, I am experiencing problems with the android emulators, so, following a couple of posts online, I am trying to enable HAXM in order to fix my issues. In order to do so, I need to disable hyper-v.
I have unchecked all the boxes about Hyper-V in windows features.
Used DG_Readiness_Tool script to disable it PS D:\DownloadsFirefox\dgreadiness_v3.6> .\DG_Readiness_Tool_v3.6.ps1 -Disable
Also, uninstalled my VPN and Oracle VM network drivers, but to no avail.
Every time I run DG_Readiness_Tool_v3.6.ps1 script, I get the same output:
###########################################################################
Readiness Tool Version 3.4 Release.
Tool to check if your device is capable to run Device Guard and Credential Guard.
###########################################################################
Disabling Device Guard and Credential Guard
Deleting RegKeys to disable DG/CG
ERROR: The system was unable to find the specified registry key or value.
ERROR: The system was unable to find the specified registry key or value.
ERROR: The system was unable to find the specified registry key or value.
ERROR: The system was unable to find the specified registry key or value.
ERROR: The system was unable to find the specified registry key or value.
ERROR: The system was unable to find the specified registry key or value.
del : Cannot find path 'C:\Windows\System32\CodeIntegrity\SIPolicy.p7b' because it does not exist.
At line:1 char:1
+ del  "$env:windir\System32\CodeIntegrity\SIPolicy.p7b"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Windows\Syst...ty\SIPolicy.p7b:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

Disabling Hyper-V and IOMMU
Disabling Hyper-V and IOMMU successful

Please reboot the machine, for settings to be applied.

After that I reboot and get a messages weather I want to confirm disabling Device Guard and Credential Guard. Then my windows starts, I run the checktool and here we go, Hyper-v is not disabled.
PS D:\DownloadsFirefox\checktool-windows-1.0.0> .\checktool.exe --verbose
CPU vendor          *  GenuineIntel
Intel64 supported   *  Yes
VMX supported       -  No
VMX enabled         -  No
EPT supported       -  No
NX supported        *  Yes
NX enabled          *  Yes
Hyper-V disabled    -  No
OS version          *  Windows 10.0.18363
OS architecture     *  x86_64
Guest unoccupied    *  Yes. 0 guest(s)

A: I would suggest you can try disable Hyper-v via Command Prompt and PowerShell
Right-click on Windows key and select Command Prompt (Admin).
Copy and paste the Dism /Online /Cleanup-Image /RestoreHealth. Press Enter.
Then run the Dism.exe /online /Cleanup-Image /StartComponentCleanup command and hit Enter.
Now type the sfc /scannow and press Enter again.
Close Command Prompt and open Windows PowerShell(with administrative privileges).
Type PowerShell in Windows search, right-click it, and select Run as Administrator.
Copy and paste the Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All.
Close PowerShell and reboot the PC.
Reference:
https://ugetfix.com/ask/how-to-disable-hyper-v-in-windows-10/


text:
Q: If we made a mistake in crontab entry what will happen then If I Made a mistake in the crontab entry, like issuing the nonexistent command coppy instead of cp, what happens upon execution of the task?

A: First note that, each cron job is run in a shell (sh i.e. dash by default, changeable via the SHELL environment variable inside crontab). Two cases:

*

*MAILTO environment variable is set: A mail will be sent to the mentioned address(es) with the error (STDERR) (and also STDOUT, if any), as if you were run it in the (used) shell

*MAILTO environment variable is null: Nothing, the error message will be thrown away as no consumer available

*MAILTO environment variable is unset: The STDERR (and STDOUT if any) will be sent to the local user's mailbox
In all cases, /var/log/syslog will have the relevant error message.

Note that people often use shell redirections to save the STDOUT/STDERR in a file e.g.:
* * * * * your_command >/tmp/cron_msg 2>&1

Or if MAILTO is set, not to have the STDOUT/STDERR in mail as teh primary intention is to run the command, if so it is a common trend to send to /dev/null too:
* * * * * your_command >/dev/null 2>&1


text:
Q: Static content not loading from spring boot war in jboss server i have placed the static content such as css, js , images in static folder under resources and all the html files in templates folder. however when i build a war and deploy it on jboss. the html is loaded but static content is not loaded and the same works fine in inbuild tomcat server.
url to access the war pages : IP:8080/warname/login
when i inspect in console of chrome i get url of js, css as IP:8080/js/jsfile.js or IP:8080/css/abc.css.
here is my project structure
image of project structure
Here is how i am using css,js in html files

A: You are referencing the static content in src or href with for example /js but this does not work when deploying as WAR file because in the app server there will be a context root added. (warname in your case)
You have to use Thymleaf syntax like
<script type="text/javascript" th:src="@{/js/searchOP.js}"></script>

Please checkout the documentation for more information: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html


text:
Q: Java file encoding conversion from ANSI to UTF8 I have a requirement to change the encoding of a file from ANSI(windows-1252) to UTF8. I wrote below program to do it through java. This program converts the characters to UTF8, but when I opened the file in notepad++ the encoding type was displayed as ANSI as UTF8. This gives me error when I import this file in access db. A file with UTF8 encoding only is desired. Also the requirement is to convert the file without opening it in any editor.
public class ConvertFromAnsiToUtf8 {

    private static final char BYTE_ORDER_MARK = '\uFEFF';
    private static final String ANSI_CODE = "windows-1252";
    private static final String UTF_CODE = "UTF8";
    private static final Charset ANSI_CHARSET = Charset.forName(ANSI_CODE);

    public static void main(String[] args) {

        List<File> fileList;
        File inputFolder = new File(args[0]);
        if (!inputFolder.isDirectory()) {
            return;
        }
        File parentDir = new File(inputFolder.getParent() + "\\"
                    + inputFolder.getName() + "_converted");

        if (parentDir.exists()) {
            return;
        }
        if (parentDir.mkdir()) {

        } else {
            return;
        }

        fileList = new ArrayList<File>();
        for (final File fileEntry : inputFolder.listFiles()) {
            fileList.add(fileEntry);
        }

        InputStream in;

        Reader reader = null;
        Writer writer = null;
        try {
            for (File file : fileList) {
                in = new FileInputStream(file.getAbsoluteFile());
                reader = new InputStreamReader(in, ANSI_CHARSET);

                OutputStream out = new FileOutputStream(
                            parentDir.getAbsoluteFile() + "\\"
                                            + file.getName());
                writer = new OutputStreamWriter(out, UTF_CODE);
                writer.write(BYTE_ORDER_MARK);
                char[] buffer = new char[10];
                int read;
                while ((read = reader.read(buffer)) != -1) {
                    System.out.println(read);
                    writer.write(buffer, 0, read);
                }
            }
            reader.close();
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Any pointers will be helpful.
Thanks,
Ashish

A: The posted code correctly transcodes from windows-1252 to UTF-8.
The Notepad++ message is confusing because "ANSI as UTF-8" has no obvious meaning; it appears to be an open defect in Notepad++. I believe Notepad++ means UTF-8 without BOM (see the encoding menu.)
Microsoft Access, being a Windows program, probably expects UTF-8 files to start with a byte-order-mark (BOM).
You can inject a BOM into the document by writing the code point U+FEFF at the start of the file:
import java.io.*;
import java.nio.charset.*;

public class Ansi1252ToUtf8 {
  private static final char BYTE_ORDER_MARK = '\uFEFF';

  public static void main(String[] args) throws IOException {
    Charset windows1252 = Charset.forName("windows-1252");
    try (InputStream in = new FileInputStream(args[0]);
        Reader reader = new InputStreamReader(in, windows1252);
        OutputStream out = new FileOutputStream(args[1]);
        Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
      writer.write(BYTE_ORDER_MARK);
      char[] buffer = new char[1024];
      int read;
      while ((read = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, read);
      }
    }
  }
}

A: On Windows 7 (64-Bit), running Java 8, I had to close every file. Otherwise, files get truncated to multiples of 4 kB. It is not enough to close the last set of files, I had to close every file to get the desired result. Posting my adapted version that adds error messages:
import java.io.*;
import java.nio.charset.*;
import java.util.ArrayList;

public class ConvertFromAnsiToUtf8 {

    private static final char BYTE_ORDER_MARK = '\uFEFF';
    private static final String ANSI_CODE = "windows-1252";
    private static final String UTF_CODE = "UTF8";
    private static final Charset ANSI_CHARSET = Charset.forName(ANSI_CODE);
    private static final String PATH_SEP = "\\";
    private static final boolean WRITE_BOM = false;

    public static void main(String[] args)
    {
        if (args.length != 2) {
            System.out.println("Please name a source and a target directory");
            return;
        }

        File inputFolder = new File(args[0]);
        if (!inputFolder.isDirectory()) {
            System.out.println("Input folder " + inputFolder + " does not exist");
            return;
        }
        File outputFolder = new File(args[1]);

        if (outputFolder.exists()) {
            System.out.println("Folder " + outputFolder + " exists - aborting");
            return;
        }
        if (outputFolder.mkdir()) {
            System.out.println("Placing converted files in " + outputFolder);
        } else {
            System.out.println("Output folder " + outputFolder + " exists - aborting");
            return;
        }

        ArrayList<File> fileList = new ArrayList<File>();
        for (final File fileEntry : inputFolder.listFiles()) {
            fileList.add(fileEntry);
        }

        InputStream in;
        Reader reader = null;
        Writer writer = null;
        int converted = 0;

        try {
            for (File file : fileList) {
                try {
                    in = new FileInputStream(file.getAbsoluteFile());
                    reader = new InputStreamReader(in, ANSI_CHARSET);

                    OutputStream out = new FileOutputStream(outputFolder.getAbsoluteFile() + PATH_SEP + file.getName());
                    writer = new OutputStreamWriter(out, UTF_CODE);

                    if (WRITE_BOM)
                        writer.write(BYTE_ORDER_MARK);
                    char[] buffer = new char[1024];
                    int read;
                    while ((read = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, read);
                    }
                    ++converted;
                } finally {
                    reader.close();
                    writer.close();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(converted + " files converted");
    }

}


text:
Q: Regular Expression: interchange words by delimiter How can I interchange words by delimiter
Example:

Surname, Name - filename.txt

I want this to be come

Name Surname - filename.txt

I have file renamer which can rename file with regular expressions (A better rename in mac, and better file renamer on windows)
is it possible at all?

A: Matching expression:
/^(.+), (.+) - (.+)$/

Replacement pattern:
$2 $1 - $3

Something along these lines should work, but this really depends on the capabilities and semantics of your regex engine and your specific input. No idea what Better Renamer allows you to do.

A: $ echo "Surname, Name - filename.txt" | ruby -e 'print gets.gsub(/(\w+),\s+(\w+)(\s+-\s+\w+)/, "\\2 \\1 \\3")'
Name Surname  - filename.txt


text:
Q: showing document type alias or name of selected node in Multi node tree picker inside content tab in Umbraco V7 I'm looking for a way to show document type alias or name of selected content in Multinode tree picker inside content tab.
This will tremendously help me to quickly identify type of content attached. Also hovering a content added in MNTP inside content shows numeric path which is not quite useful, is there a way to show path names instead of id's?
Attaching image for reference.
Kindly suggest.

A: The easiest way to do this is to simply modify the MNTP property editor and have it show the extra data. It is however not really recommended to modify these files since it will be reverted every time you upgrade your Umbraco site.
There is a bit of a hacky workaround to achieve what you want however;

Angular has something called interceptors, allowing you to intercept and modify requests being made. By registrering an interceptor you could intercept the requests to contentpicker.html and redirect it to a contentpicker.html file located somewhere else - this means you will be able to just copy this file somewhere else and not modify the one in the umbraco folder being overwritten by upgrades.
Unfortunately in this case it isn't enough to just override the view being sent to the browser, since the document type alias is not actually available to that view - so the view would never be able to show the alias even if we modified it.
To work around that, you could create a copy of the contentpicker.controller.js file and create a modified version of that to use in your custom contentpicker.html view. This modified ContentPickerController would make sure to include the contentTypeAlias in the model being used in rendering the view.
All of this can be wrapped up as a "package" in the App_Plugins folder and it will be nicely separated away from being overwritten when you upgrade Umbraco, while being automatically loaded via the package.manifest file. The only caveat is that in case something is updated in the content picker code, you would have to manually merge those updates over into your custom content picker files - fortunately the content picker is rarely updated.
Place the following files in App_Plugins/CustomContentPicker/ folder and you should have what you want without actually modifying the core code:
package.manifest
{
  "javascript": [
    "~/App_Plugins/CustomContentPicker/customcontentpicker.controller.js"
  ]
}

customcontentpicker.html

    <ng-form name="contentPickerForm">

                    {{node.name}}

                    ({{node.contentTypeAlias}})

                    <localize key="open">Open</localize>
                    <localize key="edit">Edit</localize>

                    <localize key="general_add">Add</localize>

        <input type="hidden" name="minCount" ng-model="renderModel" />
        <input type="hidden" name="maxCount" ng-model="renderModel" />

            You need to add at least {{model.config.minNumber}} items

            You can only have {{model.config.maxNumber}} items selected

    </ng-form>

    <umb-overlay
      ng-if="contentPickerOverlay.show"
      model="contentPickerOverlay"
      view="contentPickerOverlay.view"
      position="right">
    </umb-overlay>

customcontentpicker.controller.js
angular.module('umbraco.services').config([
   '$httpProvider',
   function ($httpProvider) {
       $httpProvider.interceptors.push(function ($q) {
           return {
               'request': function (request) {
                   var url = 'views/propertyeditors/contentpicker/contentpicker.html';
                   if (request.url.indexOf(url) !== -1) {
                       request.url = request.url.replace(url, '/App_Plugins/CustomContentPicker/customcontentpicker.html');
                   }
                   return request || $q.when(request);
               }
           };
       });
   }]);

// Below is contentpicker.controller.js modified

//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it

function customContentPickerController($scope, dialogService, entityResource, editorState, $log, iconHelper, $routeParams, fileManager, contentEditingHelper, angularHelper, navigationService, $location) {

    function trim(str, chr) {
        var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g');
        return str.replace(rgxtrim, '');
    }

    function startWatch() {
        //We need to watch our renderModel so that we can update the underlying $scope.model.value properly, this is required
        // because the ui-sortable doesn't dispatch an event after the digest of the sort operation. Any of the events for UI sortable
        // occur after the DOM has updated but BEFORE the digest has occured so the model has NOT changed yet - it even states so in the docs.
        // In their source code there is no event so we need to just subscribe to our model changes here.
        //This also makes it easier to manage models, we update one and the rest will just work.
        $scope.$watch(function () {
            //return the joined Ids as a string to watch
            return _.map($scope.renderModel, function (i) {
                return i.id;
            }).join();
        }, function (newVal) {
            var currIds = _.map($scope.renderModel, function (i) {
                return i.id;
            });
            $scope.model.value = trim(currIds.join(), ",");

            //Validate!
            if ($scope.model.config && $scope.model.config.minNumber && parseInt($scope.model.config.minNumber) > $scope.renderModel.length) {
                $scope.contentPickerForm.minCount.$setValidity("minCount", false);
            }
            else {
                $scope.contentPickerForm.minCount.$setValidity("minCount", true);
            }

            if ($scope.model.config && $scope.model.config.maxNumber && parseInt($scope.model.config.maxNumber) < $scope.renderModel.length) {
                $scope.contentPickerForm.maxCount.$setValidity("maxCount", false);
            }
            else {
                $scope.contentPickerForm.maxCount.$setValidity("maxCount", true);
            }
        });
    }

    $scope.renderModel = [];

    $scope.dialogEditor = editorState && editorState.current && editorState.current.isDialogEditor === true;

    //the default pre-values
    var defaultConfig = {
        multiPicker: false,
        showOpenButton: false,
        showEditButton: false,
        showPathOnHover: false,
        startNode: {
            query: "",
            type: "content",
            id: $scope.model.config.startNodeId ? $scope.model.config.startNodeId : -1 // get start node for simple Content Picker
        }
    };

    if ($scope.model.config) {
        //merge the server config on top of the default config, then set the server config to use the result
        $scope.model.config = angular.extend(defaultConfig, $scope.model.config);
    }

    //Umbraco persists boolean for prevalues as "0" or "1" so we need to convert that!
    $scope.model.config.multiPicker = ($scope.model.config.multiPicker === "1" ? true : false);
    $scope.model.config.showOpenButton = ($scope.model.config.showOpenButton === "1" ? true : false);
    $scope.model.config.showEditButton = ($scope.model.config.showEditButton === "1" ? true : false);
    $scope.model.config.showPathOnHover = ($scope.model.config.showPathOnHover === "1" ? true : false);

    var entityType = $scope.model.config.startNode.type === "member"
        ? "Member"
        : $scope.model.config.startNode.type === "media"
        ? "Media"
        : "Document";
    $scope.allowOpenButton = entityType === "Document" || entityType === "Media";
    $scope.allowEditButton = entityType === "Document";

    //the dialog options for the picker
    var dialogOptions = {
        multiPicker: $scope.model.config.multiPicker,
        entityType: entityType,
        filterCssClass: "not-allowed not-published",
        startNodeId: null,
        callback: function (data) {
            if (angular.isArray(data)) {
                _.each(data, function (item, i) {
                    $scope.add(item);
                });
            } else {
                $scope.clear();
                $scope.add(data);
            }
            angularHelper.getCurrentForm($scope).$setDirty();
        },
        treeAlias: $scope.model.config.startNode.type,
        section: $scope.model.config.startNode.type
    };

    //since most of the pre-value config's are used in the dialog options (i.e. maxNumber, minNumber, etc...) we'll merge the
    // pre-value config on to the dialog options
    angular.extend(dialogOptions, $scope.model.config);

    //We need to manually handle the filter for members here since the tree displayed is different and only contains
    // searchable list views
    if (entityType === "Member") {
        //first change the not allowed filter css class
        dialogOptions.filterCssClass = "not-allowed";
        var currFilter = dialogOptions.filter;
        //now change the filter to be a method
        dialogOptions.filter = function (i) {
            //filter out the list view nodes
            if (i.metaData.isContainer) {
                return true;
            }
            if (!currFilter) {
                return false;
            }
            //now we need to filter based on what is stored in the pre-vals, this logic duplicates what is in the treepicker.controller,
            // but not much we can do about that since members require special filtering.
            var filterItem = currFilter.toLowerCase().split(',');
            var found = filterItem.indexOf(i.metaData.contentType.toLowerCase()) >= 0;
            if (!currFilter.startsWith("!") && !found || currFilter.startsWith("!") && found) {
                return true;
            }

            return false;
        }
    }

    //if we have a query for the startnode, we will use that.
    if ($scope.model.config.startNode.query) {
        var rootId = $routeParams.id;
        entityResource.getByQuery($scope.model.config.startNode.query, rootId, "Document").then(function (ent) {
            dialogOptions.startNodeId = ent.id;
        });
    } else {
        dialogOptions.startNodeId = $scope.model.config.startNode.id;
    }

    //dialog
    $scope.openContentPicker = function () {
        $scope.contentPickerOverlay = dialogOptions;
        $scope.contentPickerOverlay.view = "treepicker";
        $scope.contentPickerOverlay.show = true;

        $scope.contentPickerOverlay.submit = function (model) {

            if (angular.isArray(model.selection)) {
                _.each(model.selection, function (item, i) {
                    $scope.add(item);
                });
            }

            $scope.contentPickerOverlay.show = false;
            $scope.contentPickerOverlay = null;
        }

        $scope.contentPickerOverlay.close = function (oldModel) {
            $scope.contentPickerOverlay.show = false;
            $scope.contentPickerOverlay = null;
        }

    };

    $scope.remove = function (index) {
        $scope.renderModel.splice(index, 1);
        angularHelper.getCurrentForm($scope).$setDirty();
    };

    $scope.showNode = function (index) {
        var item = $scope.renderModel[index];
        var id = item.id;
        var section = $scope.model.config.startNode.type.toLowerCase();

        entityResource.getPath(id, entityType).then(function (path) {
            navigationService.changeSection(section);
            navigationService.showTree(section, {
                tree: section, path: path, forceReload: false, activate: true
            });
            var routePath = section + "/" + section + "/edit/" + id.toString();
            $location.path(routePath).search("");
        });
    }

    $scope.add = function (item) {
        var currIds = _.map($scope.renderModel, function (i) {
            return i.id;
        });

        if (currIds.indexOf(item.id) < 0) {
            item.icon = iconHelper.convertFromLegacyIcon(item.icon);
            $scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon, path: item.path, contentTypeAlias: item.metaData.ContentTypeAlias });
        }
    };

    $scope.clear = function () {
        $scope.renderModel = [];
    };

    var unsubscribe = $scope.$on("formSubmitting", function (ev, args) {
        var currIds = _.map($scope.renderModel, function (i) {
            return i.id;
        });
        $scope.model.value = trim(currIds.join(), ",");
    });

    //when the scope is destroyed we need to unsubscribe
    $scope.$on('$destroy', function () {
        unsubscribe();
    });

    //load current data
    var modelIds = $scope.model.value ? $scope.model.value.split(',') : [];
    entityResource.getByIds(modelIds, entityType).then(function (data) {

        //Ensure we populate the render model in the same order that the ids were stored!
        _.each(modelIds, function (id, i) {
            var entity = _.find(data, function (d) {
                return d.id == id;
            });

            if (entity) {
                entity.icon = iconHelper.convertFromLegacyIcon(entity.icon);
                $scope.renderModel.push({ name: entity.name, id: entity.id, icon: entity.icon, path: entity.path, contentTypeAlias: entity.metaData.ContentTypeAlias });
            }

        });

        //everything is loaded, start the watch on the model
        startWatch();

    });
}

angular.module('umbraco').controller("Umbraco.PropertyEditors.CustomContentPickerController", customContentPickerController);


text:
Q: How to configure custom host in Restify in Cloud9IDE? I am not able to give custom host address as process.env.IP to restify server. It is required since Cloud9 IDE works on process.env.IP & process.env.PORT
var restify = require('restify');

var server = restify.createServer({
  certificate: ...,
  key: ...,
  name: 'MyApp',
});

server.listen(8080); //process.env.PORT will go here instead of 8080

A: Cloud9 will also accept 0.0.0.0 as the IP and 8080 as the port.


text:
Q: android appwidget invalidate I have a home screen widget that tries to mimic a list of items, basically it's just 4 views in a vertical linear layout and there's 2 arrow buttons to "scroll" through list.
I'm able to scroll just fine querying the provider using limit offset, count.
The problem is that i'm using a transparent background and when i switch to the next set of results, the text of the item draws over the previous ones. It's like that view doesn't get invalidated.
Has anyone experience something like this? I tried using an opaque background and of course it works but i wanted a transparent one. I tried searching, but haven't found nothing like this.
Thanks,


text:
Q: Qual solução para o erro: "A non well formed numeric value encountered"?    function exemplo() {

    $premio = "Jose ganhou na lotérica 2.000.000,00 mais gastou
    1.000.000,00 com quanto josé ficou?
";

    echo $premio;

    $smtNumero = explode('na lotérica ',$premio);
    $primeiroArray = explode(' mais gastou 1.000', $smtNumero[1]);

    $outroExplode = explode('0 mais gastou ', $premio);
    $segundoF = explode(' com quanto josé ficou?', $outroExplode[1]);

    unset($primeiroArray[1]);
    unset($segundoF[1]);

    $final1 = str_replace (',', '.', $primeiroArray[0]);
    $final2 = str_replace (',', '.', $segundoF[0]);

    $soma = ($final1 - $final2);

    echo $soma;

}

exemplo();

Como já mencionado, o código retorna:

"A non well formed numeric value encountered"

Como solucionar este erro?

A: O problema no seu código está ocorrendo devido a variável $final1 esta recebendo uma string como valor, sendo assim gerando erro na hora do calculo, ela está recebendo esse valor: 2.000.000.00 mais gastou 1.000.000.00 com quanto josé ficou?, por isso que não funcionaria corretamente,
Eu não entendi bem qual é o objetivo desse código, certamente é para estudos, então eu vou tentar dissecar, a minha resposta, (que ficou um pouco diferente do seu), ok!
function exemplo() {

    $premio = "Jose ganhou na lotérica 2.000.000,00 mais gastou 1.000.000,00 com quanto josé ficou?
";

    echo($premio);

    $primeiro_valor = substr($premio, 25, 12);
    $segundo_valor = substr($premio, 50, 12);

    $final1 = str_replace (',', '.', str_replace ('.', '', $primeiro_valor));
    $final2 = str_replace (',', '.', str_replace ('.', '', $segundo_valor));

    $soma = ($final1 - $final2);

    echo $soma;

}

exemplo();

Em vez de usar o explode(); optei por utilizar o substr();, que ao meu ver se enquadra melhor a seu caso, com ela determinei o ponto inicial e a quantidade de caracteres que queria, após isso utilizei o str_replace(); para remover os "." e trocar as "," por ".", por que?
Porque no php se usa o ponto, e na sua lógica anterior você só estava trocando as vírgulas por pontos, sendo assim, trocando 1.000.000,00 por 1.000.000.00 isso no php se tornaria basicamente o numeral 1, pois o numero correto, para o calculo de "um milhão" seria 1000000.00, após tratar os números eu só fiz uma soma e pronto.


text:
Q: iOS simulator with auth0 ionic/react Need help with implementing Auth0 with Ionic/React. I've followed this documentation, but have not had any luck with an ios simulator.
http works fine when opening the app in the browser, but if I try and run an ios simulator, it complains that "auth0-spa-js must run on a secure origin.".

I've tried adding the simulators host and port numbers to the allowed web origins and callback urls in the Auth0 dashboard. I've tried adding a ssl cert from charles and I've tried...

ionic cap run ios -l --external --https

which starts a server running on https but the ios simulator returns "about:blank" in the developer tools.
Has anyone had any luck with getting Auth0 to work in a simulator?


text:
Q: Which Language like Instant Messenger Server I want to run Cross-Platform XMPP Instant Messenger. What Server-Side language should I choose?

A: There's also http://prosody.im/ which uses Lua. Their mission statement:

Prosody is a modern flexible communications server for Jabber/XMPP written in Lua. It aims to be easy to set up and configure, and light on resources. For developers it aims to be easy to extend and give a flexible system on which to rapidly develop added functionality, or prototype new protocols.
Prosody is licensed under the permissive MIT/X11 license.

A: If you want to use a XMPP server, take a look at Ejabberd(written in Erlang) or maybe Tigase(written in Java)
If you want to create your own, use:

*

*Twisted Matrix, a Python framework to develop asynchronous applications

*Erlang, a functional language designed with concurrency in mind.

*Java with the NIO asynchronous library

Depending on how close to the XMPP spec you want to be, C++ might be an option but it will be quite challenging, as there is a fair amount of logic to implement :-)
If you want to optimize for speed, identify the bottlenecks of your application, and look into writing specific parts in C(XML parsing or string handling).


text:
Q: Implementing sticky headers inside a FlatList in React Native I tried to implement sticky headers inside a FlatList and encountered the following error:
undefined is not an object (evaluating '_this3.state.stickyHeaderIndices')
Code Link (Snack): https://snack.expo.io/@cmcodes/forlorn-cake

A: This error is due to the fact that this is limited to use in your Explore Screen class, since you are using functional component to render list, you have to pass the sticky header data as you have passed the data i.e via props.
You can check the updated code at
https://snack.expo.io/1JtMGGDd4


text:
Q: AWS JavaScript s3Client image uploads cutting off I have an image upload service which I'm working on switching over to use Linode Cloud Storage. This is an S3-compatible storage service, so I can make uploads using the AWS JavaScript SDK. Everything is working except that my uploaded images are getting cut off abruptly.
Here's my code:
const s3 = new S3Client({
    credentials: {
        accessKeyId: [ACCESS_KEY],
        secretAccessKey: [SECRET_KEY]
    },
    region: [REGION],
    endpoint: [ENDPOINT]
});

function uploadFile(fileName, filePath) {
    return s3.send(new PutObjectCommand({
        Bucket: bucketName,
        Key: fileName,
        Body: fs.createReadStream(filePath),
        ContentType: mime.getType(filePath),
        ContentLength: fs.statSync(filePath).size,
        ACL: 'public-read'
    }));
}

The above code results in an image like this:

Very small images work, but anything over a few megabytes gets this issue. Should I be using a different method to stream the file rather than fs.createReadStream()?

A: Okay tricky one but I finally found my answer.
First I had to switch my code to use Body: fs.readFileSync(filePath) in order to get an actual error to throw in the s3Client during upload. That bit seems like a problem with the AWS SDK's s3Client failing to notice that the upload went wrong.
The error was [ERR_STREAM_WRITE_AFTER_END]: write after end, and Googling that brought me to this issue in the Linode forums.
Turns out this is a bug in Linode Cloud Storage where it responds with HTTP/1.1 100 Continue multiple times, causing s3Client to stream the upload more than once (or maybe split the upload stream into chunks? Not sure on the exact details of what s3Client is doing). The final uploaded image is incomplete.
This is the second LCS bug I've run into. I'll likely be using a different service to avoid further problems. Arguably the s3Client should be more resilient to this, but Linode's clearly doing something wrong here since other services don't see this problem. I tried a quick switch to Backblaze B2 and my code works perfectly there.


text:
Q: How can I put a cookie in Jersey RESTful webservice? I would like to put a cookie from "PUT webservice result" to "POST webservice" by Jersey API.
Here is my code
WebResource service1 = client.resource("http://test.com");

ClientResponse logResponse = service1.accept(MediaType.APPLICATION_XML).put(ClientResponse.class, "<?xml version='1.0'?><test>1</test>");

WebResource service2 = client.resource("http://test.com/post");
WebResource.Builder builder = service2.getRequestBuilder();

for(Cookie c : logResponse.getCookies())
{
if(c.getName().equals("SESSID"))
    builder = builder.cookie(c);
}

ClientResponse test = builder.accept(MediaType.TEXT_XML).post(ClientResponse.class, "<?xml version='1.0'?><post>abc</post>");

I thought If I set a cookie by "Builder.cookie" method, the cookie value will be added on the header of request for POST web service.
So, in this case, the cookie from the PUT web service will be set into POST web service.
However, if I check the header(by logResponse.getHeaders() and test.getHeaders() methods) after two web services, first PUT web service has the Cookie but second POST web service does not have any cookies.
Anybody can help me to keep a cookie between two web services?

A: The server sets the cookie only once (i.e. only the first response has Set-Cookie header). Once the client gets the cookie, it should attach it to it's requests, but the server no longer sends the cookie in the responses. That's normal behavior. So not sure what problem you are trying to solve.
Here is how you can write a Jersey filter that will make sure it adds the cookies set by the server to every request: Jersey Client: Adding Cookies to Request


text:
Q: Custom annotation binding in Spring Controller Let's say I have the following method in my Controller:
@RequestMapping(method = {RequestMethod.GET}, value = "")
@ResponseBody
public Object getObject(@MyAnnotation String value) {
   log.debug(value) //value is populated
   ...
}

How would I go about binding something from the request to this annotated value? Does Spring offer any hooks into the binding process? Would be great if someone could point me to the right direction.
Thanks!

A: Yes, you can.
Spring uses the HandlerMethodArgumentResolver (you can see the default ones in the All Known Implementing Classes area of the javadoc) interface to decide what to pass into your controller method.
You can create and register your own HandlerMethodArgumentResolver to find your annotation.
public class MyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(MyAnnotation.class) != null;
    }

    public Object resolveArgument(MethodParameter parameter,
                           ModelAndViewContainer mavContainer,
                           NativeWebRequest webRequest,
                           WebDataBinderFactory binderFactory) throws Exception {
        // do something about it
    }
}

Spring iterates through a List<HandlerMethodArgumentResolver> of registered resolvers (some default, some custom registered), calling supportsParameter(). It uses the first one it finds that supports the parameter in question.
To register with programmatic configuration, you can extend WebMvcConfigurationSupport and override its method
@Configuration
public class DispatcherContext extends WebMvcConfigurationSupport {
    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new MyHandlerMethodArgumentResolver());
    }
}

On a side note, you can do the same thing for handler method return values with HandlerMethodReturnValueHandler.


text:
Q: Is it mandatory to reindex all indexes everyday? Is it mandatory to reindex all indexes everyday? What are the mandatory ones and what are the optional ones? Below is the crontab details I have and I see some indexers run and some don't. The ones with Jan 7 date were run manually by reindex command yesterday.
* * * * * /usr/bin/php -f /home/site/web/site.com/public_html/bin/magento cron:run &> /dev/null
* * * * * /usr/bin/php -f /home/site/web/site.com/public_html/update/cron.php &> /dev/null
* * * * * /usr/bin/php -f /home/site/web/site.com/public_html/bin/magento setup:cron:run &> /dev/null

A: No you don't have to run indexing everyday, you only have to run when any index will be invalidated. As per screenshot it seems your indexing will run when you update and save any module like when you save any product, product related indexing will run i.e product flat data and so on.
Reindexing can be performed in two modes:
Update on Save - index tables are updated immediately after the dictionary data is changed.
Update by Schedule - index tables are updated by cron job according to the configured schedule.
To set these options:

*

*Log in to the Magento Admin .

*Click System > Index Management.

*Select the checkbox next to each type of indexer to change.

*From the Actions list, click the indexing mode.

*Click Submit.

You can reindex by:
Using a cron job, which is preferred because indexing runs every minute.
Using the magento indexer:reindex [indexer] command, which reindexes selected indexers, or all indexers, one time only.
So I think you have to change indexer mode to Using a cron job so you don't have to bother about indexing manually daily.


text:
Q: What am I not understanding about SQL MAX()? Data: (log_time is a DATETIME type)
log_id  | action      | log_time            | user
--------------------------------------------------
1         Processed     2011-02-28 16:38:48   1
2         Processed     2011-03-02 16:56:43   5
3         Processed     2011-03-02 17:00:17   5
4         Processed     2011-03-03 08:59:33   5

Query:
SELECT log_time, user
FROM logs
WHERE action = "Processed"
GROUP BY action
HAVING MAX(log_time)

Result:
log_time            | user
--------------------------
2011-02-28 16:38:48   1

Clearly, this is not having the max log_time at all. If I change the query to...
SELECT MAX(log_time), user
FROM logs
WHERE action = "Processed"

Then I get, naturally:
log_time            | user
--------------------------
2011-03-03 08:59:33   1

Now, the data I obviously want is the data in row 4: March 3, but user 5. I understand that I can get this by doing a simple SELECT ... ORDER BY log_time DESC LIMIT 1. But my question is, what am I doing with these MAX() queries that isn't correct? It would seem to me that if I ran a query with a HAVING MAX() that it would give me the row that, well, had the max. What am I not understanding about how MAX() works?
Edit: To elaborate my question, basically, when I see a query...
SELECT * FROM logs WHERE action = "Processed"
GROUP BY action HAVING MAX(log_time)

... my assumption, based on how the code appears is that it will retrieve the row with the largest log_time where action is Processed. This appears to be a faulty assumption. What, then, does HAVING MAX() even mean?

A: You need to include a GROUP BY clause for the aggregate function.
SELECT MAX(log_time), user
    FROM logs
    WHERE action = "Processed"
    GROUP BY user

OR, if you're looking for a single value, don't include user at all:
SELECT MAX(log_time)
    FROM logs
    WHERE action = "Processed"

And finally, if you want the user associated with that single max value, use a subquery
SELECT l.user, l.log_time
    FROM logs l
        INNER JOIN (SELECT MAX(log_time) as max_time
                        FROM logs
                        WHERE action = "Processed") q
            ON l.log_time = q.max_time
                AND l.action = "Processed"

A: Based on the input of others, particularly Damien_The_Unbeliever, I realized that my problem was that HAVING MAX() doesn't actually do anything. It will just pipe out the date, which doesn't work as it's not being compared to anything.
When I say HAVING MAX(log_time), that translates to HAVING 2011-03-03 08:59:33, which doesn't tell the SQL what it's supposed to have, it's just a statement, like IF (5). I think. HAVING continues to be somewhat of a mystery for me, but I think this is the reason why this particular issue was causing me grief.

A: I would order by MAX(log_time) and select the top 1, since the sorting will happen anyway.

A: SELECT log_time, user
FROM logs
WHERE action = "Processed"  && log_time=(select MAX(log_time) from logs)
)

this give the output
2011-03-03 08:59:33   5

A: The HAVING-clause is used the filter GROUPS that do not meet a certain criteria. The way you have defined the criteria, the "processed"-group DOES match the HAVING clause, since its MAX(log_time) contains the maximum log_time (Or perhaps HAVING MAX(log_time) evaluates to true. Either way, it's a weird statement)...
What your probably want is to SELECT the maximum log_time, in which case the query would be:
SELECT MAX(log_time), user
FROM logs
WHERE action = "Processed"
GROUP BY action;

Now, the reason you get "1" as user is that the user-column is not part of the GROUP BY clause. This means that MySQL doesn't know which user-row that you want in your output. It could be any of the 4 rows really. So, another way to formulate the question would be:
SELECT logs.user, logs.log_time
FROM logs INNER JOIN
  (SELECT MAX(log_time) as max, action
   FROM logs
   WHERE action = "Processed"
   GROUP BY action) sub ON logs.log_time = sub.max AND logs.action = sub.action

NOTE: the SQL query that you give as an example is not a valid SQL query according to Standard SQL. It works on mysql, but that's due/thanks to how MySQL has implemented GROUP BY. In standard SQL, the only thing you can select are results of aggregate functions and/or columns mentioned in the GROUP BY clause.
So, in other database systems, you wouldn't be able to select the user-column, since it is not a GROUP BY-column and not the result of an aggregate function. In order for it to be valid Standard SQL, you'd have to write:
SELECT MAX(log_time), user
FROM logs
WHERE action = "Processed"
GROUP BY action, user -- Create groups based on both action AND user.
                      -- This allows us to SELECT the user column unambigiously.
;


text:
Q: bcc multiple addresses with swiftmailer Im using the below php code to send an email to one address and bcc 2 other addresses. It sends to the recipient fine but I can only get it to send to one of the 2 bcc addresses. (see comments in code for what ive tried)
Oddly enough though, $result comes back as 3 so it seems that its trying to send the second bcc email but it never comes through.
<?php

    $tracker='tracking@pnrbuilder.com';
    $subject = $_POST['subject'];
    $sender = $_POST['sender'];
    $toEmail=$_POST['toEmail'];
    $passedInEmail=stripslashes($_POST['message']);
    $passedInEmail=preg_replace('/ /',' ',$passedInEmail);

    require_once('swiftLib/simple_html_dom.php');
    require_once('swiftLib/swift_required.php');
    $transport = Swift_MailTransport::newInstance();
    $mailer = Swift_Mailer::newInstance($transport);
    // Create the message
    $message = Swift_Message::newInstance();
    //turn the meesage into an object using simple_html_dom
    //so we can iterate through and embed each image
    $content = str_get_html($passedInEmail);

    // Retrieve all img src tags and replace them with embedded images
    foreach($content->find('img') as $e)
        {
            if($e->src != "")
                {
                    $value = $e->src;
                    $newValue = $message->embed(Swift_Image::fromPath($value));
                    $e->src = $newValue;
                }
        }

    $message->setSubject($subject);
    $message->setFrom($sender);
    $message->setTo($toEmail);

    //this is my problem
    $message->setBcc(array('tracking@pnrbuilder.com',$sender));
    //as it is above only "sender" gets the email

    //if I change it like this:

    //$message->setBcc($tracker,$sender);
    //only "tracker" gets the email

    //same if I change it like this:
    //$message->setBcc($sender);
//$message->addBcc($tracker);

    $message->setReplyTo(array('flights@pnrbuilder.com'));
    $message->setBody($content,'text/html');

    $result = $mailer->send($message);
    if ($result=3) {
        echo 'Email Sent!';
    }
    else {
       echo 'Error!';
    }
?>

What is the proper way to do this?

A: You can find the swiftmailer tutorial here
example:
$message->setBcc(array(array('some@address.tld' => 'The Name'),array('another@address.tld' => 'Another Name')));

Try setting the names for the email addresses and see if it makes any difference.

A: This ended up being an issue on the server side, I contacted my hosting provider (GoDaddy) who were able to make some changes on their end fixing the problem. Thank you to all those who tried to help!


text:
Q: sandboxed web parts inside SharePoint 2010 Is it possible to develop a web-part in ASP.NET (framework > 2.0), to have a sandbox architecture, and deploy those web parts inside Share Point 2010 and/or MOSS 2007
we donot want to use any SharePoint dll reference with web parts we develop.
we refer to the url, section at  http://msdn.microsoft.com/en-us/library/ee539417.aspx (section Web Parts in Sandboxed Solutions)

A: i referred the following How Tos, hope it helps some one ..

*

*http://blah.winsmarts.com/2009-12-SharePoint_2010_Sandboxed_Solutions__The_basics.aspx

*_http://www.sharepointdevwiki.com/display/sp2010/SharePoint+Sandboxed+Solutions

*_http://www.endusersharepoint.com/EUSP2010/2010/04/05/introduction-to-sharepoint-2010-sandbox-solutions-for-site-collection-owners

A: I've just hit this problem - looks like it's not meant to be possible which is really annoying.
See: http://msdn.microsoft.com/en-us/library/gg615454.aspx
Specifically:

Application pages, mobile pages, and user controls (.ascx files) cannot be deployed in a sandboxed solution.

However, there is a workaround (hackaround!) here:
http://stefan-stanev-sharepoint-blog.blogspot.com/2010/02/visual-sandbox-web-parts-possible-after.html
I'd love to have a better way!


text:
Q: drop=FALSE does not work for geom_tile when I have some 0 counts for some intervals The following codes first generate some dummy data, and the values may not fall into all intervals I set up. In other words, there are some 0 counts for certain intervals. When it comes to draw a ggplot geom_tile, every thing is in a mess. I used scale_fill_manual(values=rev(rbPal(break1)), labels=rev(cuts),drop=FALSE), where drop=FALSE should fix the problem, but it did not. This code is a complete program you could try on your computer.
library(data.table)
library(ggplot2)
# we build some dummy data to table dt$y, total data contains n=15*24+3
set.seed(1)
n= 15*24 + 3
dt <- data.table(t=0:(n-1))
dt[, y := c(rep(c(1,2,3),times=5*24),9,9,9)]

# create t_in_day,day in table dt, which we will use them to locate x and y later
dt[,t_in_day := t%%24]
dt[,day := (floor(t/24)+1)]
dt2 <- copy(dt)
dt2[,day := day-1]

dt2[,t_in_day := t_in_day + 24]
dt <- dt[day<max(day)]
dd <- rbind(dt, dt2)
dd <- dd[day>0]

dd[, day_str := sprintf("day\n%03d",day)]

dd[, day_str := as.ordered(day)]
dd[, day_str := ordered(day_str,levels=rev(levels(day_str)))]

#create 10 different color panels and assign user defined intervals to corresponding colors
rbPal <- colorRampPalette(c("white","green"))
breakvect<-seq(0,10,by=1)
break1<-(length(breakvect)-1)
dd[,col1 := rbPal(break1)[as.numeric(cut(dd[,y],breaks = breakvect))]]

#label and store the intervals in cuts
cuts<-levels(cut(dd[,y],breaks = breakvect))
cuts<-gsub(","," - ",cuts)
cuts<-gsub("\\(","[",cuts)

#check the data I generated first fall to how many intervals defined by the user
print(length(unique(col1)))
print(dd)
#the graph are not created successfully even when we use drop=FALSE, everything is in a mess
ggplot(dd,aes(t_in_day,y=day_str,fill=col1)) +
geom_tile(aes(fill=col1))+
scale_x_continuous(name="time (h)",breaks = 0:(8 * 6)) +
scale_y_discrete(name="starting day") + # scale_fill_gradient(low = "white", high = "limegreen")
scale_fill_manual(values=rev(rbPal(break1)),labels=rev(cuts),drop=FALSE)


text:
Q: c++ read lines from csv and split elements by comma Below is some sample lines of a csv file.I am only interested in the second, third and fourth columns. So I want to write a c++ program to extract these elements and push them to a struct I defined. Currently I know how to get the whole line, but don't know how to get a certain column.
How can I extract these columns?
1,4872,4873,0.19109237,f,
2,4874,4875,0.2774146,f,
3,4876,4877,0.1637944,f,
4,4878,4881,0.07772251,f,
5,4881,4879,0.1285009,f,
6,4880,4881,0.13613093,f,

My code to open the file and read lines:
void ReadGraph_FromTXT()
{
        ifstream graphData("new_network.csv");
        string line;
        while (getline(graphData, line)){
                cout << line << endl;
        }
}


text:
Q: How do I replace the middle of a string? $a = "<no> 3232 </no> "

$a =~ s/<no>(.*)</no>/000/gi ;

I am expecting that $a becomes "<no> 000 </no> ", but it is not working.

A: You could forgo the fancy lookahead or lookaround assertions and come up with a slightly longer regular expression:
$str =~ s|<no>.*?</no>|<no>000</no>|gi;

It might be a little easier to read, but it's slightly counter-intuitive in that you're replacing <no>whatever</no> with <no>000</no>, i.e. you aren't just replacing the things between the <no></no>, you're replacing the whole string with another string that just so happens to have <no> and </no> in it.

A: If you just want to replace the text between the tags, then you may want to look at lookahead and lookbehind assertions. And you need to either use a regex delimiter other than "/" or escape the "/" in the regex:
$a = "<no> 3232 </no> ";
$a =~ s#(?<=<no>).*?(?=</no>)# 000 #gi;
print "$a\n";

A: Firstly, the / in  is being interpreted as the end of your pattern and that's causing syntax errors. Choose a different delimiter for your substitution operator:
s|<no>.*</no>|000|gi;

But then you have a set of capturing brackets and you're not using what they are capturing. Which makes me think that perhaps even fixing the syntax won't give you the behaviour you want. You don't want to replace the tags, so you can add those to the replacement:
s|<no>.*</no>|<no>000</no>|gi;

Or not replace them at all by using lookarounds so they aren't part of the matched text:
s|(?<=<no>).*(?=</no>)|000|gi;

But given that "it's not working" isn't a very good description of the problem, I don't know what you're expecting to see.

A: You need look-around assertions.
$a =~ s|(?<=<no> ).*(?= </no>)|000|gi;
# $a is now "<no> 000 </no> "

Have you considered reading a Perl book or two? You are not learning effectively if you have to come to Stack Overflow to ask that sort of questions that can be easily answered by reading the fine documentation.

A: Firstly, the / in the closing  is being treated as an end-quote to the regular expression. Either backslash it:
$a =~ s/<no>(.*)<\/no>/000/gi;

or use a different character to / in your regex:
$a =~ s~<no>(.*)</no>~000~gi;

Secondly, I'm guessing you're trying to parse an XML document with this and change data. I'm also guessing that you have many <no>...</no> sections in your document. The problem with the regular expression you gave is that the (.*) will match as much as possible, i.e. everything between the first <no> and the last </no> in your document, including any other tags in between. It also replaces the <no> and </no>.
You can use a non-greedy match, that is one that will match as little as possible. You can put a question mark after the * like so:
$a =~ s~<no>(.*?)</no>~000~gi;

Since this still replaces the <no>...</no>, you will probably want to put those back in:
$a =~ s~<no>(.*?)</no>~<no>000</no>~gi;

In the case where your <no> is instead a regular expression, you can't just put it into your substitution string. You can either use lookarounds as suggested by others, or just capture it and put it back in using $1..$9, like so:
$a =~ s~(<no>)(.*?)(</no>)~$1000$3~gi;

Why $3? Because $2 is whatever you captured with (.*?). Of course, since you don't actually care about what you've captured, you can just do this:
$a =~ s~(<no>).*?(</no>)~$1000$2~gi;

which is probably about as efficient as you're going to get for this problem.
As an aside, it is normally a bad idea to try to parse XML with regular expressions, because XML is too varied for regular expressions to parse. I quite like XML::LibXML for processing XML documents, but it is not at all simple to get in to. However, if you are confident about the precise format of your XML (or in fact it's not XML but just looks a bit like it) then regular expressions are OK as a local hack.
This is all covered in the perlre manpage, which is a must-read if you're going to do anything even remotely non-trivial with Perl regular expressions.
$ perldoc perlre

Hope all the examples help clarify things a bit.

A: Just to keep this as simple as possible, you have a number of problems, so lets eliminate the obvious ones first.
First, you can't use the slash character ("/") by itself in a string because it has special significance for per; for example "/n" means print a new line and the slash is also used to separate the part of the regex. When you want to use a slash as a literal, the solution is to escape the slash with a backslash to tell perl you really do want a slash character not something special. So your original code would be better written like this:
$a = "<no> 3232 <\/no> ";
$a =~ s/<no>(.*)<\/no>/000/gi;

Now perl will interpret the <\/no> as </no>
Secondly, your regex is wrong. The s/// regex instructs perl to substitute/reformat the pattern in the first section with the pattern in the second section. Your instruction as it is tells perl to substitute everything between the first two slashes with "000" and assign it to variable $a.
The brackets you used in the regex allow you to break the expression into smnaller pieces and re-arrange things but you haven't used them, however you are on the right track. To re-use the parts of the expression in the first set of slashes that you want to keep, you place brackets around them. In the second part of the expression you can refer to those "pieces" by using $1, $2 etc. to refer to the stuff within each set of brackets.
Keeping this in mind you might be tempted to come up with somethign like:
$a = "<no> 3232 <\/no> ";
$a =~ s/(<no>).*(<\/no>)/$1000$2/gi;

This is close - as suggested above - but testing will reveal that it is still not quite right; even  more mystifying the output you will get this time is </no>. This is because perl interprets the string as $1000 followed by $2 and $1000 does not refer to anything. Putting a space or something else after the $1 will correct the problem. (There's probably some way of terminating the $1 more correctly but I'll confess here that I don't know it.)
The following expression will work, but you'll get a space after the first  so your out put will be <no> 000</no>
$a = "<no> 3232 <\/no> ";
$a =~ s/(<no>).*(<\/no>)/$1 000$2/gi;

My preference would be to use a variable in place of the string "000" and for that reason my code would probably look something like this:
$a = "<no> 3232 <\/no> ";
$b = "000";
$a =~ s/(<no>).*?(<\/no>)/$1$b$2/gi;

Using a variable makes things a bit clearer in my opinion (although they could be better named!) and also allows the text to be substituted (the "000") to be easily changed without having to mess with the regex. The ? in the regex is meant to ensure that the regex doesn't get "greedy if there is more than one set of no elements in the string - this causes the .* to sstop matching as soon as it encounters the matching pattern, in this case "".


text:
Q: Get parent data based reference ID on Node.js and MongoDB I am trying to get products data based on orders products id and below is my Order Model
import mongoose from 'mongoose';

const { ObjectId, String, Number } = mongoose.Schema.Types;

const OrderSchema = new mongoose.Schema({
    user: {
        type: ObjectId,
        ref: "User"
    },
    products: [
        {
            quantity: {
                type: Number,
                default: 1
            },
            product: {
                type: ObjectId,
                ref: "Product"
            }
        }
    ],
    email: {
        type: String,
        required: true
    },
    total: {
        type: Number,
        required: true
    },
    status: {
        type: String,
        required: true,
        default: 'pending',
        enum: ["pending", "delivered"]
    }
},{
    timestamps: true
});

export default mongoose.models.Order || mongoose.model("Order", OrderSchema);

The Product Model:
import mongoose from 'mongoose';

const { String, Number } = mongoose.Schema.Types;

const ProductSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    productType: {
        type: String,
        required: true
    },
    sku: {
        type: String,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    mediaUrl: {
        type: String,
        required: true
    }
},{
    timestamps: true
});

export default mongoose.models.Product || mongoose.model('Product', ProductSchema);

And the query is like below for all orders:
const orders = await Order.find()
    .sort({ createdAt: 'desc' })
    .populate({
        path: "products.product",
        model: "Product"
    });
// console.log(orders)
res.status(200).json({ orders });

The concept is when creating an order it's creating with product id and I want to fetch the products based on the order product id.
And this way it showing

MongooseError [MissingSchemaError]: Schema hasn't been registered for model "Product".

How can I solve that?
Thanks

A: In the Order model you might be import the Product model then in the ref you use without quotation like
ref: Product

That is the way I think.
Thanks


text:
Q: modify every object in json array in mysql Json Array - [{"a":1},{"a":2}]
Is there a way that I can update/set each object in this array with a single query ?.
I can update an specific object using `
SELECT JSON_SET('[{"a":1},{"a":2}]','$[0].b','new val')

which results
[{"a": 1, "b": "new val"}, {"a": 2}]

But I need
[{"a": 1, "b": "new val"}, {"a": 2, "b": "new val"}]

. I use mysql 8.0.22

A: Here's a solution I tested:
mysql> set @j='[{"a":1},{"a":2}]';

mysql> with recursive cte as (
    select 0 as i, json_set(@j, '$[0].b', 'new val') as j
    union all
    select cte.i+1, json_set(cte.j, concat('$[',cte.i+1,'].b'), 'new val')
    from cte
    where cte.i<json_length(@j)-1
  ) select * from cte
    where i = json_length(@j)-1;
+------+------------------------------------------------------+
| i    | j                                                    |
+------+------------------------------------------------------+
|    1 | [{"a": 1, "b": "new val"}, {"a": 2, "b": "new val"}] |
+------+------------------------------------------------------+

I have to say this begs the question whether JSON is worth it. It would be far easier if you used normal rows and columns instead of JSON.

A: If you have multiple "a" then make first a JSON table and then combine it back.
With miore complicate and nested json y ou must do more work on the JSON_TABLE

SELECT JSON_SET('[{"a":1},{"a":2}]','$[0].b','new val');

| JSON_SET('[{"a":1},{"a":2}]','$[0].b','new val') |
| :----------------------------------------------- |
| [{"a": 1, "b": "new val"}, {"a": 2}]             |

SELECT
 JSON_ARRAYAGG(JSON_OBJECT("a", a, "b", "new valuze"))
     FROM
       JSON_TABLE(
         '[{"a":1},{"a":2}]',
         "$[*]" COLUMNS(
           a VARCHAR(100) PATH "$.a"
         )
       ) AS  jt1;

| JSON_ARRAYAGG(JSON_OBJECT("a", a, "b", "new valuze"))          |
| :------------------------------------------------------------- |
| [{"a": "1", "b": "new valuze"}, {"a": "2", "b": "new valuze"}] |

db<>fiddle here


text:
Q: Struggling to loop through an array of objects in particular I want to access answer's numerical value, so that later on to sum them up.
previously tried length, which is not working for objects.
here is my data:
const qData = [
    {
        id: 0,
        question: "question 1",
        answers: [
            { value: 1, text: "rafael" },
            { value: 2, text: "dontaelo" },
            { value: 3, text: "leonardo" },
            { value: 4, text: "michelangelo" }
        ]
    },
    {
        id: 1,
        question: "question 2",
        answers: [
            { value: 1, text: "rafael" },
            { value: 2, text: "dontaelo" },
            { value: 3, text: "leonardo" },
            { value: 4, text: "michelangelo" }
        ]
    }
];

export default qData;

I attempted to sum the answer values like so:
handleShowScore = () => {
  var i, newScore;
  var a = qData.answers;

  for (i = 0; i < a.length; i++) {
    newScore = newScore + a[i].value;
  }
}

A: The sample below does what you want, if I understood your question correctly
// Loop through all questions. Each question is stored in "q".
qData.forEach((q) => {
  console.log('qData:', q);

  // Make an array of all answer values
  const answerValues = q.answers.map((a) => {
     return a.value;
  });
  console.log('answerValues:', answerValues);

  // Sum all answer values together
  const totalValues = answerValues.reduce((a, b) => a + b, 0)
  console.log('totalValues: ', totalValues);
});

If you want to have the sum of a specific ID
// Find specific ID.
const question = qData.find((q) => q.id === 0);

// Make an array of all answer values
const answerValues = question.answers.map((a) => {
   return a.value;
});
console.log('answerValues:', answerValues);

// Sum all answer values together
const totalValues = answerValues.reduce((a, b) => a + b, 0)
console.log('totalValues: ', totalValues);

A: qData is an array and doesn't have the property answers, so qData.answers will not work and return undefined.
You first have to loop over the questions, then in each question you'll have to loop over the answers:

const qData = [{id:0,question:"question 1",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]},{id:1,question:"question 2",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]}];

let sum = 0;
for (const question of qData) {
  for (const answer of question.answers) {
    sum += answer.value;
  }
}

console.log(sum);

You could do this reduce the amount of loops if you use flatMap. Pulling up the answers into one large array.

const qData = [{id:0,question:"question 1",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]},{id:1,question:"question 2",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]}];

const answers = qData.flatMap(question => question.answers);

let sum = 0;
for (const answer of answers) {
  sum += answer.value;
}

console.log(sum);

Instead of using a for loop to sum the values you could also use reduce, which iterates over an array reducing it to a single value.

const qData = [{id:0,question:"question 1",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]},{id:1,question:"question 2",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]}];

const answers = qData.flatMap(question => question.answers);
const sum = answers.reduce((sum, answer) => sum + answer.value, 0);

console.log(sum);

A: It's kind of a quiz, right? Let's assume my answers are:
const myAnswers = [{question: 'question 1', myAnswer:'rafael'},{question: 'question 2', myAnswer:'dontaelo'}]

I should have 1 point from the first question, and 2 from the second. We need to go through 2 loops: 1 to find the corresponding question, 1 to find the corresponding number of points:
const myPoints = myAnswers.map(answer => qData.find(question => question.question === answer.question).answers.find(possibleAnswer => possibleAnswer.text === answer.myAnswer).value)

Thats gives me [ 1, 2 ]. Now we need to to the sum with reduce:
const reducer = (accumulator, currentValue) => accumulator + currentValue;
const myScore = myPoints.reduce(reducer, 0);

I have 3 points ;-)


text:
Q: favicon not showing on inner pages of magento In one of my magento website I have added favicon using

magento admin panel > system > configuration > design > HTML head > favicon icon

It was displaying nicely in magento home page but not showing in inner pages. I have changed the current configuration scope to store view and did the same proccess. still it is not working. I hacve cleared caches and re-indexed. but it is not working.
Why is it so? How can I solve this?
Thank you.

A: @ jatinder kumar you may need this only?
<link rel="icon" href="http://navaani.in/media/favicon/stores/17/favicon_1.png" type="image/x-icon">
<link rel="shortcut icon" href="http://navaani.in/media/favicon/stores/17/favicon_1.png" type="image/x-icon">
<link rel="shortcut icon" href="http://navaani.in/skin/frontend/base/default/images/dresscode_images/favicon.ico">

<link rel="apple-touch-icon" href="http://navaani.in/skin/frontend/base/default/images/dresscode_images/apple-touch-icon.png">

<link rel="apple-touch-icon" sizes="72x72" href="http://navaani.in/skin/frontend/base/default/images/dresscode_images/apple-touch-icon-72x72.png">

<link rel="apple-touch-icon" sizes="114x114" href="http://navaani.in/skin/frontend/base/default/images/dresscode_images/apple-touch-icon-114x114.png">

<link href="//fonts.googleapis.com/css?family=Amaranth:200,300,400,500,600,700,800" rel="stylesheet" type="text/css">

Ask me if you want more. Thank you.

A: We experienced similar.  We resolved this (if I'm understanding your issue correctly) by overwriting the default favicon.ico in the root folder with ours.
Note, browser caching in relation to favicon.ico is extremely zealous :)  As such, you will probably only see the change by opening the site in a browser you haven't opened the site in previously or on a different machine.


text:
Q: Deriving the field-equation for the electromagnetic field in modified theory Given the lagrangian density written in the following form
$$
\mathcal{L} \propto \frac{\mathcal{L}_{(EM)}^2}{R}
$$
where $R$ stands for the Ricci tensor and $\mathcal{L}_{(EM)}$ stands for the usual electromagnetic matter lagrangian defined as
$$
\mathcal{L}_{(EM)} = -\frac{F^2}{2}.
$$
The field equation for $A_{\mu}$, using the Euler-Lagrange equation follows:
$$
\frac{1}{4}\partial_{\lambda}\frac{\partial \mathcal{L}_{(EM)}^2}{\partial(\partial_{\lambda}A_{\rho})} = \frac{1}{4} \partial_{\lambda} \frac{\partial}{\partial(\partial_{\lambda}A_{\rho})} (F^{\mu \nu}F_{\mu \nu} F^{\alpha \beta}F_{\alpha \beta}) = \frac{1}{4} \partial_{\lambda} \left( \frac{\partial(F^{\mu \nu}F_{\mu \nu}) F^{\alpha \beta}F_{\alpha \beta}}{\partial(\partial_{\lambda}A_{\rho})} + F^{\mu \nu}F_{\mu \nu} \frac{\partial(F^{\alpha \beta}F_{\alpha \beta}) }{\partial(\partial_{\lambda}A_{\rho})} \right)
$$
from the standard derivation of Maxwell's equation:
$$
 = \frac{1}{4} \partial_{\lambda} ( 4 F^{\lambda \rho} F^2 + 4 F^2 F^{\lambda \rho}) = 4 \partial_{\lambda} (F^{\lambda \rho} F^2)
$$
therefore, the field equation is
$$
\nabla_{\lambda} (F^{\lambda \rho} F^2) = 0.
$$
(Where, clearly, the other term depending on $A_{\mu}$ in the Euler-Lagrange equation vanishes)
Is this procedure correct? What about the other Maxwell equation (that usually reads $\nabla_{[\alpha}F_{\beta \gamma]} = 0$)?


text:
Q: How to access RAM for use with an FPGA for high performance computing I am exploring the idea of using an FPGA for linear algebra. I would like the ability to work on large matrices (> 4 GB). But modern high-end FPGAs have RAM on the order of megabytes.
Please describe how I may either:

*

*add external RAM chip

*access and use RAM of a connected pc

Any other comments or feedback is welcome.
I currently have a Digilent basys2. I am a beginner.

A: For a variety of reasons, the Digilent Basys2 and the Xilinx Spartan-3E are not going to work for you.
For that amount of RAM, you will need something like DDR2 or DDR3 SDRAM running at a fairly high clock rate.  This is not something that you can just solder down onto a prototype PCB.  The PCB needs to be designed for interfacing to memory, ideally with the RAM already soldered down onto the PCB.  If you have never designed such a circuit, I suggest you get an FPGA board that already has the RAM on it.  This is going to be difficult, however, since all of the FPGA boards I saw (in 5 minutes of looking) had much less than 4 GB of RAM.
Next, you need something newer than the Spartan-3/3A/3E.  While the S3 is an otherwise good FPGA, the Spartan-6 series has much more to offer you.  It has much more internal RAM (but you still need external RAM), a lot more DSP48 blocks, and more logic.  But most important, it has a much better SDRAM interface on it than what the Spartan-3 has.  And by "much better", I mean "much easier for a beginner to successfully use".  The memory controller in the S6 is a hard-IP, which for you means that it is much easier to achieve the strict timing requirements of interfacing to SDRAM.
But controlling DDR2/DDR3 SDRAM is not easy.  Xilinx has a tool called the "Memory Interface Generator", which can be found in Core Generator.  This will generate the memory interface logic for you, and gives you lots of cool features that will make your life easier.
An alternative to the Spartan-6 would be a Virtex-5 or any of the 7-series parts.  All of these have memory interfaces as good or better than the Spartan-6.
This Virtex-7 based board has a socket for two SO-DIMM modules, which could get you past 4 GB of RAM-- but it is super expensive at US$5,000.
I should also mention that if you are doing this because you want to learn about FPGAs and electronics then I support your efforts.  But if you think that this is somehow going to be faster than standard PC's then I have bad news for you. For the money, it is hard to beat an Intel i7 based quad-core machine with a reasonable GPU card.  Just warning you, in case all you really care about is math speed.


text:
Q: how to serialize a nested json inside a graphene resolve? I am studying the library graphene, (https://github.com/graphql-python/graphene) and I was trying to understand how I can serialize / return a nested json into the graphene and perform the query in the correct way.
The code that I will insert below follows the example of the link available in the repository (it is at the end of the question).
import graphene
from graphene.types.resolver import dict_resolver

class User(graphene.ObjectType):
    id = graphene.ID()

    class Meta:
        default_resolver = dict_resolver

class Patron(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()
    age = graphene.Int()
    user = User

    class Meta:
        default_resolver = dict_resolver

class Query(graphene.ObjectType):

    patron = graphene.Field(Patron)

    @staticmethod
    def resolve_patron(root, info):
        return Patron(**{"id":1, "name": "Syrus", "age": 27, "user": {"id": 2}})

schema = graphene.Schema(query=Query)
query = """
    query something{
      patron {
        id
      }
    }
"""

if __name__ == "__main__":
    result = schema.execute(query)
    print(result.data)

The idea is basically to be able to use a multi-level json to "resolve" with graphql. This example is very simple, in the actual use case I plan, there will be several levels in json.
I think that if you use the setattr at the lowest level of json and go up, it works, but I would like to know if someone has already implemented or found a more practical way of doing it.
original example:
https://github.com/graphql-python/graphene/blob/master/examples/simple_example.py


text:
Q: PHP - объединить по значению элементов в массиве Как в массиве
array(4) {
[0]=> string(21) "itd-sd|100.99.22.12"
[1]=> string(32) "itd-sd.site.ru|100.99.22.12"
[2]=> string(21) "mt-sd|192.168.0.1"
[3]=> string(32) "mt-sd|192.168.0.22"
}

Объединить по значению элементов, чтобы был вот такой результат:
array(2) {
    [0]=> string(21) "itd-sd|100.99.22.12|itd-sd.site.ru"
    [1]=> string(21) "mt-sd|192.168.0.1|192.168.0.22"
    }

Т.е мне нужно если в значении элементов есть общее значение - то "склеить" эти элементы в один через разделитель. В первом случае объединяем по значению "100.99.22.12", во втором случае "mt-sd". Натолкните на вариант решения.

A: Вот вам заготовка, дальше думайте над критериями
$arr = [
"itd-sd|100.99.22.12",
"itd-sd.site.ru|100.99.22.12" ,
"mt-sd|192.168.0.1" ,
"mt-sd|192.168.0.22"
];

$res = [];
$arr = array_map(function ($x) { return explode('|', $x); }, $arr);
for($i=0; $i<count($arr); $i++) {
    for($j= $i+1; $j<count($arr); $j++) {
        if(array_intersect($arr[$i],$arr[$j])) {
            $res[] = implode('|', array_unique(array_merge($arr[$i],$arr[$j])));
        }
    }
}
print_r($res);

[
    [0] => itd-sd|100.99.22.12|itd-sd.site.ru
    [1] => mt-sd|192.168.0.1|192.168.0.22
]


text:
Q: loop to traverse subdirectories and execute a perl script into each subdirectory I have a parent directory with multiples subdirectories like this
Parent_directory
    subdirectory_1
        perlscript.pl
        file.fasta
    subdirectory_2
        perlscript.pl
        file_2.fasta

And I would like to run the perl scipt in each subdirectory. I'm trying with the next command
find . -type d | while read d; do perl hoz-3-v1c.pl $d/* ; done

but the output is directed to the parent directory and I want the output in each subdirectory

A: It looks like you don't have to bother with find at all in this instance.
for dirpath in Parent_directory/*/; do
    ( cd "$dirpath" && perl perlscript.pl *.fasta )
done

This assumes that the Perl script is always called perlscript.pl (as in your example directory layout) and that correct way to run your Perl script inside each directory is
perl perlscript.pl *.fasta

In the loop above, the parentheses creates a subshell.  This prevents the cd from affecting the rest of the script and we don't have to cd back out of the directory after running the Perl script.
The loop will iterate over all subdirectories of Parent_directory and execute the given commands in each.

A: If your find supports the -execdir predicate (GNU, BSDs at least):
find . -name perlscript.pl -execdir sh -c 'exec perl ./perlscript.pl *.fasta' \;

searches for the perlscript.pl files and runs perl on it with the current directory set to the directory where it's found.
We need a shell to expand the *.fasta glob.


text:
Q: MFC: Delete elements from GUI After tinkering and modifying a GUI I have been working on for some time I ended up with a group of EditControllers and Radio Buttons that I do not need any more, so I would like to get rid of them. However, if I simply delete them from the GUI edit, I get assertion errors. How am I supposed to get rid of these elements?

A: You need to remove all code from your program that refers to the deleted controls. For each control you want to delete, take its ID and search the source for statements that refer to it.

A: Start like this:

*

*Check the ID of that given control. Copy it. Now remove the control from dialog resource.

*Ensure that ID is not used by other dialogs. If not, you can use following.

*Delete that ID from resource.h.

*When you compile it, you'd get error (around GetDlgItem, DDX_Control etc). Remove or comment them. Remove appropriate CWnd-derived variables (like CEdit, CComboBox etc).

*You are done!

If given ID is used by other dialogs (check it from Resource View's context menu Resource Symbols...), then you cannot directly remove it from resource editor. You, however, need to remove it from appropriate implementation file (of CDialog/CPropertyPage-derived class).


text:
Q: Go can't set string to struct This code is get all objects from s3 and delete objects.
getAllObjects is called from DeletePhotosFromS3.
I cloud get 2 different keys in objects that is in DeletePhotosFromS3.
But deleteObjects have 2 same keys. ex [{Key: 1}, {Key: 1}].
Why deleteObjects have 2 same keys and how to set objects in []*s3.ObjectIdentifier?
func getAllObject(userID string) (*[]string, error) {
    var objects []string

    svc := initS3()
    config := model.NewConfig()

    input := &s3.ListObjectsInput{
        Bucket:  aws.String(config.AWSS3Bucket),
        Prefix:  aws.String(userID),
        MaxKeys: aws.Int64(2), // default 1000
    }

    result, err := svc.ListObjects(input)
    if err != nil {
        return &objects, err
    }

    for _, v := range result.Contents {
        objects = append(objects, *v.Key)
    }

    return &objects, nil
}

func DeletePhotosFromS3(userID string) (error) {
    var deleteObjects []*s3.ObjectIdentifier

    svc := initS3()
    config := model.NewConfig()

    objects, err := getAllObject(userID) // called getAllObject
    for _, v := range *objects {
        deleteObjects = append(deleteObjects, &s3.ObjectIdentifier{Key: &v}) // Er
    }
    ...
}

A: The iteration value v in your for loop is reused for each iteration. The Pointer &v will be the same for each item appended to the list. Fixed snippet:
for _, v := range *objects {
        vcopy := v
        deleteObjects = append(deleteObjects, &s3.ObjectIdentifier{Key: &vcopy})
}


text:
Q: Magento1 - Show catalog products only to logged-in customer I want to show product1 is only to the logged in customers and this product is not visible in STORE view.
Does anyone have a solution for this?
Thanks.

A: First you have to create one attribute to product for its visibility condition.
use catalog_product_collection_load_before event to filter the product collection based on user is logged in or not.
take a look at this question for more detail.
probably not best solution but can be helpful to start.