Q: How can i execute a python script using java? I'm trying to integrate a python script in java. I want my java program to be able to execute my python script
I tried to code a class named PythonCaller made to execute a test python script
package pythontest;

import java.io.*;
public class PythonCaller {

    public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
            // set up the command and parameter
            String pythonScriptPath = "D:\\Programmes\\test.py";
            String[] cmd = new String[2];
            cmd[0] = "D:\\Programmes\\python.exe"; // check version of installed python: python -V
            cmd[1] = pythonScriptPath;

            // create runtime to execute external command

            Process pr = Runtime.getRuntime().exec("python D:/Documents/Télécom/Programmation/workspace python/test.py");
            System.out.println("adhi");
            // retrieve output from python script
            BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            System.out.println(bfr.readLine());
            String line = "";
            try {
                while((line = bfr.readLine()) != null) {

            // display each output line form python script
            System.out.println(line);
            System.out.println("daiuh");
            }
            }
                catch(IOException e) {
                    System.out.println("Exception in reading output" + e.toString());
                }

    }
    }

When i execute it, it appears that bfr.readLine() returns null
Here is the script in test.py :
print("aiujadh")
print("f")

what i dont understand is that i did tests with the exact same code before, and it worked. I changed it because it failed to read the lines that were not "prints". Then i moved back to the working code, and it doesnt work anymore. I looked at similar topics on the internet, and i do not understand why my code doesn't work.
Can somebody try to explain me pls ?


Q: C++ reliance on argument to const reference not changing Please consider the following code:
void func1(const int &i);
void func2(int i);

void f()
{
  int a=12;
  func1(a);
  func2(a);
}

Compiled with g++ 4.6 with -O3, I can see that the compiled re-reads the value of "a" between the function calls. Changing a's definition to "const int", the compiler doesn't do that, and instead simply loads immediate value "12" into edi. The same is true if a is not const, but I change func1's signature to accept by value.
While not a bug in the code generation, this is still weird behavior. Being as it is that func1 made a commitment not to change a, why should the compiler's code change based on whether a is const or not?
Edit: Some skeptics claim that I might be reading the code wrong. The above code produces the following with -S compilation:
_Z1fv:
.LFB0:
        .cfi_startproc
        subq    $24, %rsp
        .cfi_def_cfa_offset 32
        leaq    12(%rsp), %rdi
        movl    $12, 12(%rsp)
        call    _Z5func1RKi
        movl    12(%rsp), %edi     <-- Rereading a
        call    _Z5func2i
        addq    $24, %rsp
        .cfi_def_cfa_offset 8
        ret
        .cfi_endproc

Changing a to const produces:
_Z1fv:
.LFB0:
        .cfi_startproc
        subq    $24, %rsp
        .cfi_def_cfa_offset 32
        leaq    12(%rsp), %rdi
        movl    $12, 12(%rsp)
        call    _Z5func1RKi
        movl    $12, %edi          <-- Use immediate value
        call    _Z5func2i
        addq    $24, %rsp
        .cfi_def_cfa_offset 8
        ret
        .cfi_endproc

A: In C++, const is really just logical constness and not physical constness. func1 can do a const_cast and modify i. const is like the safety of a gun - you can still shoot yourself in the foot, but not by accident.
As T.C. and juanchopanza have pointed out in the comments, casting away the constness of an object and modifying it is UB. Quoting from "Notes" here :

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.

A: Summing up the answers, I think this explains it best:
It is legal to take a const reference to a non-const variable, and then cast away the constness. Therefore, the compiler in the first case cannot assume that func1 will not change a.
It is undefined what happens if you cast away the constness to a variable declared const. The compiler in the second case may assume that func1 will not cast away the constness. If func1 does cast away the constness, func2 will receive the "wrong" value, but that's just one consequence of undefined behaviour.


Q: Sonar plugin postjob measure I have a sonar plugin that post a comment in gitlab when there is new sonar issues in a commit. I would like to add difference of code coverage and code duplication in the comment.
This is made by making a sonar plugin based on PostJob.
The issues are recovered by injection of ProjectIssues in the constructor.
Is there a way to recover the Measures in the post job?  I saw that changed in sonar 5.2 but there is no real explanation on how to proceed to read measures.
Thank you for any help.

A: if the ProjectIssues or PostJobContext have no data you are looking for,  you can use the web API rest:
WsRequest wsRequest = new GetRequest("api/...");
but beware the last measures will not be computed at the moment of @BatshSide, you have to wait for the Compute Engine to finish his work.  So as you cannot wait in 'BatchSide',  look for moving your plugin under @ComputeEngineSide


Q: brain-teaser R problem - programming problem solving in R I am trying to write a function to solve a novel problem:
Given the following data:
S = c(19, 10, 12, 10, 24, 25, 22)
k = 4

I am trying to calculate a function. I want to print the maximal subset of S in which any sum of 2 numbers in S' is not evenly divisibly by k
So one answer might be S' = [10, 12, 25] and the other could be S' = [10, 22, 24].
Another example:
if S = {1, 7, 2, 4} and K = 3
Then
1 + 7 = 8
1 + 2 = 3
1 + 4 = 5
7 + 2 = 9
7 + 4 = 11
2 + 4 = 6

That is S' = {1, 7, 4} and will never sum to a multiple of  k = 3

A: There is a linear time algorithm for this. This algorithm is well explained by orezvani in this post on Computer Science section of stackexchange.
I translated the orezvani pseudo code in R:
max_subset<-function(S,K){
  R <- S %% K
  Res <- c()
  for(k in 1:(ceiling(K/2)-1)){
    index_k = which(R==k)
    index_K_k = which(R==(K-k))
    if(length(index_k) >= length(index_K_k)){
      Res <- c(Res, S[index_k])
    }else{
      Res <- c(Res, S[index_K_k])
    }
  }
  print(R)
  Res <- c(Res, S[which(R==0)][1])
  if(K %% 2 == 0){
    Res <- c(Res, S[which(R==(K/2))][1])
  }
  return(Res)
}

I tried with different example:

*

*with S <- c(1, 7, 2, 4) and K = 3 give 1 7 4;

*with S <- c(3, 17, 12, 9, 11, 15) and K = 5 give 11 17 12 15

*with S <- c(3, 7, 2, 9, 1) and K = 3 give  7 1 3

*with S <- c(19, 10, 12, 10, 24, 25, 22) and K = 4 give 25 12 10
In order to be more understandable I tried to be as similar as possible to the pseudocode, probably my solution could be optimized using R language specific features.


Q: Pinescript issue between local and global scope if (barstate.islast)
    myLine = line.new(x1=bar_index[SHI], y1=rsi[SHI],
         x2=bar_index[FHI], y2=rsi[FHI], color=color.lime)

    line.set_extend(id=myLine, extend=extend.right)

alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line")

I'm drawing a line between certain points on RSI I named the line myLine and now I want to add an alert that fires when RSI passes thru that line.
The issue is I can't declare alertcondition inside if statement local scope and also I can't access myLine since it is in the local scope of the if statement, what shall I do in this case?

A: This will solve the myLine access problem.
However, it doesn't solve your crossover() problem, because that function expects 2 series as arguments.
You're providing a series (rsi) and a line object (myLine), which will result in an error.
I've commented out that line.
//@version=4
study("Test", shorttitle="TST")

var line    myLine      = line.new(na, na, na, na, color=color.lime, extend=extend.right)
var int     SHI         = 30
var int     FHI         = 20

rsi = rsi(close, 14)

if (barstate.islast)
    line.set_xy1(myLine, bar_index[SHI], rsi[SHI])
    line.set_xy2(myLine, bar_index[FHI], rsi[FHI])

plot(rsi)
// alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line")


Q: Google chrome browser is misbehaving I don't know what's going wrong with my chrome browser. Everything was working fine but all of a sudden the width from my css styling for divs, input elements and all other widths are disorganised. I don't know if its the width that increased or the padding or margin but what I know is that everything is disorganised. But I checked firefox and other browsers everything is okay. I cleared my cache and cookie but no solution. Please does anyone knows how I can fix this?

A: I found the silly solution. The browser was zoomed to 120% unknown to me so I adjusted it back to 100%


Q: Azure Cloud Service stops saving to table storage when storage is accessed in visual studio server explorer I am working on an azure cloud service that has two different worker roles saving entities to an azure table storage. When I run the solution locally (both in debug and release mode) it works perfectly, however when I deploy the solution (either in debug or release) to the Azure Cloud Production Environment it writes the correct data and works well; but after I open the storage account in the server explorer in visual studio to review what was saved, then the cloud service worker roles stop saving new data to the tables.
Does accessing the azure storage account from the server explorer window in visual studio freeze the storage account when an azure cloud service is running against it?

A: No, that's not possible. Could you please provide more description about how the worker role "stop saving new data to table"? Did it encountered failures? If so, what's the detailed error message? Or did it make no progress while writing table entities?


Q: Reading XML File Through Dataframe I have XML file like below format.
<nt:vars>
<nt:var id="1.3.0" type="TimeStamp"> 89:19:00.01</nt:var>
<nt:var id="1.3.1" type="OBJECT ">1.9.5.67.2</nt:var>
<nt:var id="1.3.9" type="STRING">AB-CD-EF</nt:var>
</nt:vars>

