text:
Q: How to do something like document.getElementById().value in typescript? I have some code that includes a react form that has something like this in it :
<input id="region"></input>

I have a function that is called from a button click and I want to get the value of the id "region".
I have seen that supposedly I can do something like this :
let test : string = <HTMLInputElement>document.getElementById(region).value;

But I can verify 8 ways to Sunday that does not work. I get syntax errors saying a comma is missing if I try that.
So is there a way to do this? What am I missing? treat me like an idiot since I am only 48 hours into typescript.

A: I assume you're using React due to the tag, and thus I assume the following code is in a tsx file.
let test : string = <HTMLInputElement>document.getElementById(region).value;

You cannot use arrow bracket casts in TSX files because TypeScript will assume you're trying to use a React Element. You must instead use the as form of casts:
let test : string = (document.getElementById(region) as HTMLInputElement).value;

A: I would like to add a couple of notes, because I cannot comment. While using TypeScript, and although all valid JS is valid TS as well, @Heretic Monkey is right the DOM is not generally used to manipulate the values.
Additionally, there are two mistakes in your TypeScript:
---let test : string = <HTMLInputElement>document.getElementById(region).value;---
Firstly, I believe you cannot initialize your variable and access the element's value at the same time. You ought to first assign your variable to the input element, and then use the variable to access its value. Example:
let test : string = <HTMLInputElement>document.getElementById(region);
console.log(test.value);
Secondly, the element's id should be quoted in both cases. When assigning the id inside the tag itself, and when trying to access it.
let test : string = <HTMLInputElement>document.getElementById("region");
A little late to this question, but if it is not solved and you're still struggling, give it a go. Hope it helps.

A: you must use ref in react:
Then call it in your function.
Like this
private regioninput: HTMLInputElement;

constructor(props) {
    super(props);
    this.regioninput = null;
    this.setregionInputRef = element => {
        this.stepInput = element;
    };
}

your element change :
   <input type="text" ref={this.setregionInputRef} />

A: Typescript is a superset of Javascript. Every valid Javascript code is a valid Typescript code.
If what you are trying to do isn't working as intended, it is for another reason.


text:
Q: How to extract records which have a mix of values in a specific field? I am running SQL Server 2012 and I have the following table called StayDateInfo.
An extract of this table is given below:
ResaID    StayDate    RoomCat
100       2018-03-01   STD
100       2018-03-02   STD
100       2018-03-03   STD
101       2018-04-15   STD
101       2018-04-16   STD
101       2018-04-17   DLX
101       2018-04-18   DLX

This table holds around 2 million rows.
I need to extract all 3 columns from that table where the RoomCat values by ResaID are NOT the same for each StayDate.
In the extract above, ResaID 101 will need to be in the output as it has a mix of values (STD and DLX) for its RoomCat.
How do I write my T-SQL query to achieve this?

A: Replace your actual table name with @xyz in below solution.
Input Data for my testing -
declare @xyz table (ResaID    int, StayDate    date, RoomCat varchar(10))

insert into @xyz
select 100       ,'2018-03-01',   'STD' union all
select 100       ,'2018-03-02',   'STD' union all
select 100       ,'2018-03-03',   'STD' union all
select 101       ,'2018-04-15',   'STD' union all
select 101       ,'2018-04-16',   'STD' union all
select 101       ,'2018-04-17',   'DLX' union all
select 101       ,'2018-04-18',   'DLX'

Solution -
SELECT
    *
FROM
@xyz AS X
INNER JOIN (
    SELECT ResaID FROM @xyz GROUP BY ResaID HAVING COUNT(DISTINCT RoomCat) > 1
    ) AS Y ON Y.ResaID = X.ResaID

A: With joins:
SELECT
    DISTINCT ResaID, StayDate, RoomCat
FROM
    StayDateInfo
WHERE
    ResaID IN
    (
        SELECT
            first.ResaID
        FROM
            StayDateInfo first
            JOIN StayDateInfo second ON
                first.ResaID = second.ResaID
                AND first.StayDate = second.StayDate
                AND first.RoomCat != second.RoomCat
    )

With groupings:
SELECT
  DISTINCT *
FROM
  StayDateInfo
WHERE
  ResaID IN
  (
    SELECT
      ResaID
    FROM
    (
      SELECT
          ResaID, StayDate, RoomCat
      FROM
          StayDateInfo
      GROUP BY
          ResaID, StayDate, RoomCat
    ) grouped
    GROUP BY
      ResaID, StayDate
    HAVING COUNT(1) > 1
  )

A: This should do it:
select ResaID
from table
group by ResaID
having count(distinct RoomCat) > 1

A: try this:
 declare @tableA table(ResaID INT,StayDate DATETIME,RoomCat varchar(3))

    INSERT INTO @tableA
    SELECT 100,'2018-03-01','STD'
    union all
    SELECT 100,'2018-03-02','STD'
    union all
    SELECT 100,'2018-03-03','STD'
    union all
    SELECT 101,'2018-04-15','STD'
    union all
    SELECT 101,'2018-04-16','STD'
    union all
    SELECT 101,'2018-04-17','DLX'
    union all
    SELECT 101,'2018-04-18','DLX'

    select ResaId
    from @tableA
    Group by ResaId
    Having COUNT(DISTINCT RoomCat)=2

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I encoding when a warning message appears? I have "r" to get the necessary elements from the website.
I think I did the encoding properly. But it seems to be an error and encoding error.
I also upload errors with my code.
Could you tell if something went wrong?
Tell me how to fix the wrong thing.
library(httr)
library(rvest)
library(stringr)

list.url <- "https://section.blog.naver.com/sub/SearchBlog.nhn?type=post&option.keyword=%EA%B3%B5%EB%B6%80&term=period&option.startDate=2017-07-15&option.endDate=2017-07-16&option.page.currentPage=1&option.orderBy=date"
titles = c()

for(i in 1:30){
  url = modify_url(list.url, query=list(option.page.currentPage=i))
  h.list = read_html(url, encoding = 'utf-8') ## url Change coding

  title.links = html_nodes(h.list, 'h5 a')
  article.links = html_attr(title.links, 'href')

  article.links = unique(article.links)
  article.links = article.links[grep('http://blog.naver.com', article.links)]

  for(link in article.links){
    h = read_html(link, encoding='CP949')
    h = read_html(paste0('http://blog.naver.com', html_attr(html_nodes(h, '#mainFrame'), 'src')), encoding = 'CP949')

#Get into the site, get the title
    title = str_trim(repair_encoding(html_text(html_nodes   (h, '.pcol1.itemSubjectBoldfont')), from = "UTF-8"))
    titles = c(titles, title)

    print(link)

  }
}

Warning messages:
1: In stringi::stri_conv(x, from = from) :
  the Unicode codepoint \U00008bb2 cannot be converted to destination encoding
2: In stringi::stri_conv(x, from = from) :
  the Unicode codepoint \U00007231 cannot be converted to destination encoding
3: In stringi::stri_conv(x, from = from) :
  the Unicode codepoint \U00002b50 cannot be converted to destination encoding
4: In stringi::stri_conv(x, from = from) :
  the Unicode codepoint \U0000fe0f cannot be converted to destination encoding

Results when you type"guess_encoding(titles)"
      encoding language confidence
1        UTF-8                1.00
2     UTF-16BE                0.10
3     UTF-16LE                0.10
4 windows-1255       he       0.08
5 windows-1255       he       0.06
6   IBM420_ltr       ar       0.03
7   IBM420_rtl       ar       0.02

Results when you type"guess_encoding(title)"
       encoding language confidence
1        UTF-8                1.00
2 windows-1255       he       0.11
3     UTF-16BE                0.10
4     UTF-16LE                0.10
5 windows-1250       hu       0.09
6 windows-1252       fr       0.07
7 windows-1255       he       0.03


text: Q: Пауза на видео если оно вышло за область видимости Подскажите, как понять, находится ли элемент (тег video) в области видимости или нет. Если нет, то ставить video на паузу (.pause()). Если такая тема была, дайте ссылочку, пожалуйста..не могу найти. Тегов (video) может быть 2..3..4 и т.д.


text:
Q: Save CSV with same name as current open CSV I have a macro that runs a separate loop macro from personal workbook on a CSV (without opening it) and should re-save the document with the same name.
I get this error when it tries to save.

Run-time error '1004':
You cannot save this workbook with the same name as another open workbook or add-in. Choose a different name or close the other workbook or add-in before saving.

I need this as there is a tool looking for this document name.
This is the macro that opens the csv and runs the loop macro (without opening Excel).
Sub ExcelMacroExample()
    Dim xlApp
    Dim xlBook

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Open("F:\Folder\specific name.csv", 0, True)
    xlapp.workbooks.open("C:\Users\name\AppData\Roaming\Microsoft\Excel\XLSTART \Personal.xlsb")
    xlApp.Run "Personal.xlsb!LoopColumnC "
    xlApp.Quit

    Set xlBook = Nothing
    Set xlApp = Nothing
End Sub

The macro for LoopColumnC is where it tries to save.
Sub LoopColumnC()
    '
    ' LoopColumnC Macro
    '

    '
    'This is to disregard any popups.
    Application.DisplayAlerts = False
    'This is the actual loop. Works just fine.
    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 3).End(xlUp).Row
    For i = 2 To lastRow
        If Cells(i, 3).Value = 1 Then Cells(i, 3).Value = Cells(i - 1, 3).Value
      Next i

    'Here is where it errors out because the file it is trying to save as is already opened in the background.
    ThisWorkbook.SaveAs "F:\Folder\specific name.csv",

    Application.DisplayAlerts = True

End Sub

A: You should modify your code to pass the worksheet object directly to the called macro - don't rely on Activesheet etc.
Sub ExcelMacroExample()
    Dim xlApp
    Dim xlBook

    Set xlApp = CreateObject("Excel.Application")
    'if you want to save with the same name then you can't open as read-only...
    Set xlBook = xlApp.Workbooks.Open("F:\Folder\specific name.csv", 0, True)
    xlapp.workbooks.open("C:\Users\name\AppData\Roaming\Microsoft\Excel\XLSTART \Personal.xlsb")
    xlApp.Run "Personal.xlsb!LoopColumnC", xlBook.Worksheets(1) '<< passes the sheet

    xlBook.Close '<<
    xlApp.Quit

    Set xlBook = Nothing
    Set xlApp = Nothing
End Sub

Your processing macro receives the sheet object:
'gets a worksheet object from the caller
Sub LoopColumnC(ws As Worksheet)

    Dim lastRow As Long
    'operate on the provided worksheet
    lastRow = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row
    For i = 2 To lastRow
        If ws.Cells(i, 3).Value = 1 Then
            ws.Cells(i, 3).Value = ws.Cells(i - 1, 3).Value
        End If
    Next i

    Application.DisplayAlerts = False
    ws.Parent.SaveAs "F:\Folder\specific name.csv" 'ws.Parent = workbook
    Application.DisplayAlerts = True

