text:
Q: Передача данных из БД в функцию Django Я хотел бы получать данные из БД, подставлять их в API запрос и размещать результат на странице. Есть БД, в ней есть поля серия и номер паспорта. Хотелось бы реализовать функционал подстановки серии и номера паспорта в функцию, которая производит API запрос к серверу.
Models.py
from django.db import models
class client(models.Model):
    family = models.CharField('Фамилия', max_length=25)
    name = models.CharField('Имя', max_length=25)
    patronymic = models.CharField('Отчество', max_length=25)
    serial = models.CharField('Серия паспорта', max_length=25)
    number = models.CharField('Номер паспорта', max_length=25)

jsonparse.py
import requests

def parsej(x, y):
    URL = "url"
    headers_auth = {
        "serial": x,
        "number": y
    }
    result = requests.post(URL, json=headers_auth)
    content = result.json()

    return content

print(parsej('53 03', '244787'))

Как передать значение из БД SQlite в функцию Python?

A: Если django то у вас должен быть файл views.py в котором вы создаете функции контроллеры для обращения к БД за данными и к внешним источникам. Таким образом вы можете написать примерно следующее, предполагая что parsej у вас в файле utils.py в каталоге с models.py и views.py данного приложения django
# views.py

from .utils import parsej

def get_data(request):
    if request.method == "GET":
        passport_info = client.objects.get(1)
        result = parsej(x=passport_info.serial, y=passport_info.number)
        # обработка результата
        context = {"passport_info":passport_info, "result": result}
        return render(request, "app/view_info_by_passport.html", context=context)

# urls.py

from django.contrib import admin
from django.urls import path
from .views import get_data

urlpatterns = [
    path('', get_data, name="get_data"),
    ...
]

<!-- view_info_by_passport.html -->

<html>
<body>
<h3>{{passport_info.serial}} {{passport_info.number}}</h3>
{{result}}
</body>
</html>

Так же возможно на странице нужно будет выбирать конкретного человека из списка или в функции get_data проверять авторизацию пользователя и для него запрашивать данные с сервера API, но это уже другой вопрос.


text:
Q: Problems with the `graphs` library According to the documentation for version 3.0.0 of PGF/TikZ (Section 19 Specifying Graphs, page 258), the powerful graphs library:

[...] offers a powerful path command for specifying how the nodes in a
  graph are connected by edges and arcs: The graph path command, which
  becomes available when you load the graphs library.

A few lines below there are some examples of the use of the path; amongst those examples one finds:
\tikz
  \graph [nodes={draw, circle}, clockwise, radius=.5cm, empty nodes, n=5] {
    subgraph I_n [name=inner] --[complete bipartite]
    subgraph I_n [name=outer]
};

and
\tikz
\graph [nodes={draw, circle}, clockwise, radius=.75cm, empty nodes, n=8] {
subgraph C_n [name=inner] <->[shorten <=1pt, shorten >=1pt]
subgraph C_n [name=outer]
};

which should produce the following images (taking directly from the documentation):

However, when I try the exact same code in a "real" document:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{graphs}

\begin{document}

 \tikz
  \graph [nodes={draw, circle}, clockwise, radius=.5cm, empty nodes, n=5] {
    subgraph I_n [name=inner] --[complete bipartite]
    subgraph I_n [name=outer]
};
\tikz
  \graph [nodes={draw, circle}, clockwise, radius=.75cm, empty nodes, n=8] {
    subgraph C_n [name=inner] <->[shorten <=1pt, shorten >=1pt]
    subgraph C_n [name=outer]
};

\end{document}

This is all I get (image zoomed at 400%):

Even more disppointing is the following example on page 276:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{graphs}

\begin{document}

\tikz \graph [simple] {
subgraph K_n [n=8, clockwise];
% Get rid of the following edges:
1 -!- 2;
3 -!- 4;
6 -!- 8;
% And make one edge red:
1 --[red] 3;
};

\end{document}

The documentation shows this as the result:

but I only get an error message:
! Missing $ inserted.
<inserted text>
$
l.15 }
    ;
?

Am I missing something? Is some other library required in order to get the expected graphs?

A: Based on looking through the pgf documentation's LaTeX source and also this answer, I believe that the documentation should list that both the graphs and graphs.standard libraries are included to produce these graphics.
All your examples work if I use \usetikzlibrary{graphs,graphs.standard} instead of only \usetikzlibrary{graphs}. Here is one sample:
Code
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{graphs,graphs.standard} % both are required, in this order

\begin{document}
\tikz \graph [simple] {
  subgraph K_n [n=8, clockwise];
  % Get rid of the following edges:
  1 -!- 2;
  3 -!- 4;
  6 -!- 8;
  % And make one edge red:
  1 --[red] 3;
};
\end{document}

Output

redpajama_set_name: RedPajamaStackExchange


text:
Q: Measuring last-level cache misses through PAPI on AMD machine running Ubuntu Linux It looks like by default PAPI (Performance Application Programming Interface) is not supporting to measure last-level cache misses (L3) on my AMD machine running Ubuntu Linux. However, I can measure L1/L2 cache misses. You can see the details of the processor below. I heard that it is possible to measure last level cache misses if install appropriate driver. Could some one provide me more information about this, please?
$ uname -a
Linux 2.6.32-21-server #32-Ubuntu SMP Fri Apr 16 09:17:34 UTC 2010 x86_64 GNU/Linux

$cat /proc/cpuinfo
processor   : 0
vendor_id   : AuthenticAMD
cpu family  : 16
model       : 8
model name  : Six-Core AMD Opteron(tm) Processor 8431
fpu     : yes
fpu_exception   : yes
cpuid level : 5
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nonstop_tsc extd_apicid pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt
bogomips    : 4788.66
TLB size    : 1024 4K pages
clflush size    : 64
cache_alignment : 64
address sizes   : 48 bits physical, 48 bits virtual
power management: ts ttp tm stc 100mhzsteps hwpstate

A: Try using Valgrind's cache grind profiler or perf or perf expert.
All of these will give LastLevel cache details as L3 turns out to be in most of the cases.
You need to load all these modules.
Command for executing:
VALGRIND:
valgrind --tool=cachegrind ./exe

PERFEXPERT:
perfexpert_run_exp ./exe

PERF:
perf stat -e <hardware counter> ... -e <hardwarecounter> ./exe

A: you can also use perf tool. first you need to check whether your counters are able to count last level cache misses or not by using "perf list" command. then you can read them with perf_record..


text:
Q: Best way when using prepared statement in nested loop When executing multiple queries in nested loops what is the best way? I have a code like follows:
String sql1 = SQLContainer.SOME_SQL;
String sql2 = SQLContainer.SOME_SQL2;
    if (someThings != null) {
        for (Some some : someThings) {
            ps = con.prepareStatement(sql1);
            ps.setString(1, some.name);
            ps.setString(2, some.type);
            ps.executeUpdate();

            if (some.getParams != null) {
                for (Some2 some2 : some.params) {
                    ps = con.prepareStatement(sql2);
                    ps.setString(1, some2.name);
                    ps.setString(2, some2.value);
                    ps.setString(3, some2.type);
                    ps.executeUpdate();
                }
            }
        }
    }

*

*Is it ok to use like that?

*Should I make 2 diferent loop, one for sql1 and one for sql2?

*Should I create 2 different methods for different loops?

*Or what should i do?

The sqls are just insert statements and two sqls are somehow related with each other. I dont want to insert somes when i get error from some.params too.