I built a dataframe on it using below code. Though the code is displaying 3 rows and retrieving id and type fields it'snot displaying actual value which is 89:19:00.01, 1.9.5.67.2, AB-CD-EF
spark.read.format("xml").option("rootTag","nt:vars").option("rowTag","nt:var").load("/FileStore/tables/POC_DB.xml").show()

Could you please help me if I have to add any other options to above line to bring the values as well please.

A: You can instead specify rowTag as nt:vars:
df = spark.read.format("xml").option("rowTag","nt:vars").load("file.xml")

df.printSchema()
root
 |-- nt:var: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _VALUE: string (nullable = true)
 |    |    |-- _id: string (nullable = true)
 |    |    |-- _type: string (nullable = true)

df.show(truncate=False)
+-------------------------------------------------------------------------------------------+
|nt:var                                                                                |
+-------------------------------------------------------------------------------------------+
|[[ 89:19:00.01, 1.3.0, TimeStamp], [1.9.5.67.2, 1.3.1, OBJECT ], [AB-CD-EF, 1.3.9, STRING]]|
+-------------------------------------------------------------------------------------------+

And to get the values as separate rows, you can explode the array of structs:
df.select(F.explode('nt:var')).show(truncate=False)
+--------------------------------+
|col                             |
+--------------------------------+
|[ 89:19:00.01, 1.3.0, TimeStamp]|
|[1.9.5.67.2, 1.3.1, OBJECT ]    |
|[AB-CD-EF, 1.3.9, STRING]       |
+--------------------------------+

Or if you just want the values:
df.select(F.explode('nt:var._VALUE')).show()
+------------+
|         col|
+------------+
| 89:19:00.01|
|  1.9.5.67.2|
|    AB-CD-EF|
+------------+


Q: When I do a delete:TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing table http://1.z9ls.com/t6/701/1555244797x1822611239.png
one table is article,the other is category:
article:article_id,article_title,article_category_id...and article_category_id
is the foreign key and references category_id of table category.
When I delete an article：object references an unsaved transient instance - save the transient instance before flushing: com.wjh.blog.domain.Category
Attention:when I DELETE a article，but not insert or update.
//I have already use the @Transactional
//this is the code of ArticleDaoImpl.java
 @Override
    public void delete(Long article_id) {
        Article article = new Article();
        article.setArticle_id(article_id);
        this.getHibernateTemplate().delete(article);
    }

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.wjh.blog.domain.Category" table="category">
        <id name="category_id" column="category_id">
            <generator class="native"/>
        </id>
        <property name="category_name" column="category_name"/>
        <property name="category_parent_id" column="category_parent_id"/>
        <set name="category_articles" inverse="true">
            <key column="article_category_id"></key>
            <one-to-many class="com.wjh.blog.domain.Article"/>
        </set>
    </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.wjh.blog.domain.Article" table="article" >
        <id name="article_id" column="article_id">
            <generator class="native"/>
        </id>
        <property name="article_title" column="article_title"/>
        <property name="article_content" column="article_content"/>
        <property name="article_time" column="article_time"/>
        <property name="article_pic" column="article_pic"/>
        <property name="article_desc" column="article_desc"/>
        <!--category-->
        <many-to-one name="article_category" class="com.wjh.blog.domain.Category"
                     column="article_category_id" cascade="save-update,persist" ></many-to-one>

    </class>
</hibernate-mapping>


Q: Python - cannot set wallpaper with tempfile Code:
import urllib.request
import tempfile
import shutil
import ctypes

SPI_SETDESKWALLPAPER = 20
with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f:
    shutil.copyfileobj(response, f)
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, 0)

However, if you use tempfile.NamedTemporaryFile(delete=False) it works.
The docs state:

If delete is true (the default), the file is deleted as soon as it is
  closed.

In my original code the file isn't deleted until after having exited the body of the with statement when it is automatically closed. So why isn't SPI_SETDESKWALLPAPER working?

A: You need to read the next couple sentences in the documentation, which read something like this:

Under Unix, the directory entry for the file is either not created at all or
  is removed immediately after the file is created. Other platforms do not
  support this; your code should not rely on a temporary file created using
  this function having or not having a visible name in the file system.

A: I figured out the problem:
To begin with, the value  of the fWinIni parameter needs to be changed:
SPIF_UPDATEINIFILE = 0x01
SPIF_SENDCHANGE = 0x02
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)

This preserves the wallpaper after logging off.
Second, the temp file needs to be closed in order for SystemParametersInfoW to work. Therefore, delete=False is necessary.
Finally, delete the temp file manually using os.remove(f.name).


Q: How to tell nuget to add package resource files as links, and not copy them into project directory Intro (how to pack resources into a nuget package)
To pack some resource files into a nuget package, what one would normally do, is the following.
Put all the resource files into the content\ directory of a nuget package. This would be specified by the following line in a .nuspec file:
<files>
  <file src="Project\bin\Release\script.js" target="content\js\script.js" />
<files>

Now, when this nuget package gets installed into AnotherProject, the following file structure emerges:
Solution.sln
packages\Project.1.0.0\content\js\script.js  // the original resource file
AnotherProject\js\script.js                  // a physical copy
AnotherProject\AnotherProject.csproj         // <Content /> tag (see below)

During package installation, AnotherProject.csproj was injected with tag:
<Content Include="js\script.js" />

and this is for the physical copy of the original resource (which is under packages\ directory).
The actual problem (how to pack resources into a nuget package as link)
My aim is not to have the physical copy of a resource file in the AnotherProject directory but rather a "link" to the original resource under packages\ directory. In the csproj, this should look like this:
<Content Include="packages\Project.1.0.0\content\js\script.js">
  <Link>js\script.js</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

Brute force solution that I would rather avoid
Now, one "do it the hard way" workaround I can think of is:

*

*not putting resource files under content\ so they do not get added automatically,

*writing Install.ps1 script that would hack the csproj file structure and add the necessary XML piece manually,

This, however, has the following drawbacks:

*

*all my nuget packages need the same script piece in their Install.ps1,

*when installing my packages, there would be a nasty "project reload prompt" in Visual Studio.

A: Since NuGet currently does not support this out of the box your options are either to use PowerShell or to use a custom MSBuild target.
PowerShell

*

*Leave your resources outside of the Content directory in your NuGet package (as you already suggested).

*Add the file link using PowerShell in the install.ps1.

You should be able to avoid the project reload prompt if you use the Visual Studio object model (EnvDTE). I would take a look at Project.ProjectItems.AddFromFile(...) to see if that works for you.
MSBuild target

*

*NuGet supports adding an import statement into a project that points to an MSBuild .props and/or .targets file. So you could put your resources into the tools directory of your NuGet package and reference them from a custom MSBuild .props/.targets file.

Typically the custom .props and .targets are used to customise the build process. However they are just MSBuild project files so you could add items for your resources into these project files.
Note that .props are imported at the start of the project file when a NuGet package is installed, whilst .targets are imported at the end of the project.
Customising NuGet
Another option, which would take more work, would be to modify NuGet to support what you want to do.


Q: How to write unit test case IHttpClientFactory I have a method in service layer to  connect to a service and i am using IHttpClientFactory. My method is working fine. Now i am trying to write unit test cases for the same.
public async Task<MyObject> MyMethodAsync(string arg1, string arg2)
{
    var client = _httpClientFactory.CreateClient("XYZ");

    var Authkey = "abc";
    var AuthToken = "def";

    var headers = new Dictionary<string, string>
        {
            { Authkey,AuthToken }
        };

    client.AddTokenToHeader(headers); //This method set  the DefaultRequestheader from the dictionary object

    var reqData = new
    {
        prop1 = "X",
        prop2 = "Y"
    };//req object

    var content = new StringContent(JsonConvert.SerializeObject(reqData), Encoding.UTF8, "application/json");

    //This is httpClient Post call for posting data
    HttpResponseMessage response = await client.PostAsync("postData", content);
    if (!response.IsSuccessStatusCode || response.Content == null)
    {
        return null;
    }

    MyObject myObject = JsonConvert.DeserializeObject<MyObject>(response.Content.ReadAsStringAsync().Result);//read the result to an object
    return myObject;
}

For the above method i am writing test cases. Here i am trying to set the Post methods out put a status code OK and expecting the
MyMethodAsync method to be true as the PostAsync is true. Here i am getting an exception

System.InvalidOperationException : An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

[Test]
public async Task MyMethodAsync_Gets_True()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent("It worked!")
    };

    //Mock the httpclientfactory
    var _httpMessageHandler = new Mock<HttpMessageHandler>();
    var mockFactory = new Mock<IHttpClientFactory>();

    //Specify here the http method as post
    _httpMessageHandler.Protected()
      .Setup<Task<HttpResponseMessage>>("SendAsync",
       ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
       ItExpr.IsAny<CancellationToken>())
       .ReturnsAsync(new HttpResponseMessage
       {
           StatusCode = HttpStatusCode.OK
       });

    var httpClient = new HttpClient(_httpMessageHandler.Object);
    mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

    var arg1 = "X";
    var arg2 = "D101";

    var service = new MyService(_mockAppSettings.Object, mockFactory.Object);
    var result = await service.MyMethodAsync(arg1, arg2);
    // Assert
    Assert.IsNotNull(result);
}

Can someone show what mistake i am doing here?

A: As the exception says you have to

*

*either call the PostAsync with an absolute url

*or set the BaseAddress of the HttpClient

If you choose the second one all you need to do is this:
var httpClient = new HttpClient(_httpMessageHandler.Object);

