text:
Q: R Shiny equivalent in Python? Creating a window-based tool I am trying to transfer an app i build in R Shiny to Python Code.
It's main use is to set the input parameters for a data analysis to be run which should create and output pdf file.
So far I managed to understand that DASH might be the tool to go with. But is there a way to launch a DASH app in an external window (not in a browser window)? Like the following:

After setting the Input values I want to have a button to click "Run" or something similiar to run the underlying code and generate a PDF Report. How would you do that with Python and do you maybe know a good Tutorial how to build a basic app like this?

A: I'm not exactly sure what you mean in the first part of your question. You may be able to use an IDE with integrated broswer to view your app during developement if you don't want to use a broswer. But the whole point of dash is to be a web based application, so it would be best on a browser.
Alternately, you can save the rendered output from browser to a .html file if you need to share it without having a live server host your application.
For the second part of your question, for a button click to generate a pdf report, refer to the documentation of callback in dash.
The callback function for the Run Analysis button can then be something on the lines of
def generate_report():
    #Code to generate required pdf
    # Code to download on client
    return link_to_pdf

Hope this gives some pointers in the direction.


text:
Q: Email expiration tokens without usage of database and crontab deletion I have API server with Auth (registration, login, forgotten password, etc..) based on JWT token session.
When user forgot password, he gets email with unique token and link where he can reset his password.
At this moment, I am generating UUID token which is saved into database with expiration field.
After user reset his password or token expires, this token is invalidated. Invalidated tokens are deleted every midnight by crontab to keep database clean.
Is there any other way to do this? Maybe without usage of database?
I was thinking about bundling token UUID into JWT string. This way I do not need database row.
But then I realized, that this token will be valid until it expires, so user can change his password infinitely. Only fix I see is add this token into revoked list (in database) until it expires, but then I again used database :D
Any ideas?

A: Auth is a complex domain, I would use an existing solution like Auth0 to handle this, as there are too many flows to consider.
That said, you can send a JWT token in the reset password link. It will have the expiry date and user id. Signed JWT tokens cannot be manipulated by users, so we can trust them on when they expire. This way you do not need a DB entry at all to track this.

A: I found answer in this article:
Create JWT token which is encrypted by secret made from current user's password hash + time of last password change. This way, token is one-time-use, because after user changes the password, next time someone tries to use this token again, token will not get decrypted correctly (not encrypted by same secret). In addition, if new password is same as old, token will still not be usable, because of additional timestamp information.
Another solution offered by @Horatiu Jeflea is to also use user's time of last password change to our advantage. Just ignore password change requests if token was generated before last change. In this solution is (I personally think) small chance that two password changes take place at same time what can mess this up, so I will use the first solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Table header doesn't follow table body dimensions when I fix table header and make body scrollable So, basically following image easily describes my issue. What I need is thead headers being aligned with tbody cells while keeping the functionality of fixed header with scroll bar for tbody. Can anyone help me with that please?
Right now, if you inspect it on the Codepen, the thead have same width as tbody but somehow the size of cells in the thead is different one compared to tbody.
https://codepen.io/seva98/pen/qBZZrKG

.container {
  width: 600px
}

table {
  display: inline-grid;
  grid-template-areas: "head-fixed" "body-scrollable";
  width: calc(100%);
}

th,
td {
  width: 33%;
  padding: 2px 16px;
}

thead {
  grid-area: head-fixed;
}

tbody {
  grid-area: body-scrollable;
  overflow: auto;
  height: 200px;
}

/* width */

::-webkit-scrollbar {
  width: 10px;
}

/* Track */

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

 ::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle on hover */

 ::-webkit-scrollbar-thumb:hover {
  background: #555;
}

        Heading 1
        Heading 2
        Heading 3

        0
        Short
        Loooooooooong text

        1
        Short
        Loooooooooong text

        2
        Short
        Loooooooooong text

        3
        Short
        Loooooooooong text

        4
        Short
        Loooooooooong text

        5
        Short
        Loooooooooong text

        6
        Short
        Loooooooooong text

        7
        Short
        Loooooooooong text

        8
        Short
        Loooooooooong text

        9
        Short
        Loooooooooong text

        10
        Short
        Loooooooooong text

        11
        Short
        Loooooooooong text

A: Set a minimum width for td,th and also align its to left
Add this to td,th
  th,td {
       text-align: left;
       min-width:100px;
  }

instead of using
th,td {
    width: 33%;
}

Try this code pen :  https://codepen.io/Rayeesac/pen/mdPPwgg
For more information try this: Why width property doesn't work on my table?


text:
Q: output the count of the items as header pandas Here is my dataframe:
'''
 customer product     product1
0        A    hats        shoes
1        A   socks        shoes
2        B   socks        shoes
3        C    hats        shoes
4        C    None  accessories
5        B   socks        shoes
6        A    hats        shoes
7        C    None  accessories

'''
I want to output something like this:
customer    shoes   hats    socks   accessories
A             #       #        #    #
B             #       #        #    #
C             #       #        #    #

I tried group by like this:
'''
dfB.set_index('customer').groupby(['product', 'product1']).agg({'product':['count'], 'product1':['count']}) '''

I got output like this:
'''
 product product1
                   count    count
product product1
 hats   shoes          3        3
 socks  shoes          3        3

'''
Please help

A: IIUC
we can set the index to 'customer' then stack the dataframe allowing you to do a aggregation with value_counts
df2 = df.set_index('customer').stack().groupby(level=0).value_counts().unstack()

-
print(df2)
          None  accessories  hats  shoes  socks
customer
A          NaN          NaN   2.0    3.0    1.0
B          NaN          NaN   NaN    2.0    2.0
C          2.0          2.0   1.0    1.0    NaN

if you don't care about None you can convert it to a true null value and it will be ignored in the groupby
print(df.replace('None',np.nan).set_index('customer').stack().groupby(level=0).value_counts().unstack())

          accessories  hats  shoes  socks
customer
A                 NaN   2.0    3.0    1.0
B                 NaN   NaN    2.0    2.0
C                 2.0   1.0    1.0    NaN

A: You could melt then pivot_table
# df = df.replace('None', None) # If `'None'` and not `None`

(df.melt('customer', value_name='product')
   .pivot_table(index='customer', columns='product', aggfunc='size'))

product   accessories  hats  shoes  socks
customer
A                 NaN   2.0    3.0    1.0
B                 NaN   NaN    2.0    2.0
C                 2.0   3.0    1.0    NaN


text:
Q: How do i figure how long file_get_contents took to load a web page? I'm using file_get_contents to load a webpage's content, how would i check how long it took to get the page?!

A: Sorry for asking this, it's very simple and easy to do, all that's needed to be done is declaring a variable with the returned number of seconds from the time() function as it's value, and then compare it later
<?php
$before = time();
//ProcessHere
$now = time()-$before;
?>


text:
Q: Не загружается изображение в Base64 string на сервер Android Пытаюсь решить эту проблему больше 2х недель, изображение в формате bas64encodeToString не грузится на сервер. Загружаю данные на сервер с помощью Retrofit 2. Если загружать просто текст, никаких проблем. Понимаю что может быть большой вес и не загружаться, но с IOS все загружается без всяких проблем. На сервере лимит - вес картины 5Мб.
Так я перевожу в Base64String:
public static void imgToBase64ToString(){
    Global.image.clear();
    Bitmap bm = BitmapFactory.decodeFile(Global.path.get(0));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
    Global.image.add("data:image/jpeg;base64," + encodedImage);
    Global.path.clear();
}

Post запрос:
@POST("event")
Call<CreateEvent1> addEvent(@Header("Authorization") String key, @Header("x-access-token") String token, @Body CreateEvent1 createEvent1);

Сама ошибка (Лог):
E/Error: java.net.SocketTimeoutException: timeout
    java.net.SocketException: Socket closed
W/System.err: java.net.SocketTimeoutException: timeout
        at com.example.golspire.Activity.Events.CreateEventActivity2$1.onFailure(CreateEventActivity2.java:135)
        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onFailure$1$retrofit2-DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:96)
        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$$ExternalSyntheticLambda0.run(Unknown Source:6)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
W/System.err: Caused by: java.net.SocketException: Socket closed
        at java.net.SocketInputStream.read(SocketInputStream.java:209)
        at java.net.SocketInputStream.read(SocketInputStream.java:144)
        at okio.Okio$2.read(Okio.java:140)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
        at okio.RealBufferedSource.indexOf(RealBufferedSource.java:358)
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:230)
        at okhttp3.internal.http1.Http1ExchangeCodec.readHeaderLine(Http1ExchangeCodec.java:242)
        at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.java:213)
        at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.java:115)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:94)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:43)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
W/System.err:     at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:172)
W/System.err:     at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)


text:
Q: Creating multiple different factories using the same create method So I have different factories: factory_1, factory_2
They have different traits trait_1_factory_1, trait_2_factory_1 etc
Is possbile to create factory_1 and factory_2 with specific trairs from the same command, like:

FactoryBot.create(
  :factory_1, traits_1_factory_1,
  :factory_2,
  :factory_2, traits_1_factory2
  )

I tried different combinations of () {} [] but doesn't seem to work for me? Is this possbile?
Is this the only solution
Factory.create(:factory_1, traits_1_factory_1)
Factory.create etc.
Thank you

A: I believe you want to create objects using different factories here i.e. when you say Factory.create, you mean FactoryBot.create.
Unfortunately, i couldn't find any direct command to accomplish such thing. Here is something using a Hash and a loop.
factories_and_traits = { factory_1: [trait_1_factory_1, trait_2_factory_1],
                         factory_2: [trait_1_factory_2] }

factories_and_traits.each do |factory, traits|
  FactoryBot.create(factory, *traits)
end

A: No, it is not possbile to create factory_1 and factory_2 from the same command.
Here, 'factory1' is the Model or class whose objects are created.
FactoryBot.create(:factory1)
If you are doing it for making spec DRY, then rather than doing as above, you can do as below :
[
  [:factory_1, traits_1_factory_1],
  [:factory_2, traits_1_factory2]
].each do |factory|
  FactoryBot.create(*factory)
end

Store multiple factories in array and iterate it.


text:
Q: 599Item.js:12 Uncaught TypeError: product.map is not a function in react I'm putting together my first react as an exercise to understand but I get this error
599Item.js:12 Uncaught TypeError: product.map is not a function in component item.js on line 12
I copy the component item,js, it has a prop that is the product object
import React, {useState, useEffect} from "react";
import '../App.css';
import 'materialize-css/dist/css/materialize.css';
import Count from './ItemCount';

export const Item =(({product}) =>  {

  const [sellProduct, setSellProduct] = useState(product);

  useEffect(() => {
    setSellProduct({product});
  }, [product]);

  const mensaje = () => {
    alert ('Gracias por su compra');
  }

return (
    <>
    {
      sellProduct.map((item) => {
        return(
          <Count stock={item.stock} onAdd ={mensaje} >

{item.name}
 - {item.category}

{item.description}

{item.price}

          </Count>
        )
      })
    }
    </>
  )
});

expor default Item;

I take the prop out in a fetch and pass it to the child component, which passes the prop to the items component and I copy the code of both
ItemListContainer(parent)
import React, { useEffect, useState } from "react";
import '../App.css';
import 'materialize-css/dist/css/materialize.css';
import ItemList from './ItemList';

export const ItemListContainer =() =>  {

  const [swSell,setSwSell] = useState([])

  useEffect(() => {
    fetch('https://fakestoreapi.com/products')
      .then((res) => res.json())
      .then((data) => {
        setSwSell(data);
      })
      .catch((err) => {
        console.log(err);
      });
    }, []);

  return(

      {
        swSell.map((item) =>(

            <ItemList item={swSell} />

        ))
      }

    )}
export default ItemListContainer;

ItemList(child), this passes to the Item component
import React from "react";
import '../App.css';
import 'materialize-css/dist/css/materialize.css';
import Item from './Item';

export const ItemList = (({item}) =>  {
  return (

      {
        item.map((item) =>(
          <Item product= {item} />
        ))
      }

  )
});

export default ItemList;

I appreciate your help

A: In Item component instead of
product.map((item)...

replace it with
product && product.map((item)...

A: The error:

product.map is not a function in react

arise since the product props that you set as sellProduct is not an array. It is actually an item (object) of swSell array.
So, first, change this:
const ComponentName = (({ ... }) => {
   ...
})

into this:
const ComponentName = ({ ... }) => {
   ...
}

Next, since the swSell state is a collection of item object where the item is the product itself, then you only need two component here: ItemList as parent and Item as the child that render the item details

const Item = ({item}) =>  {
    return (

{item.name}
 - {item.category}

{item.description}

{item.price}

    )
};

function ItemList() {
    const [swSell,setSwSell] = React.useState([])

    React.useEffect(() => {
        fetch('https://fakestoreapi.com/products')
            .then((res) => res.json())
            .then((data) => {
                setSwSell(data);
            })
            .catch((err) => {
                console.log(err);
            });
    }, []);

    return (

            {swSell.map((item) => (

                    <Item item={item} />

            ))}

    );
}

ReactDOM.render(<ItemList />, document.querySelector('.react'));


text:
Q: upstream timed out (110: Connection timed out) while reading response header from upstream I'm new to nginx server. The problem I'm facing currently is connection timed out issue after making a call from the iOS app. The Json I'm receiving is huge hence there is a timeout logged on the server.
Also checked with various answers posted here on stackoverflow regarding the same. But didn't help me out.
Below is my access log and error log. Please help.
Error log
upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxxxxxxxxxx, server: xxxxxxxxxxx, request: "POST /api/event/gallery HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock", host: "xxxxxxxxxxx"

Access log
"POST /api/event/gallery HTTP/1.1" 504 192 "-" "mysite/2 CFNetwork/889.9 Darwin/16.7.0"

nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    client_max_body_size 50M;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

A: Update
While I was checking with this issue I increased the time setting -request_terminate_timeout in the \etc\php\7.0\fpm\pool.d\www.conf and encountered the HTTP status code 499.
Access log
"POST /api/event/gallery HTTP/1.1" 499 0 "-" "mysite/2 CFNetwork/889.9 Darwin/16.7.0"

So i started to investigate this issue and found out that there is load balancer in place (AWS ELB), which has a time out setting in place that defaults to 60 sec. Referr https://www.cadence-labs.com/2017/07/fix-nginx-timeout-499-client-closed-request/.
After increasing the timeout over there (ELB) I managed to get the result in postman. But it turned out to be highly erratic. Meaning I would get a response once in 4-5 tries.
So I managed to add some settings in
etc\nginx\sites-available\default
Added below settings over there in every server and location blocks.
fastcgi_read_timeout 540;
proxy_connect_timeout 3000s;
proxy_send_timeout   3000;
proxy_read_timeout   3000;

and restarted nginx.
This solved the issue. But I still think that the time taken by response is high and the performance is not at an acceptable level.
Also any recommendations/comments/suggestions to address this issue in a better way are most welcome.

A: I'd like to add that I got to this question through a search, and my root cause was a bug leading to an infinite loop in my application code that nginx was waiting to return.
Odds are if you are reading this page because something previously fast is returning this error, the issue is with whatever your upstream is trying to do and not with nginx.


text:
Q: ASP .NET Web API ModelBinder single parameter Currently I've got this ModelBinder that works just fine:
public class FooModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var body = JObject.Parse(actionContext.Request.Content.ReadAsStringAsync().Result);
            IEnumerable<Foo1> media = new List<Foo1>();
            var transaction = body.ToObject<Foo2>();

            media = body["Media"].ToObject<List<Foo3>>();

            transaction.Media = media;
            bindingContext.Model = transaction;

            return true;
        }
    }

As you can see I'm mapping the whole bindingContext.Model, but what I really want to do is to map just the Media field of the Model and all of the other fields to map as default.
This is my controller:
public HttpResponseMessage Post([ModelBinder(typeof(FooModelBinder))] Foo request)
        {
            //do something
        }

Is this achievable?

A: Here's how all of our model binders are defined:
public class FooBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
    if (bindingContext.ModelType == typeof(Foo))
    {
        return FooParameter(actionContext, bindingContext);
    }

    return false;
}

If you want to make multiple parameters from your input you can just specify your desired binder in the your controller method.
    public async Task<HttpResponseMessage> GetFoo(
        [ModelBinder] Foo1 foo1 = null, [ModelBinder] Foo2 foo2 = null)
    {
       ...
    }

I may have misunderstood your question but this is an example of real code in our system.


text:
Q: Disable a button in PXWizard So I'm stuck with this trying to workout how to disable the Next button of a PXWizard. I'd like to only enable it once all entries are valid etc. I know the Next button is tied up to an Action somehow. But even if the Action itself is disabled. The button remains enabled. Hence if I clicked on the Next button then, I get an exception that the button is disabled. Can anyone point me in the right direction ? Unfortunately I couldn't find anything online regarding how to use the PXWizard.
TIA


text:
Q: Handling regularly updated files on Amazon S3 and CloudFront If I am regularly overwriting files on S3, CloudFront caches them when I serve them in the browser. I was looking into Invalidation but there's a limit on how many validations at once it seems which wont work for a multi-teant website.
The only solution I can see is when overwriting a file, delete the old file and change the name of the new file (I was just going to add the TIMESTAMP to the end) so that CloudFront doesn't pull the cached version.
Would this be the most advised way to handle this sort of thing?

A: Here's the link to the specifics of the invalidation limits: http://aws.amazon.com/cloudfront/faqs/#Is_there_a_limit_to_the_number_of_invalidation_requests