End Sub


text:
Q: Varieties dominated by products of curves Let $X$ be an irreducible smooth projective variety of dimension $d$. Do there exist irreducible smooth projective curves $C_1, C_2,\ldots, C_d$, an open subset $U\subset C_1\times C_2\times\ldots\times C_d$ and a dominant morphism $f:U\to X$.

A: Ulrich observes in the comments that C. Schoen provides counterexamples in his paper "Varieties dominated by product varieties".  Beyond Schoen's work, this problem has some interesting history, which I learned from this note of Oort.
Grothendieck, in attempting to  prove the Weil conjectures, had hoped that every variety was rationally dominated by a product of curves.  He asked Serre if this was true; Serre showed that a sufficiently general surface contained in an explicit Abelian variety of dimension $5$ is a counterexample.  (See p. 145 of the Grothendieck-Serre Correspondence, which is a really amazing book.)  The counterexample is quite beautiful and very simple, and of a rather different nature than Schoen's.
Essentially Serre observes that of $S\subset A$ is a smooth surface passing through the origin and satisfying the following property:
$(*)$ If $C, C'$ are curves contained in $S$, then $C+C'$ is not contained in $S$
then $S$ cannot be rationally dominated by a product of curves.  This is because the rational map must extend to a  morphism (as it is a map into an Abelian variety) given by adding two maps $C\to A, C'\to A$.  So it suffices to find a surface $S$ satisfying $(*)$.  Serre does this by writing down an explicit analytic germ at the origin satisfying $(*)$ (not too hard) and then approximating this germ by an honest surface (which one may take to be a complete intersection, for example).
Oort notes that Schoen seems not to have been aware of Serre's counterexample.