httpClient.BaseAddress = new Uri("http://nonexisting.domain"); //New code

mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

With this modification the exception will be gone.
But your test will fail because the response.Content will be null and that's why MyMethodAsync will return with null.
To fix this let's change the Setup to this:
public static async Task MyMethodAsync_Gets_True()
{
    //Arrange
    MyObject resultObject = new MyObject();
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(JsonConvert.SerializeObject(resultObject))
    };

    var _httpMessageHandler = new Mock<HttpMessageHandler>();
    _httpMessageHandler.Protected()
        .Setup<Task<HttpResponseMessage>>("SendAsync",
          ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
          ItExpr.IsAny<CancellationToken>())
        .ReturnsAsync(response);
    ...

    //Act
    var result = await service.MyMethodAsync(arg1, arg2);

    //Assert
    Assert.NotNull(result);
}


Q: Is there a way to create a .net project in eclipse using no template I have eclipse 2021 installed on my laptop which is running Ubuntu 20.04 and I have .net 6 installed with snap when I go to create a .net project it says no template selected it in preferences the .net folder is in the snap folder. I just want to create a blank project , how can I do this. photo


Q: bsmultiselect Select one option at a time on div I was trying to use "setSelected" option on my multiselect, but I nnoticed that this does not work with divs (at least I couldn't reach it myself). I am trying to make two synced multiselects, using this example: https://dashboardcode.github.io/BsMultiSelect/snippetJs.html but with the last two inputs only.

var options = [

       { text: 'item1', value: 'item1'},
       { text: 'item2', value: 'item2'},

   ];

    var teste1 = null;
    var teste2 = null;
    let isTeste2 = true;
    var $testes = $('#teste1-id')
    if (isTeste2)
        $testes = $testes.add('#teste2-id')

    var install = function () {
        $testes.bsMultiSelect({
            options: options
        });
        if (isTeste2) {
            $('#teste1-id').on('dashboardcode.multiselect:change', function () {
                $('#teste2-id').bsMultiSelect("UpdateOptionsSelected");
            })
        }

    }
    install();

    $("#btn").click(
       function(){
          options[0].selected = true;
          var api1 = $testes.BsMultiSelect();
          api1.updateOptionSelected(0);
       }
    )

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Teste1

    Teste2:

<button id="btn">Click Me</button>

Could you help me find a solution, please?

A: For only "one select":

var options = [
       { text: 'item1', value: 'item1', selected: true},
       { text: 'item2', value: 'item2', selected: false},
];

function isValidSelection(v){
    var l = options.filter(function(item){
         return item.selected==true;
    }).length;
    var r = ( !v ) || (v && l==0);
    return r;
}

var teste1 = null;
var $teste1 = $('#teste1-id')

var install = function () {
   $teste1.bsMultiSelect({
       options: options,
       setSelected: function(o,v){
           if (isValidSelection(v)){
              o.selected = v;
              return true;
           }
           else{
              return false;
           }
       }
   });
}
install();

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Test it (only one select allowed)


Q: How to set headers in SQLPLUS? I have set following SQLPLUS commands:
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING ON
SET LINESIZE 100
SET PAGESIZE 1000
SET SPACE 0
SET TERMOUT OFF
SET TRIMOUT OFF
SET TRIMSPOOL ON
SET VERIFY OFF

But i am getting the result as:
ERROR_CODE
----------
ERROR_DESC
----------------------------------------------------------------------------------------------------
ERROR_COUNT
-----------
EXCP098

EXCEPTION: Processing not allowed

          2

EXCP014

EXCEPTION: UNKNOWN STATUS

         11

i.e. all the column headings and column values are in a new line instead of all column header should be in the same row and then record 1 should be in the first row and then record 2 should be in the second row.
I want it should be displayed as:
ERROR_CODE             ERROR_DESC                          ERROR_COUNT
-----------------------------------------------------------------------
EXCP098             EXCEPTION: Processing not allowed         2

EXCP014             EXCEPTION: UNKNOWN STATUS                11

A: If "ERROR_DESC" is too long to fit on a line (together with "ERROR_CODE" and "ERROR_COUNT"), you have a few options to try:

*

*return just a substring,

*TRIM the value, or

*change the data type for "ERROR_DESC".

What's working and appropriate, depends on your overall context. After all, the display in SQLPlus is usually not the most important aspect.


Q: Parallel Solution search I have written some code in python using multiprocessing package. It sort of searches for a solution for an equation in 6 different ways.So I have 6 different processes running the same function with different parameters. I would like to stop all the sub-processes once the solution has been found by one of the sub-process.Right now after using the join function, the result is that even if the solution is found , the other processes continue , till they find one . I'm using join()  .
for i in range(N):
                    p=multiprocessing.Process(target=mysolver,args=(g,h,q,B[i],i,dic,))
                    jobs.append(p)
                    p.start()

            for p in jobs:
                    p.join()

This how I call the function for solving. Usually N is 6 -10 .

A: You need to have a list containing a reference to all threads and accessible by all threads. This list of threads should be ready before you start the threads. The thread that finds a solution first can kill the others using the list, taking care of not commiting suicide.
You might face a racing condition in case one of the threads dies before you call join. As such you might be calling join on a already dead thread. A quick and dirty workaround is to let each thread wait few milliseconds fot the main thread to call join for all threads.
An other cleaner solution is to use a flag that is checked by all threads while they look for a solution. If they find it to be true, they should immediately terminate by returning. The thread that finds a solution can set the flag to true and return. Now all threads will nicely join the main thread.


Q: Diffing between two entire directories/projects in hg or git? I inherited a project originally stored in CVS with all the revisions. I made quite a few edits, and I'm trying to compare all the changes I made in the original directory, in regards to new files added versus the old ones.
Is there some sort of utility for hg/git where I can do a tree diff, or something of that nature? So that say, there's a mark between newly added files, deleted files, am I asking for too much?

A: I don't really understand what you want, but isn't diff -ur enough for you? It will work even on directories without any kind of version control.

A: git diff does exactly that. but it only works for git projects.
hg diff, svn diff pretty every version control system can diff directory trees

A: From git diff manpage:

git diff [--options] [--] [<path>...]

[...]
    If  exactly two paths are given, and at least one is untracked, compare the two files / directories. This behavior  can  be  forced  by --no-index.

If you want to compare two versions (e.g. two tagged releases, or two branches) in two different repositories, you can use trick described in GitTips page on Git Wiki, under "How to compare two local repositories".
Assuming that you are inside one repository, and second repository is in /path/to/repo, so its GIT_DIR is /path/to/repo/.git if it is non-bare repository, you can something like the following:
$ GIT_ALTERNATE_OBJECT_DIRECTORIES=/path/to/repo/.git/objects \
   git diff $(git --git-dir=/path/to/repo/.git rev-parse --verify A) B

where A and B are revisions you want to compare.  Of course you can also specify path limiter in above expression.
Explanation: GIT_ALTERNATE_OBJECT_REPOSITORIES variable can be used to make git commands concatenate object database of the two repositories.  git --git-dir=... rev-parse ... is used to turn name (extended SHA-1 expression) in repository given as parameter to git-dir option into unique SHA-1 identifier.  The $( ... ) construct puts result of calling given command in command line.  git diff is used to compare two revisions (where one is from alternate object repository).
Alternate solution would be to simply import other repository into given repository, using git remote add (and git fetch).  Then you would have everything locally, and would be able to do comparision inside single repository.

A:
Is there some sort of utility for hg/git where I can do a tree diff... [s]o that say, there's a mark between newly added files, deleted files... [emphasis added]

Yes. We can git diff the current directory against another directory and...
...mark the added, deleted, and modified files:
git diff --name-status --no-index ./ path/to/other/dir

...show only added files:
git diff --diff-filter=A --name-status --no-index ./ path/to/other/dir

... show only deleted files:
git diff --diff-filter=D --name-status --no-index ./ path/to/other/dir

...show only modified files:
git diff --diff-filter=M --name-status --no-index ./ path/to/other/dir

See also: https://git-scm.com/docs/git-diff

A: To simply create a diff patch in git's diff format from two arbitrary files or directories, without any fancy repository stuff or version control:
git diff --no-index some/path other/path > some_filename

Jakub Narębski's comment on knittl's answer hinted at the answer... For simplicity's sake, that's the full command.
The > part creates a file and redirects the output to it. If you don't want a file and just want the output printed in your console so you can copy it, just remove the > some_filename part.

For convenient copying and pasting, if you've already cded to a directory containing the original directory/file named a and the modified directory b, it'll be:
git diff --no-index a b > patch

A: It's not git-specific, but as a general diff utility for Windows, I really like WinMerge.

A: There Are Following Another Ways For Diffing between two entire directories/projects.

*

*In Git There is Syntax:
Syntax: git-diff [] [--] […]
This form is to view the changes you made relative to the index (staging area for the next commit). In other words, the differences are what you could tell Git to further add to the index but you still haven’t.
Here is the.
URL: https://git-scm.com/docs/git-diff
git diff --no-index directory 1 project /path directory 2 project/path >>  File name

*Using Linux Command diff --brief --recursive dir1path/ dir2Path/

*If you are using windows there is an application WinMerge.

A: Creating the patch from dir1 to dir2 (--binary only needed for binaries):
git diff --no-prefix --no-index --binary dir1 dir2 > dir.diff

Applying the patch to contents of working directory, which has the same contents as dir1:
cd dir1_copy
git apply ../dir.diff

git apply has default -p1 which strips the leading directories in diff commands.


Q: MetPy Wet Bulb Temperature function returns error when output of Most Unstable Parcel function is used as input When attempting to use the find the wet-bulb temperature for a parcel returned by MetPy's most_unstable_parcel function, I am getting an error that seems to be related to the Pint attributes of the most unstable parcel pressure.  It is necessary to strip away those attributes by coercing the pressure to be of type int or float.
See discussion, below.
I would greatly appreciate some help in understanding how to use the most unstable parcel pressure without resorting to the artifice of coercing it to a type that requires re-assigning units.  Thank you!
Example Calculation (data from OUN 20220328 00Z sounding):
from metpy.units import units
import metpy.calc as mpcalc

#  Construct a sample sounding:
p = [972.0, 942.8, 925.0, 910.1, 878.2, 850.0, 847.3, 826.0, 817.0, 787.5]*units('hPa')
T = [25.4, 22.4, 20.6, 19.3, 16.4, 13.8, 13.6, 11.6, 11.1, 9.4]*units('degC')
Td = [6.4, 5.3, 4.6, 4.1, 2.9, 1.8, 1.7, 0.6, -0.2, -2.9]*units('degC')
h = [345,  610,  776,  914, 1219, 1497, 1524, 1737, 1829, 2134]*units('m')

#  Find the Most Unstable Parcel
MUp = mpcalc.most_unstable_parcel(p,T,Td,h)

# MUp
# (972.0 <Unit('hectopascal')>,
#  25.4 <Unit('degree_Celsius')>,
#  6.4 <Unit('degree_Celsius')>,
#  0)

#  Next compute the wet-bulb-temperature for this parcel:

Twb = mpcalc.wet_bulb_temperature(MUp[0],MUp[1],MUp[2])

When this is executed, we get the following error traceback:
IndexError                                Traceback (most recent call last)
Input In [4], in <module>
----> 1 Twb = mpcalc.wet_bulb_temperature(MUp[0],MUp[1],MUp[2])

File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/xarray.py:1230, in preprocess_and_wrap.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
   1227     _mutate_arguments(bound_args, units.Quantity, lambda arg, _: arg.m)
   1229 # Evaluate inner calculation
-> 1230 result = func(*bound_args.args, **bound_args.kwargs)
   1232 # Wrap output based on match and match_unit
   1233 if match is None:

File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/units.py:288, in check_units.<locals>.dec.<locals>.wrapper(*args, **kwargs)
    285 @functools.wraps(func)
    286 def wrapper(*args, **kwargs):
    287     _check_units_inner_helper(func, sig, defaults, dims, *args, **kwargs)
--> 288     return func(*args, **kwargs)

File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/calc/thermo.py:3073, in wet_bulb_temperature(pressure, temperature, dewpoint)
   3071 ret = it.operands[3]
   3072 if ret.size == 1:
-> 3073     ret = ret[0]
   3074 return units.Quantity(ret, temperature.units)

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed

After running a few permutations of inputs, I discovered that it is possible to use the output pressure value if one first coerces it to, say, type float or int.
#  Reformat the pressure value as input to
#  wet_bulb_temperature()

d = float(MUp[0].magnitude)*units('hPa')
Twb1 = mpcalc.wet_bulb_temperature(d,MUp[1],MUp[2])
print(Twb1)

#  output is 14.209821596989343 degree_Celsius

# As far as Python is concerned, the two instances of pressure are
# identical:

print(MUp[0]==d)

#  Output:  True

It's just not clear to me why the pressure output from most_unstable_parcel (e.g. MUp[0]) cannot be used directly as an input to the wet-bulb temperature calculation.

A: This is a bug with MetPy's wet_bulb_temperature function in handling NumPy scalars, so thank you for identifying the issue! A pull request fixing this has been submitted, which should make it into the upcoming MetPy v1.3.0 release.
For now, you will need to somehow override the array shape recognition that exists in wet_bulb_temperature. Converting from a NumPy scalar to a Python scalar as you discovered is one such way to do so. Another is converting to 1D NumPy arrays, like the following:
Twb = mpcalc.wet_bulb_temperature(
    *(np.atleast_1d(arg) for arg in (MUp[0], MUp[1], MUp[2]))
)


Q: Boost.flyweight and Boost.MPL I have a question regarding flyweight options, given the definition below, based on http://www.boost.org/doc/libs/1_40_0/libs/flyweight/test/test_basic.cpp
typedef boost::flyweights::flyweight<
    std::string,
    boost::flyweights::tag<int>,
    boost::flyweights::static_holder_class<boost::mpl::_1>,
    boost::flyweights::hashed_factory_class<
        boost::mpl::_1,
        boost::mpl::_2,
        boost::hash<boost::mpl::_2>,
        std::equal_to<boost::mpl::_2>,
        std::allocator<boost::mpl::_1>
    >,
    boost::flyweights::simple_locking,
    boost::flyweights::refcounted
> StringFlyweight;

StringFlyweight    test1("Hello World");

what value has boost::mpl::_1 and boost::mpl::_2 ? When are asigned ?
boost::mpl::_1 is most probably std::string. boost::mpl::_2 should be size_t ? If true, how is deducted ?
I don't understand how is key_type chosen.
I have read http://www.boost.org/doc/libs/1_41_0/libs/flyweight/doc/tutorial/lambda_expressions.html but I it is my first contact with Boost.MPL and is not enough :)

A: boost::mpl::_1 and boost::mpl::_2 are placeholders; they can be used as template parameters to differ the binding to an actual argument to a later time. With this, you can do partial application (transforming a metafunction having an n-arity to a function having a (n-m)-arity), lambda expressions (creating a metafunction on-the-fly where it is needed), etc.
An expression containing at least a placeholder is a placeholder expression, which can be invoked like any other metafunction, with some arguments that will replace the placeholders.
In your example, assuming the following typedef
typedef boost::flyweights::hashed_factory_class<
    boost::mpl::_1,
    boost::mpl::_2,
    boost::hash<boost::mpl::_2>,
    std::equal_to<boost::mpl::_2>,
    std::allocator<boost::mpl::_1>
> hashed_factory;

we can assume that at some other point in the code, the hashed_factory will be invoked with some parameter:
typedef typename
    boost::mpl::apply<
       hashed_factory,
       X,
       Y
    >::type result; // invoke hashed_factory with X and Y
                    // _1 is "replaced" by X, _2 by Y

I did not look in Flyweight code, but we can suppose that _1 will be bound to the value type of the flyweight, and _2 to the key type (since it is used for hashing and testing equality). In this case, I think both will be std::string since no key type is specified.
I'm not sure my explanation about MPL's placeholders is quite clear, feel free to read the excellent MPL tutorial that explains very well metafunctions, lambda expressions and other template metaprogramming features.


Q: How do I create an array of ascending and then descending numbers? For example:
I have min and max values and a number of increments which may be odd or even;
if I have min = 3 and max = 10 and increments = 15 then I want:
3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3

However, if increments = 16 I want (notice the two 10's in the middle):
3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3

I have to create these arrays add-hoc using just min, max, and number of increments.
UPDATE:
To make this clearer the number of increments is equal to the number of items that must be in the array and the items are decimals.
so if min = 5.0 and max = 15.0 and increments = 6 then the array would contain:
5.0, 10.0, 15.0, 15.0, 10.0, 5.0

A: Linq way:
int min = 3;
int max = 10;
int increments = 15;

Enumerable
    .Range(min, max - min + 1)
    .Concat(Enumerable
        .Range(min, max - min + 1)
        .Reverse()
        .Skip(increments % 2))
    .ToArray();

A: This should work:
public static IEnumerable<decimal> NewMethod(decimal min, decimal max, int count)
{
    var increment = (max - min) / (int)((count - 1) / 2);

    for (var i = min; i < max; i += increment)
        yield return i;

    if (count % 2 == 0)
        yield return max;

    for (var i = max; i >= min ; i -= increment)
        yield return i;
}

Sample test:
var min = 3.0m;
var max = 10.0m;
var count = 16;

MessageBox.Show(string.Join(", ", NewMethod(min, max, count)));

Edit: You have to cope with floating point types losing precision, otherwise you will be missing an element in the final result set. Tinker a bit with Math.Round over the i += and i -= part, that's up to you. I have updated code to replace double with more reliable decimal type. But there is no guarantee this should not fail every time. Easier is to avoid cases where you will need decimal types in the result like { 1, 2.2, 3.4 } etc.

A: Here's a one-way ramp that handles floating point values correctly.  You should be able to modify it to make a triangle waveform.  When implementing a ramp, care must be taken to make sure not to accumulate either round-off errors, or off-by-one errors for various inputs.
void Packet::SetRamp( const SampleType start /*= Signal::One*/,
                      const SampleType finish /*= -Signal::One */ )
{
    SampleType slope, current;
    SampleOffsetType len;
    len = GetLength();
    if ( len < 2 )
        throw std::range_error( "packet is not large enough to set ramp into" );
    slope = ( finish - start ) / ( len - 1 );
    for ( SampleOffsetType row = 0; row < len; row++ )
    {
        current = slope * row + start;
        SetSample( row, current );
    }
}


Q: Do we have a way to include full source into APK? I'm developing samples for different Android technologies and want to include the full source code (Eclipse project) archived into the APK. That should allow anyone with Google Market access to easily reuse the code.
Is there a proper way to automatically pack the code/resources and put it into assets?
I'm using Eclipse under Win//Linux.
Currently I have to manually 7z-compress the src&res and put it into assets before signing.

A: Sure, just compress it and include it in a directory under your APK (e.g. raw). But be aware that your APK will at least x2 its size.


Q: Display calendar to pick a date in java In other languages like VB, C#, in occasions where you want the user to enter a date, say in a text box,we can make a calendar to appear once you click on it. So the user can click on the corresponding date and that date will be put to the text box.
By that way we can get rid of problems that can be caused due to dates in an incorrect format. I need to know how we can achieve this in java?
Actually, I need to combine this with a JTable. there is a column where the date need to be entered. But users may enter dates in various formats. So I thought of going to something like this. Hope there is a way to do this, easily.
Will anyone please show me how to do this. Any help is greatly appreciated..
Thank you.

A: Another easy method in Netbeans is also avaiable here,
There are libraries inside Netbeans itself,where the solutions for this type of situations are available.Select the relevant one as well.It is much easier.After doing the prescribed steps in the link,please restart Netbeans.
Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette.  Lots of goodies here!  Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)

A: I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

A: I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DateTextField extends JTextField {

    private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
    private static final int DIALOG_WIDTH = 200;
    private static final int DIALOG_HEIGHT = 200;

    private SimpleDateFormat dateFormat;
    private DatePanel datePanel = null;
    private JDialog dateDialog = null;

    public DateTextField() {
        this(new Date());
    }

    public DateTextField(String dateFormatPattern, Date date) {
        this(date);
        DEFAULT_DATE_FORMAT = dateFormatPattern;
    }

    public DateTextField(Date date) {
        setDate(date);
        setEditable(false);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        addListeners();
    }

    private void addListeners() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent paramMouseEvent) {
                if (datePanel == null) {
                    datePanel = new DatePanel();
                }
                Point point = getLocationOnScreen();
                point.y = point.y + 30;
                showDateDialog(datePanel, point);
            }
        });
    }

    private void showDateDialog(DatePanel dateChooser, Point position) {
        Frame owner = (Frame) SwingUtilities
                .getWindowAncestor(DateTextField.this);
        if (dateDialog == null || dateDialog.getOwner() != owner) {
            dateDialog = createDateDialog(owner, dateChooser);
        }
        dateDialog.setLocation(getAppropriateLocation(owner, position));
        dateDialog.setVisible(true);
    }

    private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
        JDialog dialog = new JDialog(owner, "Date Selected", true);
        dialog.setUndecorated(true);
        dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        return dialog;
    }

    private Point getAppropriateLocation(Frame owner, Point position) {
        Point result = new Point(position);
        Point p = owner.getLocation();
        int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
        int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());

        if (offsetX > 0) {
            result.x -= offsetX;
        }

        if (offsetY > 0) {
            result.y -= offsetY;
        }

        return result;
    }

    private SimpleDateFormat getDefaultDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        }
        return dateFormat;
    }

    public void setText(Date date) {
        setDate(date);
    }

    public void setDate(Date date) {
        super.setText(getDefaultDateFormat().format(date));
    }

    public Date getDate() {
        try {
            return getDefaultDateFormat().parse(getText());
        } catch (ParseException e) {
            return new Date();
        }
    }

    private class DatePanel extends JPanel implements ChangeListener {
        int startYear = 1980;
        int lastYear = 2050;

        Color backGroundColor = Color.gray;
        Color palletTableColor = Color.white;
        Color todayBackColor = Color.orange;
        Color weekFontColor = Color.blue;
        Color dateFontColor = Color.black;
        Color weekendFontColor = Color.red;

        Color controlLineColor = Color.pink;
        Color controlTextColor = Color.white;

        JSpinner yearSpin;
        JSpinner monthSpin;
        JButton[][] daysButton = new JButton[6][7];

        DatePanel() {
            setLayout(new BorderLayout());
            setBorder(new LineBorder(backGroundColor, 2));
            setBackground(backGroundColor);

            JPanel topYearAndMonth = createYearAndMonthPanal();
            add(topYearAndMonth, BorderLayout.NORTH);
            JPanel centerWeekAndDay = createWeekAndDayPanal();
            add(centerWeekAndDay, BorderLayout.CENTER);

            reflushWeekAndDay();
        }

        private JPanel createYearAndMonthPanal() {
            Calendar cal = getCalendar();
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.setBackground(controlLineColor);

            yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                    startYear, lastYear, 1));
            yearSpin.setPreferredSize(new Dimension(56, 20));
            yearSpin.setName("Year");
            yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
            yearSpin.addChangeListener(this);
            panel.add(yearSpin);

            JLabel yearLabel = new JLabel("Year");
            yearLabel.setForeground(controlTextColor);
            panel.add(yearLabel);

            monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                    12, 1));
            monthSpin.setPreferredSize(new Dimension(35, 20));
            monthSpin.setName("Month");
            monthSpin.addChangeListener(this);
            panel.add(monthSpin);

            JLabel monthLabel = new JLabel("Month");
            monthLabel.setForeground(controlTextColor);
            panel.add(monthLabel);

            return panel;
        }

        private JPanel createWeekAndDayPanal() {
            String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
            JPanel panel = new JPanel();
            panel.setFont(new Font("Arial", Font.PLAIN, 10));
            panel.setLayout(new GridLayout(7, 7));
            panel.setBackground(Color.white);

            for (int i = 0; i < 7; i++) {
                JLabel cell = new JLabel(colname[i]);
                cell.setHorizontalAlignment(JLabel.RIGHT);
                if (i == 0 || i == 6) {
                    cell.setForeground(weekendFontColor);
                } else {
                    cell.setForeground(weekFontColor);
                }
                panel.add(cell);
            }

            int actionCommandId = 0;
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 7; j++) {
                    JButton numBtn = new JButton();
                    numBtn.setBorder(null);
                    numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
                    numBtn.setActionCommand(String
                            .valueOf(actionCommandId));
                    numBtn.setBackground(palletTableColor);
                    numBtn.setForeground(dateFontColor);
                    numBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            JButton source = (JButton) event.getSource();
                            if (source.getText().length() == 0) {
                                return;
                            }
                            dayColorUpdate(true);
                            source.setForeground(todayBackColor);
                            int newDay = Integer.parseInt(source.getText());
                            Calendar cal = getCalendar();
                            cal.set(Calendar.DAY_OF_MONTH, newDay);
                            setDate(cal.getTime());

                            dateDialog.setVisible(false);
                        }
                    });

                    if (j == 0 || j == 6)
                        numBtn.setForeground(weekendFontColor);
                    else
                        numBtn.setForeground(dateFontColor);
                    daysButton[i][j] = numBtn;
                    panel.add(numBtn);
                    actionCommandId++;
                }

            return panel;
        }

        private Calendar getCalendar() {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(getDate());
            return calendar;
        }

        private int getSelectedYear() {
            return ((Integer) yearSpin.getValue()).intValue();
        }

        private int getSelectedMonth() {
            return ((Integer) monthSpin.getValue()).intValue();
        }

        private void dayColorUpdate(boolean isOldDay) {
            Calendar cal = getCalendar();
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
            int i = actionCommandId / 7;
            int j = actionCommandId % 7;
            if (isOldDay) {
                daysButton[i][j].setForeground(dateFontColor);
            } else {
                daysButton[i][j].setForeground(todayBackColor);
            }
        }

        private void reflushWeekAndDay() {
            Calendar cal = getCalendar();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    String s = "";
                    if (dayNo >= 1 && dayNo <= maxDayNo) {
                        s = String.valueOf(dayNo);
                    }
                    daysButton[i][j].setText(s);
                    dayNo++;
                }
            }
            dayColorUpdate(false);
        }

        public void stateChanged(ChangeEvent e) {
            dayColorUpdate(true);

            JSpinner source = (JSpinner) e.getSource();
            Calendar cal = getCalendar();
            if (source.getName().equals("Year")) {
                cal.set(Calendar.YEAR, getSelectedYear());
            } else {
                cal.set(Calendar.MONTH, getSelectedMonth() - 1);
            }
            setDate(cal.getTime());
            reflushWeekAndDay();
        }
    }
}