You can only have 3 invalidation requests in progress at any given
  time. If you exceed this limit, further invalidation requests will
  receive an error response until one of the earlier requests completes.

The AWS recommendation is:

it is recommended that you either implement a versioning system for
  your files and/or set a short expiration period.

The short expiration period is straightforward, but has obvious downsides.  To implement a versioning system, you could track the file version in a database, and append the version as a querystring parameter:
file.jpg?v=2
This way you can set a long expiration period, and the file only invalidates when you specifically upload the new file and update the version.
As noted below in the comments, the default behavior is that CloudFront ignores the query string when building up the cache key, so be sure to enable Forward Query Strings under the Default Cache Behavior settings to use this versioning approach.


text:
Q: How to call function on hyperlink text click How can I call this on_search function by clicking on the text (item.name)?
$.each(docs, function(i, item) {
            $('#body').append($('
' + item.name

'));
       });

// call this function whenever user clicks the text
function on_search() {
     var url ='http:myhomepage/select/?wt=json&json.wrf=?&q='+item.name;
     $.getJSON(url, on_text);
    }

A: Give  a class set at event handler to it.
   $.each(docs, function(i, item) {
                $('#body').append($('
' + item.name

'));
    $(".my-anchor").click(on_search);
           });

    // call this function whenever user clicks the text
    function on_search() {
         var url ='http:myhomepage/select/?wt=json&json.wrf=?&q='+item.name;
         $.getJSON(url, on_text);
        }

A: Not sure if each link needs to be wrapped inside its own div. In fact, to make this work well, you may want to put all of these links inside a particular div.
From there, here's what you do:
$('#divName').find('a').click(function (event) {
    var url=...
    event.preventDefault(); // Stops the browser from actually following the link
    [...]
});

A: if you add an id or a class you can the just add
   $('.yourClass').click(function()
    {
        var x = $(this).attr('href');
        on_search();
        // you would probably want to pass the item name as a parameter: on_search(x);
    });


text:
Q: I have a problem with reading from a file #include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{

    fstream file, save_file;
    vector<string> words;

    for (int i = 0; i < 1000; i++)
        file >> words[i];

    cout << words[0];

    return 0;
}

I want to save these words in a vector, but I can't. I have a message: zad1.exe is already runing! Please close it first to compile successfully! I don;t know why.

A: Here is my solution:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

int main()
{

    std::fstream file("test.txt"), save_file;

    std::vector<std::string> words;
    std::string line;
    for (int i = 0; i < 1000; i++){
        file >> line;
        words.push_back(line);
    }

    std::cout << words[0];

    return 0;
}

Instead of test.txt write your file path

A: On some operating systems you cannot write to a file if that file is a running program. That is what the error message is telling you. You are creating a program called zad1.exe and it is currently running so you cannot create a new version of zad1.exe until you stop the version that is already running.
Are you working on Windows? If so then use the task manager to kill any versions of zad1.exe that you can see.
Plus you have many problems with the code as pointed out in the comments above. But the first task is to kill those running programs.


text:
Q: Download (update) file from URL in Android. File's name is changing Okay, so I can download file from serwer WWW (my server)
    private void OnlyDownFile() {
        nameFiles = "test.xlsx";
        final String allUrlString = "http://xx.xxx.x.xxx/test/" + nameFiles;
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Uri Download_Uri = Uri.parse(allUrlString);
        DownloadManager.Request request = new DownloadManager.Request(Download_Uri);

        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setAllowedOverRoaming(false);
        request.setTitle("My Data Download");
        request.setDescription("Android Data download using DownloadManager.");
        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, nameFiles);
}

And this is okay and works well (I download from my server)
I have a PROBLEM with update file. I want to check: Do you have newer file (at Serwer)? Yes - download newer. No - use the last which you download.
And situation where you don't have Internet - use the last which you download, otherwise TOAST "Turn on Internet"(Toast is no problem :) ).
I don't have any idea How check newer file ? and problem with other names?


text:
Q: rdkafka consumer query about partition size Let's say I don't have access to the set of producers that commits on the partition of interest, but just have control over a bunch of C++ consumers.
Since I'm running benchmarks over a complex program, I'd like to know the spread between the offset my consumers are fetching and the total offset stored in the partition.
e.g., >> reading message #1234 of 5678 total in partition 0 of topic foo
I misunderstood the purpose of RdKafka::Consumer->outq_len() and RdKafka::Topic->OFFSET_END, because they seem always equal to 0 and -1, respectively.
How can I acquire the 5678 value of my example?

A: You need to subscribe to librdkafka's statistics to get an updated view of your consumer's lag.
Register an Event callback class and regularily call poll() on your handle, check for EVENT_STATS and then parse the corresponding JSON message and look for lo_offset, hi_offset and consumer_lag.


text:
Q: Averaging the digits of pi in Python As a preface, I must admit that this is my first real attempt to code a simple program from scratch, and I've just begun my foray into learning python.
As a simple project, I wanted to write a program to find the average value of the digits of π. In other words, we all know that π=3.141529....., but I set out to determine the value of (3+1+4+1+5+....)/(# of digits summed).
This was the result:
#retrieve the value of pi
n=math.pi

#request the number of digits of pi to average over
mag=input("how many terms?")
mag=int(mag)-1

#generate a string populated with the whole number values of the digits of py
k=int(round(n*10**(mag),0))
digits=[int(d) for d in str(k)]
print(k)

#sum the specified values of the digits of pi
print(sum(digits))

#recall the length of the string
print(len(digits))

#calculate average
print((sum(digits)/len(digits)))

The code runs well enough, but I am curious about what tweaks I could make to improve the program or simplify it.
Most specifically, I would like to know if there there is a simpler or more direct way to cast the individual digits of pi into a list or string of integers for manipulation. For instance, is there a specific operator one could use to call individual digits of a given number, like digit(0) returns 3 with respect to pi.
Any advice is greatly appreciated!


text:
Q: How to get Http header values in Apache Camel- Jersey Rest API I have an application which uses Apache Camel to build an API. It basically uses blueprint.xml to define routes and processing is done by a bean(please note its not any processor bean. Just a plain Java bean). It uses Jersey client to invoke the backend system Rest API.
My requirement is to get the http headers in the code to be able to send them to our custom logging system.
a) I tried @httpHeaders annotation but this does not inject the headers on my code.
b) Since its not using any BeanProcessor i dont have an Exchange object from where i can get the header values.
Please help with a way to get header values on the code.

A: Add the request context to your class
 @Context
 private HttpServletRequest request;

and get the headers in your endpoint using request.getHeader

Returns the value of the specified request header as a String.


text:
Q: Web programming download and run file on client with client's permission Just a big disclaimer, this is not malware related, I want the user to be required to check a box and click a button, or something along those lines.
I'm creating a website for an application that I've made, and I generate a unique build of the application for each customer, every time they want to use the application.
This means they have to download it each and every time they want to use it. The application is just for windows.
What I would like to happen is:

*

*User clicks run button.

*User says "Yes, I would like to run it".

*File is downloaded onto the users machine.

*File is executed.

I know that Java applets are capable of doing this, but they're not used anymore and also require java (yes they are also blocked by default, but again, that's not the issue).
Are there any alternatives to Java applets?
Best regards

A: Unless you use ActiveX (and restrict the users to using Internet Explorer), this cannot be achieved without browser plug-in support.
With ActiveX you can pretty much do anything (even run commands from the command prompt on the client's machine). Of course, for that to happen, you need the user's permission beforehand.
EDIT: As commented below, Microsoft is phasing out ActiveX support. So, as of now, what you're trying to achieve needs magic.


text:
Q: Какие есть разновидности программирования? Учусь на программиста. Хочу определится с выбором будущей профессии, поскольку на учебе дают всего по немногу. Поэтому прошу рассказать, какие есть виды профессий по программированию и соотвественно разновидностей программирования.
A: Всё cy6erGn0m сказал правильно, но, думаю, стоит некоторые пояснить.

*

*Сайты. Ну это понятно. Информационные сайты, для мобильных, приложения - типа зохо и прочих офисов.

*Обычные приложения. Для разных ОС - Windows, Мак, юниксы различные и более редкие типы.

*Серверные приложения. Это приложения типа игровых серверов, банковских, различных IM-сообщений, баз данных и много чего другого. Когда есть специализированная программа-клиент.

*Мобильные приложения. Java-приложения, игры, нокии, симбианы, айфоны, андроиды, екниги и что-то там ещё. То есть на мобильных телефонах, смартфонах и подобных приборах.

*Встраиваемые системы. О, это весьма интересная отрасль. Плееры, телефоны, навигаторы, роботы, брелоки цифровые, термометры, управлялки разные. То есть тесно связанные с электроникой и часто работающие в одной микросхеме. Микроконтроллеры 8, 16, 32 бит (ARM, Atmel, Microchip, STM, Freescale, Motorola и иные), цифровые сигнальные процессоры, ПЛИС (программируемые логические интегральные схемы) или просто логические схемы (хотя мало кто этим занимается в обычной жизни). Цифровая электроника.

*Научные разработки. Это программирование на спец. языках математических (как пример MATLAB), в средах моделирования (ANSYS) и просто написание программ, решающих научные и инженерные задачи. И САПР.

Не указанные направления:

*

*Системное программирование. То есть написание драйверов для оборудования, написание ядра ОС. Низкоуровневое программирование. Компиляторы и интерпретаторы, думаю, относятся к этому же.

*Игры. Странно, что их не указали. Но это гигантская отрасль индустрии =) Разработка 2D и 3D игр... DirectX и OpenGL. Шейдеры. И для консолей игровых.