A: For another family of counter-examples to Grothendieck's question one can take any compact quotient of the unit ball of $\mathbb{C}^n$ (for $n\ge 2$). At least for a topologist/geometer it is a very natural family of examples.
Let me explain this : suppose that we have a surjective holomorphic map $f : S_1 \times \cdots \times S_n\to X= B/\Gamma$ where $\Gamma$ is a torsion free cocompact lattice in ${\rm PU}(n,1)$ ($n\ge 2$) and where the $S_{j}$'s are compact Riemann surfaces. We will derive a contradiction.
At the level of fundamental groups, $f_{\ast}$ has an image of finite index since $f$ is surjective. Replacing $\Gamma$ by a finite index subgroup we assume that $f_{\ast}$ is surjective.
Now we have the following fact:
The group $\Gamma$ is not generated by a family of pairwise commuting, nontrivial, normal subgroups $(H_i)_{1\le i \le N}$ if $N\ge 2$.
This can be seen easily using the fact that the Zariski closure of each such $H_i$ should be ${\rm PU}(n,1)$.
Going back to the morphism $f : S_1 \times \cdots \times S_n \to X$ this says that (after possibly reordering the indices) $f_{\ast}(\pi_{1}(S_{j})$ is trivial for $j\ge 2$.
Hence for a fixed $j\ge 2$ the map $z\mapsto f(p_{1}, \ldots , z, \ldots ,p_{n})$ from $S_{j}$ to $X$ induces the trivial morphism on $\pi_{1}$, hence is constant (since there is no compact Riemann surface in the unit ball of $\mathbb{C}^{n}$).
This implies that $f$ factors through the projection from the product of the $S_{j}$'s onto $S_{1}$ : $f=g\circ pr_{1}$ where $pr_{1}$ is the first projection and $g : S_{1}\to X$ is holomorphic. But this is impossible if $f$ is dominant.
I have not thought on whether we can push this argument to answer the original question (where $f$ is only defined on an open set of the product of the $S_{j}$'s).


text:
Q: Creating data service in Angular I am trying to create a base data service then use it later
(function () {
'use strict';
angular.module('app.core').factory('dataService', ['$http','$q', dataService]);

var dataService = function ($http, $q) {
    var service = {
        httpPost: httpPost,
        httpGet: httpGet,
        httpDelete: httpDelete
    };
    return service;
........

Then trying to consume it by another service
(function () {
"use strict";
angular.module('app.features').factory('customerService',  ['dataService',customerService]);
var customerService = function (dataService) {
    var service = {
        search: search,
        ....
    };
    return service;
.....

But when I try to consume the customer service from the customer controller
(function () {
'use strict';
angular.module("app.features").controller("CustomerCtrl",
["$scope", "$rootScope", "$stateParams", "customerService", "$modal", "toaster",
function ($scope, $rootScope, $stateParams, customerService, $modal, toaster) {
......

I then get the following error
[ng:areq] Argument 'fn' is not a function, got undefined
and the error message is Module 'ngLocale' is not available
and when I remove the customer service reference from the controller the error is gone.
Also here is the modules declaration
//The root for all other modules
(function () {
'use strict';
angular.module("app", [
"app.core", //angular and external code
    "app.directives",//Componenets
    //Custome modules, refacactor later to module per feature
    "app.features"
]);
})();

(function () {
'use strict';
 angular.module('app.core', [
    //Angular modules
    "ngAnimate",
    "ngCookies",
    "ngResource",
    "ngSanitize",
    "ngTouch",
    //3rd party
    "ngStorage",
    'ui.utils',
    'ui.load',
    "ui.router",
    "ui.bootstrap",
    "ui.jq",
    "ui.validate",
    "oc.lazyLoad",
    "pascalprecht.translate"
]);
})();

Scripts refernces
<!-- Vendor scripts -->
<script src="scripts/dependencies/jquery/jquery.min.js"></script>
<script src="scripts/dependencies/angular/angular.js"></script>
<script src="scripts/dependencies/angular/angular-animate/angular-animate.js"></script>
<script src="scripts/dependencies/angular/angular-cookies/angular-cookies.js"></script>
<script src="scripts/dependencies/angular/angular-resource/angular-resource.js"></script>
<script src="scripts/dependencies/angular/angular-sanitize/angular-sanitize.js"></script>
<script src="scripts/dependencies/angular/ngstorage/ngStorage.js"></script>
<script src="scripts/dependencies/angular/angular-touch/angular-touch.js"></script>
<script src="scripts/dependencies/angular/angular-ui-utils/ui-utils.js"></script>
<script src="scripts/dependencies/angular/angular-ui-router/angular-ui-router.js"></script>
<script src="scripts/dependencies/angular/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="scripts/dependencies/angular/oclazyload/ocLazyLoad.js"></script>
<script src="scripts/dependencies/modules/angularjs-toaster/toaster.js"></script>

<!--Application starter& Configuration-->
<script src="scripts/app/app.module.js"></script>

<!--Rename to app.js-->
<script src="scripts/app/main.js"></script>

<!--core-->
<script src="scripts/app/core/core.module.js"></script>
<script src="scripts/app/features.module.js"></script>
<script src="scripts/app/directives/directives.module.js"></script>

<script src="scripts/app/core/dataService.js"></script>
<script src="scripts/app/config.js"></script>
<script src="scripts/app/config.lazyload.js"></script>
<script src="scripts/app/config.router.js"></script>

<!-- all my modules script goes here..-->

<!--Directives-->
<script src="scripts/app/core/ui-load.js"></script>
<script src="scripts/app/directives/setnganimate.js"></script>
<script src="scripts/app/directives/ui-butterbar.js"></script>
<script src="scripts/app/directives/ui-focus.js"></script>
<script src="scripts/app/directives/ui-fullscreen.js"></script>
<script src="scripts/app/directives/ui-jq.js"></script>
<script src="scripts/app/directives/ui-module.js"></script>
<script src="scripts/app/directives/ui-nav.js"></script>
<script src="scripts/app/directives/ui-scroll.js"></script>
<script src="scripts/app/directives/ui-shift.js"></script>
<script src="scripts/app/directives/ui-validate.js"></script>
<script src="scripts/app/directives/ui-panel.js"></script>

Any ideas!

A: One thing to check would be if you are defining the sub modules 'app.directives' and 'app.features'
angular.module('myApp.directives',[]);
angular.module('myApp.features',[]);

Above is the setter for these modules. I can see only the getter for the 'app.features' module where you are attaching the 'customerService' and 'CustomerCtrl' in your current code.
Also another thing to check would be the order of calling you js files in you index.html (if they are separate). If one is dependent upon another it should be called before the dependent resource.
Please give it a try and let me know. Sometimes these things bug a lot :) and believe me it has happened several times to me.


text:
Q: Call a HTTPS WCF Service with Certificate authentication i create a wcf service and hosted it on windows azure. The wcf service is a https one. When ever i call the service the client needs a certificate to verify its authenticity.
When i type the service url on broswer it asks for a verifying certificate and the serivce runs.

So far so good.
Now i need to access the same service in an MVC 4 application. So i made a simple ajax call.
<script>
$(document).ready(function () {
    $("#GetAdjustedSalary").click(function () {
        var salary = parseFloat($("#salary").val());
        var infalation = parseFloat($("#inflation").val());

        $.ajax({
            url: "https://newtonsheikh.cloudapp.net/SalaryService.svc/adjustedsalary?a=" + salary + "&b=" + infalation,
            type: "GET",
            dataType: "JSON",
            contentType: "application/json",
            success: function (data) {
                alert(data);
            }

        });
    });
});
</script>

But i dont get the result. Instead i always get abort error 403.

Do i need to write something on the web.config file in the MVC application? I am stuck and really need help out here.
Thanks

A: Got a solution:
In the ajax call i made a call to the controller
<script>
$(document).ready(function () {
    $("#GetAdjustedSalary").click(function () {
        var salary = parseFloat($("#salary").val());
        var infalation = parseFloat($("#inflation").val());

        var object = {
            salary: salary,
            infalation: infalation
        }

        var data = JSON.stringify(object);

        $.ajax({
            url: "Home/GetData/",
            type: "POST",
            data: data,
            dataType: "JSON",
            contentType: "application/json",
            success: function (data) {
                $("#answer").html(data);
            }

        });
    });
});

Then in the controller:
[HttpPost]
    public ActionResult GetData(string salary, string infalation)
    {
        string output = "";

        try
        {
            X509Certificate Cert = X509Certificate.CreateFromCertFile("d://Cert//newton2.cer");

            ServicePointManager.CertificatePolicy = new CertPolicy();
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://newtonsheikh.cloudapp.net/SalaryService.svc/adjustedsalary?a="+salary+" &b="+infalation+"");
            Request.ClientCertificates.Add(Cert);
            Request.UserAgent = "Client Cert Sample";
            Request.Method = "GET";
            HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
            Console.WriteLine("{0}" + Response.Headers);
            Console.WriteLine();

            StreamReader sr = new StreamReader(Response.GetResponseStream(), Encoding.Default);
            int count;

            char[] ReadBuf = new char[1024];
            do
            {
                count = sr.Read(ReadBuf, 0, 1024);
                if (0 != count)
                {
                    output +=  new string(ReadBuf);
                }

            } while (count > 0);

        }
        catch (Exception ex)
        {
            //Throw the exception...lol :P
        }

        output = output.Replace("\0", "");

        string jsonString = JsonConvert.SerializeObject(output, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

        return Json(jsonString, JsonRequestBehavior.AllowGet);
    }

The CertPolicy Class:
class CertPolicy : ICertificatePolicy
{
    public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
    {
        // You can do your own certificate checking.
        // You can obtain the error values from WinError.h.

        // Return true so that any certificate will work with this sample.
        return true;
    }
}


text:
Q: How is it possible to input a string into an array of pointers to character? My problem is how is it possible to input a string into an array of character pointers? Is memory being dynamically allocated here or something? What is actually getting stored in the array 'name'?
char *name[20];
printf("Enter a string:");
scanf("%s",name);
printf("%s",name);

This code works fine. It prints the string I enter. How is it possible to treat char *name[20] just like char name[20]?

A:
Is memory being dynamically allocated here or something?

No.

This code works fine. It prints the string I enter. How is it possible to treat char *name[20] just like char name[20]?

The behaviour of the program is undefined.
It is undefined, because it violates the requirements of the scanf and printf functions.
The C standard says of %s specifier for both scanf and printf (quoting the standard draft document N1570):

the  corresponding  argument  shall  be  a pointer  to  the  initial  element  of  a  character  array ...

name is not a pointer to the initial element of a character array. It is (actually an array, but) after decaying, a pointer to an initial pointer to character in an array of pointers to characters. Thus the requirements are violated and behaviour of the program is undefined.

what did you mean by "behaviour is undefined"?

It means that nothing about the behaviour of the program is guaranteed. As far as the language is concerned, the program might:

*

*Produce output that you expect.

*Produce output that you didn't expect.

*Produce output that you want to be produced.

*Produce some output that you didn't want.

*Not produce output at all.

*Crash

*Not crash

*Behave differently on another system.

*Behave differently on the same system.

*Behave differently when you're debugging it.

*Behave differently only when you are on vacation.

*Behave differently for any reason possible.

*Behave differently for seemingly no reason at all.

*Behave the same always

*Behave exactly the same as if you had used char name[20] despite not having used it.

*Not behave like that.

*Have any behaviour whatsoever.

Undefined behaviour is to be avoided.

A: scanf and printf expected an array of characters, but you gave it an array of pointers. However, they can't tell the difference because they are variadic. This causes undefined behavior, so anything is possible.
What likely happened here is that scanf simply wrote the characters into the memory of the pointer array and printf treated the data as characters because neither of the functions know that the chunk of memory you gave it is supposed to store pointers instead of characters. Printing out the second element gave you the fifth character likely because your system has four byte pointers, so the second pointer element starts at the fifth byte and therefore a fifth character.
Again, your code exhibits undefined behavior, so the previous paragraph is only speculation. None of this is guaranteed by the standard and you shouldn't rely on it, ever.

A: Although eerorika's answer is perfectly correct, from what I feel OP may need some more detailed explanation of what's going on here…
What you declare with your char * name[20] is NOT an array that points to 20 characters. It IS an array of 20 pointers to memory (each pointer is treated as pointing to a character or an array of characters). The [20] in the declaration already specifies that you need 20 elements, and what is preceeding (char * in your case) specifies what these elemnts are. So the correct declaration(in your context) is simply char name[20].
Now the compiler sees that you need a block of memory of 20 characters and it reserves the memory for you (on stack, no dynamic allocation here). Then char name[20] is a continuous block of reserved memory that can hold 20 characters.
You get an address to the beginning of this block as &name[0] or simply name. The latter only since a static array variable – which is the entire block of 20 chars in your case – is implicitly convertible (not identical to) a pointer to the beginning of that block of memory, i.e. char *. (If you feel like you do not understand this last statement, you may consult e.g. this short article or google around a bit,e.g., on difference between char array and char pointer in c.
The following illustrates what happens with the correct code and what with yours and why it is undefined behaviour (UB) and why it (un)luckily works in your case.
With the correct declaration char name[20] you get
char [20] memory block uninitialized
?character means that the content in every cell of the buffer is not yet specified but the compiler treat it as a character.
When you pass this into scanf and a user enters, say, "HelloKitty", this answer will be filled into the char [20] block of memory reserved by the compiller.
char [20] memory block after passing it to scanf
That's what you want to get.
Now here is what you actually get with your char * name[20] declaration. At the beginign the situation is like this
char * [20] memory block uninitialized
?pointer means that the content in every cell of the buffer is not yet specified but the compiler treat it as a pointer to character.
When you pass this into scanf and the user enters theirs "HelloKitty" this answer will be filled into the char * [20] block of memory reserved by the compiller as previously.
Now more attention is needed. This is possible only due to the fact that scanf is not type-safe. It takes whatever adress it gets (the address of name[0] in your case) and fill it in carelessly, according to what its format specifiers specify. So it hapilly fill an array of characters into a block of memory that is supposed to contain an array of poiners. Now, every character has a binary representation, indeed. So what happens under the hood is that the char * [20] memory block will be filled in with "zeros and ones" that represent the string "HelloKitty" (up to the length of that string).
char * [20] memory block after passing it to scanf
?!pointer means that the content is still treated as a pointer to character by the compiller, yet the value of that pointer (the address it technically points to) has been rewritten by calling scanf. (note: even though "HelloKitty" contains 11 characters including the terminating nul, not 11 cells are rewritten since sizeof each cell equals sizeof of a pointer. Typically sizeof of a pointer is 4 times that of char on a 32bit architecture, so only 2 cells and a part of the third one wil be rewritten)
Now why it all works fine for you is just because printf is just as ignorant of its actual types as its sister scanf. So printf takes the address of name[0] and (re)interpret its "zeros and ones" (back) to the "HelloKitty" string.
Practically, your program will not likely (see below) invoke UB, as long as you pass the name variable  between printf and scanf (or like functions) only. The (binary) content of the memory block reserved for char * name[20] is somewhat (see below) guaranteed to be eqivalent to the (binary representation of) the "HelloKitty" string. As long as the content read by scanf does not exceed the memory block provided to it, the program does not get likely (see below) corrupted in any way. You may just as well write int i; scanf("%s",&i); printf("%s",&i); and the program will (likely) work fine as long as the user eneters less than 3 characters as an input. (supposing sizeof int is 4 chars))
Technically, you code falls in UB. This is just what the standard says. The standard cannot treat every single case of "when the code would actually work if the programmer write something weird". And yes, treating char * [20] as char [20] in scanf is "something weird." Simultaneously, by specifying something UB, the standard gives some freedom to compiler implementers. If you were to write a compiler, you may decide to parse the format in scanf compile-time and generate a special set of instructions that rely on the fact that correct type is provided for name (the fact that I can hardly imagine such scenario - at least for the %s switcher - does not change anything).  So the program is UB. Period. :)
ps.> Consider using scanf("%20s", name) in your code. This will prevent scanf from reading characters beyond the length of the memory block, which would result in yet another UB.


text:
Q: setTimeout start without reason and can't be stopped I activate a tooltip when I move the mouse over an image :

............

Tooltip Text

And it will disappear after I move away the cursor.
Here are the javascript code relative to it:
    function imgover(img, tip) {

        document.getElementById('tooltip6').innerHTML = tip;
        var DivHeight = document.getElementById('tooltip6').scrollHeight;
        //alert(DivHeight);

        //document.getElementById('tooltip6').style.display = 'block';
        document.getElementById('tooltip6').style.height = DivHeight + 'px';
        document.getElementById('tooltip6').style.opacity = '1';
        document.getElementById('tooltip6').style.overflow = 'visible';

    }
    var timeVar;

    function imgout() {

       timeVar =  setTimeout(function () {
            document.getElementById('tooltip6').style.height = '0px';
            document.getElementById('tooltip6').style.opacity = '0';
            document.getElementById('tooltip6').style.overflow = 'hidden';

        }, 3000);
    }

    function imgover_tooltip6() {
        clearTimeout(timeVar);
    }

There are many issues here:
Even when I put in comment the function imgover_tooltip6(), the setTimeout will work fine only the first time, and then when I move again my cursor over the image, the tooltip will disappear (sometimes right away) even though the cursor is still on the image.
And when I move the cursor over the tooltip (before it disappear) the setTimeOut is not stopped, and the tooltip will still disappear.
Here is a link to my site to illustrate the exemple ( the images concerned are those of the carousel in the top)

A: If I understood your problem correctly, you must call clearTimeout(timeVar) before setting setTimeout again to the same variable.
function imgover(img, tip) {
   clearTimeout(timeVar);
   .....
}
function imgout() {
   clearTimeout(timeVar);

   timeVar =  setTimeout(function () {
        document.getElementById('tooltip6').style.height = '0px';
        document.getElementById('tooltip6').style.opacity = '0';
        document.getElementById('tooltip6').style.overflow = 'hidden';

    }, 3000);
}

The reason why the tooltip gets hidden after hovering over the image multiple times, is that when you hover over the image for the first time, timeVar gets the id of the first timer, 1, and when hovering over for the second time, it gets 2. Now when the clearTimeout(timeVar) is called, it clears timer 2, but 1 is still left running and will not get cleared, because timeVar didn't contain it's id anymore.

A: You are not calling clearTimeout for timeVar. you should call imgover_tooltip6 in imgout before setting the timeout.
function imgout() {
   imgover_tooltip6();
   timeVar =  setTimeout(function () {
        document.getElementById('tooltip6').style.height = '0px';
        document.getElementById('tooltip6').style.opacity = '0';
        document.getElementById('tooltip6').style.overflow = 'hidden';

    }, 3000);
}

also call imgout on mouseout of div#tooltip6.

Tooltip Text


text:
Q: Escape quote in Dart Regex I'm trying to use the regex /^[a-zA-Z0-9_$&+:;=?@#|'<>.^*()%!-]+$/ with dart regex. I've seen you can use raw strings. So Ive put the above in between r'' like this:
r'^[a-zA-Z0-9_$&+:;=?@#|'<>.^*()%!-]+$' but  the ' is messing it up. How do I tell dart this is a special character..
EDIT
I tried this but it doesn't seem to work
static final RegExp _usernameRegExp = RegExp(
    r"^[a-zA-Z0-9_$&+:;=?@#|'<>.^*()%!-]+$",
  );

So I have a TextField with a text controller for a username. A method like this
static bool isValidUsername(String username) {
    return (_usernameRegExp.hasMatch(username));
  }

I pass the controller.text as the username.
I've a function:
bool get isUserNameValid => (Validators.isValidUsername(userNameTextController.text.trim()));

I can type all the given characters in to the textbook but not '

A: Your RegExp source contains ', so you can't use that as string delimiter without allowing escapes. It also contains $ so you want to avoid allowing escapes.
You can use " as delimiter instead, so a raw string like r"...".
However, Dart also has "multi-line strings" which are delimited by """ or '''. They can, but do not have to, contain newlines. You can use those for strings containing both ' and ". That allows r'''...'''.
And you can obviously also use escapes for all characters that mean something in a string literal.
So, for your code, that would be one of:
r'''^[\w&+:;=?@#|'<>.^*()%!-]+$'''
r"^[\w&+:;=?@#|'<>.^*()%!-]+$"
'^[\\w&+:;=?@#|\'<>.^*()%!-]+\$'

(I changed A-Za-z0-9$_ to \w, because that's precisely what \w means).
In practice, I'll always use a raw string for regexps. It's far too easy, and far too dangerous, to forget to escape a backslash, so use one of the first two options.
I'd probably escape the - too, making it [....\-] instead of relying on the position to make it non-significant in the character class. It's a fragile design that breaks if yo add one more character at the end of the character class, instead of adding it before the -. It's less fragile if you escape the -.


text:
Q: Computing $\mathrm{Tor}_{i}^{R}(M,(x^k))$, where $R=\mathbb{Z}[x]/(x^n)$ Computing $\mathrm{Tor}_{i}^{R}(M,(x^k))$, where $R=\mathbb{Z}[x]/(x^n)$.
Let $M$ be any $R$ module. $k$ and $n$ are positive integers. I think I have a valid free resolution for $(x^k)$ given by
$$ \cdots \overset{\cdot x^{n-k}}{\longrightarrow}R\overset{\cdot x^k}{\longrightarrow}R\overset{\cdot x^{n-k}}{\longrightarrow}R\overset{\cdot x^k}{\longrightarrow} (x^k)\longrightarrow0$$
We then tensor with $M$ to and take homology. This is where I am running into trouble. With the complex$$ \cdots \overset{1\otimes \cdot x^{n-k}}{\longrightarrow}M\overset{1\otimes\cdot x^k}{\longrightarrow}M\overset{1\otimes\cdot x^{n-k}}{\longrightarrow}M\longrightarrow0$$
I know I should get that $\mathrm{Tor}_{0}^{R}(M,(x^k))=M\otimes_R(x^k)$, but I am having trouble computing that directly. I get $M/(M\otimes (x^{n-k}))$ which I am not sure how to make sense of. Similarly, describing the kernels of these maps is eluding me. Thank you for your help.

A: As $(x^k)\cong R/(x^{n-k})$ as $R$ modules, then the tensor product
$$M\otimes_R(x^k)\cong M\otimes_R R/(x^{n-k})\cong M/(x^{n-k}M).$$
The $\text{Tor}_0^R$ as you compute it is the cokernel of
$\cdot x^{n-k}$ on $M$, that is $M/(x^{n-k}M)$, so it does all check out.


text:
Q: Error in displaying retrieved JSON content In continuation to my question asked here, i have created a test app to check the json parsing using jquery.
It doesnt seem to work. I can append data in the click function. However getting data from that url and parsing seems to fail. Can someone provide some useful hints?

Header

Paragrapgh

Paragraph.

<button>Click me</button>

TIA,
Praveen S

A: The callback is provided so that you can bypass the same origin policy. Thus retrieved JSON data is enclosed within the function name and cannot be parsed directly. Details of doing this with jquery are given here. Please refer the example given below

Please find the working example here.

A: the url does not return a json like you would like try without the     callback=function
with the callback it uses a method called jsonp:
http://ajaxian.com/archives/jsonp-json-with-padding


text:
Q: Fill Factor for Datawarehouse - SQL Server I am planning to set up a script to rebuild all the indexes in one particular database. How do I set the fill factor? How do I determine the fill factor here.
My database is used for data-warehouse purpose. It is insert/update heavy system. Could some suggest me which is the good fill factor rate and how do I know if this fill factor is right.
I am using SQL Server 2008 database.

A: You want a fillfactor of 0 because you are probably loading the file once every period (every night, once a week). If you are going to do massive inserts/updates and you may find that its a lot quicker to drop all the indexes, load the table and recreate all the indexes. So if you are not going to add rows as they come in you want as few reads as possible when searching for something so you want your pages to be totally full. If you are doing inserts you want empty spaces on the page to avoid page splits and that is why you would set a fill factor of not 0.


text:
Q: Does the app run on API level lower than x when AndroidManifest has attribute introduced in x? My use case is "android:xlargeScreens" in <supports-screen> but I wanted to make the question general.
What will happen if I have that attribute in (introduced in API 9), and try to install the app on a phone running API <9?
A side question is whether I also need to set "android:targetSdkVersion" or "android:minSdkVersion" to 9.
Thanks!

A: Attributes that are not supported by lower API levels are just ignored. So you will be able to run your application on older devices without any problems (assuming your code not using functions and classes introduced in newer APIs).
The targetSdkVersion value is used to detect what your defaults should be, while minSdkVersion is used to verify whether your app can even run on the device.
I strongly recommend your reading Android API Levels


text:
Q: Displacement and Interval together in FLP I am using Fused Location Api to get location updates. When I set 15 minute as time interval then I got onLocationChanged() called after every 15 minute. And when I set 50 meter as minimumDisplacement then onLocationChanged() is not called until user moves 50 meter from its original position.
But I need to have onLocationChanged() called when either 15 minute passed or 50 meter distance covered.
I wrote two LocationRequest and two FusedLocationProvider and BroadcastReceiver for handling this problem but my applications worked good in moving user but not worked correct in time interval. I can get location after 15-20 minute but after some hours, the time interval increase and after that i can't get location that user moved and now get location again..
This is some times, I try get location:
2019-03-05 10:24:30.233
2019-03-05 10:39:59.147
2019-03-05 10:39:59.147
2019-03-05 10:51:16.783
2019-03-05 10:56:05.147
2019-03-05 11:01:16.407
2019-03-05 11:16:16.160
2019-03-05 11:31:19.197
2019-03-05 11:49:34.203
2019-03-05 12:46:24.280

And in this situation, I can't get locations until start moving!
This is my service and this service is forground:
public class LFPService extends Service {

private FusedLocationProviderClient mFLPClientTimeInterval;
private FusedLocationProviderClient mFLPClientDistanceInterval;
private LocationRequest mLocationRequestTimeInterval;
private LocationRequest mLocationRequestDistanceInterval;

private static final int NOTIFICATION_ID=123456789;

/**
 * The fastest rate for active location updates. Updates will never be more frequent
 * than this value.
 */
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =15*60*1000;//OfflineData.getGPSIntervalSetting(KITILApplication.getappContext())*1000;//15*60*1000;
        //OfflineData.getGPSIntervalSetting(KITILApplication.getappContext())*1000;

/**
 * The desired interval for location updates. Inexact. Updates may be more or less frequent.
 */
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS;//+60000;

private static final long MAX_WAITE_TIME=OfflineData.getTimeIntervalSetting(KITILApplication.getappContext())*1000;

private NotificationManager mNotificaionManager;
private static final String CHANNEL_ID = "channelLocation_01";

private static final String TAG = LFPService.class.getSimpleName();

private final IBinder mBinder = new LocalBinder();
private Handler mServiceHandler;

@Override
public void onCreate() {
    super.onCreate();

    mNotificaionManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
        mNotificaionManager.createNotificationChannel(mChannel);
    }
    startForeground(AppConstant.SERVICE_NOTIFICATION_ID, getMyActivityNotification(this));

    mFLPClientTimeInterval = LocationServices.getFusedLocationProviderClient(this);
    mFLPClientDistanceInterval = LocationServices.getFusedLocationProviderClient(this);
    getLastLocation();

    createLocationRequest();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(intent!=null&&intent.getAction()!=null&&intent.getAction().equals("LFPStartUpdateLoc")) {
        requestLocationUpdate();
    }else if(intent!=null&&intent.getAction()!=null&&intent.getAction().equals("LFPStopUpdateLoc")){
        removeLocatinUpdate();
    }
    return START_STICKY;
}

@Override
public void onDestroy() {
    removeLocatinUpdate();
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public class LocalBinder extends Binder {
    public LFPService getService() {
        return LFPService.this;
    }
}

private void createLocationRequest() {
    //Location Request for Time Interval
    mLocationRequestTimeInterval = new LocationRequest();
    mLocationRequestTimeInterval.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequestTimeInterval.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequestTimeInterval.setSmallestDisplacement(0);
    mLocationRequestTimeInterval.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //Location Request for Distance Interval
    mLocationRequestDistanceInterval = new LocationRequest();
    mLocationRequestDistanceInterval.setInterval(0);
    mLocationRequestDistanceInterval.setFastestInterval(0);
    mLocationRequestDistanceInterval.setSmallestDisplacement(50);
    mLocationRequestDistanceInterval.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

public void requestLocationUpdate() {
    try {
        mFLPClientTimeInterval.requestLocationUpdates(mLocationRequestTimeInterval, getIntervalPendingIntent());
        mFLPClientDistanceInterval.requestLocationUpdates(mLocationRequestDistanceInterval,getDisplacementPendingIntent());// mLocationCallback,null);
        if (AppConstant.ENABLE_LOG_APPLICATION)
            HelperMethods.recordLogOnDB("LFPService/requestLocationUpdate/System Date= " + HelperUtility.convertDateToString(new Date()));
    }catch (SecurityException ex){
        //Turn off permission
    }
}

public  void removeLocatinUpdate(){
    if (AppConstant.ENABLE_LOG_APPLICATION)
        HelperMethods.recordLogOnDB("LFPService/removeLocationUpdate/System Date= " + HelperUtility.convertDateToString(new Date()));
    mFLPClientTimeInterval.removeLocationUpdates(getIntervalPendingIntent());
    mFLPClientDistanceInterval.removeLocationUpdates(getDisplacementPendingIntent());
}

private PendingIntent getIntervalPendingIntent(){
    Intent intent=new Intent(this,LFPIntervalUpdateBroadcastReceiver.class);
    intent.setAction(LFPIntervalUpdateBroadcastReceiver.ACTION_PROCESS_UPDATES);
    return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}

private PendingIntent getDisplacementPendingIntent(){
    Intent intent=new Intent(this,LFPDisplacementBroadcastReceiver.class);
    intent.setAction(LFPDisplacementBroadcastReceiver.ACTION_PROCESS_UPDATES);
    return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}

private void getLastLocation() {
    try {
        mFLPClientTimeInterval.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                permissionStatus = true;
                if (task.isSuccessful() && task.getResult() != null) {
                    mLocation = task.getResult();
                }
            }
        });
        mFLPClientDistanceInterval.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                permissionStatus = true;
                if (task.isSuccessful() && task.getResult() != null) {
                    mLocation = task.getResult();
                }
            }
        });
    } catch (SecurityException ex) {
        permissionStatus = false;
    }
}

public static Notification getMyActivityNotification(Context context) {
    Intent intentMain = new Intent(context, CategoryActivity.class);
    intentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentMain, 0);

    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder;
    if (AppConstant.DEBUG_MODE)
        Log.e("TEST=Noti Start service", "createNotification");

    Uri alarmSound = Settings.System.DEFAULT_NOTIFICATION_URI;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String channelId = "KITIL_LFPService_id";
        CharSequence channelName = "KITIL_LFPService";
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
        mNotificationManager.createNotificationChannel(notificationChannel);
        builder = new NotificationCompat.Builder(context, channelId);
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.ic_launcher);
        builder.setContentTitle("")
                .setTicker("")
                .setContentText("" + OfflineData.getCartableCount(context) + ".")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(
                        Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setDefaults(Notification.DEFAULT_ALL).setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
        if (AppConstant.DEBUG_MODE)
            Log.e("TEST=Noti Start service", "apiO");
    } else {
        builder = new NotificationCompat.Builder(context, null);
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.ic_launcher);
        builder.setContentTitle("")
                .setTicker("")
                .setContentText(" " + OfflineData.getCartableCount(context) + ".")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(
                        Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setDefaults(Notification.DEFAULT_ALL).setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
        if (AppConstant.DEBUG_MODE)
            Log.e("TEST=Noti Start service", "apiBelowO");
    }
    //mNotificationManager.notify(AppConstant.SERVICE_NOTIFICATION_ID, builder.build());
    return builder.build();
}
}

Can I get location with setSmallestDisplacement OR setInterval? I think with my code, I wrote displacement over interval.


text:
Q: Append a background image based upon their data-attribute via jQuery? I'm probably missing some basic thing.. oh well, you guys probably know.
To make things a bit more dynamic, I would like to have specific objects have a background-image added by their unique data-attribute. Their data attribute will be the file name, while the path will always be same, printed already in the jQuery.
I know the problem lies within the image URL path, because the quotes aren't completed before the first '+'.. But how to fix that?
Html:

jQuery
$(document).ready(function() {
    $('.FPNewsitem').each(function() {
        var itemImage = $(this).data("imgname");
        $(this).css("background-image", "url('../images/newsitems/" + itemImage + ".jpg');");
    });
});

What am I doing wrong?
update: JSFiddle

A: *This answer was given before OP changed the code.
There is no attribute called background-image. What you need is css which is used to style the elements. You don't need ; when you use my code.
$(this).css("background-image", "url('../images/newsitems/" + itemImage + ".jpg')");

Check out more about jQuery.css

A: Check this out this may help u out
Use .css   $(this).css
 instead of attr
$(this).css

Jsfiddle


text:
Q: Fail to load ApplicationContext SpringBoot with SpringSecurity and JUnit Jupiter I'm working on a REST API using Spring Boot. Currently, the V1 of the API is complete. So, I'm implementing Spring Security to manage authentication and authorization.
Since I've implemented Spring Security, my JUnit Jupiter tests does not work (no one works).
I searched a lot a solution on internet, but all answers I found are for JUnit4 and not JUnit5 (so I don't have all required classes).
I got the classical "Fail to load ApplicationContext" error, but I don't know how to solve it.
Can you help me?
Here is my code for one class (UserController):
gradle.build:
plugins {
    id 'jacoco'
    id 'org.springframework.boot' version '2.6.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web:2.5.6'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6'
    implementation 'org.projectlombok:lombok:1.18.22'
    annotationProcessor 'org.projectlombok:lombok:1.18.22'
    developmentOnly 'org.springframework.boot:spring-boot-devtools:2.5.6'
    testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.6'
    implementation 'com.h2database:h2'
    runtimeOnly 'com.h2database:h2'
}

test {
    systemProperty 'spring.profiles.active', 'test'
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}

Application:
@SpringBootApplication
public class BackendApplication {
    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }
}

UserController sample:
@RestController
@RequestMapping("/api/v1/users")
public class UserController extends AbstractCrudController<User, Long> {

    @Autowired
    public UserController(CrudService<User, Long> service) { super(service); }

    @GetMapping("")
    @Override
    @Secured({ "ROLE_XXXXX" })
    public ResponseEntity<ResponseListDto<User, Long>> findAll() {
        return super.findAll();
    }

    // ...
}

MockedUserControllerTest sample:
@SpringBootTest
public class MockedUserControllerTest {

    @Mock
    private UserService service;

    @InjectMocks
    private UserController controller;

    private static User user;
    private static List<User> users;

    @BeforeAll
    public static void beforeAll() {
        user = new User();
        user.setId(1L);
        user.setUsername("A user name");
        user.setFirstname("First-Name");
        user.setLastname("Last-Name");
        user.setPassword("A Gre4t P4ssw0rd!");
        user.setMail("first-name.last-name@mail.com");
        user.setBirthDate(Date.valueOf("1980-01-15"));
        user.setKey("A-key");
        user.setNewsletter(Boolean.TRUE);

        users = List.of(user);
    }

    @Test
    public void testFindAll() {
        when(service.findAll()).thenReturn(users);
        assertEquals(new ResponseEntity<>(new ResponseListDto<>(users, null, null), HttpStatus.OK),
                controller.findAll());
    }

    //...
}

Thank you in advance for looking my problem.

A: For a @SpringBootTest you should use @MockBean annotation, because the Spring context will load in order to run the tests. The loaded context will create mocked beans from the dependencies being annotated by @MockBean and it will inject them into that service, which is being tested.
For pure unit tests the @SpringBootTest annotation should be skipped and Mockito (@Mock annotation) can be used. Spring context will not load in this case, the test will focus on that specific class you are testing. With the created Mocks, you can control the behaviour of dependencies, you can arrange different scenarios for your test.

A: After some other basic researches (how to write tests with junit5 and mockito), I solved my problem myself.
Here is the answer which helped me: https://stackoverflow.com/a/40962941/13523752
What I wanted is a class test only for the controller I specified. So I didn't need the ApplicationContext. That oriented my research.
Note: I'll do other test classes to test all the process. In this tests I'll need the ApplicationContext.
On my test class, I removed the annotation @SpringBootTest to replace it by @ExtendWith(MockitoExtension.class).
The next thing I did is in the @BeforeAll method I have. I had MockitoAnnotations.initMocks(MockedUserControllerTests.class) to load the mocks I annotated.
Now my test work. I only have to extend this solution on all other mocked test classes.
A sample of the test class I have now:
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class MockedUserControllerTest {
    @Mock
    UserService service;

    @InjectMocks
    UserController controller;

    // ...

    @BeforeAll
    public static void beforeAll() {
        MockitoAnnotations.initMocks(MockedUserControllerTest.class);

        // ...
    }

    // ...
}


text:
Q: How to stop editor from poking into my usercontrol properties? Had a lot of fun tracking this one down:
Me.DataNodeEditor1.Root = CType(resources.GetObject("DataNodeEditor1.Root"), DataNodeLib.DataNode)

Its automatically generated by the designer. I don't want this property to have anything to do with the designer. I tried adding "< Browsable(False) >" to the property and it removed it from the editable properties list but It automatically still generates stuff into it. How to stop it?


text:
Q: Use control from Expression Blend in VS 2010 I know that I can open my WPF app in VS and Expression Blend at thee same time and work it.
If I change color button in EB, VS refresh project and that's work's fine.
My question is: Can I make simple button in Expression Blend (not all application just button) and use it in a different Visual Studio WPF project? How can I do this?

A: I believe that this should be your answer, actually when in WPF , WP or W8 you create a control the simple way to do very thing is to right click over it and click on "MakeIntoUserControl". As you click over it the option you would notice that it would create respective file of UserControl.xaml. In Expression Blend you need to build the project so that things may go fine. The very UserControl you made would now appear in the assets as you type the name of the UserControl.
Build the project again and Right click over project and click on "Edit in Visual Studio"
Now  as you go to Visual Studio , you will notice that same user control would be there with same name.

I hope it does the job for you.
Regards.


text:
Q: How to untar an archive from Pharo Smalltalk? I see there is a GZipReadStream class in Pharo 3.0 for working with gunzip files, but I was unable to find a similar class for untar archives (.tar files).
Do you know if there is a way to untar an archive from Pharo? Maybe without using OSProcess?

A: A module exists for Visualworks Smalltalk and is available in Cincom public store repository.
http://www.cincomsmalltalk.com/publicRepository/Tar%28Bundle%29.html
I'm not aware of any port for Squeak/Pharo, and it's probably not a straight forward task, but it might be a good source of inspiration.
I didn't see any copyright notice also...

A: I don't think the kernel can decompress tar files. You said no OSProcess - would NativeBoost be cheating? NBMacShell run: 'tar ...'. Don't be distracted by "Mac". It uses the standard C library so I don't see why it wouldn't work in Linux/GNU.


text:
Q: Recommended bit-rate value for x264 1st pass I use x264 to encode content for an Adaptive Bit-Rate workflow.
So I run a 1st pass to find the "optimal"GOP structure (but with a --keyint target value) to a given bit-rate X.
And next I run different 2nd pass encoding using the statistic file (coming from the 1st pas) to generate encoding (different bit-rate and resolution) with the same GOP structure - it's a requirement for ABR streaming.
My question is: Depending of the different bit-rate I use in the second pass, what will be the best choice for bit-rate parameter of the 1st pass to optimize the video quality of all 2nd pass encoding ? Should I use the min or the max bit-rate, or a median value ?


text:
Q: WooCommerce addclass to payment gateway selected at checkout I am trying to add a class to an element when a payment option is selected on the checkout page of WooCommerce. Here is my code, just for testing using the console to get a response:
jQuery(document).ready(function() {
    jQuery("#payment_method_extra_payment_option").on( "click", function() {
        console.log('1');
    });
});

I am targeting the radio button which has this id name. It is not working.
I have also tried using click(), which also does not working.
I can get this code to work when targeting a piece of text outside the payment options. I don't understand why this does not work.

A: I have managed to solve this by using:
jQuery(document).ajaxComplete(function () {...

Instead of
jQuery(document).ready(function() { ...

I have been able to addClasses now and also amend field validation based on chosen payment gateway.

A: The payment options are probably added to the dom after document.ready. So the click event listener won't be added to that element. You should use the .on function in an event-delegation approach:
$( "#the_parent_of_the_payment_method_extra_payment_option" ).on( "click", "#the_payment_method_extra_payment_option", function() {
    console.log('1');
});

(The id's in this code sample are illustrative)
See this chapter for more information: http://api.jquery.com/on/#direct-and-delegated-events

A: Got the same problem.
This works on mine.
jQuery(document).ready(function(){
    jQuery(document).on('click', "#payment_method_extra_payment_option", function(){
        // do your code here
    });
});


text:
Q: how i can send compressed images to the server (not the original one) I'm looking for sending the compressed images to the server when the form is submit but the FileList contains the original images, how replace them by the compressed one ?
here the code to compress images
const Compress = require('compress.js');
    const compress = new Compress();
    const inputFile = document.querySelector('#upload')

    let dataList = new DataTransfer()
    console.log('datalist avant event');
    console.log(dataList);
    inputFile.addEventListener('change', (evt) => {
      const files = [...evt.target.files]

      compress.compress(files, {
        size: 3, // the max size in MB, defaults to 2MB
        quality: 0.75, // the quality of the image, max is 1,
        maxWidth: 1920, // the max width of the output image, defaults to 1920px
        maxHeight: 1920, // the max height of the output image, defaults to 1920px
        resize: true // defaults to true, set false if you do not want to resize the image width and height
      }).then((files) => {

        for (const file of files) {
          const base64str = file.data
          const imgExt = file.ext
          const blobFile = Compress.convertBase64ToFile(base64str, imgExt)
          const fileCompressed = new File([blobFile], file.alt, { type: 'image/jpeg' })

          const image = new Image();
          image.src = file.prefix + file.data

          var span = document.createElement('span');

          span.innerHTML = [
            '
',
            '

',
            '<input type="hidden" name="name_files" value="', fileCompressed.name, '" />',
            '',
            '
'
          ].join('');
          document.getElementById('list').insertBefore(span, null);
        }
      })
    }, false)


text:
Q: is there a way to prevent views from beeing scaled in android? I have a custom view that is scaling to 200% when the user clicks on it.
Now I want to prevent some controls/views in that custom view from beeing scaled.
Is there some way to do this?

A: After further investigating I think there is no way to programmatically freeze a view as described. As a dirty workaround you can put the view that should not be scaled in another container that is positioned over the scaled view.


text:
Q: multi-Insert using sqlsrv_query the code below is designed to insert n rows into a table. However, for all n >=108, it manages to insert only 108 rows. Works fine for n<108.  I run the query on database and it works as expected. Has any of you guys had a similar issue?. Any help would be appreciated.
    $data = "a1='1', a2='2', a3='3', a4='4', a5='5', a6='6'";
    $queryInsert =
    "   SELECT $data INTO [$tableName]
        DECLARE @i int
        SET @i=1
        WHILE (@i < $n)
        BEGIN
            INSERT [$tableName]
            SELECT $data
            SET @i = @i + 1
        END
    ";
    $stmt1 = sqlsrv_query($conn1, $queryInsert);

EDIT: PHP7, Driver version: 4

A: Apparently this works now. No idea why.
$data = "a1='1', a2='2', a3='3', a4='4', a5='5', a6='6'";
    $queryInsert =
    "   SELECT $data INTO [$tableName]
        DECLARE @i int
        SET @i=1
        WHILE (@i < $n)
        BEGIN
            INSERT [$tableName]
            SELECT $data
            SET @i = @i + 1
        END
    ";
    $stmt1 = sqlsrv_query($conn1, $queryInsert);
    sleep ( 1 );


text:
Q: How to properly generate a GS1-128 (formerly EAN-128) barcode in TCPDF We are trying to generate correct EAN-128 codes for product labels, with TCPDF library, but
our client says that the barcode scanner doesn't read the generated barcode.
The original(old) barcode and string:

The code string is:
$codeString = "(01)08437013308045(3013)2675(15)161201(10)150518"

If we pass the string directly to the TCPDF function, like this:
$label->write1DBarcode($codeString, 'C128A', $x, $y, $w, $h);

we're getting correct output (which the scanner won't read) but the bars are more dense comparing to the original barcode which seems shorter and less dense (they say it's EAN-128):

We found here (EAN-128 with FNC1) that adding chr(241) before the $codeString should help but if we add it, the resulting image is stripped off of everything in human readable code:

Since we don't own a barcode reader, we can't check the errors ourselves.
What we are missing here? We're using TCPDF version 6.2.12.

A: There are a number of problems here that I'll work through.
Firstly, you have misread the text of the original barcode which contains the fixed-length Application Identifier (AI) field (3103)2775 representing net weight.
You have written a code containing (3013)2675 which is invalid. There is no AI (3013) and unfortunately this would prefix match with the legitimate AI (30) representing an item count which is a variable-length field. Therefore a decoder would continue to read the remaining data until the end of the code into AI (30) since there is no subsequent field terminator character (FNC1). That's a lot of items – more than eight digits worth in fact so the reader may indicate a fault!
The "extraction" part of this answer provides background on how GS1 data is encoding within a Code 128 barcode to produce a valid GS1-128 symbol.
Let's assume that you meant to encode the GS1 data (01)08437013308045(3103)2675(15)161201(10)150518.
The raw data that you need to encode in the Code 128 is {FNC1}0108437013308045310326751516120110150518.
This has been derived as follows:

*

*The data begins with an FNC1 flag character (indicating the presence of GS1-formatted data).

*The parentheses around the AIs have been omitted.

*Since your data consists of only fixed-length AIs there are no instances where we have to terminate a variable-length field with an FNC1 separator character [*].

[*] Note that the list of AIs provided in the GS1 General Specifications §3.2 "GS1 Application Identifiers in Numerical Order" indicates whether they require termination by an FNC1 character when followed by additional data.
How does this knowledge translate into code for TCPDF? I've never used it sorry, but this might be helpful:
Your $codeString variable would need to be defined something like:
$codeString = chr(241).'0108437013308045310326751516120110150518';

This assumes that the linked to answer on the support forum is correct in stating that TCPDF uses ASCII ordinal 241 to indicate an FNC1 character. (There is some doubt whether this is the case.) If it works then this is a library-specific choice and you shouldn't read much into the fact that they have chosen value 241. See here for details about encoding non-data characters such as FNC1.
I also notice that you pass C128A to the type parameter of write1DBarcode which limits the symbol to mode A (numbers, uppercase letters and control characters.) This would be terribly inefficient and is likely to result in a symbol that is too wide (or too dense when rescaled) to scan with most standard equipment used for logistics applications.
Code 128 supports a mode C that provides double-density compression of digits so you should use this, probably by passing type=C128C or type=C128 (auto) assuming that TCPDF's auto-encoding is any good and future symbols that you will create may need to contain letters.
$label->write1DBarcode($codeString, 'C128', $x, $y, $w, $h);

As far as the human-readable text beneath the barcode is concerned, if this doesn't display correctly for properly encoded data then you may need to raise a bug report or feature request against TCPDF.


text:
Q: No Ansible config file or /etc/ansible directory after trying pip and yum install So I have been trying to install Ansible for some server management however it seems that yum and pip both don't want to co-operate:

*

*I tried a yum install which refuses to work because it cant seem to find any more repo's for babel/jinja2.

*pip installation works, however it left me without any Ansible.cfg file, or any /etc/Ansible directory at all. It seems to have installed it to the python 2.7 directory which is showing python configuration files but not anything to do with the standard Ansible configuration files that I have been seeing in the documentation.

Questions:

*

*Is there any work around for this, or is there any way to just use Ansible through python directly (meaning update inventory lists and create playbooks that would I guess be saved to pythons directory?).

*Also is there a way to force yum to install Ansible regardless of the jinja2/babel dependencies so I can at least work on creating my first few playbooks and getting familiar with the basics?

I'm not sure if these packages are necessary to Ansible operations and if it would create a dependency loop issue when trying to later install/update. Please go easy as I am new and trying to learn more about the capabilities of Ansbile. Os is RHEL 7.5 btw, and no it doesn't have a subscription I've been using EPEL which doesn't seem to work!

A: Ansible works fine from any directory. You don't need to use /etc/ansible.

*

*Install Ansible from pip

*Create work directory with recommended structure

*Use -i to point your current inventory (testing or production, for example).

*Create ansible.cfg in the root of your directory if you need:
[defaults]
#inventory      = /etc/ansible/hosts
inventory      = hosts

A: You might want to try with Centos 7. Take a look at Is CentOS exactly the same as RHEL? and reiew for example How to Install and Configure Ansible on CentOS 7.


text:
Q: Simples formulário de contato enviando email via Amazon SES com PHP Para um simples formulário de contato pretendo utilizar o Amazon SES com PHP. Basicamente o PHP vai enviar um email para mim mesmo com o email do usuário que me contactou para dar uma resposta.
Pesquisando, me deparei com as seguintes alternativas:

*

*Utilizar a classe PHP Mailer com as credenciais do Amazon SES.

*Configurar o Postfix como relay do Amazon SES para utilizar a função mail() do PHP.

*Utilizar o PHP Mailer juntamente com o Postfix como relay do Amazon SES.

Dúvidas:

*

*Qual a finalidade de utilizar o Postfix como relay do SES se posso apenas utilizar o PHP Mailer informando o servidor e credenciais?

*Porque algumas pessoas configuram o Postfix como relay do SES e mesmo assim utilizam o PHP Mailer, mesmo o PHP Mailer sendo capaz de utilizar o SES diretamente?

*Qual a melhor pratica, utilizando o Amazon SES, para enviar emails de contato e emails transacionais simples com PHP?

A: As três alternativas funcionam,
porém você deve considerar a necessidade de resistência da aplicação e a quantidade de envio.
Na alternativa 1, seu sistema está conectado diretamente no SMTP da Aws e está bloqueado enquanto opera a lista de envio, enquanto nas opções 2 e 3 o sistema delega ao Serviço de email local a tarefa de comunicar a fila de mensagens para a AWS, o que pode acontecer de maneira muito rápida e liberar o sistema para dar sequência a outras atividades.
Para um sistema simples como o formulário de contato, use a opção 1 mas para mensagens transacionais de uma aplicação eu recomendo uma estrutura mais robusta como a opção 3 que você mencionou.


text:
Q: VirtualHost Configuration causing issues I am quite new to VirtualHosts,
My use case is:
The domain mobc.in should be redirected to /var/www/html/mobc
And all other requests should be redirected to /var/www/html
The configuration that I am using it is
<VirtualHost *:80>
    DocumentRoot /var/www/html
</VirtualHost>
<VirtualHost *:80>
     DocumentRoot /var/www/html/mobc
     ServerName www.mobc.in
     ServerAlias mobc.in *.mobc.in
     ErrorLog logs/mobc.in-error_log
    CustomLog logs/mobc.in-access_log common
</VirtualHost>

This is not serving the purpose and even mobc.in is being redirected to /var/www/html
Kindly help me.

A: Remove the fist virtualhost tags and contents. Just use the 2nd one and use the default documentroot in httpd.conf


text:
Q: Calling back a view managed by the UINavigationController I have somes UIViewsControllers managed by a UINavigationController, but in a specific moment a call a UIViewController that I don`t want to be managed by my UINavigationController, then a I triggered a modal segue to that UIViewController, in that view a placed a buttom that call back my last UIVIewController (managed by the UINavigationController) by a modal segue, but when that view did load again, it doesn't show the header bar with the back buttom...
Some idea about that?

A:
by a modal segue, but when that view did load again, it doesn't show the header bar with the back buttom...

This description means you're creating a new instance of the view controller and presenting it on its own.
What you should be doing is presenting a new navigation controller with this new view controller as the root. Or, dismissing the first modal (to go back to the original nav + view controller).


text:
Q: Error: Main method is not static in class. Kotlin Project I need to create a runnable Jar file which is a console app from the Kotlin project. I set up this project using gradle init. I tried all solutions I could find online by moving the main method out of the class, wrapping it in a companion object, and using JvmStatic annotation but I still keep getting an error message "Error: Main method is not static in class com.yk.ConsoleGradle.App, please define the main method as:
public static void main(String[] args)"
I am using ./gradlew jar to build the project
class App {
    val greeting: String
        get() {
            return "Hello World!"
        }

    fun main(args: Array<String>){
        println("Hello kotlin")
    }
}

application {
    // Define the main class for the application.
    mainClass.set("com.yk.ConsoleGradle.AppKt")
}
tasks.jar{
    manifest {
        attributes(mapOf("Implementation-Title" to project.name,
                "Implementation-Version" to project.version, "Main-Class" to "com.yk.ConsoleGradle.App" ))

    }
}

Here is the output of jar tf
jar tf /ConsoleGradle/app/build/libs/app-1.0.1.jar
META-INF/
META-INF/MANIFEST.MF
META-INF/app.kotlin_module
com/
com/yk/
com/yk/ConsoleGradle/
com/yk/ConsoleGradle/AppKt.class
com/yk/ConsoleGradle/App.class

Any help appreciated.

A: If you don't want to declare the main function inside the App class you could just create an App.kt file with the following code:
class App {
    val greeting: String
        get() {
            return "Hello World!"
        }
}

fun main(args: Array<String>){
    println("Hello kotlin")
}

also you need to update your gradle jar task as:
jar {
    manifest {
        attributes "Implementation-Title": project.name
        attributes "Implementation-Version": project.version
        attributes "Main-Class": "com.yk.ConsoleGradle.AppKt"
    }
}

notice the Main-Class is specified as AppKt instead of App.
This is because the main function is a top-level function and for top-level functions inside App.kt the Kotlin compiler creates a class called AppKt.class.

A: I don't know if this is the right approach for what you're doing, but how about
class App {
    val greeting: String
        get() {
            return "Hello World!"
        }
    companion object {
        @JvmStatic
        fun main(args: Array<String>){
            println("Hello kotlin")
        }
    }
}

The companion object akes the function accessible through the class instead of through an instance, and the JvmStatic annotation generates a static method for Java interop


text:
Q: Activity state only restored when launched from Eclipse I have the problem that the state of my activity gets only restored (after killing or put to background) if I launch the App via the Eclipse Run menu.
If I export the App and put it manually on the (same) device, the state gets not restored when I kill and restart the App.
I assume I overlook something. Can anyone tell me what? Thanks!

A: May be an old thread, but this may help others.
This is a known defect
http://code.google.com/p/android/issues/detail?id=18338
Installing and launching app from eclipse, or launching from apps menu will restore the state, but if we are installing the app manually (by copying to SD card etc.) and launch directly will not restore the sate.

A: The android system automatically remembers the state when you close the app. You specifically have to kill it from Settings -> Applications -> Your app -> Kill


text:
Q: Start a QLineEdit with a 0 that cant be deleted but modified I need to start a QLineEdit with just one 0 inside it, but 2 conditions are needed:

*

*The user cannot delete that 0 never.

*The user is capable to change that 0 for a bigger number.

for me the best solution was using inputMasks but as you have to limit them, thats not the solution. Then I tried using RegEx but I could'nt make it work.

A: If a currency symbol is all that you need, and the input is indeed essentially numerical, then instead of QLineEdit, it might be easier to use a QSpinBox and then set a currency character as the prefix:
QSpinBox* pSpinBoxCurrency = new QSpinBox( this );
pSpinBoxCurrency->setRange( 0, 9999 );
pSpinBoxCurrency->setPrefix("$");

This is a quick and simple method. If you need more sophisticated input/output capabilities for that widget but it's still essentially numerical, then the next best step is to subclass QSpinBox and re implement validate(), valueFromText(),  textFromValue(), etc. It's still an int or float under the hood, but you have more control over how it appears and what input it accepts.
There have been cases where that still wasn't enough for what I needed, and in those instances I had the most success writing a new widget that shows the numbers/data exactly how I wanted and just popping up a transient pre-populated QSpinbox to allow number entry. But I suggest trying to get the built-in classes to do most of what you want first.


text:
Q: Is there anyway to reduce nrepl (ritz-repl) startup time? I wasn't using ritz-nrepl before, and nrepl took around 10 sec which is long but still bearable since I don't restart it that often.
When I tried out ritz-repl, it took nearly 30s to boot, and consumes around 1.3G memory.
This makes me reluctant to use it.
I even threw in a SSD hoping it can increase the speed, because I heard someone mention that he "hardly notice the lein repl startup time" using ubuntu + ssd. But I can't tell the difference myself between ssd and hdd. I don't know if I did something wrong or if its just a myth.

A: There might be ways to reduce the startup time of an nrepl server that includes ritz but for the most part you will be stuck with at least the 10 seconds it takes to boot up the jvm on your machine. For me that is kind of an unacceptable delay when doing interactive development.
As an alternative you can use a smarter code reloading approach using the clojure.tools.namespace library. It basically keeps a dependency graph in memory and reloads only those namespaces that have been changed since you last refresh.
This will work out of the box for some but not all Clojure code.  See the 'Preparing Your Application' section of the readme for more info on those edge cases to avoid.
Hope this helps!


text:
Q: error with custom writable comparable I have a class genkey which implements writable and comparable. I need to pass an object of this class from mapper to reducer. The mapper works all fine. Now when I finally try to get the ouput through context.write i get the following error...
class org.apache.hadoop.io.Text is not class genkey
here is my code
public static class Mappertwo extends Mapper<Object, Text, genkey, IntWritable> {
    private genkey ky=new genkey();
    public void map(Object key , Text value , Context context)
        throws IOException , InterruptedException{

        .............

        context.write(ky,one);
    }
}
public static class Reducertwo extends Reducer<genkey, IntWritable, Text, IntWritable>
{
     public void reduce(genkey ukey , Iterable<IntWritable> values , Context context)
        throws IOException , InterruptedException{

        IntWritable result = new IntWritable();
        Text nw=new Text();
        int sum=0;

        for (IntWritable val : values){
            sum += val.get();
        }

        String s=ukey.getkey();
        nw.set(s);
        result.set(sum);
        context.write(nw,result);
        //this line here gives the error...                        }
}

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{
    if (args.length != 5) {
        System.err.println("exceeded array limit:");
        System.exit(-1);
    }

     Configuration conf1 = new Configuration();
     Job job1= new Job(conf1, "round2");
     conf1.set("t",args[2]);
     DistributedCache.addCacheFile(new Path("/user/hduser/out/part-r-00000").toUri(),job1.getConfiguration());
     job1.setJarByClass(MapSide.class);
     job1.setMapperClass(Mappertwo.class);
     job1.setCombinerClass(Reducertwo.class);
     job1.setReducerClass(Reducertwo.class);
     job1.setOutputKeyClass(Text.class);
     job1.setOutputValueClass(IntWritable.class);
     job1.setMapOutputKeyClass(genkey.class);
     FileInputFormat.addInputPath(job1, new Path(args[0]));
     FileOutputFormat.setOutputPath(job1, new Path(args[3]));
     System.exit(job1.waitForCompletion(true)?0:1);
}

A: You defined that you want to write Text, IntWritable. If you want to write genkey, IntWritable your reducer definition must look like this:
public static class Reducertwo extends Reducer<genkey, IntWritable, genkey, IntWritable>

On the same page, your job output key class needs to be set to that as well:
 job1.setOutputKeyClass(genkey.class);


text:
Q: crear input a partir de un select Trato de generar un input cuando seleccione una opción en un select, el problema es que no puedo adaptarlo a otros select porque lo que hago es usar un Id, incurriría a una mala práctica si utilizo el mismo id para otros select:
HTML

Tipo de pago

    <input style="height:40px" list="pago" id="tipo_pago" type="text" name="tipo_pago" required data-
    parsley-trigger="change" placeholder="Tipo de pago" onkeyup="mayus(this);" autocomplete="off"
    class="form-control option"/>
   <datalist id="pago">
       <option id="1" value="1">
       <option value="BONO">
       <option value="CONTADO">
   </datalist>

JavaScipt
Encontré este código en internet para poder generar un input cuando selecciono una opción de un select:
window.addEventListener('load', function () {
        var select = document.querySelector(".option");
        var i = "";
        var input = document.querySelector("#input");
        select.addEventListener('change', function (e) {
            e.preventDefault();
            input.innerHTML = '';
            for (i = 0; i < select.value; i++) {
                createInputs();
            }
        });
        function createInputs() {
            var element = document.createElement('div');
            element.innerHTML = `
                <select style="width: 200px; height:40px" data-parsley-trigger="change" class="form-control" class="mdb-select md-form">
                    <option value="" disabled selected>Selecciona</option>
                    <option>Mustard</option>
                    <option>Ketchup</option>
                    <option>Relish</option>
                </select>
            `;
            input.appendChild(element);
        }
    });

No sé si haya otra forma que no sea la de capturar un id, sino una clase que pueda adaptarla a cualquier select y que no me tome el value=1, porque no puedo añadir el nombre de esa opción

A: si quieres generar un input al seleccionar un select puedes hacer esto
select = document.getElementById('select');
select.addEventListener('click',function(){
    temp = `<input type="text" id="tu_id" value="el_valor">`
});

y luego lo puedes poner donde tu quieras con
element = document.getElementById('elemento')
element.innerHtml = temp

y si quieres capturar por clase tambien lo puedes hacer, y si quieres capturar vaios select por clase y añadir un evento lo haces con un ciclo for


text:
Q: Design for multiple interacting timers I'm designing a system that needs timers at all levels of a component hierarchy.  Multiple timers may be active at once, but they need to interact with each other (stopping a component's timer stops its descendants' timers, while starting a component's timer starts its ancestors' timers and stops its siblings' timers).
The timers each have different limits, and will be sending tick, start, stop, and expire events to listeners.
This is still early in the design phase (implementation language is still undetermined), but I want to avoid a threading mess.  Any advice?

A: It's hard to give advice based on what you've posted. Perhaps avoid threads completely and just have a single timer and database table of events. When the timer goes off, you select all the events older than now and fire them off. Then select the min timestamp of the event table subtract now and sleep for that interval. Loop.
while (1) {
    SELECT * FROM EVENTS WHERE ev_time < now() order by ev_time;
    while (num_rows_selected > 0) {
        for (i = 0; i < num_rows_select; ++i) {
             fetch row
             process row
        }
        SELECT * FROM EVENTS WHERE ev_time < now() order by ev_time;
    }
    SELECT MIN(ev_time)-NOW() as Interval FROM EVENTS
    sleep(Interval);
}


text:
Q: how to dynamically generate the formControl I would like to be able to dynamically create my formControl variables which corresponds to the name of my columns of my Table object without having to write hard in the createInput() method that I inject into my formArray.
I tried that but it does not work :
import { Component, OnInit } from '@angular/core';
import { ParameterService } from '../service/parameter.service';
import { Table } from '../model/table.model';
import { FormControl, FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { Typpar } from '../model/typpar.model';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  typpar: Typpar;
  table: Table;
  fileUrl: any;

  formGroup: FormGroup;
  inputRows: FormArray;

  numberOfLineForm: FormGroup;

  // On injecte une instance de FormBuilder et de ParameterService en dépendance de notre component
  constructor(public ps: ParameterService, private formBuilder: FormBuilder, private sanitizer: DomSanitizer) { }

  ngOnInit() {
     // initialize our form using FormBuilder in the ngOnInit hook.
     // We'll create a formGroup that allows the user to add new inputRows dynamically:
    this.formGroup = this.formBuilder.group({
      inputRows: this.formBuilder.array([this.createInput()])
    });
    console.log(this.formGroup);

    this.numberOfLineForm = this.formBuilder.group({
      numberOfLine: ['']
    });
    console.log(this.numberOfLineForm);

    this.ps.getAllColumns().subscribe(res => {
      this.table = res;
      this.createInput();
      console.log(this.table);
    });

    this.ps.getAllParams().subscribe(res => {
      this.typpar = res;
      console.log(res);
    });
 }

  // Permet de récupéer formData dans la vue qui est une instance de FormArray
  get formData() { return this.formGroup.get('inputRows') as FormArray; }

  // method to create a form group as the first inputRow in our array
  createInput(): FormGroup {
    // Comment récupérer le bon nombre de formControl qui correspondent
    // aux nom de mes columns de mon objet Table sans avoir à les mettres en dure
    console.log(this.table);
    if (this.table && this.table.columns.map) {
      this.table.columns.map((column) => {
        this.formGroup.addControl(column.name, new FormControl(''));
      });
    }
    return this.formGroup;

Here is my dashboard component html :

<form [formGroup]='formGroup' (ngSubmit)='submitForm(formGroup.value)' class="table">

{{ column.name }}

                <ng-container *ngFor="let column of table?.columns">
                    <select *ngIf="column?.dropdown; else noDropdown" formControlName="{{column.name}}">
                        <option *ngFor="let param of column?.parameters;" value="{{param.id}}">{{param.libelle}}></option>
                    </select>
                    <ng-template #noDropdown>
                        <input class="myInput" formControlName="{{column.name}}" type="{{ column.type }}" name="{{column.name}}_{{i}}" maxLength="{{ column.length }}" required="{{ column.nullable }}" value="{{ column.dataDefault }}" placeholder=" ">
                    </ng-template>
                </ng-container>
                 1" (click)="deleteInputLine($event, i)" id="deleteIcon" src="../../assets/img/cancel.png" />

        <button type="button" class="btn btn-info" (click)="addInputRow($event)">Ajouter une ligne</button>

        DownloadFile

</form>

the console error :

A: Your syntax is off in a few places. Don't call createInput() inside the formarray. Then you are not pushing values to your formarray, but instead pushing it to the formgroup. Then you are iterating both the formarray and your table.columns array in template. You should just iterate the formarray, and based on the index you can refer to your table.columns array. Here is a shortened minimal example of your code. Speaking of which, you should always provide a minimal sample of the issue you are facing (tip for future questions). But back to question, here are some fixes:
ngOnInit() {
  this.formGroup = this.formBuilder.group({
    inputRows: this.formBuilder.array([]) // don't call createInput!
  });
}

Your createInput function should add new formgroups to the formarray instead:
get formData() { return this.formGroup.get('inputRows') as FormArray; }

// method to create a form group as the first inputRow in our array
createInput() {
  if (this.table && this.table.columns.length) {
    this.table.columns.map((column) => {
      this.formData.push(
        this.formBuilder.group({
          // add dynamic name with brackets
          [column.name]: ['']
        })
      );
  }
})

And finally iterate the formarray in template:
<form [formGroup]='formGroup' (ngSubmit)='submitForm(formGroup.value)'>

    <ng-container [formGroupName]="i" >
      <input [formControlName]="table.columns[i].name" >
    </ng-container>

</form>

DEMO: STACKBLITZ


text:
Q: Target only a selector with this Not sure how to explain this, but I would like to target a selector only within this.
So lets say I have

And I execute this:
 $("li").each(function(i,v){
   $(".a",$(this)).append("1");
   $(".b",$(this)).append("2");
   $(".c",$(this)).append("3");
 });

Unfortunately this doesn't work as expected, but I'm sure there is a way that it does.
I've tried using if hasClass("a"),etc. but I would like to avoid that route if possible. Any suggestions?
I also know I can do $("li:eq("+i+").a") as a selector, but I am trying to use this here.
Unfortunately this doesn't work either: $(this).find(".a")

A: You want to do something more like this
$("li").each(function(i,v){
   if ( $(this).hasClass('a') ) $(this).text("1");
   if ( $(this).hasClass('b') ) $(this).text("2");
   if ( $(this).hasClass('c') ) $(this).text("3");
});

It's the LI that has the class, so you have to check it, right now you're using the context selector wich searches for an element with that class inside the LI.
Also note that when you're not appending elements but really just setting the elements text, use text()
As a final sidenote, your example could also be done like this
$("li").text(function(i) { return i+1 })

But I'm guessing it's just an example and that you didn't just want a number ?


text:
Q: Storing invalid format of XML in active MQ I am stuck on below,
I have set content type as XML in my proxy.
As below:
<parameter name="transport.jms.ContentType">
    <rules xmlns="">
        <jmsProperty>contentType</jmsProperty>
        <default>application/xml</default>
    </rules>
</parameter>

Sending below message into the queue which is correct one
<Data>
<name>abc</name>
<account>1212</account>
</Data>

But if any tag is missing in it as below. I dont want lose that message instead I want it to store in one special queue
<Data>
<name>abc
<account>1212</account>

Any guidance will be appreciated.Thanks


text:
Q: Angular make entire Handsontable readonly in HTML I would like to make my Handsontable completely readonly, I have found some solutions on how to make it readonly via a controller but I would like to do the same in the HTML only. So no javascript changes.
<hot-table id="demoTable"
           colHeaders="true"
           datarows="gridData"
           settings="gridPreferences"
           height="300">

    <!-- BasicData -->
    <hot-column data="row_id" title="'ID'" type="'text'"></hot-column>

Here is an example column in the table, is it possible to make it readonly right here?

A: You can make individual hot-columns read only by adding the attribute read-only
<hot-column data="row_id" title="'ID'" type="'text'" read-only></hot-column>
---------------------------------------------------------^

The attribute isn't documented well but example usage can be found in the plugin's README.


text:
Q: Is it possible to add function definitions programmatically in swift I'm creating a struct that holds 3 float values,
struct Col {
  var r: Float
  var g: Float
  var b: Float
}

and I'd like to add a bunch of function definitions that are equivalent to the built in math functions, but that operate piecewise on the members of my struct
I can do it by hand, eg
func pow(a: Col, b: Col) -> Col {
  return Col(r: pow(a.r, b.r), g: pow(a.g, b.g), b: pow(a.b, b.b))
}

but this is tedious and error prone.
What I'd like to do is create a function to turn the original math function into my Col version, so that I could call it like this:
defineColVersion(pow, noArgs: 2)

and it defines the new version, without overwriting the built in function that operates on Doubles
Is there any way to do this in Swift?
Thanks

A: I actually think this is exactly what you want:
func toCol(f: (Float, Float) -> Float) -> (Col, Col) -> Col {
    return { a, b in
        Col(r: f(a.r, b.r), g: f(a.g, b.g), b: f(a.b, b.b))
    }
}

func toCol(f: Float -> Float) -> Col -> Col {
    return { c in
        Col(r: f(c.r), g: f(c.g), b: f(c.b))
    }
}

let pow = toCol(Darwin.pow)
let sin = toCol(Darwin.sin)
let log = toCol(Darwin.log)

let a = Col(r: 0.4, g: 0.2, b: 0.7)
let b = Col(r: 0.3, g: 0.9, b: 0.3)

pow(a, b)
sin(a)
log(b)

The two overloaded functions toCol take a unary/binary function on Floats and returns a new function which does the same on your Col type. With those two, you can easily create a pow function for your Col type.

A: It is not possible to programmatically define new functions in a static language like Swift. What you can do, however, is to make a higher-kinded function:
func init(a: Col, b: Col, function: (Float, Float) -> Float) -> Col {
    return self.init(r: function(a.r, b.r), g: function(a.g, b.g), b: function(a.b, b.b))
}

Col(Col(1, 2, 3), Col(3, 4, 5)) { $0 * $1 }
Col(Col(1, 2, 3), Col(3, 4, 5)) { pow($0, $1) }

A: func init(first: Col, second: Col, function: (Float, Float) -> Float ) {
    newR = function(first.r,second.r)
    newG = function(first.g,second.g)
    newB = function(first.b,second.b)
    return self.init(r:newR,g:newG,b:newB)
}

I'm not in a position to compile this so it probably has some errors but hopefully it will be useful. You would use it like so:
first = Col(r:1,g:2,b:3)
second = Col(r:1,g:2,b:3)
combined = Col(first:first,second:second) { pow($0,$1) }


text:
Q: Double rendering of col and row headers using HandsOnTable I have a problem with both column and row headers being rendered what looks like twice!
I'm using an app called Hype (link). Everything else works ok (seemingly) except for headers. I've reported the issue on Hype forums (here) where those who are familiar with the Hype product can download my test document.
All help appreciated.

A: We need the actual fiddle with your Handsontable instance. This doesn't help us much. I can guess at the issue, it's the "clone" instance of the table which gets rendered on top of the actual table to allow for freezing of panes.
You're probably modifying the CSS on only one of these, making the second one go out of whack. The solution is to either modify them both or to use Handsontable methods to modify the table.