A: The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components.
I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .

A: *

*Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

*Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");

*Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;

*Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);

Your Java application now has a drop-down date selection dialog.


Q: C# UI automated testing - Does anyone succeeded to capture the command prompt window object? I have an UI automated test developed with White. One of the cases needs to open cmd and write some commands. The problem is when I input the first command. I tried something like:
Process.Start("CMD.EXE");

///Thread.Sleep(2000);

SendKeys.SendWait(command);

The problem is that sendkeys starts to input before the windows is opened, and trims the command, skipping first characters (depending on window appearance moment). It works with a sleep, but I'm trying to avoid such practices.
In order to avoid this I would insert a timer to wait for the window to be visible. So my questions:

*

*Can this window be captured, so I can wait for it?

OR

*

*Any other way to send the command?

A: for this special case ,you could execute the cmd  to run your commands as args, i mean, avoid sendKeys and execute the cmd like this : Process.Start("CMD.EXE", "/c echo hello world");
note that /c will execute the cmd and exit while /k execute the cmd and return to the CMD prompt.


Q: Data.Aeson encoding optional keys I have the following problem, I have a JSON format with optional keys that I need to generate from my haskell code.
Lets make an example
{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Data.Aeson

data Person = {
    name :: String,
    shoeSize :: Maybe Int,
    favoriteColor :: Maybe String,
    favoriteFood :: Maybe StringC
} deriving (show, eq, generic)

instance ToJSON Person -- Generic instance

now, if I try encoding a Person without a shoesize I still get a key "shoeSize" set to null, what is the Aeson way of making keys optional in encoding
edit, example of an encode
encode $ Person "windwarrior" Nothing "green" Nothing

should result in
{"name":"windwarrior", "favoriteColor":"green"}

A: Use TemplateHaskell to derive the ToJSON instance instead of Generic. The TH functions optionally take an Options which has the omitNothingFields option.

A: There is the Options datatype with an omitNothingFields field for Generics as well so you don't have to use TemplateHaskell, however there's currently (v0.11.2.0) a bug that makes it generate invalid JSON under certain circumstances, e.g. several record fields. It has been fixed but is in master.
You can also handwrite instances if you prefer, for your example:
instance ToJSON Person where
    toJSON (Person name shoeSize favoriteColor favoriteFood) = object fields
      where
        consMay attr = maybe id ((:) . (attr .=))
        conss = consMay "shoeSize" shoeSize
              . consMay "favoriteColor" favoriteColor
              . consMay "favoriteFood" favoriteFood
        fields = conss ["name" .= name]


Q: Why is the order of haystack and needle inconsistent in PHP functions in_array and strpos? The order of parameters haystack and needle in these 2 very core PHP functions is not consistent:

*

*http://php.net/manual/en/function.in-array.php (needle, haystack)

*http://php.net/manual/en/function.strpos.php (haystack, needle)

Why is this the case?

A: Needle/Haystack in PHP
They are actually not inconsistent like many think. You have partly discovered the consistency:

*

*All string functions are (haystack, needle)

*All array functions are (needle, haystack)
Rasmus Lerdorf (the creator of PHP) states this in a talk in 2019 around 25 minutes in:
25 Years of PHP - phpday 2019
https://youtu.be/iGOAQli7tGc?t=1485
Inconsistencies in PHP
At 16:45, he has a slide titled "What was he thinking?" and he addresses "naming inconsistencies". (needle/haystack issue is just one of them)
https://youtu.be/iGOAQli7tGc?t=1005
In this talk he also explains that his design decisions for PHP are almost all based on the idea that PHP is a "wrapper for underlying C libraries", and has kept the parameters in the same order as the underlying code.


Q: Cut off string at not allowed tags in regex I got this fine working regex to use with php's preg_match_all to match a string containing 0 to x lines before and 0 to y lines after a specific word in a sentence/string:
'(?:[^\.?!<]*[\.?!]+){0,x}(?:[^\.?!]*)'.$word.'(?:[^\.?!]*)(?:[\.?!]+[^\.?!]*){0,y}'.'(?:[\.?!]+)'

Now, I want the string to be cut off when specific tags occur. So I was thinking about implementing this part in this string above:
(?:(<\/?(?!'.$allowed_tags.')))

in which $allowed_tags is a php variable that could look like this for example: '(frame|head|span|script)'
Despite trying to get this to work with lookahead, lookbehind and other conditions I can't get it working properly and I unfortunately have to admit this is way beyond my programming skills.
Hopefully someone can help me with this? I am sure someone among you geniuses can :)
Thanks a lot in advance!
Example input-output:
For example I would like to grab this part:

Tradition, Expansion, Exile.
Individual paths in Chinese contemporary art

The contemporary art world craves for novelty: the best reason for Chinese art to be so trendy is also the worst one.

from this complete string:

Tradition, Expansion, Exile.
Individual paths in Chinese contemporary art

The contemporary art world craves for novelty: the best reason for Chinese art to be so trendy is also the worst one.

That means in this example

 are allowed tags and
 and
 aren't.

A: Assuming you define div and span tags as “illegal” as per your comment, the following regex will match x sentences before and y sentences after the sentence conatining $word, as long as those sentences do not contain the “illegal” tags:
'(?:(?<=[.!?]|^)(?:(?<!<div|<\/div|<span|<\/span)>|[^>.!?])+[.!?]+){0,x}[^.!?]*'.$word.'[^.!?]*[.!?]+(?:(?:<(?!\/?div|\/?span)|[^<.!?])*[.!?]+){0,y}'

Split up and explained (quotes and string concatenation operator removed, comments and line breaks added for better reading):
                                     // 0 TO X LEADING SENTENCES
(?: ---------------------------------// do not create a capture group
  (?<=[.!?]|^) ----------------------// match only after sentence end or start of string
  (?: -------------------------------// do not create a capture group
    (?<!<div|<\/div|<span|<\/span)> -// match “>” only if not preceded by span or div tags
    |[^>.!?] ------------------------// or any any other, non punctuation character
  )+ --------------------------------// one or more times
  [.!?]+ ----------------------------// followed by one or more punctuation characters
){0,x} ------------------------------// the whole sentence repeated 0 to x times
                                     // MIDDLE SENTENCE WITH KEYWORD