*Параллельное программирование, в том числе и на GPU. CUDA и OpenCL, OpenMP, MPI. Расчёты на графическом модуле.

*Разработка библиотек общего назначения для каких-либо функций. Например, рендеринг шрифта. Или аудио- и видеокодеки.

*Написание плагинов и скриптов к существующим системам. Для фотошопа, например.

*Олимпиадное программирование и решение задач. Сюда можно отнести и программирование на различных "непрактичных" языках.

*Программирование для бухгалтерских, финансовых и прочих деловых продуктов. Типа 1С: Предприятия.

*Программирование экспертных систем. Думаю, оно стоит быть вынесенным отдельно.

*Программирование баз данных. Серьёзных, которые куда как больше, чем две-три таблички=) Недаром для них создан язык специальный.

Но это не все, их куда как больше. Просто я часть не знаю, а часть не смог вспомнить.
A: *

*Web-разработка сайтов

*Разработка веб-приложений (может пересекаться с первым)

*Разработка "обычных" приложений, толстых клиентов

*Разработка серверных приложений

*Разработка мобильных приложений (j2me, android, iphone, etc)

*Разработка средств автоматизированного тестирования

*Разработка автоматических тестов

*Разработка приложений для встраиваемых систем (embedded systems)

*Всякая Science-разработка

A: Тема очень обширная и почти всё, что я знаю, уже сказали. Добавлю только немного про "встраиваемые системы". Правильное их название - "Системы реального времени". Область очень актуальная и связана не только с программированием различных прошивок под плееры, телефоны и тп. В сферу её употребления входят всевозможные роботы, автоматизированные системы (типа управления светофорами в развитых странах), космические спутники, медицинское оборудование и ещё много чего. Используемое ПО (кроме простых прошивок) - ОС типа Qnx. Языки программирования - структурный С, Smalltalk, различные функциональные и рекурсивно-логические языки типа Lisp, Erlang, Prolog.
A: Еще есть реверс-инжиниринг: восстановление исходного алгоритма работы программы при наличии всяких ограничений :-). Обычно продолжается в виде реализации модифицированного алгоритма работы в своей программе. Учитывая, что как правило требуется разбор бинарного кода, без наличия каких-либо исходных кодов разбираемого программного продукта, то требуется высокая квалификация: умение работать со специализированными инструментами (дизассемблеры, отладчики), знание ассемблера и работы ПК на низших уровнях и пр.
Платят соответственно очень хорошо.


text:
Q: C# setting property to interface class using dependency injection I have the following class that implements dependency injection for ISecurityRepository:
public class SecurityService : BaseService
    {
        ISecurityRepository _securityRepo = null;

        public SecurityService(ISecurityRepository securityRepo)
        {
            _securityRepo = securityRepo;
        }
}

Then I have the SecurityRepository class as follows:
public class SecurityRepository : BaseRepository, ISecurityRepository
    {
        public bool ValidateLogin(string userName, string password)
        {
            return true;
        }
}

Then BaseRepository class:
public abstract class BaseRepository
    {

        private string _customString = null;
        public string CustomString{
            get {
                return _customString ;
            }
            set
            {
                value = _customString ;
            }
        }
}

What I need is to set CustomString on BaseRepository class value from SecurityService class. Something maybe like this:

public class SecurityService : BaseService
        {
            ISecurityRepository _securityRepo = null;

            public SecurityService(ISecurityRepository securityRepo)
            {
                _securityRepo = securityRepo;

                // something like this or better way
                _securityRepo.CustomString = "ABCD";
            }
    }

The idea is that within SecurityRepository class I can access CustomString value.


text:
Q: Windows universal app Rest API Raspberry Pi I have Windows Core running on a Raspberry PI. How do I create a rest API in a Windows universal app to run on it?  I want to be able send remote commands to the Raspberry PI from a mobile device. I did several search and couldn't find much information. Thanks.

A: As noted here there's a Restup open source project for this
and NuGet package for it
There's also some experimental (ie fun side project) from Damian on the ASP.NET team about hosting DNX (the host process for your ASP.NET Core apps) located here but that will need some updating to the latest bits.


text:
Q: Does a git repo always have to be in its own directory I would like to have multiple files in a folder with are managed by different git repositories. Is it possible?
I have the following folder structure for a project. It is part of a Git repository:
plugins/
 - plugin.a.php
 - plugin.b.php
 - plugin.c.php

I would like plugin.b.php to be part of another repo. For example, I want the development of this plugin to be hosted on github. To use and develop concurrently on different projects.
When I use a git submodule for plugin.b.php, I need an empty folder to init the submodule, so I have a structure of:
plugins/
 - plugin.a.php
 newfolder/
     - plugin.b.php
 - plugin.c.php

plugin.b.php will not load as, for example, my App only loads files from the root of plugins/. And, I don't want to have to modify the App.
Is there anyway to do this? I can think of lots of situations where I would like to use a similar workflow. Even having both plugin.b.php and plugin.c.php in different repos.
Thanks

A: Have a look at --git-dir, --work-tree, GIT_DIR and GIT_WORK_TREE.
You should be able to create a repository somewhere else and set it's working directory to your normal path. Just add the one file to the second repository.

A: See @tanascius' answer which provides the correct answer to using multiple git repos in one directory.
I am tentativly answering my own question in relation to: the question's example and GitHub. As there is a small caveat...
It is not possible for pluginb & pluginc to have same named files in the plugins folder. Although this is unlikely, as github repos, they both have github README files causing a conflit.
For this low file count situation I've settled for using a symbolic link (and keeping the repos inside the main repo which is optional):
.git/
.gitignore = .repos/
.repos/
     .git/
     - pluginb/
         README
         plugin.b.php
     - pluginc/
         README
         plugin.c.php
plugins/
     - plugin.a.php
     - symbolic-link = plugin.b.php
     - symbolic-link = plugin.c.php


text:
Q: Where do I find my -I/usr/local directory? I am trying to run this code sample to test swig on Ubuntu 12.04. I have python 2.7.3 installed on my system. This code seems to be for networked machines. How can I find where my python is installed and what should I replace these directory paths be?
cc -c example.c example_wrap.c \
-I/usr/local/include/python1.5 \
-I/usr/local/lib/python1.5/config

A: You can replace the lines with python-config --includes which automatically creates the correct statements for the compiler and your installed python version. python-config itself is installed through python-dev, which you will need in case you haven't installed it yet.
So for calling the compiler on the command line:
cc -c example.c example_wrap.c $(python-config --cflags) -fPIC

Also, python1.5? Where did you find that example?

A: /usr/local is standard for any Posix operating system, see the Filesystem Hierarchy Standard (FHS).  You you get the python version you need with apt-get (I think the command is sudo apt-get install python1.5 but I'm not on a ubuntu system at the moment so I can't try it), it will put it in the standard places, which is likely /usr/local.
To answer the other part of your question, you can find where your python is installed using which python.  python is likely a symbolic link to python2.7, so you may have to explicitly run python1.5 which you can find with which python1.5 if it's been installed.
Python 1.5 is a very, very old version of Python.  Where did you get the code sample from?


text:
Q: How to convert size_t to char* in kernel C? I use a size_t variable in my kernel module. when I want to write it to a file it must be cast to char* according to vfs_write signature:
extern ssize_t vfs_write(struct file *, const char __user *, size_t, loff_t *);

I use this function that uses vfs_write (I found it on internet):
int file_write(struct file *file, unsigned long long offset, unsigned
char *data, unsigned int size)
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

the nbytes variable is size_t I try (char *) cast for convert nbytes to char* but the kernel immediately crashes. here is my code.
index_filename = "/home/rocket/Desktop/index_pool";
index_file = file_open(index_filename,O_WRONLY | O_CREAT, 0644);
if(index_file == NULL)
    printk(KERN_ALERT "index_file open error !!.\n");
else{
    // file_write(index_file, 0, nbytes, nbytes); => this crashs also
    file_write(index_file, 0, (char*) nbytes, 100);
    file_close(index_file);
}

Is there a way to safely convert size_t type to char * one in Kernel ?