A: SQL in a loop will have bad performance unless you do it right.
In your case, I'd strongly suggest to use batched SQL.
This would look like this for your first loop:
    int p1Count = 0;
    int BATCHSIZE = 1000;
    if (something) {
            PreparedStatement ps1 = con.prepareStatement(SQLContainer.SOME_SQL);
            for (Some some : someThing) {
                ps1.setString(1, some.name);
                ps1.setString(2, some.type);
                ps1.addBatch();
                if(++p1Count % BATCHSIZE == 0) {
                    ps1.executeBatch();
                }
                ...
            }
            ps1.executeBatch();

Just the same, you should split up your loops to do one kind of SQL at a time - so first do all the updates for some then (in second loop) do all the updates for some2
As long as you keep this within one transaction, you're fine.
You could probably keep the nested code as well - but your counters for s1 and s2 would be independent, so you really should not do that with autocommit on as there'd be no way of telling which items have been processed and which not.
In that case you'd end up with something like
        int p1Count = 0;
        int p2Count = 0;
        int BATCHSIZE = 1000;
        if (something) {
            try(PreparedStatement ps1 = con.prepareStatement(SQLContainer.SOME_SQL);
                   PreparedStatement ps2 = con.prepareStatement(SQLContainer.SOME_SQL2)) {
              for (Some some : someThing) {
                ps1.setString(1, some.name);
                ps1.setString(2, some.type);
                ps1.addBatch();
                if(++p1Count % BATCHSIZE == 0) {
                    ps1.executeBatch();
                }
                if (somethingElse) {
                    for (Some2 some2 : some.param) {
                        ps2.setString(1, some2.name);
                        ps2.setString(2, some2.value);
                        ps2.setString(3, some2.type);
                        ps2.addBatch();
                        if(++p2Count % BATCHSIZE == 0) {
                            ps2.executeBatch();
                        }
                    }
                }
              }
              p2.executeBatch();
              p1.executeBatch();
            } //End try-with-resource
        }

A: Put this in a private function and pass the parameters i.e. sql1, some.name, some.type
ps = con.prepareStatement(sql1);
ps.setString(1, some.name);
ps.setString(2, some.type);
ps.executeUpdate();

Based on the condition call the same function with different parameters.


text:
Q: How to convert ZonedDateTime/OffsetDateTime to Date using ThreeTenABP? Using the ThreeTen Android Backport library, what is the simplest way to convert a ZonedDateTime or OffsetDateTime into an old-school java.util.Date instance?
If I had full Java 8 libs at my disposal, this of course would be the way to do it (as in this question):
Date.from(zonedDateTime.toInstant());

But I cannot use that on Android; specifically Date.from(Instant instant) is missing.

A: Well, one straightforward way is to get milliseconds since epoch and create the Date from that:
long epochMilli = zonedDateTime.toInstant().toEpochMilli();
Date date = new Date(epochMilli);

Feel free to point out if there's some preferable way.

A: See DateTimeUtils which handles the methods added to classes like java.util.Date:
http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/DateTimeUtils.html
Edit: using that, the complete code would be:
DateTimeUtils.toDate(zonedDateTime.toInstant())


text:
Q: Why is RegionMeasure so slow when calculating intersection area of a 2D and a 3D object? If you think this description is too long, you can read the problem directly
I know normally when one wants to calculate an region, this guide is useful. However, when it comes to calculating an intersection of a plane and a solid figure, this Integrate and Boole method seems to be complicated.
Since version 10, there are some new function related with Regions, which provide a more elegant way to express the problem, so I hoped to solve the problem this way.
Here is an example problem(from somewhere else). Suppose we want to calculate the intersection area of a tetrahedron and a plane. The classical way to solve would be like this:
Show[RegionPlot3D[
2 Sqrt[3] x + 6 y + Sqrt[6] z <= 3 &&
3 + 6 y >= 2 Sqrt[3] x + Sqrt[6] z &&
3 + 4 Sqrt[3] x >= Sqrt[6] z && 1 + Sqrt[6] z >= 0, {x, -2,
2}, {y, -2, 2}, {z, -2, 2}, PlotPoints -> 100],
ContourPlot3D[
Sqrt[3] x == 3 y + Sqrt[6] z, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]]

And an classical way to solve would be like this (code taken from somewhere else):
Block[{dA, z},
z = z /. Solve[Sqrt[3] x == 3 y + Sqrt[6] z, z][[1]];
dA = Sqrt[1 + D[z, x]^2 + D[z, y]^2];
Integrate[
Boole[Sqrt[3] x == 3 y + Sqrt[6] z &&
2 Sqrt[3] x + 6 y + Sqrt[6] z <= 3 &&
3 + 6 y >= 2 Sqrt[3] x + Sqrt[6] z &&
3 + 4 Sqrt[3] x >= Sqrt[6] z && 1 + Sqrt[6] z >= 0]*
dA, {x, -Infinity, Infinity}, {y, -Infinity, Infinity}]]
(*1*)

My attempt was to express the problem with graphic objects: Tetrahedron and InfinitePlane.
Graphics3D[{Tetrahedron[{{0, 0, Sqrt[3/2]}, {2/Sqrt[3],
0, -(1/Sqrt[6])}, {-(1/Sqrt[3]),
1, -(1/Sqrt[6])}, {-(1/Sqrt[3]), -1, -(1/Sqrt[6])}}],
InfinitePlane[{{0, 0, 0}, {Sqrt[3], 1, 0}, {Sqrt[2], 0, 1}}]}]

Problem
However, when I tried this:
RegionMeasure@
RegionIntersection[
Tetrahedron[{{0, 0, Sqrt[3/2]}, {2/Sqrt[3],
0, -(1/Sqrt[6])}, {-(1/Sqrt[3]),
1, -(1/Sqrt[6])}, {-(1/Sqrt[3]), -1, -(1/Sqrt[6])}}],
InfinitePlane[{{0, 0, 0}, {Sqrt[3], 1, 0}, {Sqrt[2], 0, 1}}]]

The code is going to evaluate forever, even some subtle change like changing RegionMeasure to Area won't help. (The analytical result seems to be relatively easy to obtain by geometry.) Am I making any mistake in this process?
My concern is that this problem is indeed quite simple, but required some effort to solve in Mathematica. Is there an easier way?

A: RegionMeasure chooses a method which is slow when exact non-rational coefficients are present. I will correct this for a future version. Thanks for pointing it out. In Mathematica 10 the example works fast with approximate coefficients.
In[1]:= Timing@RegionMeasure@N@
        RegionIntersection[
        Tetrahedron[{{0, 0, Sqrt[3/2]}, {2/Sqrt[3],
        0, -(1/Sqrt[6])}, {-(1/Sqrt[3]),
        1, -(1/Sqrt[6])}, {-(1/Sqrt[3]), -1, -(1/Sqrt[6])}}],
        InfinitePlane[{{0, 0, 0}, {Sqrt[3], 1, 0}, {Sqrt[2], 0, 1}}]]

Out[1]= {0.241963, 1.}


text:
Q: Retrieving the MSBuild content into an artifact? Directory 'D:\a\1\a' is empty. Nothing will be added to build artifact 'drop' I try to understand how this MSBuild command is working with Azure DevOps Pipeline in Yaml. I get this error:

Here is my MSBuild instruction in my Azure Pipeline project:
- task: MSBuild@1
  inputs:
    solution: '**/Beper-EDI.sln'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'
    msbuildArguments: # Optional
    clean: true
    #maximumCpuCount: false # Optional
    #restoreNugetPackages: false # Optional
    #logProjectEvents: false # Optional
    #createLogFile: false # Optional
    #logFileVerbosity: 'normal' # Optional. Options: quiet, minimal, normal, detailed,

The build is correct. I can build my project. Then I try to publish my artifact by using:
- task: PublishBuildArtifacts@1
  inputs:
    ArtifactName: 'drop'
    pathToPublish: '$(Build.ArtifactStagingDirectory)'

I can process the pipeline but at the end my artifact is empty.

During my build I can see that the bin/Release folder and obj/Release folder are created and code is compiled.:
Starting: MSBuild
==============================================================================
Task         : MSBuild
Description  : Build with MSBuild
Version      : 1.192.2
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/build/msbuild
==============================================================================
"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.192.2\ps_modules\MSBuildHelpers\vswhere.exe" -version [17.0,18.0) -latest -format json
"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.192.2\ps_modules\MSBuildHelpers\vswhere.exe" -version [17.0,18.0) -products Microsoft.VisualStudio.Product.BuildTools -latest -format json
"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.192.2\ps_modules\MSBuildHelpers\vswhere.exe" -version [16.0,17.0) -latest -format json
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\msbuild.exe" "D:\a\1\s\Beper-EDI.sln" /nologo /nr:false /dl:CentralLogger,"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.192.2\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=|SolutionDir=D:\a\1\s"*ForwardingLogger,"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.192.2\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"  /p:platform="Any CPU" /p:configuration="Release" /p:_MSDeployUserAgent="VSTS_10aa52a5-54c3-4730-90df-e99d0388b1f5_build_50_0"
Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
Build started 12/30/2021 8:07:45 AM.
Project "D:\a\1\s\Beper-EDI.sln" on node 1 (default targets).
ValidateSolutionConfiguration:
  Building solution configuration "Release|Any CPU".
Project "D:\a\1\s\Beper-EDI.sln" (1) is building "D:\a\1\s\Nppg.Core.BusinessServices\Nppg.Core.BusinessServices.csproj" (2) on node 1 (default targets).
PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
Project "D:\a\1\s\Nppg.Core.BusinessServices\Nppg.Core.BusinessServices.csproj" (2) is building "D:\a\1\s\Nppg.Core.Reports\Nppg.Core.Reports.csproj" (3:2) on node 1 (default targets).
PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
Project "D:\a\1\s\Nppg.Core.Reports\Nppg.Core.Reports.csproj" (3:2) is building "D:\a\1\s\Submodules\nppg-core\Nppg.Core\Nppg.Core.csproj" (5:3) on node 1 (default targets).
PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".

How can I make sure the system let me access my /Release folder?

A:
Retrieving the MSBuild content into an artifact? Directory 'D:\a\1\a' is empty. Nothing will be added to build artifact 'drop'

That because the source of the task PublishBuildArtifacts is $(Build.ArtifactStagingDirectory).
But the MSBuild task not generate the file in the $(Build.ArtifactStagingDirectory) folder, so we need to copy the files from the output folder of the task MSBuild to the folder $(Build.ArtifactStagingDirectory) by the copy task after MSBuild task:
- task: CopyFiles@2
  displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)'
  inputs:
    SourceFolder: '$(Build.SourcesDirectory)'
    Contents: '**\bin\release\**'
    TargetFolder: '$(Build.ArtifactStagingDirectory)'


text:
Q: Listen for rejected promises on the front-end Using node.js, we can listen for rejected promises using:
process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at:', p, 'reason:', reason);
  // application specific logging, throwing an error, or other logic here
});

is this the best way to listen for unhandledRejections on the front-end?
https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection

A: Yes, window.addEventListener("unhandledrejection", …) is the front-end equivalent to node's process.on('unhandledRejection', …). It's not the "best" way to listen to them, it's the only way.


text:
Q: Redirect for multiple Angular 9 apps I'm using Spring Boot 2.2 and Angular 9.
I have 3 Angular 9 apps placed on 3 folders, Main (/), Admin (/admin) and Support (/support).
I have this code to redirect to the index page of each app:
@GetMapping("/**/{path:[^\\.]*}")
public String redirectMain()
{
    return "forward:/index.html";
}

@GetMapping("/admin/**/{path:[^\\.]*}")
public String redirectAdmin()
{
    return "forward:/admin/index.html";
}

@GetMapping("/support/**/{path:[^\\.]*}")
public String redirectSupport()
{
    return "forward:/support/index.html";
}

But all the request are catch by the redirectMain function. What am I doing wrong? (I'm testing this functions using PostMan to make the requests to make sure this works, before trying with the Angular Router itself. Also, I'm trying with /admin and /admin/ and /support and /support/).


text:
Q: Change values when copying records from one table to another I have the following code to copy data from one table to another:
INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT
  CategoryId, Author, Title
FROM MyDbBackup.Books

I need to apply the following transformation when copying CategoryId values:

+---------------------+-----------------+
|     Old CategoryId  |  New CategoryId |
+---------------------+-----------------+
|                  1  |               2 |
|                  2  |               1 |
|                  3  |               3 |
|                  4  |               4 |
|                  5  |               8 |
|                 14  |               6 |
|                 15  |               7 |
|                 18  |               5 |
|                 22  |               9 |
+---------------------+-----------------+

How can I do this?

A: You could use case when
INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT
  case when CategoryId = 1 then 2
       when CategoryId = 2 then 1
       when CategoryId = 5 then 8
       when CategoryId = 14  then 6
       when CategoryId = 15  then 7
       when CategoryId = 18  then 5
       when CategoryId = 22  then 9
       else cateogoryId end, Author, Title
FROM MyDbBackup.Books

or a  less verbose way
INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT
  case CategoryId
       when  1 then 2
       when 2 then 1
       when 5 then 8
       when 14  then 6
       when 15  then 7
       when 18  then 5
       when 22  then 9
       else cateogoryId end, Author, Title
FROM MyDbBackup.Books

A: As said in the comments by Panagiotis Kanavos, you'll need to use a CASE expression:
CASE CategoryID WHEN 1 THEN 2
                WHEN 2 THEN 1
                WHEN 5 THEN 8
                WHEN 14 THEN 6
                WHEN 15 THEN 7
                WHEN 18 THEN 5
                WHEN 22 THEN 9
                ELSE CategoryID END

A: One method is to use a lookup table a join:
select v.newid, b.author, b.title
from MyDbBackup.Books b join
     (values (1, 2), (2, 1), (3, 3), (4, 4), (5, 8), (14, 6), (15, 7), (18, 5), (22, 9)
     ) v(oldid, newid)
     on b.CategoryId = v.oldid;

An alternative is to use a case expression.  However, using the join ensures that only the set of books with the old ids is in the result set.  So, it does both the lookup and filtering.
If you don't want the filtering, you can use a left join instead of an inner join.

A: Since there is no formula, then the conversion must be done one by one:
INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT CASE CategoryID WHEN 1 THEN 2
                       WHEN 2 THEN 1
                       WHEN 5 THEN 8
                       WHEN 14 THEN 6
                       WHEN 15 THEN 7
                       WHEN 18 THEN 5
                       WHEN 22 THEN 9
                      ELSE CategoryId ID END AS CategoryId
       , Author, Title
FROM MyDbBackup.Books


text:
Q: HTML/JS Contact Form Not Sending or Showing Error Message I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            Thank You! E-mail was sent.

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            Oops! An error occured. Please try again later.

          <form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
            <fieldset>

                    Name (Required)
                    <input type="text" required name="field[]" class="form-control">

                    Email (Required)
                    <input type="email" required name="field[]" class="form-control">

                    Subject
                    <input type="text" name="field[]" class="form-control">

                    Message (Required)
                    <textarea name="field[]" required class="form-control" rows="5"></textarea>

              <input type="submit" class="btn btn-primary" value="Send Message">
            </fieldset>
          </form>

The JS
/**
 * Contact Form
 */