[^.!?]* -----------------------------// match 0 or more non-punctuation characters
$word -------------------------------// match string value of $word
[^.!?]* -----------------------------// match 0 or more non-punctuation characters
[.!?]+ ------------------------------// followed by one or more punctuation characters
                                     // 0 TO Y TRAILING SENTENCES
(?: ---------------------------------// do not create a capture group
  <(?!<\/?div|\/?span) --------------// match “<” not followed by a “div” or “span” tag
  |[^<.!?] --------------------------// or any non-punctuation character that is not “<”
  )* --------------------------------// zero or more times
  [.!?]+ ----------------------------// followed by one or more punctuation characters
){0,y} ------------------------------// the whole sentence repeated 0 to y times

Note the lookbehind assertion used for matching sentences before $word will only match opening and closing tags without attributes, and has to match both the opening and closing tag variants literally, as lookbehind assertions cannot be of variable length. There are other limitations and gotchas:

*

*notably that the regex will return an “illegal” tag if it is located inside the sentence containing $word

*and that “inside” a sentence literally means “following the closing punctuation of the preceding sentence”, which, although formally correct, might not be what is expected.

All of this goes to highlight the limitations of a regex based approach to the problem. In this light, you might think that switching to a more programatic approach (like parsing all sentences into an array irrespective of tags, then scanning for “illegal” tags and trimming or rejecting the array accordingly, which would allow for a more flexible tag matching regex) would work better, and you would be right, were it not for the underlying difficulty of matching a natural language construct like a sentence with a regex with any degree of accuracy. I’ll leave you to ponder what the “sentence splitting” regex used in this question and answer would do to the following:

“T.J. Hooker was plaid (sic.) by W. Shatner of Starship Enterprise (!) fame”

It’s not pretty. And neither is the result.


Q: Read a column file in julia I would not like to pickaxe a lot in the language just to read a file with numerical data arranged by columns. Is there an easy way to do this now in julia 1.1? Surprisingly this simple task is not on the manual. In python one would do something like this:
def read2col(filename, length):
    data = []
    for line in open(filename,'r'):
        for word in line.split():
            data.append(word)

data = np.reshape(data,(length,2))
data = np.asarray(data, dtype=np.float64)
return data

A: There is already an inbuilt function in Julia that does exactly that:
using DelimitedFiles
reshape(readdlm("myfilename.txt"),:,2)

Let's give it a spin:
shell> more file.txt
1 2 3
4 5 6
7 8 9
10 11 12

julia>  reshape(readdlm("file.txt"),:,2)
6×2 Array{Float64,2}:
  1.0   8.0
  4.0  11.0
  7.0   3.0
 10.0   6.0
  2.0   9.0
  5.0  12.0