A: Of course it would crash - you're trying to write 100 bytes of whatever memory location nbytes is pointing at. Which because it isn't a pointer is extremely unlikely to be a valid area of memory. And even if it was, it might not be 100 bytes in size.
What you want to be passing instead to vfs_write is a pointer to nbytes. And the size of that would be sizeof(nbytes). So you'd call your wrapper function like this
file_write(index_file, 0, (char*) &nbytes, sizeof(nbytes));

That will write out the how ever many bytes that a size_t is at the memory location of nbytes
If you want to write out the value of nbytes, which is different to what you appear to be asking in the question, you need to store it in a string and pass that to your function like this:
char temp_string[20];
sprintf(temp_string,"%zu",nbytes);
file_write(index_file, 0, temp_string, strlen(temp_string));

A:
Is there a way to safely convert size_t type to char * one in Kernel ?

yes there is.
you should use sprintf function in linux/kernel.h library
so you should do something like this:
sprintf(destination_char_star, "%zu", your_s_size_var);

be carefull you should allocate memory to char star if needed.


text:
Q: Solr: change managed schema to schema and add new field in WINDOWS when using DIH I am trying to learn and create SOLR search engine for text search.
My initial step is to load a table of content from SQL to Solr. I have imported data using data import handler but Solr loaded only id field. Later I realised that the managed schema does not work with DIH. So I am currently switching form managed schema to classic schema.
One of the step that Solr learning material asks me to do is add new field through schema API and it has given below commands for UNIX. I am not sure its equivalent windows command. Since POST command cannot be used in windows.
curl -X POST -H 'Content-type:application/json' --data-binary '{
  "add-field":{
     "name":"sell-by",
     "type":"tdate",
     "stored":true
  }
}' http://localhost:8983/solr/gettingstarted/schema

Below is the command I used which failed,
curl -X  java -jar example\exampledocs\post.jar  -H 'Content-type:application/json' --data-binary '{
  "add-field":{
    "name":"FIN",
    "type":"int",
      "stored":true
  }
}' http://localhost:8983/solr/#/firstcore/schema

Your advice or help would be much appreciated. I am stuck here for long time. I could not find how to add fields in windows. Any advice would be very much appreciated.

A: There are some problem with your request parameter.

*

*First of all type integer not available by default if you are implemented it then it is fine.

*You have not specified request HTTP method so it takes as GET while it require POST. I think you removed it after try requesting it by POST but it may end-up with Method Not Supported.

*Above problem Method Not Supported is not because of POST method, it is because your URL was wrong, It should be http://localhost:8983/solr/firstcore/schema.

These are the problem which I find from your provided data and here is my example of adding field.
And Yes I am using Postman as a rest client

After success operation you will see you schema file of you collection will updated in Files menu on SOLR WebApp:
To check that:

*

*Go to the WebApp

*Select Collection

*Click on Files

*Go to your chema file.

*Find your added field.


text:
Q: How do I get the user id and using it to post new comment in the store method in laravel? This code does not seem to capture the user id from the session so I can use it as a foreign key in the database for the place the user is adding a comment to.

public function store(Request $request, $place_id) {

  // find place in the database
  $place = Place::find($place_id);

  // find user in the database
  $user = User::find(\Auth::id());

  // create review instance
  $review = new Review([
    'review' => request('review'),
    'rating' => request('rating')
  ]);

  // save review (creating relationship) in the places table as reviews
  $place - > reviews() - > save($review);

  // save review (creating relationship) in the users table as reviews
  $user - > reviews() - > save($review);

  $reviewData = Review::find($review - > id);

  if (request() - > wantsJson()) {
    return $reviewData; // Returns JSON, thanks to Laravel Magic™
  }

  // return view
  return view('place');

}

A: When creating models for relationships, use create instead of save.
$user->reviews()->create($review);

The create method will associate the relevant relationship id.
I can see that you are saving the $review twice. Once in place_reviews and once in user_reviews. Consider changing your database logic, so reviews belongs to User and Place instead. This would be a lot more sensible structure:
Controller
 $review = new Review([
    'review' => request('review'),
    'rating' => request('rating')
 ]);

 $review->user()->associate($user);
 $review->place()->associate($place);

 $review->save();

Review model
public function user()
{
    return $this->belongsTo(User::class);
}

public function place()
{
    return $this->belongsTo(Place::class);
}

Review table
$table->unsignedInteger('user_id');
$table->unsignedInteger('place_id');

User and place model
public function reviews()
{
    return $this->hasMany(Review::class);
}

You also have the option to use belongs to many relationships, if one Review could relate to multiple Place.
Another tip:
You may also consider using findOrFail to ensure your user is valid. This way your code will throw an Exception if there is no user id, as opposed to proceeding with a null user, which could be cause for hard-to-find errors.
$userId = \Auth::id();
$user = User::findOrFail($userId);

A: You should do like this.
   $user = \Auth::user();
    if(!is_null($user)){

    $user_id = $user->id;

}


text:
Q: Representation of probability measure over product spaces Trying to obtain some exchangeability-related results, I ended up with the following questions, which I couldn't answer (at least, not in the negative); this is also related to this MO thread (edit: actually, not really)
Given a measurable space $(S,\mathscr{S})$, let $\pi$ be a probability measure on the product space $(S^2,\mathscr{S}^2)$. Also, endow the set $\mathcal{P}(S)$ of probability measures over $(S,\mathscr{S})$ with the $\sigma$-algebra generated by the measurable maps $\nu \mapsto \nu(F)$, with $F \in \mathscr{S}$ (and similarly for $\mathcal{P}(S)^2$).

Question. Is it true that we can find always a probability measure $\mu$ on $\mathcal{P}(S)^2$ such that
  $$
\pi(A)=\int_{\mathcal{P}(S)^2} (\alpha \otimes \beta)(A) \,\mu(\mathrm{d}(\alpha\otimes \beta))\,\,\,\,\,?
$$
  for all $A \in \mathscr{S}^2$.

[Here, given probability measures $\alpha,\beta$ on $(S,\mathscr{S})$, we let $\alpha \otimes \beta$ denote their product measure]

A: It's true; we can use the following rather trivial construction.
Notation: for measurable $A \subset S^2$, let $F_A : \mathcal{P}(S)^2 \to [0,1]$ be the "evaluation map" $F_A(\alpha, \beta) = (\alpha \otimes \beta)(A)$.
Consider the map $T : S^2 \to \mathcal{P}(S)^2$ defined by $T(x,y) = (\delta_x, \delta_y)$.  This is the natural way to embed a space into its space of probability measures: map a point to a point mass.  We note that $T$ is measurable, since for any $F_A$ we have $F_A(T(x,y)) = (\delta_x \otimes \delta_y)(A) = 1_A(x,y)$.  So $F_A \circ T = 1_A$ is a measurable map from $S^2$ to $[0,1]$.  Since the $F_A$ generate the $\sigma$-algebra on $\mathcal{P}(S^2)$, the measurability of $T$ follows.
Now for a given measure $\pi$, simply let $\mu = \pi \circ T^{-1}$ be the pushforward of $\pi$ under $T$. Then by change of variables
$$\begin{align*}\int_{\mathcal{P}(S)^2} F_A(\alpha, \beta) \,\mu(d\alpha, d\beta)  &= \int_{S^2} F_A(T(x,y))\,\pi(dx, dy) \\ &= \int_{S^2} 1_A(x,y)\,\pi(dx,dy) \\ &= \pi(A).\end{align*}$$


text:
Q: In docker-compose, can I use environment variable to construct another invironment variable? In docker-compose, can I use environment variable to construct another invironment variable?
eg:
environment:
  - HOST: localhost
  - WITH_PORT: ${HOST}:8080 #host read from env variable above

If it is possible - then how can I achieve it?

A: TL;DR: NO
docker-compose docs explain this too here
docker-compose is a fancy way of writing docker run ... commands (correct me if I am wrong?). So, a simple test tells me that you can create an environment variable in docker-compose using another env variable only if that variable is present in your development environment.
So,
environment:
  - HOST: localhost
  - WITH_PORT: ${HOST}:8080 #host read from env variable above

Here, HOST needs to exist at your environment and not in container environment (which is probably not what you want).
~ $ docker run -it -e c=${a} -e a=b ubuntu env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=4f27e057b515
TERM=xterm
c=
a=b
HOME=/root
 ~ $ docker run -it -e c=${PATH} -e a=b ubuntu env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ba84596bfdf3
TERM=xterm
c=/usr/local/opt/bison/bin:/Users/username/anaconda3/bin:/Users/username/anaconda2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/opt/puppetlabs/bin:/usr/local/munki:/Applications/apache-maven-3.5.4/bin:/Users/username/opt/packages/cassandra/bin:/Users/username/bin
a=b
HOME=/root


text:
Q: Coordinates of Circles in a Pattern of a Truncated Icosahedron on a Sphere (soccer ball) Given are circles of a certain radius $r_c$. These are arranged on a sphere with the radius $r_s$ in a pattern of hexagons and pentagons similar to a soccer ball (truncated icosahedron). Five circles are fitted into a pentagon and seven into a hexagon.
In the center of the sphere sits an icosahedron. A line is drawn from each of its corners to the center of each pentagon.
What is needed:

*

*Using the center of one pentagon as north pole, the longitude and latitude for the centers of the circles

*the longitude and latitude of the centers of the pentagons

*The radius of the sphere.

To illustrate the matter, pictures of the object in question can be found here:
http://i.imgur.com/pU4pmOp.jpg
http://imgur.com/a/tfdpS
To build the real life object I calculated the length of the sides of a hexagon using $r_c$. Using the side length I could calculate the circumscribing sphere of a truncated icosahedron. But since the base for this calculation puts the circles on a plane and not the sphere itself, it is neither accurate nor does it give me the coordinates.
Context:
I am building a ball of speakers. I have already done that IRL but now I want to construct a CAD model. Where real life wire can be bent to fit, CAD is merciless. So I need to get to the bottom of this mathematically.


text:
Q: Article with "general truth" I don't understand what rule should we apply for the phrase.
On the one hand, there are many general truths, so we need to use a article.

The fact that you're reading this is a general truth.

I googled the phrase and find out that almost all people use the phrase without an article.

Can there be empirical evidence for general truth?

And, as far as I've understood, we should use the when we're talking about same general truth in two or more sentences.
Please, clarify when I should use an article with the phrase and which one for what situation.

A: Going from A something to a THE something:
A general truth can be a very simple idea but difficult to follow.
For example, a watched pot never boils. A pot with water in it you are watching as it boils.
The pot [the one I mentioned above as a general proposition] does not boil is just a perception; the water or liquid in it will, in fact, boil at some point but will seem like a long time if you are watching it instead of doing something else while it getting to the boiling poin.
No article is used with about abstract nouns; an article would be used only if the abstract notion is in the form X of Y. The beauty of this principle is that it is simple.
Truth is difficult to understand even though philosophers have discussed it through the ages.
Beauty is a  hallmark of Renaissance painting.
Rudeness on the telephone can come back to haunt you.
**They achieved great insight into the problem.
You can add adjectives to the abstract nouns but they still do not take a or the.
The public statues in Ancient Greece were known for their great beauty.
But here we have an exception: truth can be an abstract uncountable noun or it can be countable.  For example: "Truth is difficult to understand" versus A truth about him is that he is very clever, in fact. [general] Also: In life, general truths [countable] are hard to accept.  BUT: The truth of the matter is that I don't like strawberries. [x of y, abstract noun].
The fact that you're reading this is a general truth. [countable noun, general statement]
Can there be empirical evidence for general truth? [abstract noun, no article].
The general truth of the experience was that I hated it. [abstract noun in the X of Y form].
Finally, a truth can be the truth if it is specific to a situation:
The truth is one has to work really hard to sort out the use of articles versus no articles in English.
The idea here is: there is a specific truth to the situation regarding use of articles versus no articles in English.


text:
Q: jQuery mobile css and js equvalent code for desktop I wanted to have a collapsible list in my html. Here is the end result in jsfiddle using jquery mobile, however, I cannot use jquery mobile since I am using jquery in my code already and it seems to mess with my desktop ui. Are there equivalent code I can reference to create the same result?
Relevant code
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

My Phonebook

A

Adele

Agnes

B

Billy

Bob

C

Calvin

Cameron

Chloe

Christina


text:
Q: How to parse LocalDateTime with leading spaces? I'm trying to parse dates from html pages using LocalDateTime. And I couldn't come up with solution to make the following test pass.
(Using TestNG) First row always fails
static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss u");

    @DataProvider(name = "dateTimeFormats")
public Object[][] dateTimeFormats() {
    return new Object[][]{
            {"Mon Jan  5 06:41:07 2015", LocalDateTime.of(2015, 1, 5, 6, 41, 7)},
            {"Sun Jan 25 00:48:23 2015", LocalDateTime.of(2015, 1, 25, 0, 48, 23)},
            {"Mon Aug 14 07:58:00 2006", LocalDateTime.of(2006, 8, 14, 7, 58, 0)}
    };
}

@Test(dataProvider = "dateTimeFormats")
public void testParsePostDateTime(String dateTimeString, LocalDateTime expectedResult) {
    LocalDateTime result = LocalDateTime.parse(dateTimeString, DATE_TIME_FORMATTER);
    assertEquals(result, expectedResult);
}

Any ideas which date pattern should be used?

A: You can use the pattern "E MMM ppd HH:mm:ss u". Explanation of p-symbol see javadoc. It means padding the next field up to the width as there are count of p-letters available.


text:
Q: Word for not being able to focus on one task In Hebrew, my native language, we have a word describing the inability of one to focus on a certain task and instead thinking or doing one or many related/unrelated things. This word roughly translates to "being scattered" or "being dispersed". Are there any other more appropriate words to describe such thing?
Note: if this word can be used in the context of not speaking to the point during a conversation it also fits the usage of the Hebrew one.

A: The word closest to the examples you already gave is scatterbrained:

[Merriam-Webster]
: having or showing a forgetful, disorganized, or unfocused mind : having the characteristics of a scatterbrain

A: The person is:

*

*absentminded;

*inattentive;

*miles away (informal);

*in a world of his/her own (informal); and,

*(maybe) daydreaming.

I like the above suggestions better, even though, per any dictionary, these all are synonyms of 'distracted' which already exists as an answer in this thread.

A: "Distracted" is the word you are looking for, where you are not concentrated. That's when while doing one task your mind reacts to what your eyes are watching and what you are thinking, you get drawn away from your task, and you get distracted by other things.

A: scattered
I can't find a good dictionary definition of this, but this book title shows pretty clearly how it can be used for your concept:

Smart but Scattered: The Revolutionary "Executive Skills" Approach to Helping Kids Reach Their Potential

all over the place
This phrase works great for the context you're interested in.  Example:

John's comments included some interesting points, but he was all over the place and in the end he didn't help our case.  I think we should leave him off the speaker list for next time.

Finally, the most obvious word:
unfocused
(needs no explanation; usage: the same as "all over the place")

Edit (4/23): There is another one gaining traction in the US at least:
ADHD (as an adjective)
This is an acronym for a neurodevelopmental diagnosis, Attention Deficit/Hyperactivity Disorder, which is a subtype of ADD, Attention Deficit Disorder.  Example showing how it's starting to be used in the US:

Prof. X is a good teacher but if you want to get questions answered in office hours, make sure you bring a written list of your questions with you.  Keep coming back to your list if he goes off on ADHD tangents.

Be careful with this one.  It hasn't lost the stigma everywhere yet.

A: to wander TFD

(of the mind, thoughts, etc) to lose concentration or direction

As in:

He frequently wandered off the point during our conversation.

A: As to the sense of "not speaking to the point during a conversation", you could say prevaricate, or more informally "beating around the bush", but these don't extend to the other sense you mean.

A:
Distractible
  (also distractable)
     Easily distracted.

(Oxford).
in fact easily-distracted is useful in its own right.


text:
Q: How to filter documents by embedded arrays in MongoDB using Java I have the following document:
{
    "_id": {
        "$oid": "5d4037f811b787414dcfb3a5"
    },
    "id": 1,
    "seats": [{
        "available": true
    }, {
        "available": true
    }, {
        "available": true
    }, {
        "available": false
    }]
}

How to query using mongodb-java-driver only the documents that have number of seats available greater than 3?
What I want is something like this: (seats.available eq true) gt 3
Is it possible?

A: i think this might be a duplicate to Query for documents where array size is greater than 1
so something like this i would guess:
{ $where: "this.seats.available.length > 3" }

A: To count the number of available seats, we can use $reduce aggregation stage. It would count the seats whose availability are marked as 'true'. In the next pipeline stage, the documents are filtered which have the count of available seats greater than 3.
db.checks.aggregate([
    {
        $addFields:{
            "availableSeats":{
                $reduce:{
                    "input":"$seats",
                    "initialValue": 0,
                    "in":{
                        $sum:[
                            "$$value",
                            {
                                $cond:[
                                    {
                                        $eq:["$$this.available",true]
                                    },
                                    1,
                                    0
                                ]
                            }
                        ]
                    }
                }
            }
        }
    },
    {
        $match:{
            "availableSeats":{
                $gte: 3
            }
        }
    }
]).pretty()