jQuery(document).ready(function ($) {
    "use strict";
    $ = jQuery.noConflict();

    var debug = false; //show system errors

    $('.liveForm').submit(function () {
        var $f = $(this);
        var showErrors = $f.attr('data-show-errors') == 'true';
        var hideForm = $f.attr('data-hide-form') == 'true';

        var emailSubject = $f.attr('data-email-subject');

        var $submit = $f.find('[type="submit"]');

        //prevent double click
        if ($submit.hasClass('disabled')) {
            return false;
        }

        $('[name="field[]"]', $f).each(function (key, e) {
            var $e = $(e);
              var p = $e.parent().find("label").text();

            if (p) {
                var t = $e.attr('required') ? '[required]' : '[optional]';
                var type = $e.attr('type') ? $e.attr('type') : 'unknown';
                t = t + '[' + type + ']';

                var n = $e.attr('name').replace('[]', '[' + p + ']');

                n = n + t;
                $e.attr('data-previous-name', $e.attr('name'));
                $e.attr('name', n);
            }
        });

        $submit.addClass('disabled');

        $f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');

        $.ajax({
            url: $f.attr('action'),
            method: 'post',
            data: $f.serialize(),
            dataType: 'json',
            success: function (data) {
                $('span.error', $f).remove();
                $('.error', $f).removeClass('error');
                $('.form-group', $f).removeClass('has-error');

                if (data.errors) {
                    $.each(data.errors, function (i, k) {
                        var input = $('[name^="' + i + '"]', $f).addClass('error');
                        if (showErrors) {
                            input.after('' + k + '');
                        }

                        if (input.parent('.form-group')) {
                            input.parent('.form-group').addClass('has-error');
                        }
                    });
                } else {
                    var item = data.success ? '.successMessage' : '.errorMessage';
                    if (hideForm) {
                        $f.fadeOut(function () {
                            $f.parent().find(item).show();
                        });
                    } else {
                        $f.parent().find(item).fadeIn();
                        $f[0].reset();
                    }
                }

                $submit.removeClass('disabled');
                cleanupForm($f);
            },
            error: function (data) {
                if (debug) {
                    alert(data.responseText);
                }
                $submit.removeClass('disabled');
                cleanupForm($f);
            }
        });

        return false;
    });

    function cleanupForm($f) {
        $f.find('.temp').remove();

        $f.find('[data-previous-name]').each(function () {
            var $e = jQuery(this);
            $e.attr('name', $e.attr('data-previous-name'));
            $e.removeAttr('data-previous-name');
        });
    }
});

The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc@gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>

A: <?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
    //redirect to contact form
    echo "Please enable Javascript";
    exit;
}
require_once "config.php";

//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";

//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);

if ($data['errors']) {
    echo json_encode(array('errors' => $data['errors']));
    exit;
}

$html = '

' . $mail->Subject . '

';

foreach ($data['fields'] as $label => $val) {
    $html .= '
' . $label . ': ' . $val . '
';
}

$html .= '

';

$mail->setup($html, $_REQUEST, array());

$result = array('success' => 1);
if (!$mail->Send()) {
    $result['success'] = 0;
}

echo json_encode($result);
exit;


text:
Q: How to query android call log data with group by date I am querying call dates in call log database in android phone. After reading some articles, they said this needs to make some injection in my query method like this.
Cursor cursor = activity.getContentResolver().query(
                    CallLog.Calls.CONTENT_URI,
                    new String[] { CallLog.Calls.DATE},
                    "" + ") GROUP BY (" + CallLog.Calls.DATE,
                    null, CallLog.Calls.DATE + " DESC");

When I run my app and I got the following error message.
near ")": syntax error (code 1): , while compiling: SELECT date FROM calls WHERE ((() GROUP BY (date) AND ((type != 4)))) ORDER BY date DESC

Actually, I can't figure out how this query was built and why ((type !=4)) filter was appended to GROUP BY clause. I am currently using (compileSdkVersion 19, minSdkVersion 10 and targetSdkVersion 19). Is there any way to make raw query to Call Log Database because I want to write the query with my own to group dates.

A: CursorLoader cl = new CursorLoader(getActivity(), CallsQuery.CONTENT_URI, CallsQuery.PROJECTION, null, null,            CallLog.Calls.DEFAULT_SORT_ORDER);

You can use the DEFAULT_SORT_ORDER which is date DESC
public static final String DEFAULT_SORT_ORDER
The default sort order for this table
Constant Value: `"date DESC"`

A: Just remove the extra brackets from your query and change it as below:
   Cursor cursor =mActivity.getContentResolver().query(
            CallLog.Calls.CONTENT_URI,
            new String[] { CallLog.Calls.DATE},
            " GROUP BY " + CallLog.Calls.DATE,null,CallLog.Calls.DATE + " DESC");


text:
Q: React hook form pass errors to child component (TS) Cant get error validation to work in child component. I've watched the multistep tutorial video but I believe it's out of date with the latest version (perhaps I'm wrong).
I have a parent component in which I instantiate the methods, it contains one field and then a component:
const OD= () => {
    const methods = useForm();
    const {
        register,
        handleSubmit,
        formState: { errors },
    } = methods;

    return (
        <FormProvider {...methods} >
           <Field>
              Complaint:*
              <Textarea {...register("Complaint", { required: true })}/>
              {errors.Complaint && <RequiredMessage/>}
           </Field>
           <Allergens />
        </FormProvider>
    )
}

Inside my component I then have the following:
const Allergens = () => {
    const { register, formState: { errors } } = useFormContext();
    return(
        Allergy*
        <Input {...register("Allergy")} />
        {errors.Allergy&& <RequiredMessage/>}
    )
}

The register works fine and I can see it collecting data from the parent and child component, the errors work fine on the parent but not on the child (allergens).
I have no syntax errors, is there anything im missing?
Thanks!

A: I think it's a mistake. Inside of Allergens component input you registered the input like {...register(("Allergy"))}. You used double brackets, Remove one of them. What is actually need is {...register("Allergy")}.


text:
Q: How to plot in matlab using the besselh function with a given range of k (reduced frequency)? I am using a Matlab function called besselh which gives an exact solution to Theoderon's lift deficiency function for a two-dimensional airfoil executing a simple harmonic motion in incompressible flow with a given range of k.
I am trying to plot the real part of this function with the given range of k. I feel I am missing something really simple in my code. Perhaps, I might be using the for loop wrong by including the "plot" function within the loop?
for k=10^-10:0.2:1.5 %range of k
H=(besselh(1,2,k))/(besselh(1,2,k)+i*besselh(0,2,k)) %Bessel function
plot(k,real(H))
%plot(k,imag(H))
end

Below is a picture of how the plot should look like (solid line).
Any help would be appreciated, thank you in advance!

A: You are trying to plot each point individually. Just calculate the function across the whole range for k and then plot:
k = 10^-10:0.2:1.5; %range of k
% notice the ./ means element-wise vector division
H = (besselh(1,2,k)) ./ (besselh(1,2,k) + i * besselh(0,2,k)); %Bessel function
plot(k,real(H))


text:
Q: Java Recursion in an If/Else statement I'm trying to figure out why the top block of Code executes but the bottom block of code does not. All I did to get the other to execute was switch the conditions position in my if/else statement
public static void onTheWall(int bottles){
    if (bottles == 0){
        System.out.println("No bottles of beer on the wall,"
                           + " no bottles of beer, ya' can't take one down, ya' can't pass it around,"
                           + "cause there are no more bottles of beer on the wall!");
    } else if (bottles <= 99){
        System.out.println(bottles + " bottles of beer on the wall, "
                           + bottles + " bottles of beer, ya' take one"
                           + " down, ya' pass it around, "
                           + (bottles - 1) + " bottles of beer on the wall");
        onTheWall(bottles-1);
    }
}

public static void onTheWall(int bottles){
    if (bottles <= 99){
        System.out.println(bottles + " bottles of beer on the wall, "
                           + bottles + " bottles of beer, ya' take one"
                           + " down, ya' pass it around, " + (bottles - 1)
                           + " bottles of beer on the wall");
        onTheWall(bottles-1);
    } else if (bottles == 0){
        System.out.println("No bottles of beer on the wall,"
                           + " no bottles of beer, ya' can't take one down, ya' can't pass it around,"
                           + "cause there are no more bottles of beer on the wall!");
    }
}

A: public static void onTheWall(int bottles){
         if (bottles == 0){
                System.out.println("No bottles of beer on the wall," + " no bottles of beer, ya' can't take one down, ya' can't pass it around," + "cause there are no more bottles of beer on the wall!");
            } else if (bottles <= 99){
                System.out.println(bottles + " bottles of beer on the wall, " + bottles + " bottles of beer, ya' take one"
                + " down, ya' pass it around, " + (bottles - 1) + " bottles of beer on the wall");
            onTheWall(bottles-1);
            }
    }

Your recursive call does not happen since at the start bottles is 0. Try moving the location of your recursive call or changing the elseif to an if.

A: The problem has nothing to do with recursion but with the fact that the conditions in the "if" and the "else" are not mutually exclusive.
You can only safely switch the order of the "if" and the "else" if the conditions are exclusive. Remember that in an if/elseif chain, only the first matching condition will be executed. If the conditions are not mutually exclusive, the order will matter.

A: Your switching the conditions if (bottles <= 99) and else if (bottles == 0) causes the first block to execute because the first condition (bottles <= 99) is true for bottles=0.
If you are expecting the else if to execute before the if statement, then that is never going to happen.
Maybe your condition should be something like if (bottles > 0 && bottles <= 99) in which case your second block will execute if bottles=0 as you expect it to.

A: In the second method, the branch bottles == 0 will never execute.
Because when bottles == 0, the bottles <= 99 is true. It's an infinite recursive loop.


text:
Q: How can i read tcp/udp header in application layer without using raw sockets? Is there any "Api or system calls" to get whole packet from network layer without cutting the headers?

A: You can't, unless your un-named operating system provides it via the recvmsg() function, which I believe Linux can do. Otherwise your question embodies a contradiction in terms.


text:
Q: jQuery Math Equation (slight return) I need a little help adjusting this code, any advice is appreciated:
The desired result is to have two values returned instead of just one, so for example:
Input Value = " " (Text box )
this.value = 226 - this.value * .5;  ( value #1 Text Box2)
this.value = 226 - this.value * .9;  ( value #2 Text Box3)

HTML
<form id='myform'>
    <input value=" "/>

    click to calculate THR

</form>

CODE
$('a.THR').click(function() {
    $('#myform :text').each(function() {
    this.value = 226 - this.value * .5;
    });
});

A: Ok, I'm not really sure what you want to accomplish but if you just want to make two calculations and display the results you can do this:
HTML:
<input id="number" value="" />

click to calculate THR

JS:
$('a.THR').click(function() {
    var value = parseInt( $( "#number" ).val() );
    $( "#answer1" ).html( 226 - value * 0.5 );
    $( "#answer2" ).html( 226 - value * 0.9 );
    return false;
});

Since you have only one input field there's no reason to use an each loop, just give it an id and refer to it directly. The containers for the results can be anything you want as long as you can refer to them with jQuery (ids are a good choice).


text:
Q: PowerQuery formula bar error cycling reference What is wrong with this pquery formula; Expression.Error: A cyclic reference was encountered during evaluation.
Table.AddColumn(#"Changed Type", "Custom", each Table.SelectRows(
 tblOrders (2),
(InnerTable)=>InnerTable[Order Date] = [Category]
)[Value])


text:
Q: Data Conflict 409 Error I am getting a Document Conflict 409 error when I try to add a document to CouchDB. The scenario is as follows.

*

*Add Doc1 Rev1 to Couch using HTTP PUT

*Delete Doc1 Rev1 from Couch using HTTP DELETE

*Add Doc1 Rev2 to Couch using HTTP PUT

Why would step 3 cause Couch to return a Data Conflict 409 error? How can a document be in conflict with a deleted document? Any insight would be greatly appreciated.
Jim

A: This is by design. To create a document, don't pass a _rev value in the body.


text:
Q: Use template or void? I need to implement a small function which does the byte swapping for an array with given length.
void myFunc (MYTYPE arrayPointer, const int& length)
{

unsigned int* tmp = (unsigned int*)     arrayPointer;
for (int j=0; j < length; j = j + 4)
{
  *tmp = htonl (*(tmp));
tmp++;

}

}

I don't want the user to do typecasting while using the function.  I think I have two options left:
1. Replace MYTYPE with (void*)
2. Use templates.
Which option is better or preferable? Is there any better way than these two?

A: Templates, obviously. You're going to need an enable_if on sizeof(T)==4.


text:
Q: Adjust divider width if image is present I have a divider with float left property housing some text, then divider float right housing an image.  Total width of both dividers should be no bigger than 735 and I am reserving 200 for image. How can I adjust the width of the first divider to be 535 if image is present and 735 if image is hidden?

        some text here

A: To do this in pure CSS would be easy, you'd need a different approach. Only float one div and then the other will automatically take up the remaining space
DEMO http://jsfiddle.net/kevinPHPkevin/gAUR5/
img {
    width: auto;
    height: auto;
    max-width: 200px;
    display: block;
}

Set the img css to display: none and see that the other div takes up all the remaining space.

A: I am not sure if this properly answers your question, but I think one solution may be to set the left div (division)'s width to "auto" instead of going for a fixed width. Also, you should consider floating both elements right so that the left div can respond to changes in the right div's size.
Otherwise, you will need to rely on javascript to affect the DOM elements (JQuery will make this easier).

A: If you can use JQuery, this will do this trick:
$(document).ready(function(){
    var width;
    if($('#outerdiv #rightdiv img').is(":visible")) {
        width = 735;
    } else {
        width = 535;
    }
    $('#outerdiv #leftdiv').css('width', width);
});

If you can't use JQuery, I don't think what you want to do is possible.


text:
Q: Что это за кодировка такая? Лазил по одному скрипту для телеги, в поисках текста копирайта. В итоге оказалось что копирайт был как-то зашифрован, что ли.
Вместо Bot By там было написано вот это:

Erw#E|

Скрипт написан на php. уж больно интересно что это за шифр такой. вот та часть кода в которой он был вписан:
define('A9029', array(
    'A' => 3,
   '9029' => 'Erw#E|#CQrlow|'
));

Позже фрагмент 'A9029' встречался вовремя отправки сообщения в телегу:
tgBotMessage($sRandomName, openKey(A9029['9029'], A9029['A']), MESSAGE);

Функция openKey:
function openKey($text, $current)
{
    $sResult = '';

    for($i=0; $i < strlen($text); $i++) {
        $symbol = ord($text[$i]) - $current;

        if($symbol < $current) {
            $symbol = 255 - $current;
        }
        $sResult .= chr($symbol);
    }

    return $sResult;
}

уж больно интересно что это.
И если кто знает, как закодировать так же другой текст)
Спасибо.

A: <?php

function encode($text, $current)
{
    $sResult = '';

    for($i=0; $i < strlen($text); $i++) {
        $chr = ord($text[$i]) + $current;
        $sResult .= chr($chr);
    }

    return $sResult;
}


text:
Q: How can I find and delete all files in subfolders by matching part of the file name Windows 10. Photos stored by month like this:
Photos > Year > Month
For example, the photos for December 2011:
Photos > 2011 > 12
There are duplicate files of nearly every photo like this:
IMG_3257.JPG
IMG_3257 (1).JPG
How can I search the entire Photos directory and remove the duplicates containing ' (1)' in the file name? Like this one:
Photos > 2011 > 12 > IMG_3257 (1).JPG

A: You can use the DEL command to delete files containing (1) in the name from current directory tree.
 DEL /Q /F /S "*(1)*"

Step by Step Instruction:
Step 1: Navigate to your Pictures folder.
Step 2: Press Ctrl+L or F4
Step 3: Type cmd and press Enter
Step 4: Type or Copy and past the command DEL /Q /F /S "*(1)*" or DEL /Q /F /S "*(*)*" depending on your requirement and hit Enter.
Parameters:

*

*/F Forces deletion of read-only files.

*/S Deletes specified files from the current directory and all sub
directories. Displays the names of the files as they are being
deleted.

*/Q Specifies quiet mode. You are not prompted for delete confirmation
You may use the below parameter to prompt for confirmation before deleting a file.

*

*/P Prompts for confirmation before deleting the specified file.

A: Welcome aboard, Jay :-)
If you want a GUI based solution, then:

*

*download the excellent (and free) Double Commander

*install (or use the portable version) and run it

*navigate to the top directory, beneath which you have your pictures

*press Alt+F7 (or use menu item Commands/Search)

*enter (1) as the file name (or *(1).jpg, or even *(*).jpg)

*when shown the results, click on the button "feed to listbox"

*press Ctrl+A to select all

*press F8 to delete them

If that sounds like a lot of work, it's because I detailed it step by step. In practise, a few seconds will see it done, and you will find Double Commander to be much more useful than the built in Windows Explorer :-)


text:
Q: in spark sql getting problem while joining two dataframes . pleses solve my problem I have two dataframes ,the first data frame 10 columns , (street ,state(rows are CA ,US).etc) and 2 nd data frame  two columns (state and state full name) I want to join these two data frames using state but I don't want join  state columns in that replace state with full name.
I have used,
tranDF.join(stateDF,tranDF("state")===stateDF("state"),"inner").show(false)
my required columns are
street city state_NM beds ...etc

I want one columns from stateDF that should replace state column from tranDF please any one answer my question

A: The below way should work...

  trandf.join(statedf,trandf("state")===statedf("state"),"inner")
    .selectExpr("trans.street", "trans.city", "state.statefullname", "trans.type")
    .show(false)

Explanation : create alias for each df as 'trans' and 'state'
after inner join  select the columns only you wanted and that are relavent. using select or selectExpr  as shown below.

Full example in spark with scala with walmart data..
package examples

import examples.JoinDemo.trandf
import org.apache.log4j.Level
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._

object JoinDemo extends App {
  val logger = org.apache.log4j.Logger.getLogger("org")
  logger.setLevel(Level.WARN)

  val spark = SparkSession.builder().appName("JoinDemo").master("local").getOrCreate()

  import spark.implicits._

  val mycsvdata = """
    |"statefullname","state"
    |"Alabama","AL"
    |"Alaska","AK"
    |"Arizona","AZ"
    |"Arkansas","AR"
    |"California","CA"
    |"Colorado","CO"
    |"Connecticut","CT"
    |"Delaware","DE"
    |"District of Columbia","DC"
    |"Florida","FL"
    |"Georgia","GA"
    |"Hawaii","HI"
    |"Idaho","ID"
    |"Illinois","IL"
    |"Indiana","IN"
    |"Iowa","IA"
    |"Kansas","KS"
    |"Kentucky","KY"
    |"Louisiana","LA"
    |"Maine","ME"
    |"Montana","MT"
    |"Nebraska","NE"
    |"Nevada","NV"
    |"New Hampshire","NH"
    |"New Jersey","NJ"
    |"New Mexico","NM"
    |"New York","NY"
    |"North Carolina","NC"
    |"North Dakota","ND"
    |"Ohio","OH"
    |"Oklahoma","OK"
    |"Oregon","OR"
    |"Maryland","MD"
    |"Massachusetts","MA"
    |"Michigan","MI"
    |"Minnesota","MN"
    |"Mississippi","MS"
    |"Missouri","MO"
    |"Pennsylvania","PA"
    |"Rhode Island","RI"
    |"South Carolina","SC"
    |"South Dakota","SD"
    |"Tennessee","TN"
    |"Texas","TX"
    |"Utah","UT"
    |"Vermont","VT"
    |"Virginia","VA"
    |"Washington","WA"
    |"West Virginia","WV"
    |"Wisconsin","WI"
    |"Wyoming","WY"
  """.stripMargin.lines.toList.toDS
val mycsvdata1 =
  """
    |"opendate","street","city","state","long","lat","type"
    |1962-03-01,"5801 SW Regional Airport Blvd","Bentonville","AR",-94.239816,36.350885,"DistributionCenter"
    |1962-07-01,"2110 WEST WALNUT","Rogers","AR",-94.07141,36.342235,"SuperCenter"
    |1964-08-01,"1417 HWY 62/65 N","Harrison","AR",-93.09345,36.236984,"SuperCenter"
    |1965-08-01,"2901 HWY 412 EAST","Siloam Springs","AR",-94.50208,36.179905,"SuperCenter"
    |1967-10-01,"3801 CAMP ROBINSON RD.","North Little Rock","AR",-92.30229,34.813269,"Wal-MartStore"
    |1967-10-01,"1621 NORTH BUSINESS 9","Morrilton","AR",-92.75858,35.156491,"SuperCenter"
    |1968-03-01,"1303 SOUTH MAIN","Sikeston","MO",-89.58355,36.891163,"SuperCenter"
    |1968-03-01,"65 WAL-MART DRIVE","Mountain Home","AR",-92.35781,36.329026,"SuperCenter"
    |1968-07-01,"2020 SOUTH MUSKOGEE","Tahlequah","OK",-94.97185,35.923658,"SuperCenter"
    |1968-07-01,"1500 LYNN RIGGS BLVD","Claremore","OK",-95.61192,36.327143,"SuperCenter"
    |1968-11-01,"2705 GRAND AVE","Carthage","MO",-94.31164,37.168985,"SuperCenter"
    |1969-04-01,"1800 S JEFFERSON","Lebanon","MO",-92.64733,37.678528,"SuperCenter"
    |1969-04-01,"2214 FAYETTEVILLE RD","Van Buren","AR",-94.34581,35.456536,"SuperCenter"
    |1969-05-01,"1310 PREACHER RD/HGWY 160","West Plains","MO",-91.87408,36.719145,"SuperCenter"
    |1969-05-01,"3200 LUSK DRIVE","Neosho","MO",-94.39016,36.86429,"SuperCenter"
    |1969-11-01,"2500 MALCOLM ST/HWY 67 NORTH","Newport","AR",-91.24695,35.586065,"Wal-MartStore"
    |1970-03-01,"185 ST ROBERT BLVD","St. Robert","MO",-92.135741,37.827415,"SuperCenter"
    |1970-10-01,"1712 EAST OHIO","Clinton","MO",-93.76042,38.364214,"SuperCenter"
    |1970-10-01,"4901 SO. MILL ROAD","Pryor","OK",-95.30295,36.294174,"SuperCenter"
    |1970-11-01,"1201 N SERVICE ROAD EAST","Ruston","LA",-92.64696,32.52476,"SuperCenter"
    |1970-11-01,"3450 S. 4TH TRAFFICWAY","Leavenworth","KS",-94.93555,39.298776,"Wal-MartStore"
    |1971-02-01,"4820 SO. CLARK ST","Mexico","MO",-91.88404,39.179316,"SuperCenter"
    |1971-02-01,"1101 HWY 32 WEST","Salem","MO",-91.51423,37.630896,"SuperCenter"
    |1971-04-01,"2000 JOHN HARDEN DR","Jacksonville","AR",-92.12244,34.879419,"SuperCenter"
    |1971-05-01,"2415 N.W. MAIN ST","Miami","OK",-94.87142,36.880746,"SuperCenter"
    |1971-06-01,"3108 N BROADWAY","Poteau","OK",-94.61829,35.052793,"SuperCenter"
    |1971-06-01,"2050 WEST HWY 76","Branson","MO",-93.25668,36.64417,"Wal-MartStore"
    |1971-06-01,"1710 SO. 4TH ST","Nashville","AR",-93.85214,33.985613,"SuperCenter"
    |1971-08-01,"724 STADIUM WEST BLVD","Jefferson City","MO",-92.25329,38.568287,"SuperCenter"
    |1971-09-01,"701 WALTON DRIVE","Farmington","MO",-90.41404,37.779206,"SuperCenter"
    |1971-10-01,"101 EAST BLUEMONT AVENUE","Manhattan","KS",-96.56932,39.184986,"SuperCenter"
    |1971-11-01,"2025 BUS. HWY 60 WEST","Dexter","MO",-89.97428,36.784453,"SuperCenter"
    |1971-11-01,"2250 LINCOLN AVENUE","Nevada","MO",-94.35075,37.838563,"SuperCenter"
    |1971-11-01,"2802 WEST KINGS HIGHWAY","Paragould","AR",-90.5102,36.065711,"SuperCenter"
    |1971-11-01,"1301 HWY 24 EAST","Moberly","MO",-92.4344,39.420353,"SuperCenter"
    |1971-12-09,"1907 SE WASHINGTON ST.","Idabel","OK",-94.83154,33.883578,"SuperCenter"
    |1972-02-01,"1802 SOUTH BUSINESS HWY 54","Eldon","MO",-92.58395,38.311355,"Wal-MartStore"
    |1972-03-01,"2400 SOUTH MAIN","Fort Scott","KS",-94.73389,37.823295,"Wal-MartStore"
    |1972-05-01,"1155 HWY 65 NORTH","Conway","AR",-92.43401,35.075467,"SuperCenter"
    |1972-05-01,"4000 GREEN COUNTRY RD","Bartlesville","OK",-95.92404,36.733398,"SuperCenter"
  """.stripMargin.lines.toList.toDS
  val trandf: DataFrame = spark.read.option("header", true)
    .option("sep", ",")
    .option("inferSchema", true)
    .csv(mycsvdata1).as("trans")