or if you want a different ordering just transpose with '
julia>  reshape(readdlm("file.txt")',:,2)
6×2 reshape(::LinearAlgebra.Adjoint{Float64,Array{Float64,2}}, 6, 2) with eltype Float64:
 1.0   7.0
 2.0   8.0
 3.0   9.0
 4.0  10.0
 5.0  11.0
 6.0  12.0

A: (untested)
function read2col(filename, len)
    asfloat64(s) = try x = parse(Float64, s); return x catch; return missing; end
    data = []
    for word in split(read(filename, String), r"\s+")
        push!(data, word)
    end
    data = reshape(data,(len, 2))
    data = asfloat64.(data)
    return data
end

or even
asfloat64(s) = try x = parse(Float64, s); return x catch; return missing; end
read2col(fname, len) = asfloat64.(reshape(split(read(fname, String), r"\s+"), (len, 2)))

A: The laziest way to do it is to use CSV.jl
using CSV
for row in CSV.File("file.txt",delim=' ',ignorerepeated=true)
  println("a=$(row.a), b=$(row.b), c=$(row.c)")
end

delim=',': a Char or String that indicates how columns are delimited in a file; if no argument is provided, parsing will try to detect the most consistent delimiter on the first 10 rows of the file


Q: How do I make a modulino in Perl6? I want to make a modulino (a file that can run as either a module or a script) in Perl6.
The following code "processes" file names from the command line:
sub MAIN ( *@filenames )
{
    for @filenames -> $filename
    {
        say "Processing $filename";
    }
}

Saving this as main.pm6 I can run it and it works:
perl6 main.pm6 hello.txt world.txt
Processing 'hello.txt'
Processing 'world.txt'

So, I want this to be a module so that I can add functions and make testing it easier. However, when I add a module declaration to it, it no longer outputs anything:
module main;
sub MAIN ( *@filenames )
{
    for @filenames -> $filename
    {
        say "Processing '$filename'";
    }
}

Which results in nothing output:
perl6 main.pm6 hello.txt world.txt

So, how can I build a modulino in Perl6?
I'm using Perl6 running on MoarVM from the January 2015 release of Rakudo Star.
UPDATE:
When I try wrapping the module in braces:
module main
{
    sub process (@filenames) is export
    {
        for @filenames -> $filename
        {
            say "Processing '$filename'";
        }
    }
};

sub MAIN ( *@filenames )
{
    process(@filenames)
}

I also get errors:
===SORRY!=== Error while compiling main.pm6
Undeclared routine:
    process used at line 14. Did you mean 'proceed'?

A: The MAIN sub needs to be declared outside the module, but it still must be able to see process.
There are multiple ways to achieve this, eg by not declaring a module at all
sub process(@filenames) {
    for @filenames -> $filename {
        say "Processing '$filename'";
    }
}

sub MAIN(*@filenames) {
    process(@filenames);
}

by making process our-scoped and calling it by its longname
module main {
    our sub process(@filenames) {
        for @filenames -> $filename {
            say "Processing '$filename'";
        }
    }
}

sub MAIN(*@filenames) {
    main::process(@filenames);
}

or by exporting process and importing it in the body of MAIN
module main {
    sub process(@filenames) is export {
        for @filenames -> $filename {
            say "Processing '$filename'";
        }
    }
}

sub MAIN(*@filenames) {
    import main;
    process(@filenames);
}

In my opinion the most appropriate option is to add MAIN to the module and import it into the script's mainline. This way, everything declared within the module is visible within MAIN without having to explicitly export everything:
module main {
    sub process(@filenames) {
        for @filenames -> $filename {
            say "Processing '$filename'";
        }
    }

    sub MAIN(*@filenames) is export(:MAIN) {
        process(@filenames);
    }
}

import main :MAIN;

Note that this does not export MAIN by default, ie users of your module will only get it if they provide the :MAIN tag.


Q: Can a bot click a link that makes a modal window in javascript? I have a form that launches in a modal window (fancybox to be exact) that loads a page that triggers an event in Google Analytics. I'm trying to keep bots from clicking it.
Since the fancybox uses jQuery to load the html page, can a bot reach the page and trigger the event? I'm trying to determine if the events are real.
I'm getting a difference between unique events and total events and trying to explain why there would be a discrepancy. Is the only way to explain it as genuine people clicking or could it be bots?

A: Yes, a bot can do that. There's many ways of creating bots, and different methods will make most bots undetectable unless you have some really complex checks in place. I believe reCaptcha has a tonne of checks for example, ranging from the movement of the mouse, the react time of the user, user agents and so on and so forth.
Bots can come in all shapes and forms, including some that might use Selenium to imitate a user using an actual browser, or they could even be written in a lower level and move the mouse and cause key presses on a system level.
What it comes down to is how much energy/time you're willing to expend to make it harder for bots to do their thing. I doubt you'll ever get 100% accuracy on stopping bots.
But yes, a bot can trigger a button press event, or even press the button directly like a normal user would


Q: Limit number of results for Songkick API I'm trying to limit the number of results that this pulls:
http://api.songkick.com/api/3.0/search/venues.json?query={venue term}&apikey={API KEY}

I've tried adding on maxResults, limit, results.. none of them seem to work.
I can't find anything in the documentation. Anyone know?
Thanks!

A: The documentation for venue search mentions the per_page argument, that limits how many items are returned for each request.
You can try using:
http://api.songkick.com/api/3.0/search/venues.json?query={venue term}&per_page=10&apikey={API KEY}
It accepts any value between 1 and 50.


Q: FileHelpers Library: AfterReadRecord Compilation Error I'm hoping there's an expert in using the FileHelpers library here.
I'm using the 2.9.9 stable version from Nuget and trying to use the AfterReadRecord event handler to test if fields are empty.
The code I have is shown in simplified form below:
public class Test
{
 public class MyClass
 {
  public string Name;
 }

 public static void engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<MyClass> e)
 {
  if (String.IsNullOrWhiteSpace(e.Record.Name))
  {
   throw new InvalidDataException("Name is required");
  }
 }

 public void ReadCSV()
 {
  FileHelperEngine engine = new FileHelperEngine(typeof(MyClass));
  engine.Options.IgnoreFirstLines = 1;
  engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
  engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
 }
}

There's a compilation error on that last line in the ReadCSV file. The error is:
Cannot implicitly convert type 'FileHelpers.Events.AfterReadHandler<MyClass>' to
'FileHelpers.Events.AfterReadHandler<object>'

I'm stuck. Any helpers?
Jake

A: The problem is that u are using a version of the engines that don't use generics but using generics in the handler
Try with this:
  var engine = new FileHelperEngine<MyClass>();
  engine.Options.IgnoreFirstLines = 1;
  engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
  engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);