text:
Q: AngularJS Factory Data Not Updating In Controller I'm not sure what I've done wrong this is how I've setup other factories to share data as far as I can see, but even though the array should be passed by reference and I don't overwrite the array so the reference isn't lost the template never loads with the data I can see coming down from the find all request.  Can anyone see what it is that I have/haven't done to get this factory to work and shared between controllers?
I originally set this up not using a service so I know the data returned from the request does work with the view, and if you look at my stubs the data is there (and it looks the same), but the view never updates.  If this is something other than a glaring error that I've missed and don't seem to understand I'd appreciate a quick comment as well since I assumed it was the fact objects/arrays are passed by reference that makes this all work.
Contacts Controller
// Stripped down for brevity...
(function () {

    'use strict';

    function ContactsController(ContactsFactory,
                                ContactsResource) {

        var vm = this;

        vm.contacts = ContactsFactory.get();

        vm.findAll = function () {

            ContactsResource
                .all()
                .then(function (response) {
                    ContactsFactory.add(response.contacts); // <-- an array of objects for example: [{id: 5, username: "Richard39", email: "Sanford.Marilyne@Gibson.org",…},…]
                });
        };

        vm.remove = function (contact, index) {

            ContactsResource
                .remove()
                .then(function (response) {
                    ContactsFactory.remove(index);
                });
        };

        function init() {
            vm.findAll();
        }

        init();
    }

    ContactsController.$inject = [
        'ContactsFactory',
        'ContactsResource'
    ];

    angular
        .module('app')
        .controller('ContactsController', ContactsController);

})();

Contacts Service
// Stripped down for brevity...
(function () {

    'use strict';

    function ContactsFactory() {

        var contacts = [];

        function get() {
            return contacts;
        }

        function add(contacts) {

            console.log(contacts) // <-- array of objects

            angular.forEach(contacts, function(contact) {

                console.log(contact) // <-- object
                contacts.list.push(contact);
            });

            console.log(contacts) // <-- objects pushed onto array [Object, Object, Object, Object, Object,…]

            // But no update in view, which worked with same resource
            // request, prior to switching to factory to share between
            // controllers
        }

        function remove(index) {
            contacts.splice(index, 1);
        }

        // ---
        // PUBLIC API.
        // ---

        return {
            get: get,
            add: add,
            remove: remove
        };
    }

    ContactsFactory.$inject = [];

    angular
        .module('app')
        .factory('ContactsFactory', ContactsFactory);

})();

UPDATE
Using @Rob's suggest makes this work, and I noticed if I added service.contacts as the return value to the getter it also works, and I verified contacts could be removed.  So I'm still interested in knowing why this works versus just using an array for contacts like the examples above.  Are arrays not passed by reference as I originally thought, and it's only objects?  I'd just like to put a name to what I did wrong so it's memorable.
(function () {

    'use strict';

    function ContactsFactory() {

        var service = {
            contacts: []
        };

        function get() {
            return service.contacts;
        }

        function add(contacts) {
            angular.forEach(contacts, function(contact) {
                service.contacts.push(contact);
            });

            console.log(contacts);
        }

        function remove(index) {
            contacts.splice(index, 1);
        }

        return {
            contacts: service.contacts, // <-- Rob's suggestion
            get: get, // <-- this also works now as well
            add: add,
            remove: remove
        };
    }

    ContactsFactory.$inject = [];

    angular
        .module('app')
        .factory('ContactsFactory', ContactsFactory);

})();


text:
Q: Access my system data which has private IP I need to give my laptop to someone for few days, i have my files in that out of which i'm not sure which one's i'll require. So looking for a solution if possible. How can i access those files by logging any time to that system either through remote or any other way. Everyone uses wifi router here, so each of the systems will have private IP(the one i'll use to access my system and the latter too)

A: The easiest option to install Teamviewer on your laptop and also on your other computer from where you will access.


text:
Q: Python Flask Templeta  newline doesnt work im using python Flask and got this template
{% extends "base.html" %}
{% block content %}
{% for ticket in tickets %}
       Ticket: {{ ticket.id }} Subject: {{ ticket.subject }}

{% endfor %}
{% endblock %}

but
 and
 doesnt work, the Text (
) is not displayed and there is no new line.
Anyone an idea?
Thank you

A: got 2 templates one called ticket.html and one called tickets.html i copied tickets.html to ticket.html but then referenced ticket.html in the route of tickets

A: Try this:

Ticket: {{ ticket.id }} Subject: {{ ticket.subject }}


text:
Q: setinterval to reload php page unless "edit" button is clicked right now I have an interval function in jquery that reloads a page every few seconds :
setInterval(function () {
$('div#tab2').load('morefour.php?doc=' + encodeURIComponent(ktitle));
}, 3000);
});

What I actually want to do now is if this input is clicked :
<input type='image' class='edit' src='edit.png'>

stop the setinterval function.

A: setInterval returns a handle you can use with clearInterval to cancel it. The handle will be a number greater than zero.
So save the handle from the setInterval call:
var handle = setInterval(function () {
    $('div#tab2').load('morefour.php?doc=' + encodeURIComponent(ktitle));
}, 3000);

...and then use it to cancel it if the button is pressed:
$("input.edit").click(function() {
    if (handle) {
        clearInterval(handle);
        handle = 0;
    }
});

Also note in that first snippet above, I've moved the interval parameter (3000) to where it should be (as Jared pointed out, you had it as a second parameter to load, where of course it should be a second parameter to setInterval).

A: You can use window.clearInterval() like here.

A: You can do this by using a flag:
<script type="text/javascript">
    var flag = true;
</script>

and change the setInterval statement to something like this:
setInterval(function () {
    if (flag) {
        $('div#tab2').load('morefour.php?doc=' + encodeURIComponent(ktitle));
    }
}, 3000);

and change the flag in image onclick:
<input type='image' class='edit' src='edit.png' onclick="javascript:flag=false">


text:
Q: Invalid State Machine Definition I'm making a 4 lambda step function, leading to a gigantic JSON which is prone to errors. I put it through a JSON formatter, so I'm not sure what I'm getting wrong here. Any help appreciated, thank you.
On that note, is there a tool that would help me translate CF step functions to HCL/JSON?
This is the JSON:
{
   "StartAt":"StartState",
   "States":{
      "StartState":{
         "Type":"Pass",
         "Next":"GetLastExecutionDateTime"
      },
      "GetLastExecutionDateTime":{
         "Type":"Task",
         "Parameters":{
            "Payload.$":"$"
         },
         "Resource":"${aws_lambda_function.read.arn}",
         "Retry":{
            "ErrorEquals":[
               "States.ALL"
            ],
            "IntervalSeconds":"2",
            "MaxAttempts":"1",
            "BackoffRate":"2"
         },
         "Next":"GetDeltaRecordsNumber",
         "ResultPath":"$.lastExecutedDateTime",
         "OutputPath":"$.lastExecutedDateTime.Payload"
      },
      "GetDeltaRecordsNumber":{
         "Type":"Task",
         "Parameters":{
            "Payload.$":"$"
         },
         "Resource":"${aws_lambda_function.count.arn}",
         "Retry":{
            "ErrorEquals":[
               "States.ALL"
            ],
            "IntervalSeconds":"2",
            "MaxAttempts":"6",
            "BackoffRate":"2"
         },
         "Next":"DeltaRecordsNumber",
         "ResultPath":"$.Payload"
      },
      "DeltaRecordsNumber":{
         "Type":"Choice",
         "Choices":{
            "Variable":"$.Payload.Payload.totalRows",
            "NumericEquals":"0",
            "Next":"EndState"
         },
         "Default":"Iterator"
      },
      "Iterator":{
         "Type":"Map",
         "Next":"PassNewExecutionDateTime",
         "Iterator":{
            "StartAt":"ExecuteSqlQuery",
            "States":{
               "ExecuteSqlQuery":{
                  "Type":"Task",
                  "Resource":"${aws_lambda_function.query.arn}",
                  "OutputPath":"$.Payload",
                  "Parameters":{
                     "Payload.$":"$"
                  },
                  "End":"True"
               }
            }
         },
         "ItemsPath":"$.Payload.Payload.iterations",
         "Retry":{
            "ErrorEquals":[
               "States.ALL"
            ],
            "IntervalSeconds":"1",
            "MaxAttempts":"1",
            "BackoffRate":"1"
         },
         "Catch":{
            "ErrorEquals":[
               "States.ALL"
            ],
            "Next":"EndState",
            "ResultPath":"$.Payload"
         },
         "ResultPath":"null"
      },
      "PassNewExecutionDateTime":{
         "Type":"Pass",
         "Next":"StoreNewExecutionDateTIme",
         "OutputPath":"$.Payload.Payload"
      },
      "StoreNewExecutionDateTIme":{
         "Type":"Task",
         "Resource":"${aws_lambda_function.write.arn}",
         "OutputPath":"$.Payload",
         "Parameters":{
            "Payload.$":"$"
         },
         "Retry":{
            "ErrorEquals":[
               "States.ALL"
            ],
            "IntervalSeconds":"2",
            "MaxAttempts":"1",
            "BackoffRate":"2"
         },
         "Next":"EndState"
      },
      "EndState":{
         "Type":"Pass",
         "End":"true"
      }
   }
}