  val statedf: DataFrame = spark.read.option("header", true)
    .option("sep", ",")
    .option("inferSchema", true)
    .csv(mycsvdata).as("state")

  trandf.join(statedf,trandf("state")===statedf("state"),"inner")
    .selectExpr("trans.street", "trans.city", "state.statefullname", "trans.type") // you want only columns from state df
    .show(false)

}

Result :
+--------------------------+--------------+-------------+-------------+
|street                    |city          |statefullname|type         |
+--------------------------+--------------+-------------+-------------+
|1201 N SERVICE ROAD EAST  |Ruston        |Louisiana    |SuperCenter  |
|1303 SOUTH MAIN           |Sikeston      |Missouri     |SuperCenter  |
|2705 GRAND AVE            |Carthage      |Missouri     |SuperCenter  |
|1800 S JEFFERSON          |Lebanon       |Missouri     |SuperCenter  |
|1310 PREACHER RD/HGWY 160 |West Plains   |Missouri     |SuperCenter  |
|3200 LUSK DRIVE           |Neosho        |Missouri     |SuperCenter  |
|185 ST ROBERT BLVD        |St. Robert    |Missouri     |SuperCenter  |
|1712 EAST OHIO            |Clinton       |Missouri     |SuperCenter  |
|4820 SO. CLARK ST         |Mexico        |Missouri     |SuperCenter  |
|1101 HWY 32 WEST          |Salem         |Missouri     |SuperCenter  |
|2050 WEST HWY 76          |Branson       |Missouri     |Wal-MartStore|
|724 STADIUM WEST BLVD     |Jefferson City|Missouri     |SuperCenter  |
|701 WALTON DRIVE          |Farmington    |Missouri     |SuperCenter  |
|2025 BUS. HWY 60 WEST     |Dexter        |Missouri     |SuperCenter  |
|2250 LINCOLN AVENUE       |Nevada        |Missouri     |SuperCenter  |
|1301 HWY 24 EAST          |Moberly       |Missouri     |SuperCenter  |
|1802 SOUTH BUSINESS HWY 54|Eldon         |Missouri     |Wal-MartStore|
|3450 S. 4TH TRAFFICWAY    |Leavenworth   |Kansas       |Wal-MartStore|
|101 EAST BLUEMONT AVENUE  |Manhattan     |Kansas       |SuperCenter  |
|2400 SOUTH MAIN           |Fort Scott    |Kansas       |Wal-MartStore|
+--------------------------+--------------+-------------+-------------+
only showing top 20 rows

A: Check if below code works for you,
joinDF= (tranDF.alias("a").join(stateDF.alias("b"),
         col("a.state") == col("b.state") ,how='inner')
         .drop(col("a.state")).drop(col("b.state")))


text:
Q: Advice on data capture management system I'm looking at a potential piece of work involving a fairly complex data capture and management site and am wondering how best to approach it. I would be using a LAMP architecture.
The backend will involve:
Mass user creation via user uploaded csv file - I have done this before so am confident about this part.
Once registered, users will submit confidential information on a regular basis. Although the data is confidential, I would simply be planning on storing this in a MySQL database, which would be backup on a regular basis.
There would be different roles involved:

*

*An administrator, who would monitor user activity and create new roles and user accounts where required.

*End users - who would simply be supplying information via forms, with the ability to edit their profiles, view previous submissions and other basic stuff like that

*Management users - who can run a series of pre-defined reports on the data and display this information within the browser. They may also carry out "free-form queries" on the
data as well as extract selected results as spreadsheets. A number of these standard reports would also be made available as web services/feeds. The free-form queries part is
slightly concerning, as I don't know yet what the data actually is, plus there is a strong likelihood that new questions would be dynamically added to the data capture forms over time. The database structure would have to be flexible to accommodate this, plus I would have to provide this capacity for free-form queries, which I've never done before. Can anyone suggest a sensible approach to this?
There would also be some form of versioning, so that if a user updates/revises certain data, the changes would be tracked and the previous record(s) would still be available. I would be planning to incorporate this into the database design, so that instead of updating and overwriting data in the database, a new record would always be created, with the "overwritten" one simply being flagged as archived. This way, I think I would always be able to retrieve the live data row, as well as the archived rows (organised by date). Does that make sense?
Thanks in advance for any pointers, this is a bit more complex than what I've worked on before (mainly standard CMSs) - I think i know how to handle the above, but would be grateful for any advice a more experienced developer could provide.

A: If you are going to use that versioning system, I recommend that you also create views to get all the records that are active and have the user interface always use the views (except where they are looking at changes) not directly access that table. I would also put a trigger on the tables to make sure one and only one record is marked as active. Then you have the issue of the unique key and the key to identify the record in the PK/FK relationships (you don't want to have to change this every time you add another record).
Alternatively, you could set up audit tables if you just need to go back to old data if you need to research a change. If you need to see history frequently audit tables can be hard to query as they don't usually have the whole record structure just the old and new values, the column name and some meta data like when the change was made and by whom.
Possibly you could have a history table that is exactly like the orgional table with a few extra columns (for when the change was made and by whom as well a new surrogate key) and taking the autonumbering and unique index off the orginal PK.  Then the active records are all in one table, the inactive records are in another table (populated by trigger) and you use views only when you want to see both sets of data together.
The key to all of this is to use triggers to populate the history wherever you intend to store it. Databses are not just affected by the user application, so you need to make sure all changes to the database are recorded not just those done by the user interface or you will have gaps in your history. I can't speak for all databases but in SQl Server, triggers act once on each batch of data, don't write them assuming they will act one record at a time if someone updates a roup of prices in one query. It is generally critical to write triggers in a set-based fashion.  Looping through records is slow and in a trigger can bring your entire system to a halt while you loop through the million records that hada 10% price increase.


text:
Q: Valgrind output report I'm quite new with C++ and i realized a program, with the ITK library for medical imaging. It has a high computational cost and at the end of the running, my laptop seems to lost speed and functionality. This is the Valgrind output:
==6258== HEAP SUMMARY:
==6258==     in use at exit: 3,573,521 bytes in 25,493 blocks
==6258==   total heap usage: 271,050 allocs, 245,557 frees, 5,231,125,547 bytes allocated
==6258==
==6258== LEAK SUMMARY:
==6258==    definitely lost: 283,640 bytes in 11,812 blocks
==6258==    indirectly lost: 3,101,916 bytes in 11,816 blocks
==6258==      possibly lost: 0 bytes in 0 blocks
==6258==    still reachable: 187,965 bytes in 1,865 blocks
==6258==         suppressed: 0 bytes in 0 blocks

I know that it is not perfect and not all of the memory blocks are deallocated, but i want to know if these results could be tragic or they do not affect the performance of the PC, so much.
My laptop has a 4Gb of RAM, quadcore.


text:
Q: iOS facebook graph api comments Is there way to fetch facebook comments with graph api without logging. When user is logged in comments can be fetch without problem, first I fetch user comment box object from web and after that make second request with id of comment box. If user is logged out in first request completition handler returns error The operation couldn't be completed. (com.facebook.sdk.core error 8.)
let request = FBSDKGraphRequest(graphPath: "http://testapi.club/test.php", parameters: nil, HTTPMethod: "GET")
        request.startWithCompletionHandler { (connection, result, error) in
            if error == nil {
                print(result)
                let og_object = (result as! Dictionary<String, AnyObject>)["og_object"]
                let objecId = (og_object as! Dictionary<String, AnyObject>)["id"]
                let requestForComments = FBSDKGraphRequest(graphPath: "/\(objecId!)/comments", parameters: ["summary": "true","filter": "toplevel", "order":"chronological"], HTTPMethod: "GET")
                requestForComments.startWithCompletionHandler({ (connection, result, error) in
                    if error != nil {
                        print(error.description)
                    }else {
                        print(result)
                    }
                })
            }else{
                print(error.localizedDescription)
            }
        }


text:
Q: How to place text after the relative positioned element? I have absolute positioned div tag (child) placed inside relative positioned div tag (parent). I want to show the text after parent div, but it is placed in incorrect position.
HTML

The text which should be shown after parent div

CSS
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 20px;
  left: 30px;
}

What to do?
Updated
Type mistakes has been corrected.
Solution, proposed by Vitorino Fernandes, to indicate height of the parent div is good. But what to do if I don't know exact height of the parent div? Can I omit the height of the parent div and put the text excatly after it?

A: typo mistake should be position not postion should be height:100px not height 100px and add height to relative element

.parent {
  position: relative;
  width: 250px;
  height:300px;
  border:1px solid red;
}
.child {
  position: absolute;
  top: 20px;
  left:30px;
  width: 200px;
  height:100px;
  background-color: red;
}

The text which should be shown after parent div


text:
Q: Why does VC++ introduce the nonstandard keyword: __leave? According to MSDN:

The __leave statement is more efficient because it does not cause
  stack unwinding.

To my understanding, that is to say: "Such a common code snippet is dangerous!"
struct A
{
    int* p;

    A() : p(new int) {}
    ~A() { delete p; }
};

void f()
{
    __try
    {
        A a;
        ... // Doing somthing
        if (the thing has gone bad) __leave;
        ... // Continue
    }
    __finally
    {}
}

Is it a best practice to totally avoid __leave in C++ projects?

A: http://msdn.microsoft.com/en-us/library/yb3kz605.aspx
says:

For C++ programs, C++ exception handling should be used instead of structured exception handling. For more information, see Exception Handling in the C++ Language Reference.

Edit:
Also, it's usually good to refrain from compiler specific features.

A: It depends.  __try/__finally are built for Win32 structured exception handling, which is not quite the same as C++ structured exception handling.  If you're writing a Win32 driver, you must use Win32 SEH.  If not, I'd stick with C++ EH.


text:
Q: Is it possible to escape a character inside a handlebar? I would like to be able to insert a comma inside handlabars.js, for example: {{ JOURNAL \, }} rendering a comma for each item that exists, so there won't be nonsense commas due to a non existing key-value pair. Thank you all!
{{#each items}}
 <button class="accordion-button"
     {{#if (equals type "article")}}  {{AUTHOR}} {{TITLE}} {{JOURNAL}}, {{VOLUME}}({{NUMBER}})  {{MONTH}} {{YEAR}}                        {{/if}}
 </button>
{{/each}}

A: You can check if JOURNAL exists. Then include it and a trailing comma only if it does.
{{#if JOURNAL}}{{JOURNAL}}, {{/if}}

You can also create your own custom helper:
Handlebars.registerHelper('ifExistAddComma', function (str) {
    return str === undefined ? '' : `${str}, `;
})

{{ifExistAddComma JOURNAL}}

See playground
Edit: You can write a more complex (but also more general) custom helper for joining any number of arguments with a custom deliminator:
Handlebars.registerHelper('join', function (delim, ...args) {
  args.pop() // remove meta information
  return args
    .filter(arg => arg !== undefined) // filter out undefined properties
    .join(delim);
})

{{join ', ' AUTHOR TITLE JOURNAL (join '' VOLUME '(' NUMBER ')') MONTH YEAR}}

author, title, journal, volume(number), month, year

See playground


text:
Q: Finding duplicates in a 2D array Lets say I have a 2D array with values called int map[][] = new int[10][10]. The default values in the array are 0's and some values in map[][] can change to -1, -2, -3, etc.
Let's say the values in the 2D array are changing constantly and I want to my program to perform something when there are for example, 3 of -3's found or if 2 of -2's found, etc.
I have no idea how to implement this. Please can someone help?

A: You need to build a frequency map for the input 2D array, by iterating the array and adding to the map the values which are not equal to 0.
It is convenient to use Stream API for this, where the input array is converted into a IntStream of int numbers, which is filtered and the frequencies are counted for non-zero numbers.
When the frequency map is ready, the values which occur only once may be excluded.
static Map<Integer, Integer> calculateFrequency(int[][] arr) {
    return Arrays
        .stream(arr) // Stream<int[]>
        .flatMapToInt(a -> Arrays.stream(a)) // IntStream
        .boxed() // Stream<Integer>
        .filter(x -> x != 0) // do not count 0
        .collect(Collectors.groupingBy(x -> x, Collectors.summingInt(x -> 1))); // build the map
}

static Map<Integer, Integer> removeSingles(Map<Integer, Integer> frequencyMap) {
    return frequencyMap
        .entrySet()
        .stream() // Stream<Map.Entry<Integer, Integer>>
        .filter(x -> x.getValue() > 1) // do not count single
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // build the map
}

// test
int[][] arr = new int[10][10];
arr[0][1] = -1;
arr[3][2] = -1;
arr[7][7] = -1;
arr[1][2] = -2;
arr[8][5] = -3;

Map<Integer, Integer> frequencyMap = calculateFrequency(arr);
System.out.println("frequencyMap: " + frequencyMap);

System.out.println("without singles: " + removeSingles(frequencyMap));

output:
frequencyMap: {-1=3, -2=2, -3=1}
without singles: {-1=3, -2=2}


text:
Q: Having issue in deleting task, when I click on remove all tasks in my list remove Having issue in deleting task. When I click on remove all tasks in my list remove from firebase and from page I want to remove the task on which I clicked remove.

that's the code for remove task in reducer

case 'REMOVE_TASK':
        return  omit(state, action.payload);

and that's my code in tasksItems for remove task

const removeTask = ({ id } = {}) => {
    const payload = {id:id}
        database.ref('tasks').remove().then(()=>{
            dispatch({ type: 'REMOVE_TASK', payload})

            console.log('removed');
        })

}


text:
Q: CPU max utilization limited to 1/N CPU's for MOST multi-threaded Apps on any Win OS : WHY? I understand multi-threading and tasking to some extent but know that outside of the OS, most Windows Apps are limited to using only 1/N CPU's for averaged max. utilization.
That is 50% for a dual core, 25% of 4 CPU and 12.5% of all 8 CPU's.  This does not change the result if using Procexp.exe to deallocate CPUs or choose even or odd numbered CPUs.
My question
Is there any way to increase the utilization beyond this OS restricted limit. I understand if one imposed 100% to one App. The OS could blue screen from a non-responding hardware I/O within the expected or required timeout period, but even 50% or 75% would improve my results.
Yet explorer.exe etc in the OS can perform at 50% or more(?) at times when doing large tasks.

*

*normally the CPU is 98~99.5% idle with just a browser open and 10 tabs ( Brave)

I am using Win7 i7-4770S Haswell 3.1GHz with 16GB RAM on LibreOffice SCALC.exe with a spreadsheet with 1.5 million cells of CV19 US data and did a search/replace the ' text prefix to attempt to convert text to a cell number for daily dates (with some options from text to values) and it is still running (yes) and obvious I used the wrong method.
If not possible to change OS utilization ratios, then should I rewrite this question on converting 400 text entries to a value of dates '1\20\2020 to a value for reformatting to my preference.

*

*this text file was downloaded from the GitHub repository for JHU CV19 US county daily mortality cumulative totals and imported into SCALC using text to column conversion.

SCALC is still running !" ,  at 12.5% according to PERFMON using 11 threads.
The problem started with a search and replace of 1 character in a 1.5 million cell spreadsheet. I chose "similarity-option" which was a mistake but the problem is not Excel or Open Office Apps , many apps are multi-threaded but limited to 1/N CPUs on average with no way to change this. I can prove this with images but some of you will know this to be true.
Others do not understand the question.  yes it is possible to write or for Windows to do this but not canned apps.
EXAMPLE 1  simple startup recovery of a large file process only took seconds and peaked above 20% .  It can peak well over 12.5% avearge for a second but not sustained I supposed when there is a memory thruput limitation.  (SO I guess it nothing can improve this ?)

Here a search a replace 0 with 0 on 1.5 million cells
Averaged exactly 12.5% just before I captured the screenshot.

Here almost EXACTLY 1/N or 12.5% of all CPU workload dedicated to 1 Application with many threads.
I can duplicate this test on MANY OTHER APPLICATIONS under Windows with this architecture. So is it architecture - Memory cache bus limited and any fix?
As others have written on this forum, 1/N CPU's limited or 12.50 %
This is the proof.

More proof on multi-thread MS App i=only using 1/N CPU % average MAX

Update
Installed WordPerfect 2020 with QUattro Pro and ran the exact same multi-threaded process and got exactly THE SAME RESULT
MAX CPU USE on all 8 CPUs = 1/8 = 12.5%

Example #4

*

*of a multi-threaded process again utilized all CPu's but in total only 1/N CPUs or 12.5% is Mark Russinovich's  Process Explorer ,aka PROCMON.exe. which was independent of all other processes using few resources.

I doubt it was Mark's ability to program multi-threading here. :) (MS Fellow)

My CPU Latency is on top

A: Not all tasks are inherently capable of being split into a task that is able to simultaneously run on every core of the CPU.
Each core in your CPU is a fully fledged processor. It is able to maintain information on the execution state of one hardware "thread". Each core has its own cache and data handling independent of every other core. They might share a cache and memory bus, but they are otherwise completely separate.
That thread translates roughly to what is known in software as a thread.
The problem you are seeing is that the particular task doing the work within that software is inherently single threaded.
A single thread is only capable of executing on one core at a time. On an 8 core processor that means that a single thread can use at most 1/8th of your processor, or 12.5% according to task manager. On a 4 core processor that is 1/4 or 25%.
A program can have many threads, but those threads can only work on things that are completely unrelated to each other. One thread might be handling updating data being the scenes, another might be updating the GUI and so on.
What threads cannot do is work on the exact same data at the same time without communicating with each other and it is that limit you are seeing.
In order to use more than one CPU core the task being done has to be split up and parcelled out to multiple threads. That splitting up is a programming problem and is down to the software engineers to implement. Whether or not any given task is multithreaded is down to the complexity of that task and whether it can be split up in the first place

*

*does the task contain data that can be split out into independent data sets in order to be worked on by separate threads?

*has the software been written to split up that particular task into separate threads?

If the data is completely dependent on being worked on in a particular way then there is no way it will ever use more than one core.
If the data can be split up but requires lots more work to split and re-merge then software engineers may decide it is not worth the effort and instead stick to using one thread/core.
If the data can be split up and the software is designed to do so then you will see more than 1 core in use.
I know for a number of tasks Excel supports multi-core calculations but it depends entirely on data having absolutely no dependencies on each other.


text:
Q: Problem with hive thrift or with HiveMetastore by Apache Airflow We have a problem when possible trying to connect with Hive Metastore by HiveMetastoreHook in Apache Airflow
thrift.transport.TTransport.TTransportException: b'Error in sasl_decode (-1) SASL(-1): generic failure: Unable to find a callback: 32775'
We googled this issue but still have not find any answer
But for temporary fix - We do REcreate our hive external table on which the issue happens and restart this task. Then after a few days this problem happens again and again and again. And we have no any idea where we need to fix.
NOTE:
This happens only on one big table ,
we have hive 3.1.0 and Airflow 1.10.5 ,
this issue reproduces from python3 cli by import airflow,
select this big table from hive is fine (data is fine too)
Full stack trace
[2021-06-30 18:05:41,143] {{base_hook.py:84}} INFO - Using connection to: id: our_hive_metastore_connection. Host: server_name, Port: someport, Schema: our_schema, Login: some_login, Password: None, extra: {'authMechanism': 'GSSAPI', 'kerberos_service_name': 'some_name'}
>>> hm.get_table(table_name='some_big_table', db='some_schema')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/lib/python3.6/site-packages/airflow/hooks/hive_hooks.py", line 608, in get_table
 return client.get_table(dbname=db, tbl_name=table_name)
 File "/usr/local/lib/python3.6/site-packages/hmsclient/genthrift/hive_metastore/ThriftHiveMetastore.py", line 2253, in get_table
 return self.recv_get_table()
 File "/usr/local/lib/python3.6/site-packages/hmsclient/genthrift/hive_metastore/ThriftHiveMetastore.py", line 2266, in recv_get_table
 (fname, mtype, rseqid) = iprot.readMessageBegin()
 File "/usr/local/lib64/python3.6/site-packages/thrift/protocol/TBinaryProtocol.py", line 134, in readMessageBegin
 sz = self.readI32()
 File "/usr/local/lib64/python3.6/site-packages/thrift/protocol/TBinaryProtocol.py", line 217, in readI32
 buff = self.trans.readAll(4)
 File "/usr/local/lib64/python3.6/site-packages/thrift/transport/TTransport.py", line 62, in readAll
 chunk = self.read(sz - have)
 File "/usr/local/lib/python3.6/site-packages/thrift_sasl/__init__.py", line 166, in read
 self._read_frame()
 File "/usr/local/lib/python3.6/site-packages/thrift_sasl/__init__.py", line 180, in _read_frame
 message=self.sasl.getError())
thrift.transport.TTransport.TTransportException: b'Error in sasl_decode (-1) SASL(-1): generic failure: Unable to find a callback: 32775'```

Is anybody have some idea what we need to fix?
Appreciate for help!


text:
Q: How to solve W/NetworkRequest: No App Check token for request? I cannot pass user info to firebase database, and I think this is the issue. My Authentication part works well, and can pass image to firebase storage. Can anyone explain to me what does this error mean?

Here is my method:

Also, in logcat, it shows "one way function results will be dropped but finished with status OK and parcel size 4", which I think is the same issue if I am not wrong

Here are my dependencies:

Can anyone help me please?

A: Searching elsewhere I found this answer:
"Seems like you have enabled App Check in your Firebase project. This feature was announced a few days ago, so it's unlikely you will find any info online. Check the docs to see if you have followed all the setup steps: https://firebase.google.com/docs/app-check "


text:
Q: func.apply with THIS applying to no object I don't understand why the following code passes this and arguments to func.apply.
I tried to play with the code to figure out what it is doing, searched on the internet, etc., but couldn't find anything about using apply this way.
 function work(a, b) {
     alert( a + b );
 }

 function spy(func) {
     function wrapper(...args) {
         wrapper.calls.push(args);
         return func.apply(this,arguments);
     }
     wrapper.calls = []
     return wrapper;
 }
 work = spy(work)
 work(1, 2); // 3
 work(4, 5); // 9

The following call returns the result of wrapper
work.apply(this,arguments(a,b))

The result of spy is the same as the above.
But what makes this and arguments do the right thing in wrapper? Because without the this it doesn't work and why when i declare
let work = spy(work)

It doesn't work.

A: work is already declared here (function declaration). You can use var instead if you want to redeclare.
In this particular example, you are not using this inside work function. So it doesn't make a difference even if you invoke func like this func(...args) as below:
function work(a, b) {
 alert( a + b );
}

function spy(func) {
   function wrapper(...args) {
      wrapper.calls.push(args);
      console.log({ this: this });
      return func(...args);
   }
   wrapper.calls = []
   return wrapper;
 }
var work = spy(work)
work(1, 2);
work(4, 5);


text:
Q: Swift 5 Add alpha to UILabel with attributed text I have a UILabel that incorporates two different strings/font via attributed text.
I would like to incorporate an alpha on the attrs2 of the UILabel. But leave the first part of the string with no alpha.
Code:
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.textAlignment = .center
        let attrs1 = [NSAttributedString.Key.font : UIFont(name:"SFMono-Bold", size: 20)]

        let attrs2 = [NSAttributedString.Key.font : UIFont.sfMonoMedium(ofSize: 20)]

        let attributedString1 = NSMutableAttributedString(string:"Fast credit card\n payments", attributes:attrs1 as [NSAttributedString.Key : Any])

        let attributedString2 = NSMutableAttributedString(string:" using Square.", attributes:attrs2 as [NSAttributedString.Key : Any])

        attributedString1.append(attributedString2)
        label.attributedText = attributedString1

        return label
    }()

Pseudo:
let attrs2 = [NSAttributedString.Key.font : UIFont.sfMonoMedium(ofSize: 20), NSAttributedString.Key.font.alpha..... : 0.75]

or
attrs2.alpha = 0.75

A: You can do that with the .foregroundColor attribute.
let attrs2: [NSAttributedString.Key: Any] = [
    .font : UIFont.sfMonoMedium(ofSize: 20),
    .foregroundColor: UIColor.black.withAlphaComponent(0.5),
]


text:
Q: visualise unconnected graph in Gephi I have a graphviz file generated in Python as follows:
strict graph G {
    iruo;
    valentin6232;
    shockwaver;
    jojo6938;
    beahero;
}

Unfortunately, if I open the graph file in Gephi it does not show any of the unconnected nodes. If I connect at least one edge it shows only the nodes of the connected edges. What's going on?

A: I fiddled around a bit and saw that if you introduce an empty attribute, Gephi successfully show all nodes, unconnected or not.
strict graph G {
    iruo [];
    valentin6232 [];
    shockwaver [];
    jojo6938 [];
    beahero [];
}

However, the dot program is capable of handling nodes that don't have any attributes, so I guess this issue is something specific to Gephi.


text:
Q: Creating Reboot Procedure For Legacy Linux Server I have a legacy Linux System which has some processes ( manually or automatically started )  running under different users. The server is not restarted since long time, and current staff doesn't know what specifically must be run there and what to start manually after restart.
I have to do a storage migration so that, I'll shutdown and restart it.
In Windows, I can open services.msc and note "manually started" and "automatically but stopped" processes for proper restart even if I don't know what is running there.
What is the procedure for Linux to learn exactly what to restart or what to stop and how to do it after proper reboot ?

A: Under a RHEL or CentOS-based system, pay attention to what services are set to run by checking the chkconfig list or ntsysv commands.
For any individual processes that run under particular users, take note of them. See if you can identify the programs in a ps -ef output, for example.


text:
Q: getting corrupt file error while connecting c++ with mysql I'm trying to connect MySql with C++ using visual studio 2019 but i'm getting a corrupt file error ,I downloaded the no-install-1.1.12-winx64 version of the connector(my pc is 64bit), then i downloaded boost 1.75.0 and linked it. i did my linkings as follows: (on All configurations, Win32/x64 platforms):
Configuration properties:
General:
(its a dll library so) conf. Type: .dll
VC++ Directories:
include directories - $(SolutionDir)mysql-connector-c++-noinstall-1.1.12-winx64\include
Library directories:
$(SolutionDir)mysql-connector-c++-noinstall-1.1.12-winx64\lib;
C/C++:
General:
Additional include Directories - $(solutiondir)boost_1_75_0
Linker:
General:
Additional Library Directories - $(SolutionDir)mysql-connector-c++-noinstall-1.1.12-
winx64\lib;C:\Program Files\MySQL\MySQL Server 8.0\lib
input:
mysqlcppconn.dll;libmysql.dll;%(AdditionalDependencies)
Im not a veteran when it comes to C++ linking so im pretty sure i did something wrong on the linking, please help! (Visual Studio 2019, Windows 10 64bit,10.0, Build 19041, 19041.vb_release.191206-1406)
here is the code i get this error on:
int main(){
cout << endl;
            cout << "Running 'SELECT 'Hello World!'" << endl;

            try {
                sql::Driver* driver;
                sql::Connection* con;
                sql::Statement* stmt;
                sql::ResultSet* res;

                driver = get_driver_instance();
                con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
                con->setSchema("test");

                stmt = con->createStatement();
                res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
                while (res->next()) {
                    cout << "\t... MySQL replies: ";
                    /* Access column data by alias or column name */
                    cout << res->getString("_message") << endl;
                    cout << "\t... MySQL says it again: ";
                    /* Access column data by numeric offset, 1 is the first column*/
                    cout << res->getString(1) << endl;
                }
                delete res;
                delete stmt;
                delete con;

            }
            catch (sql::SQLException& e) {
                cout << "# ERR: SQLException in " << __FILE__;
                cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;
                cout << "# ERR: " << e.what();
                cout << " (MySQL error code: " << e.getErrorCode();
                cout << ", SQLState: " << e.getSQLState() << " )" << endl;
            }

            cout << endl;

            return EXIT_SUCCESS;
}

here is the error log:
Error       'unicodeescape' codec can't decode bytes in position 243133: truncated mysqlcppconn.dll 8020
Error       bad char for the integer value: '8' (base 8)        lib\mysqlcppconn.dll    428
Error       can't assign to binary operator     \mysqlcppconn.dll   7306
and a millon copy of those and some more...
(i also tried steps found here to no avail: https://dev.mysql.com/doc/connector-cpp/1.1/en/connector-cpp-apps-windows-visual-studio.html#connector-cpp-apps-windows-linking)
P.S., before writing this i was simply getting the "cant read from a corrupt file 0x06" error but for some reason while i was trying to get a copy of the error log for this question i started getting these error above.
Please help! Thanks...

A: Ok so basicly i solved it with the most "programmer" way ever, I just went crazy and deleted the whole project and started again, this time making sure that everything is x64 bit (i made sure that its 64 bits before but it seems i overlooked something) and made sure that i followed the docs word by word, and what do you know, it worked!


text:
Q: How to save and load HTML5 Canvas to & from localStorage? I want the user to be able to save canvas drawings to the localStorage (using the Save button)under a custom name and then be able to load (using the load button) previous drawings from the localStorage.

A: First step will be to get image data from canvas.
var imageData = myCtxt.getImageData(0,0,WIDTH,HEIGHT);

Now store it to localStorage after stringifying it:
localStorage.setItem(savekey, JSON.stringify(idt));

To read and set the data back you can use following:
var idt = localStorage.getItem(savekey) || null;
if (idt !== null) {
    var data = JSON.parse(idt);
    ctx.putImageData(idt, 0, 0);
}

I have put the functions to handle the functionality in your fiddle.
Regarding localStorage you can read this and this questions.

A: First option
If you want to save just a bitmap then you can save it this way:
localStorage.setItem(canvasName, canvas.toDataURL());

and then load like this:
var dataURL = localStorage.getItem(canvasName);
var img = new Image;
img.src = dataURL;
img.onload = function () {
    ctx.drawImage(img, 0, 0);
};

I recommend to use canvas.toDataURL() instead of ctx.getImageData() because ctx.getImageData() JSON string size will be just enormous even if canvas is empty.
Second option
If you want to store canvas as lines array then you should store lines coords in some variable and save it`s json:
localStorage.setItem(canvasName, JSON.stringify(linesArray));

Then you can load lines array and redraw canvas:
var lines = JSON.parse(localStorage.getItem(canvasName));
lines.forEach(function (line) {
    ctx.beginPath();
    ctx.strokeStyle = line.color;
    ctx.moveTo(line.x1, line.y1);
    ctx.lineTo(line.x2, line.y2);
    ctx.stroke();
});


text:
Q: How to label lines in Tilemill? I am designing my map with tilemill. Now I am struggling with data visualization. I would like to visualize the road name like the 1st image instead of the second image. I have loaded the data source of tilemill from shapefile which contain Road name that field I want to visualize. Can anybody help me on this issue, whether it is possible or not to make the annotation from data?

A: I found the Tilemill/Mapbox documentation a little tough to navigate for beginners as well.  Having just figured this out, a few clarifications:
a) Start with the mapbox/tilemill guide to styling labels. LINK  Note that you call the desired table (layer) with the # (for example #roads).  Use the layers button to find which column in the table contains the road names (for example 'ROAD_NAME').  You'll then use that column info to create labels like so:
#roads {
   **text-name: [ROAD_NAME];**
   text-size: 16;
   text-fill: #fff;
}

b) To get the effect you reference in the first attached image, you'll probably want to align your labels to the road lines (follow the same tutorial link above).
#roads {
   text-name: [ROAD_NAME];
   text-size: 16;
   text-fill: #fff;
   **text-placement: line;**
}

c) Sometimes you want to get more specific with what you're styling.  A common example: road types defined as residential, motorway, highway or bikepath in a column called ROAD_TYPE.
#roads [ROAD_TYPE = "motorway"] {
   text-name: [ROAD_NAME];
   text-size: 16;
   text-fill: #fff;
   text-placement: line;
}