Q: How to 'translate' a string of words using a map? Search through a maps keys and displaying the value I have a map that contains Spanish words as keys and the same word in English as the values for each key. I want to translate a string of words from Spanish to English. I'm assuming I'll need to parse the string to separate the words. I don't know how to search through the map keys and then to display the value.
    map<string, string> trans;
    tran["rearrancar"] = "reboot";
    tran["pantalla"] = "screen";
    tran["texto"] = "text";
    tran["virus"] = "virus";
    tran["tinta"] = "ink";
    tran["mitad"] = "half";
    tran["interno"] = "internal";
    tran["memoria"] = "memory";
    tran["papel"] = "paper";
    tran["energia"] = "power";
    tran["fallo"] = "bug";
    tran["pelo"] = "hair";
    tran["el"] = "the";
    tran["dos"] = "two";
    tran["todas"] = "all";
    tran["en"] = "in";
    tran["de"] = "of";
    tran["los"] = "the";
    tran["comprar"] = "buy";
    tran["tarde"] = "afternoon";
    tran["quieres"] = "want";
    tran["muchachos"] = "boys";
    tran["tienen"] = "have";
    tran["ordenador"] = "computer";
    tran["con"] = "with";
    tran["antes"] = "before";
    tran["vacio"] = "empty";
    tran["tu"] = "you";
    tran["hambre"] = "hunger";
    tran["contaminado"] = "corrupt";
    tran["a"] = "to";
    tran["una"] = "a";
    tran["la"] = "the";
    tran["cafe"] = "brown";
    tran["su"] = "your";
    tran["es"] = "is";
    tran["quiero"] = "want";
    tran["vamos"] = "go";
    tran["mi"] = "my";
    tran["barco"] = "ship";
    tran["nosotros"] = "we";
    tran["casa"] = "house";
    tran["yo"] = "I";
    tran["borrar"] = "delete";
    tran["necesita"] = "necessary";
    tran["despues"] = "after";

    string paragraph ("yo quiero una ordenador virus
    todas de los muchachos tienen interno memoria
    mi pelo es cafe
    tu quieres tinta con su papel
    rearrancar el ordenador a vacio el pantalla");

Would it be better to store each word into an array of strings?
Edit: I can now search the map for the word to translate but it crashes after the 4th translated word. I'm sure it has something to do with the parameters in my for loop but I don't know what to put in it.
    stringstream ss(paragraph);
    string word = "";
    for (int i = 0; i < paragraph.length(); i++) {
        getline(ss, word, ' ');
        cout << tran.find(word)->second << " ";
    }

Paragraph is the string containing the paragraph to be translated. Tran is the name of my map containing the Spanish keys and English values.

A: Your loop loops paragraph.length() times (the number of characters in paragraph), but each time you extract a word. See the problem?
Use while (getline(ss, word, ' ')) instead. getline will return the stream it was given, and converting it to bool is equivalent to !ss.fail(). This basically loops until an extraction fails (reached the end of the stream and did not extract anything).
You also never checked if the search for the word in the map fails and therefore have the possibility of trying to dereference tran.end().
Some other minor problems with your code includes using namespace std which can be considered bad practice, and some typos involving the difference between tran and trans.
The fixed code:
#include <iostream>
#include <map>
#include <string>
#include <sstream>

int main()
{
    std::map<std::string, std::string> tran;
    tran["rearrancar"] = "reboot";
    tran["pantalla"] = "screen";
    tran["texto"] = "text";
    tran["virus"] = "virus";
    tran["tinta"] = "ink";
    tran["mitad"] = "half";
    tran["interno"] = "internal";
    tran["memoria"] = "memory";
    tran["papel"] = "paper";
    tran["energia"] = "power";
    tran["fallo"] = "bug";
    tran["pelo"] = "hair";
    tran["el"] = "the";
    tran["dos"] = "two";
    tran["todas"] = "all";
    tran["en"] = "in";
    tran["de"] = "of";
    tran["los"] = "the";
    tran["comprar"] = "buy";
    tran["tarde"] = "afternoon";
    tran["quieres"] = "want";
    tran["muchachos"] = "boys";
    tran["tienen"] = "have";
    tran["ordenador"] = "computer";
    tran["con"] = "with";
    tran["antes"] = "before";
    tran["vacio"] = "empty";
    tran["tu"] = "you";
    tran["hambre"] = "hunger";
    tran["contaminado"] = "corrupt";
    tran["a"] = "to";
    tran["una"] = "a";
    tran["la"] = "the";
    tran["cafe"] = "brown";
    tran["su"] = "your";
    tran["es"] = "is";
    tran["quiero"] = "want";
    tran["vamos"] = "go";
    tran["mi"] = "my";
    tran["barco"] = "ship";
    tran["nosotros"] = "we";
    tran["casa"] = "house";
    tran["yo"] = "I";
    tran["borrar"] = "delete";
    tran["necesita"] = "necessary";
    tran["despues"] = "after";

    std::string paragraph(
            "yo quiero una ordenador virusu todas de los muchachos tienen");
    std::stringstream ss(paragraph);
    std::string word;
    while (std::getline(ss, word, ' '))
    {
        auto findResult = (tran.find(word));
        std::cout
                << (findResult != tran.end() ?
                        findResult->second : "[translation not found]") << " ";
    }
}


Q: AWS Cognito: Add custom claim/attribute to JWT access token My app creates a custom attribute "userType" for each new signed-up user. Now I would like this "userType" claim/attribute to be added to the JWT access token whenever the user signs in or the token gets refreshed.
Is there an option to tell cognito to add my custom claim/attribute to the JWT access token? (Without a pre token generation Lambda)

A: Custom attributes are not available in Cognito access token. Currently it is not possible to inject additional claims in Access Token using Pre Token Generation Lambda Trigger as well. PreToken Generation Lambda Trigger allows you to customize identity token(Id Token) claims only.

A: You can use ID token to get the token with custom attributes.
Access tokens are not intended to carry information about the user. They simply allow access to certain defined server resources.
You can pass an ID Token around different components of your client, and these components can use the ID Token to confirm that the user is authenticated and also to retrieve information about them.
How to retrieve Id token using amazon cognito identity js
cognitoUser.authenticateUser(authenticationDetails,{
  onSuccess: function(result) {
    var accessToken = result.getIdToken().getJwtToken();
    console.log('accessToken is: ' + accessToken);
  },
  onFailure: function(err) {
    alert(err.message || JSON.stringify(err));
  },
});

A: I have the same problem when I want to create several microservice. There isn't a way I can customize an access token, but only an identity token. However, I use client credentials in the machine-to-machine which needs access token. So, in no way I can customize my token. At last, I decide to add such info(like user type) in the event header. It's not a very secure way compared to customize a token, but there isn't any other easy way to do it right now. Otherwise, I have to rewrite the authorizer in Cognito. Like rewriting a customize authorizer and it's very painful.

A: I have the same issue with Cognito; exist other tools like "PingFederate"Auth-server of Ping identity and Auth0 Auth-server; I know that the requirement isn't part of the standard, but these applications were my alternatives to fix this issue

A: The responses suggesting to use the ID Token for authorization in your backend systems are bad security practice. ID Tokens are for determining that the user is in fact logged in and the identity of that user. This is something that should be performed in your frontend. Access Tokens on the other hand are for determining that a request (to your backend) is authorized. ID Tokens do not have the same security controls against spoofing that Access Tokens have (see this blog from Auth0: https://auth0.com/blog/id-token-access-token-what-is-the-difference/).
Instead, I recommend that your backend accept an Access Token as a Bearer token via the Authorization HTTP header. Your backend then calls the corresponding /userinfo endpoint (see: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) on the authorization server that issued the Access Token, passing such said Access Token to that endpoint. This endpoint will return all of the ID Token information and claims, which you can then use to make authorization decisions in your code.


Q: TADOQuery.Open executes a statement but only once I use this code to copy row from Table1 to Table2, but it gives me

Command Text does not return a result set

 ADOQuery1.Close;
 ADOQuery1.SQL.Clear;
 ADOQuery1.SQL.Add('insert into Table1');
 ADOQuery1.SQL.Add('select Field1 ,Field2 from Table2');
 ADOQuery1.SQL.Add('where ArtNo= 1');
 ADOQuery1.Open;
 ADOQuery1.Refresh ;

If I don't use
 ADOQuery1.Open;

it gives me

ADOQuery1: Cannot perform this operation on a closed dataset.

It copies what I want but only once. How to copy many times? Thank you.

A: For scripts that do not open a cursor (like insert, update or exec ones) use the ExecSQL Method of TADOQuery.
It returns a Integer representing the number of affected rows by your query.
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('insert into Table1');
ADOQuery1.SQL.Add('select Field1 ,Field2 from Table2');
ADOQuery1.SQL.Add('where ArtNo= 1');
NumRows := ADOQuery1.ExecSQL;
ShowMessageFmt('Affected rows on Table2: %d', [NumRows]);


Q: How to bind drowpdown list with one static value and rest from database I am working with asp.net mvc I want to add a dropdown list that holds one static value and other values coming from database
@Html.DropDownListFor(Function(model) model.nDepartmentID,
  New SelectList(ViewBag.txt, "Value", "Text"), New With
 {Key .[class] = "select1",Key .style = "width: 150px;"})

A: Use below code
@Html.DropDownListFor(m => m.nDepartmentID, (SelectList)ViewBag.DepartmentList, "Select Any Department", new {@class="select1",@style="width: 150px;" })

Your controller Action will be
public ActionResult ShowPage()
{
      var deptmnts=db.Departments.ToList();
      ViewBag.DepartmentList=new SelectList(deptmnts,"ID","DepartmentName");
      retun View();
}


Q: what does it mean to delete a file on android Naturally I thought to delete a file means to remove it from existence. So when I do
File file = new File(absPath);
....//add content
file.delete();

I expect that no further operation can be executed on file or it would throw an exception. But how come I can still add content to the file such as shown here Android saving Bitmap to SD card. So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there? I am not in a position to test this now, so I was hoping for authoritative reference.

A:
how come I can still add content to the file such as shown here Android saving Bitmap to SD card.

That code creates a new file after deleting the old one.

So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there?

Call delete() on a File object that points to the file. Then, do not use that same File object to write to the file again, thereby creating a new file, as the code that you link to does.


Q: Is there a way to package a simple Python project and have it perform installation over the internet I would like to know if there's a way to package a simple Python project and have it perform installation over the internet, just like when you install a module with pip.

A: Sure there is. This is how all the 3rd party packages we are all using did.
The formal pypa explain how to do it here.
Basically you need to package your project to a wheel file and upload it to the pypi repository. To do this you need to declare (mainly in setup.py), what is your package name, version, which sub-packages you want to pack to the wheel etc..

A: If your packages are required for a particular project, it is straightforward to contain them in the Git repository. You can put them in the directory named wheelhouse, which comes from the name of the previous default directory created by pip wheel.
If you put the private package foo in the wheelhouse, you can install as follows:
pip install foo -f wheelhouse


Q: MySQL query works through workbench but not mysqli I am attempting to call my PHP class and run the function get_group_count which counts the number of groups for a certain user ID. The mysqli query uses a stored procedure that works in MySQL Workbench but not with PHP's mysqli.
Public function:
public function get_group_count($userID) {
    if($this->status()) {
        $db = Database::getInstance();
        $con = $db->getConnection();

        $pull = $con->prepare("CALL get_group_count(?)");
        $pull->bind_param('i', $userID); // line 19

        if(!$pull->execute()) {
            $pull->close();
            return false;
        };

        $pull->store_result();
        $pull->bind_result($count);
        $pull->fetch();
        $pull->close();

        return $count;
    };
    return false;
}

Error:
Call to a member function bind_param() on a non-object in ... on line 19

Stored procedure:
DELIMITER //
CREATE PROCEDURE get_group_count(IN userID int)
BEGIN
    SELECT (SELECT count(*) FROM groups WHERE adminID = userID) + (SELECT count(*) FROM members WHERE userID = userID) AS count;
END //
DELIMITER ;

When calling the procedure through MySQL Workbench it returns a total number of rows from the groups table and members table.
Note: I also get the same error when attempting to run the query through mysqli rather than the stored procedure.
How can I fix this?
EDIT:
$con var_dump:
object(mysqli)#4 (19) {
  ["affected_rows"]=>
  int(1)
  ["client_info"]=>
  string(6) "5.5.45"
  ["client_version"]=>
  int(50545)
  ["connect_errno"]=>
  int(0)
  ["connect_error"]=>
  NULL
  ["errno"]=>
  int(2014)
  ["error"]=>
  string(52) "Commands out of sync; you can't run this command now"
  ["error_list"]=>
  array(1) {
    [0]=>
    array(3) {
      ["errno"]=>
      int(2014)
      ["sqlstate"]=>
      string(5) "HY000"
      ["error"]=>
      string(52) "Commands out of sync; you can't run this command now"
    }
  }
  ["field_count"]=>
  int(1)
  ["host_info"]=>
  string(25) "Localhost via UNIX socket"
  ["info"]=>
  NULL
  ["insert_id"]=>
  int(0)
  ["server_info"]=>
  string(14) "5.5.45-cll-lve"
  ["server_version"]=>
  int(50545)
  ["stat"]=>
  string(52) "Commands out of sync; you can't run this command now"
  ["sqlstate"]=>
  string(5) "HY000"
  ["protocol_version"]=>
  int(10)
  ["thread_id"]=>
  int(36623197)
  ["warning_count"]=>
  int(0)
}

$pull var_dump:
bool(false)
NULL

EDIT2: Ended up switching to PDO, everything works now.

A: After looking at the $con dump, it appears that the last query you're executing on this connection is not using its result. mysqli uses unbuffered queries by default, so you need to either fetch the result of the previous query executed into a buffer manually, or free the memory that it's using to make room for your new query, with either store_result() or free_result(), respectively.