And this is the error:
╷
│ Error: error creating Step Function State Machine (dev-main-workflow): InvalidDefinition: Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: Expected value of type [ARRAY] at /States/GetLastExecutionDateTime/Retry, SCHEMA_VALIDATION_FAILED: Expected value of type [ARRAY] at /States/GetDeltaRecordsNumber/Retry, SCHEMA_VALIDATION_FAILED: Expected value of type [ARRAY] at /States/DeltaRecordsNumber/Choices, SCHEMA_VALIDATION_FAILED: Expected value of type Boolean at /States/Iterator/Iterator/States/ExecuteSqlQuery/End, SCHEMA_VALIDATION_FAILED: Expected value of type [ARRAY] at /States/Iterator/Retry, SCHEMA_VALIDATION_FAILED: Expected value of type [ARRAY] at /States/Iterator/Catch, SCHEMA_VALIDATION_FAILED: Value is not a Reference Path: Reference path didn't start with '$' at /States/Iterator/ResultPath, SCHEMA_VALIDATION_FAILED: Expected value of type [ARRAY] at /States/StoreNewExecutionDateTIme/Retry, SCHEMA_VALIDATION_FAILED: Expected value of type Boolean at /States/EndState/End, MISSING_END_STATE: Workflow has no terminal state at null, MISSING_TRANSITION_TARGET: State "Iterator" is not reachable. at /States/Iterator'
│
│   with aws_sfn_state_machine.main-workflow,
│   on step-function.tf line 3, in resource "aws_sfn_state_machine" "main-workflow":
│    3: resource "aws_sfn_state_machine" "main-workflow" {
│
╵

A: Array missing here, it should be like
"Resource":"${aws_lambda_function.read.arn}",
         "Retry":[{
            "ErrorEquals":[
               "States.ALL"
            ],
            "IntervalSeconds":"2",
            "MaxAttempts":"1",
            "BackoffRate":"2"
         },]

Your choice flow also have the same problem, it should be
 "DeltaRecordsNumber":{
     "Type":"Choice",
     "Choices":[
       {
        "Variable":"$.Payload.Payload.totalRows",
        "NumericEquals": 0,
        "Next":"EndState"
     }
                ],
     "Default":"Iterator"
  },

There are more retries in your JSON doc, where you need to array instead of object.


text:
Q: Covert CURL to Java code I have a CURL as follows. When I call this from the command prompt, after process it returns JSON value. If I access this CURL from PHP also it gives the proper result. Now I want to access this in Java to integrate it to a java project.
curl xx.xx.xx.xx:5000/models/images/one.json -XPOST -F job_id=20yy0811-wq50r5-b629 -F image_url=http://www.mysite/public/testimage.jpg

I tried to implement it some examples I got from internet, shows HTTP errors like  400, 405 etc.
String stringUrl = "http://xx.xx.xx.xx:5000/models/images/one.json";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();

uc.setRequestProperty("X-Requested-With", "Curl");
uc.setRequestProperty("format","json");
uc.setRequestProperty("job_id", "20yy0811-wq50r5-b629");
uc.setRequestProperty("image_url", "http://www.mysite/public/testimage.jpg");
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());

It gives the result:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL:

Tried another code:
String url = "http://xx.xx.xx.xx:5000/models/images/one.json";

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("job_id", "20yy0811-wq50r5-b629");
conn.setRequestProperty("image_url", "http://www.mysite/public/testimage.jpg");

String data =  "{\"format\":\"json\"}";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
new InputStreamReader(conn.getInputStream());

It gives the result:
java.io.IOException: Server returned HTTP response code: 400 for URL:

My requirement is:
URL: xx.xx.xx.xx:5000/models/images/one.json
Parameters: job_id, image_url
Return value : json
How can I convert this CURL to java code? If someone can change this CURL to Java code it would be great.
SOLUTION:

*

*Download Apache HttpComponents

*Follow the steps in http://www.journaldev.com/7146/apache-httpclient-example-to-send-get-post-http-requests
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://xx.xx.xx.xx:5000/models/images/one.json");
//httpPost.addHeader("User-Agent", USER_AGENT);

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("job_id", "20yy0811-wq50r5-b629"));
urlParameters.add(new BasicNameValuePair("image_url", "http://www.mysite/public/testimage.jpg"));

HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
httpPost.setEntity(postParams);

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

System.out.println("POST Response Status:: "
        + httpResponse.getStatusLine().getStatusCode());

BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpResponse.getEntity().getContent()));

String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = reader.readLine()) != null) {
    response.append(inputLine);
}
reader.close();

// print result
System.out.println(response.toString());
httpClient.close();

A: setRequestProperty() sets the headers.To set Form parameters, try this:
String url = "http://xx.xx.xx.xx:5000/models/images/one.json";

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.setRequestMethod("POST");

//build it this way
Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();

You need to import ApacheHttpClient lib to use Uri.Builder class.
source: https://stackoverflow.com/a/29053050/856007


text:
Q: sonar delphi plugin custom rule How to add custom rule in sonar for delphi  language?
Our problem is we are able to add custom rule for all other languages like c#,javascript,java in sonar, but are not able to add for delphi, We can't find new rule option like the one showed in this link for adding custom rules in sonar . Someone please advise.

A: AFAIK, the Delphi plugin, developed and maintained (?) by guys from Sabre, is not extensible: it does not have a rule extension mechanism, nor does it provide an XPath rule that could be used to achieve this purpose.

A: You might want to take a look at the (early) work we are doing to do humane assessment with Delphi, using Moose.


text:
Q: Multiple XSLT files in a single pipeline with ant I have multiple XSLT files that I'm using to process my source XML in a pipeline. I know about the trick with exsl:node-set but after having some issues with this workflow, I took the decision to split the various passes into separate XSL files.  I'm much happier with the structure of the files now and the workflow works fine in Eclipse.  Our release system works with ant.  I can process the files like this:
<xslt basedir="src-xml" style="src-xml/preprocess_1.xsl" in="src-xml/original.xml" out="src-xml/temp_1.xml" />
<xslt basedir="src-xml" style="src-xml/preprocess_2.xsl" in="src-xml/temp_1.xml" out="src-xml/temp_2.xml" />
<xslt basedir="src-xml" style="src-xml/preprocess_3.xsl" in="src-xml/temp_2.xml" out="src-xml/temp_3.xml" />
<xslt basedir="src-xml" style="src-xml/finaloutput.xsl" in="src-xml/temp_3.xml" out="${finaloutput}" />

But this method, going via multiple files on disk, seems inefficient.  Is there a better way of doing this with ant?
Update following Dimitre's suggestion
I've created myself a wrapper around the various other XSLs, as follows:
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:fn='http://www.w3.org/2005/xpath-functions' xmlns:exslt="http://exslt.org/common">

<xsl:import href="preprocess_1.xsl"/>
<xsl:import href="preprocess_2.xsl"/>
<xsl:import href="preprocess_3.xsl"/>
<xsl:import href="finaloutput.xsl"/>

<xsl:output method="text" />

<xsl:template match="/">
    <xsl:apply-imports />
</xsl:template>

</xsl:stylesheet>

This has... not worked well.  It looks like the document had not been preprocessed before the final output XSL ran.  I should perhaps have been clearer here: the preprocess XSL files are modifying the document, adding attributes and the like.  preprocess_3 is based on the output of ..._2 is based on ..._1.  Is this import solution still appropriate?  If so, what am I missing?

A: The more efficient method is to perform a single, multipass transformation.
The files can remain as they are -- they will be imported using xsl:import instructions.
The savings are obvious:

*

*Just one initiation (loading of the XSLT processor).

*Just one termination.

*Eliminates the two intermediate files and their creation, writing into, closing and deleting.

A: Hmm, you say I know about the trick with exsl:node-set, but you don't use it in your attempt ("Update following Dimitre's suggestion"). In case you don't know it, or for the others (like me) who don't know how to perform multipass transformation, here is a nice article: Multipass processing.
The drawback of this approach is that it requires engine specific xsl code. So if you know the engine, you could try this. If you don't know the engine, you could try with solutions from result tree fragment to node-set: generic approach for all xsl engines.
Looking at these sources one conclusion is sure: your current solution is more readable. But you are seeking efficiency, so some readability may be sacrificed.


text:
Q: How to have intervals in dates, so that dates are not overlapped? # Add x-axis and y-axis
ax.bar(india.index.values,
       india['Confirmed'],
       color='purple')

# Set title and labels for axes
ax.set(xlabel="Date",
       ylabel="Confirmed cases",
       title="Confirmed cases in India")

fig.autofmt_xdate()
plt.show()

I want the dates in intervals like 3/20/20, 3/30/2020, 4/10/2020, 4/25/2020,....
this is the dataset
           Country  Confirmed
Date
03/20/2020  India   244
03/21/2020  India   330
03/22/2020  India   396
03/23/2020  India   499
03/24/2020  India   536
... ... ... ... ...
07/28/2020  India   1483156
07/29/2020  India   1581963
07/30/2020  India   1634746
07/31/2020  India   1695988
08/01/2020  India   1750723