The style mark-up between the {} will only apply to roads of ROAD_TYPE "motorway".
d) Finally, the tutorial on Advanced Label Placement should help with further issues once you're comfortable with the basics. LINK
Hope it helps!


text:
Q: bridging mqtt brokers hivemq and mosquitto I'm trying to bridge two MQTT brokers on the same system, HiveMQ and Mosquitto. HiveMQ is working on port 1884 and Mosquitto is running on 1883. However when I use the mosquitto_pub command to publish to the mosquitto broker at port 1883, it does not show up on port 1884 (Using MQTT.fx as a client subscribing to all topics on port 1884)
This is while I only configured the mosquitto broker with a bridge.
When I configured HiveMQ as well, it only shows an unable to connect to Bridge1, disconnected message on the HiveMQ command window. I've included the configurations below. Someone please help.
In the mosquitto.config file I have done the following under bridges.
    connection hivemq
    address 127.0.0.1:1884
    start_type automatic
    clientid clientno1
    notifications true

Meanwhile, I also editted the HiveMQ bridges.xml file to read
<?xml version="1.0" encoding="UTF-8"?>
<bridges xsi:noNamespaceSchemaLocation="http://www.hivemq.com/bridges/bridge.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<bridge>
    <connectionName>Bridge1</connectionName>
    <addresses>
        <address>
            <host>localhost</host>
            <port>1883</port>
        </address>
    </addresses>
    <clientId>bridgeClient</clientId>
    <topicPatterns>
        <topicPattern>
            <topic>#</topic>
            <qos>1</qos>
            <direction>both</direction>
            <localPrefix>local/</localPrefix>
            <remotePrefix>remote/</remotePrefix>
        </topicPattern>
    </topicPatterns>
    <cleanSession>true</cleanSession>
    <idleTimeout>10</idleTimeout>
    <notificationsEnabled>true</notificationsEnabled>
    <tryPrivate>true</tryPrivate>

</bridge>

The image shown is when I tried the same process on another system. Here, the brokers are bridged. Comparing this to what I was doing earlier, the only difference is that on my original system there is no statement saying opening ipv4 listen socket on 1883. Is this the problem?

A: You should only need to have the bridge configured in one of the brokers, having bridges configured for both will lead to problems, most likely message loops
For your mosquitto config you need to add a topic line to your mosquitto bridge so it knows what topics to send (and receive) to the hive broker
The full details about the topic directive can be found in the mosquitto.conf man page (http://mosquitto.org/man/mosquitto-conf-5.html) but the basics are:

topic pattern [[[ out | in | both ] qos-level] local-prefix remote-prefix]

To mirror all topics in both directions
topic # both

A: Bridging should only be set on the publisher/client side (mosquitto in your case), leaving default settings on Hivemq (server) should be fine
Try make changes to your mosquitto.conf
connection bridge-mosquitto-to-hivemq
address 127.0.0.1:1884
topic room1/# both 2 sensor/ myhouse/
bridge_protocol_version mqttv311
notifications true
cleansession true
try_private true

After restart your brokers, at mosquitto broker, try publish an example message below
mosquitto_pub -t sensor/room1/temperature -m '26.3'


text:
Q: SQL Alert for long running queries I want to receive a mail when a query is running for more than x seconds. I know I can set up a job running on the database but, is there any way to do the same using SQL Alerts? What kind of alert should I use?
   Thanks.

A: If you have sp_WhoIsActive (great tool, can be downloaded here: http://whoisactive.com/) you can log the results to a table and then email out if the threshold you set for the duration is tripped.
example:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
---- Load WhoIsActive To A Temp Table

IF OBJECT_ID('tempdb.dbo.#wia') IS NOT NULL DROP TABLE #wia

CREATE TABLE #wia ( [dd hh:mm:ss.mss] varchar(8000) NULL,[session_id] smallint NOT NULL,[sql_text] xml NULL,[login_name] nvarchar(128) NOT NULL,[wait_info] nvarchar(4000) NULL,[CPU] varchar(30) NULL,[tempdb_allocations] varchar(30) NULL,[tempdb_current] varchar(30) NULL,[blocking_session_id] smallint NULL,[reads] varchar(30) NULL,[writes] varchar(30) NULL,[physical_reads] varchar(30) NULL,[used_memory] varchar(30) NULL,[status] varchar(30) NOT NULL,[open_tran_count] varchar(30) NULL,[percent_complete] varchar(30) NULL,[host_name] nvarchar(128) NULL,[database_name] nvarchar(128) NULL,[program_name] nvarchar(128) NULL,[start_time] datetime NOT NULL,[login_time] datetime NULL,[request_id] int NULL,[collection_time] datetime NOT NULL)

EXEC sp_WhoIsActive
    @format_output = 1,
    @destination_table = '#wia'

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
---- Find Long Running Queries

IF OBJECT_ID('tempdb.dbo.#Temp') IS NOT NULL DROP TABLE #Temp

SELECT
[dd hh:mm:ss.mss],
session_id,
CAST(sql_text AS VARCHAR(MAX)) AS sql_text,
login_name,
wait_info,
host_name,
database_name,
program_name,
start_time
INTO #Temp
FROM
#wia

WHERE
start_time < DATEADD(HOUR,-8,GETDATE() ) -- CHANGE THIS TO WHATEVER YOU WANT

DECLARE @CNT INT = (SELECT COUNT(*) FROM #Temp )

IF @CNT > 0
BEGIN
----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------

DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)

SET @xml = CAST(( SELECT [dd hh:mm:ss.mss] AS 'td','',session_id AS 'td','', [sql_text] AS 'td','',
[login_name] AS 'td','',[wait_info] AS 'td','','',[host_name] AS 'td','',
[database_name] AS 'td','', [program_name] AS 'td','',start_time AS 'td'
FROM  #Temp
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

SET @body ='
Long Running Queries

 dd hh:mm:ss.mss 	  session_id 	  sql_text 	  login_name
 wait_info 	  host_name 	  database_name
 program_name 	  start_time

'

SET @body = @body + @xml +'
'

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'XXXXX', -- replace with your profile
@body = @body,
@importance = 'HIGH',
@body_format ='HTML',
@recipients = 'XXXXX', -- replace with your email address
@subject = 'Longing Running Queries On <SERVER_NAME>' ;

DROP TABLE #Temp

END


text:
Q: How to vertically center a div with sass (compass)? Well, everything is in the question...
I'm working on a login form that I would like to align vertically at the center of the body.
I'm new to sass and compass, and I struggle to use the right mixin for this...
The html code is pretty simple:
<body>
   <div>
       A div of unknown height to be vertically centered.
   </div>
</body>

This is the CSS3 code that would make it work:
 <style>
    html{
      height:100%;
    }
    body{
      height:100%;
      display:flex;
      align-items:center;
      /* I spared all the compatibility properties for the different browsers */
    }
</style>

___EDIT :
I came up to something like this, but I realized I misunderstood the way to use the parent selector with SASS:
div.ieVerticalCentered {
    body.verticalCentering & {
        height:100%;
        display:-ms-flexbox;
        display:-moz-box;
        display:-webkit-box;
        display:-webkit-flex;
        display:flex;
        -ms-align-items:center;
        -moz-align-items:center;
        -webkit-align-items:center;
        align-items:center;
            html.verticalCentering & {
            height:100%;
        }
    }
}

Therefore, the core question is: is it possible to apply a specific style to a parent element when a child element has a specific class.
In my knowledge, it's not possible with static CSS, but could be done with JS. Having just discovered Sass, I was wondering if something nice could be considered...

A: I finally found a solution.
A specific class should be added to the htmltag.
html.verticalCenter { // Center vertically body's block-children
    height: 100%;
    & body {
        height:100%;
        display:-ms-flexbox;
        display:-moz-box;
        display:-webkit-box;
        display:-webkit-flex;
        display:flex;
        -ms-align-items:center;
        -moz-align-items:center;
        -webkit-align-items:center;
        align-items:center;
    }
}

Or, if you've got compass :
html.verticalCenter { // Center vertically body's block-children
    height: 100%;
    & body {
        height:100%;
        @include display-box;
        @include box-align(center);
    }
}

A: I use this mixin to centre content.  It uses tranforms so not all versions of IE are supported.
MIXIN:
@mixin centre($axis: "both"){
    position:absolute;
    @if $axis == "y"{
        top:50%;
        -webkit-transform: translateY(-50%);
        -moz-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        -o-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    @if $axis == "x"{
        left:50%;
        -webkit-transform: translateX(-50%);
        -moz-transform: translateX(-50%);
        -ms-transform: translateX(-50%);
        -o-transform: translateX(-50%);
        transform: translateX(-50%);
    }
    @if $axis == "both"{
        top:50%;
        left:50%;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }
}

USAGE:
Y axis : @include centre(y);
X axis : @include centre(x);
Both axis : @include centre;

WORKING EXAMPLE: Fiddle

A: vertical-align {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Link:
https://github.com/DimitriMikadze/sass-useful-mixins


text:
Q: Bipartite Graphs and Perfect Matchings when |A|=|B|=n Question: Consider a bipartite graph G with vertex classes A and B, where $|A|=|B|=n$. Show that if $|N(S)|>|S|$ for all $S \subset A$, then for any edge e of G, G contains a perfect matching which contains e.
Answer: So far I have shown that G contains a matching which contains e using Hall's Theorem however I am unsure about how to show that this matching is perfect. I have the following theorem:
Let G be a bipartite graph with vertex classes A and B and $|A|=|B|=n$. If $\delta (G) \geq n/2$, then G has a perfect matching.
But I don't know how to show the $\delta (G) \geq n/2$ part in this case?

A: I think Hall's theorem is sufficient. Note that in your problem you have $|N(S)| > |S|$ with strict inequality (presumably for nonempty strict subsets $S$ of $A$), while Hall's theorem only requires the non-strict inequality.
Let $G'$ be the result of removing the edge $e$ and its two vertices (call them $a \in A$ and $b \in B$) from $G$.
Let $A'$ and $B'$ be the partition of the vertices of $G'$.
It then suffices to show that the smaller bipartite graph $G'$ satisfies its own condition for Hall's theorem.
Let $S'$ be any subset of $A'$. Since it is a subset of $A$ as well, it satisfies $|S'| < |N_G(S')|$, so
$$|S'| \le |N_G(S')| - 1 \le |N_{G'}(S')|$$
since the sets $N_{G'}(S')$ and $N_G(S')$ can differ by at most one vertex, namely $b$.

A: @Koala...
Can you mention cite the theorem which you have mentioned in the question
aka.
Let $G$ be a bipartite graph with vertex classes $A$ and $B$ and $|A|=|B|=n$. If $\delta(G)\geq n/2$, then $G$ has a perfect matching.
Where did u find this theorem?
I know a similar theorem called Dirac's theorem, but that works for general graphs which have minimum degree of each vertex to be at least $n/2$.