Q: React Actions using RxJS for parallel async calls I am having an existing action that calls the api with list of IDs as querystring parameter and fetches the thumbnail response for the passed IDs. In some cases, count of IDs can be 150-200 records. Hence, I am working on making this APIs call batch based and run in parallel using forkJoin and subscribe methods of RxJs. I'm facing following 3 issues regarding the implementation.

*

*I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked.

*maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/

*How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput<any>'. Type 'void' is not assignable to type 'ObservableInput<any>'.ts(2345)
Here is my current code looks like. Any help would be great on this.
const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) =>
    action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe(
        mergeMap( ({ payload }) => {

            const assetIds = Object.keys(payload);
            const meta = payload;

            const batchSize = 10;
            const maxParallelQueries = 3;

            const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = [];

            for (let count = 0; count < assetIds.length; count += batchSize) {
                fetchThumbnailObservables.push(AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize)));
            }

             forkJoin(fetchThumbnailObservables)
            .pipe(mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, maxParallelQueries)) // Issue 1 :  maxParallelQueries limit is not working
            .subscribe({
                complete: () => { },
                error: () => { },
                next: (response) => {
                     // Issue 2 :  below action dont seems to be getting invoked
                    actions.AssetActions.receivedThumbnailsAction(response, meta)
                },
             });

            // Issue 3 :  How to handle return of observable
            // Added below code for prevennting error raised by mergeMap( ({ payload }) => {
            return new Observable<any>();
        }),
        catchError((error) => of(actions.Common.errorOccured({ error })))
    );
    ```

A: I do not know Epics, but I think I can give you some hints about how to address this problem.
Let's start from the fact that you have an array of ids, assetIds, and you want to make an http call for each id with a controlled level of concurrency, maxParallelQueries.
In this case from function and mergeMap operator are yor friends.
What you need to do is
// from function transform an array of values, in this case, to a stream of values
from(assetIds).pipe(
  mergeMap(id => {
    // do whatever you need to do and eventually return an Observable
    return AssetDataService.fetchThumbnailData(id)
  }, maxParallelQueries) // the second parameter of mergeMap is the concurrency
)

In this way you should be able to invoke the http calls keeping the limit of concurrency you have established

A:

*

*I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked.

You mustn't call an action imperatively in redux-observable. Instead you need to queue them.
actions.AssetActions.receivedThumbnailsAction(response, meta) would return an plain object of the shape {type: "MY_ACTION", payload: ...} instead of dispatching an action. You rather want to return that object wrapped inside an observable inside mergeMap in order to add the next action to the queue. (see solution below)

*maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/

First guess: What is the return type of AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize))? If it is of type Promise then maxParallelQueries has no effect because promises are eager and start immediately when created thus before mergeMap has the chance to control the request. So make sure that fetchThumbnailData returns an observable. Use defer rather than from if you need to convert a Promise to an Observable to make sure that a promise is not being fired prematurely inside fetchThumbnailData.
Second guess: forkJoin is firing all the request so mergeMap doesn't even have the chance to restrict the number of parallel queries. I'm surprised that typescript doesn't warn you here about the incorrect return type in mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, ...). My solution below replaces forJoin with from and should enable your maxParallelQueries.

*How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'.ts(2345)

This is not a syntax error. In an epic you have either the option to return an empty observable return empty() if no subsequent actions are intended or dispatch another action by returning an observable of type IAction. Here my (untested) attempt to meet your requirements:
const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) =>
  action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe(
    mergeMap( ({ payload }) => {

      const assetIds = Object.keys(payload);
      const meta = payload;

      const batchSize = 10;
      const maxParallelQueries = 3;

      const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = [];

      for (let count = 0; count < assetIds.length; count += batchSize) {
        fetchThumbnailObservables.push(
          AssetDataService.fetchThumbnailData(
             assetIds.slice(count, count + batchSize)
          )
        );
      }

      return from(fetchThumbnailObservables)
        .pipe(
          mergeMap(
            fetchThumbnailObservable => fetchThumbnailObservable,
            maxParallelQueries
          ),
          map((response) =>
            // dispatch action for each response
            actions.AssetActions.receivedThumbnailsAction(response, meta)
          ),
          // catch error early so epic continue on error
          catchError((error) => of(actions.Common.errorOccured({ error })))
        );
    })
  );

Please notice that I moved catchError closer to the request (inside the inner forkJoin Observable) so that the epic does not get terminated when an error occurs. Error Handling - redux observable This is so because when catchError is active it replaces the failed observable with the one that is returned by catchError. And I assume you don't want to replace the whole epic in case of an error?
And one thing: redux-observable handles the subscriptions for you so won't need to call .subscribe or .unsubscribe anywhere in your application. You just need to care a about the lifecycle of observables. Most important to know here is when does an observable start, what happens to it when it completes, when does it complete or what happens when an observable throws.


Q: Stream compaction and transform based on the index in CUDA I have an array of float that I would like to perform a stram compaction operation on, like what is presented here: Parallel Prefix Sum (Scan) with CUDA, and then apply a transform based on the value and the address or the original element.
For example, I have an array with the values {10,-1, -10, 2}, and I want to return all the elements with an absolute value greater than 5, and apply a transform taking the value and its address in the array.
The result here would be {transform(10,0),transform(-10,2)}.
I'm trying to use thrust with this, but this code will run often on large arrays, so ideally it wouldn't use buffers and multiple traversals of the array.
Is it possible to do what I'd like to do without allocating a secondary array and doing multiple traversals? If yes, does such code exist in the wild? Or at least does anybody have any pointers to which functions of thrust or any other library I could compose to reach my goal?

A: Yes, it's possible in thrust with a single thrust algorithm call (I assume that is what you mean by "without ... doing multiple traversals") and without "allocating a secondary array".
One approach would be to pass the data array plus an index/"address" array (via thrust::counting_iterator, which avoids the allocation) to a thrust::transform_iterator which creates your "transform" operation (combined with an appropriate functor).
You would then pass the above transform iterator to an appropriate thrust stream compaction algorithm to select the values you want.
Here's a possible approach:
$ cat t1044.cu
#include <thrust/device_vector.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/copy.h>
#include <math.h>

#include <iostream>

__host__ __device__ int my_transform(int data, int idx){
  return (data - idx);  //put whatever transform you want here
}

struct my_transform_func : public thrust::unary_function<thrust::tuple<int, int>, int>
{

  __host__ __device__
  int operator()(thrust::tuple<int, int> &t){
    return my_transform(thrust::get<0>(t), thrust::get<1>(t));
    }
};

struct my_test_func
{
  __host__ __device__
  bool operator()(int data){
    return (abs(data) > 5);
    }
};

int main(){

  int data[] = {10,-1,-10,2};
  int dsize = sizeof(data)/sizeof(int);

  thrust::device_vector<int> d_data(data, data+dsize);
  thrust::device_vector<int> d_result(dsize);
  int rsize = thrust::copy_if(thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.begin(), thrust::counting_iterator<int>(0))), my_transform_func()), thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.end(), thrust::counting_iterator<int>(dsize))), my_transform_func()), d_data.begin(), d_result.begin(), my_test_func()) - d_result.begin();
  thrust::copy_n(d_result.begin(), rsize, std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;
  return 0;
}
$ nvcc -o t1044 t1044.cu
$ ./t1044
10,-12,
$

Some possible criticisms of this approach:

*

*It would appear to be loading the d_data elements twice (once for the transform operation, once for the stencil).  However, it's possible that the CUDA optimizing compiler would recognize the redundant load in the thread code that ultimately gets generated, and optimize it out.

*It would appear that we are performing the transform operation on every data element, whether we intend to save it or not in the result.  Once again, it's possible that the thrust copy_if implementation may actually defer the data loading operation until after the stencil decision is made.  If that were the case, its possible that the transform only gets done on an as-needed basis.  Even if it is done always, this may be an insignificant issue, since many thrust operations tend to be load/store or memory bandwidth bound, not compute bound.  However an interesting alternate approach could be to use the adaptation created by @m.s. here which creates a transform applied to the output iterator step, which would presumably limit the transform operation to only be performed on the data elements that are actually being saved in the result, although I have not inspected that closely either.

*As mentioned in the comment below, this approach does allocate temporary storage (thrust does so under the hood, as part of the copy_if operation) and of course I'm explicitly allocating O(n) storage for the result.  I suspect the thrust allocation (a single cudaMalloc) is probably also for O(n) storage.  While it may be possible to do all the things asked for (parallel prefix sum, stream compaction, data transformation) with absolutely no extra storage of any kind (so perhaps the request is for an in-place operation), I think that crafting an algorithm that way is likely to have significant negative performance implications, if it is doable at all (it's not clear to me a parallel prefix sum can be realized with absolutely no additional storage of any kind, let alone coupling that with a stream compaction i.e. data movement in parallel).  Since thrust frees all such temporary storage it uses, there can't be much of a storage concern associated with frequent use of this method.  The only remaining concern (I guess) is performance. If the performance is a concern, then the time overhead associated with the temporary allocations should be mostly eliminated by coupling the above algorithm with a thrust custom allocator (also see here), which would allocate the maximum needed storage buffer once, then re-use that buffer each time the above algorithm is used.


Q: MongoDB and Spring Data performance Issue I am using MongoDB with Spring Data for creating our prototype application. The save operation is very fast but for listing the results the performance is very poor even when their are just 3 to 4 records persisted. Another amazing part is the the performance deteriorates with each consecutive list operation.
Just to give an idea here is the single json which is not the largest in the world.
    {
    "enquiryId": "574feac25215eae3e2e1434b",
    "enquiryName": "Mineral Shipment",
    "dateOfEnquiry": null,
    "requiredFrom": 1465324200000,
    "requiredTo": 1483036200000,
    "source": {
      "locationId": null,
      "area": {
        "pincode": null,
        "area": null,
        "city": {
          "cityId": null,
          "cityName": "Panjim",
          "state": {
            "stateId": null,
            "stateName": " Goa 403001",
            "country": {
              "countryId": null,
              "countryName": " India"
            }
          }
        }
      }
    },
    "destination": {
      "locationId": null,
      "area": {
        "pincode": null,
        "area": null,
        "city": {
          "cityId": null,
          "cityName": "Ludhiana",
          "state": {
            "stateId": null,
            "stateName": " Punjab 141001",
            "country": {
              "countryId": null,
              "countryName": " India"
            }
          }
        }
      }
    },
    "shipment": {
      "shipmentId": null,
      "enquiryId": null,
      "shipmentName": "Mineral Shipment",
      "valueOfGoods": null,
      "categories": [
        {
          "categoryId": null,
          "categoryName": "Hazardous,Flammable",
          "subCategories": null,
          "shipmentId": null
        }
      ],
      "modes": [
        {
          "modeId": null,
          "modeName": "WATER",
          "modeDescription": null,
          "shipmentId": null
        }
      ],
      "items": [
        {
          "itemId": null,
          "itemName": "Coal",
          "shape": null,
          "form": null,
          "dimension": null,
          "weight": null,
          "quantity": null,
          "shipmentId": null
        },
        {
          "itemId": null,
          "itemName": "Nickel",
          "shape": null,
          "form": null,
          "dimension": null,
          "weight": null,
          "quantity": null,
          "shipmentId": null
        }
      ]
    },
    "transportEnquiries": [
      {
        "transportEnquiryId": null,
        "transport": {
          "transportId": null,
          "name": "Flat Bed",
          "mode": {
            "modeId": null,
            "modeName": "WATER",
            "modeDescription": "The two world wars gave a great impetus to the development of air transport in almost all the countries of the world",
            "shipmentId": null
          },
          "type": {
            "typeId": null,
            "name": "LWH",
            "modeId": null,
            "illustrationURL": null
          },
          "desc": "Description of Flat Bed"
        }
      }
    ],
    "storageEnquiries": [],
    "packagingEnquiries": null,
    "insuranceEnquiries": null,
    "documentationEnquiry": null,
    "trackingToolRequired": null,
    "customerSupportRequired": null,
    "insuranceRequired": null,
    "storageRequired": null,
    "documentationRequired": null,
    "published": false,
    "userId": null
  }

And here is the Spring Service
    public class EnquiryManagementService implements IEnquiryManagementService{

    @Autowired
    private EnquiryRepository enquiryRepository;

    public Enquiry createEnquiry(Enquiry enquiry) {
        Enquiry enquiryObj = (Enquiry)enquiry;
        Enquiry e = enquiryRepository.save(enquiryObj);
        return e;
    }

    @Override
    public List<Enquiry> listEnquiry(int start) {
         long startTime = System.currentTimeMillis();
         Page<Enquiry> enquiries = enquiryRepository.findAll(new PageRequest(start,10));
         long endTime = System.currentTimeMillis();
         System.out.println("Time Taken = "+(endTime-startTime));
         return enquiries.getContent();
    }

}

Here are the results of the times taken in processing the findAll() 4 times consequtively without adding any more records. There are only 4 records in the system and you can see the time taken is 10.7 sec, 25.7 sec, 41.9 sec, and 58.5 sec. Each request takes a lifetime of its own to complete.

*

*Time Taken = 10768

*Time Taken = 25785

*Time Taken = 41921

*Time Taken = 58530

Given below is the configuration of my system
- Intel Core i3 2330M @2.2 GHz
- 2 GB RAM
- 64 bit Windows 7
- MongoDB version locally installed on my system : 3.2
- At the time of executing this query CPU utilization 50% and memory 80%
Ideally this operation must happen in less than half a second or at max a second. Any kind of help would be great.


Q: How to get data from website's dd tag via VBA I am trying to get data from a website, but I cannot get this part of my VBA code to work.
I have tried to look here, e.g. Excel VBA to find dd & dt tag but I could not find the answer.
This is the HTML code I am trying to get data from:

Folkbokföring

Gatuadress

Postnummer

Postort

Kommun

Län

Örebro (18)

Särskild adress

Gatuadress

Poste Restante

Postadress

701 00 Örebro

I am trying to retrieve the class="UpplysningTableSecondTd" data.
Neither of the below is working, and I have tried different things.
Set All_dd = oHDoc.getElementsByClassName("rapport__list m-b-25").getElementsByClassName("UpplysningTableSecondTd")(0).innerText
Set All_dd = oHDoc.getElementsById("show7").getElementsByTag("UpplysningTableSecondTd")

Thanks.

A: I managed to solve it.
Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(0).innerText
Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(1).innerText


Q: XSSFCell Style seems to be slow I'm currently using apache POI to automatically tranfers data from xls file to xlsm file after some process. I have strong executing time constraint and the setters on XSSFCellStyle is very time consuming.
In fact i have files with thousands of cell to transfert and method on boder (SetBorder & SetBorder color) take 3 ms to 5 ms to execution each on 1 cell. In my context 1300 thousands it takes 30 sec to execute.
In a graph on JProfiler, we can see the most time spend on these methods is in state "waiting".
Is it normal for you or not ?
Thanks a lot!!

A: in for example org.apache.poi.xssf.model.StylesTable.putStyle( XSSFCellStyle ) they try to find the xfs twice.
It uses an ArrayList.
The more cells, the slower this operation is.
If you can, try to avoid a lot of dates.


Q: Iterating through my fonts list to display them more efficiently Answer located here: Setting multiple different Typefaces to the TextViews in a ListView
I have 20 fonts in a list that changes a TextView based on the user's selection. I want to keep adding more custom fonts, but it's getting very tedious doing this manually for each addition. In the following use case, the user presses a button that opens a menu (not shown). I want to display these buttons in their respective fonts, by setting a typeface to each TextView in the menu:
Typeface Aclonica = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Aclonica.ttf");
TextView fontMenuAclonica = (TextView) this.view.findViewById(R.id.fontMenuAclonica);
fontMenuAclonica.setTypeface(Aclonica);

Typeface Arimo = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Arimo-Regular.ttf");
TextView fontMenuArimo = (TextView) this.view.findViewById(R.id.fontMenuArminoRegular);
fontMenuArimo.setTypeface(Arimo);

Is there a more efficient way to do this than by repeating this code over and over again? Can't I just have one base implementation of the code and list of values for the Typeface name, TextView name, and font name?
Typeface typefaceName = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
TextView textViewName = (TextView) this.view.findViewById(R.id.resourceId);
textViewName.setTypeface(typefaceName);

Update: I suppose it's more efficient to set up a ListView:
    ListView fontsListView = (ListView) this.view.findViewById(R.id.MenuLayout);
    penis
    String[] fonts = new String[]{
            "Aclonica",
            "Amino-Regular"

    };
    ArrayList<String> planetList = new ArrayList<String>();
    planetList.addAll(Arrays.<String>asList(Arrays.toString(fonts)));
    for( int i = 0; i <= fonts.length - 1; i++) {
        planetList[i].setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/" + fonts[i] + ".ttf"));
    }

Here is the XML:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
android:id="@+id/rowTextView"
android:textSize="20sp"
android:gravity="center_horizontal"
android:padding="10dp"
android:typeface="sans"
android:fontFamily="sans-serif-light" />

How do I iterate through the TextViews that are created so that I can programmatically set their Typefaces?


Q: How to compute a least common ancestor algorithm's time complexity? I came into an article which talking about the LCA algorithms, the code is simple
http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html
// Return #nodes that matches P or Q in the subtree.
int countMatchesPQ(Node *root, Node *p, Node *q) {
  if (!root) return 0;
  int matches = countMatchesPQ(root->left, p, q) + countMatchesPQ(root->right, p, q);
  if (root == p || root == q)
    return 1 + matches;
  else
    return matches;
}

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root || !p || !q) return NULL;
  if (root == p || root == q) return root;
  int totalMatches = countMatchesPQ(root->left, p, q);
  if (totalMatches == 1)
    return root;
  else if (totalMatches == 2)
    return LCA(root->left, p, q);
  else /* totalMatches == 0 */
    return LCA(root->right, p, q);
}

but I was wondering how compute the time complexity of the algorithm,can anyone help me?

A: The complexity of LCA is O(h) where h is the height of the tree. The upper bound of the tree height is O(n), where n denotes the number of vertices/nodes in the tree.
If your tree is balanced, (see AVL, red black tree) the height is order of log(n), consequently the total complexity of the algorithm is O(log(n)).

A: The worst case for this algorithm would be if the nodes are sibling leave nodes.
Node *LCA(Node *root, Node *p, Node *q)
{
  for root call countMatchesPQ;
  for(root->left_or_right_child) call countMatchesPQ; /* Recursive call */
  for(root->left_or_right_child->left_or_right_child) call countMatchesPQ;
  ...
  for(parent of leave nodes of p and q) call countMatchesPQ;
}

countMatchesPQ is called for height of tree times - 1. Lets call height of tree as h.
Now check the complexity of helper function
int countMatchesPQ(Node *root, Node *p, Node *q) {
  Search p and q in left sub tree recursively
  Search p and q in right sub tree recursively
}

So this is an extensive search and the final complexity is N where N is the number of nodes in the tree.
Adding both observations, total complexity of the algorithm is
O(h * N)

If tree is balanced, h = log N (RB tree, treap etc)
If tree is unbalanced, in worse case h may be up to N
So complexity in terms of N can be given as

For balanced binary tree: O(N logN)
To be more precise, it is actual h(N + N/2 + N/4...)
for balanced tree and hence should come 2hN
For unbalanced binary tree: O(N2)
To be more precise, it is actual h(N + N-1 + N-2...)
for balanced tree and hence should come h x N x (N+1) / 2

So the worse case complexity is N2
Your algorithm doesn't use any memory. By using some memory to save path, you can improve your algorithm drastically.


Q: How to show only color coding in the legend of my plotly scatterplot in python I'm plotting some PCAs with plotly.express scatterplot function, and coding the samples by region (color) and breed (symbol). When I plot it, the legend show me all 67 different breeds in their combinations of symbols and colors. Is there a way to show only the color categories instead?
My data looks like this:

PC1
PC2
PC3
Breed
Region

Sample1
value
value
value
breed1
Region1

Sample2
value
value
value
breed2
Region1

Sample3
value
value
value
breed3
Region2

Sample4
value
value
value
breed1
Region1

Right now my code is just the basic command:
fig=px.scatter(pca, x="PC2",y="PC1", color="Region", symbol="Breed", labels={
    "PC2":"PC2-{}%".format(eigen[1]),
    "PC1":"PC1-{}%".format(eigen[0])
})

fig.layout.update(showlegend=True)
fig['layout']['height'] = 800
fig['layout']['width'] = 800
fig.show()

Any ideas?

A: You can add these lines:
region_lst = []

for trace in fig["data"]:
    trace["name"] = trace["name"].split(",")[0]

    if trace["name"] not in region_lst and trace["marker"]['symbol'] == 'circle':
        trace["showlegend"] = True
        region_lst.append(trace["name"])
    else:
        trace["showlegend"] = False

fig.update_layout(legend_title = "region")
fig.show()

Before adding the lines of code:

After adding the code:

I used this dataframe:
import plotly.express as px

df = px.data.medals_long()
fig = px.scatter(df, y="nation", x="count", color="medal", symbol="count")

A: *

*specifying color and symbol results in legend being combination of values in respective columns

*to have legend only be values in one column, change to use just color

*to represent second column as symbols, change each trace to use a list of symbols

*have synthesized data based on your description

full code
import pandas as pd
import numpy as np
import plotly.express as px
from plotly.validators.scatter.marker import SymbolValidator

eigen = [0.5, 0.7]

# simulate data
n = 1000
pca = pd.DataFrame(
    {
        **{f"PC{c}": np.random.uniform(1, 5, n) for c in range(1, 4, 1)},
        **{
            "Breed": np.random.choice([f"breed{x}" for x in range(67)], n),
            "Region": np.random.choice([f"Region{x}" for x in range(10)], n),
        },
    }
)

# just color by Region
fig = px.scatter(
    pca,
    x="PC2",
    y="PC1",
    color="Region",
    labels={"PC2": "PC2-{}%".format(eigen[1]), "PC1": "PC1-{}%".format(eigen[0])},
)

# build dict that maps as Breed to a symbol
symbol_map = {
    t: s for t, s in zip(np.sort(pca["Breed"].unique()), SymbolValidator().values[2::3])
}

# for each trace update marker symbol to list of symbols that correspond to Breed
for t, s in zip(
    fig.data, pca.groupby("Region")["Breed"].agg(lambda x: [symbol_map[v] for v in x])
):
    t.update(marker_symbol=s)

fig


Q: React state not being updated in Jest while working in the application When I click the button it increments the value by the amount written in the input, it works when I do that in the app but when I try to use Jest and first fireEvent.change() the value of an input to 10 and then fireEvent.click() on the button it doesnt increment it and the value stays at 0.
Here is the error that Im getting:
expect(received).toBe(expected) // Object.is equality

   Expected: 10
   Received: 0

     33 |     fireEvent.click(btnPlus);
     34 |
   > 35 |     expect(parseInt(val.textContent)).toBe(10);
        |                                       ^
     36 |   });
     37 | });
     38 |

Here is the test file:
import React from 'react';
import Counter from './Counter';
import { render, fireEvent } from '@testing-library/react';
describe('Counter works', () => {
  let comp;
  let inp;
  let btnPlus;
  let val;
  beforeAll(() => {
    comp = render(<Counter />);
    inp = comp.getByTestId('inp');
    btnPlus = comp.getByTestId('btn-+');
    val = comp.getByTestId('counter-value');
  });

  it('Counter exists', () => {
    expect(comp).toBeTruthy();
  });
  it('Input works', () => {
    expect(inp.value).toBe('');

    fireEvent.change(inp, {
      target: {
        value: 10,
      },
    });

    expect(parseInt(inp.value)).toBe(10);

    fireEvent.click(btnPlus);

    expect(parseInt(val.textContent)).toBe(10);
  });
});

The general Counter file:

const Counter = () => {
  const [state, setState] = useState({
    count: 0,
    inpText: '',
  });
  const setNum = (num) => {
    setState((prev) => {
      return {
        ...prev,
        count: prev.count + num,
      };
    });
  };
  const setInp = (e) => {
    setState((prev) => {
      return {
        ...prev,
        inpText: e?.target.value,
      };
    });
  };
  return (
    <>
      <h1
        data-testid='counter-value'
        style={{
          color: 'white',
          position: 'absolute',
          top: '45%',
          left: '50%',
          transform: 'translate(-50%,-60%)',
        }}>
        {state.count}
      </h1>
      <div id='flex'>
        <Button setNum={setNum} plus='+' num={parseInt(state.inpText)} />
        <input data-testid='inp' value={state.inpText} onChange={setInp} />
        <Button setNum={setNum} plus='-' num={-parseInt(state.inpText)} />
      </div>
    </>
  );
};

And the Button:

const Button = (props) => {
  return (
    <button
      data-testid={`btn-${props.plus}`}
      onClick={() => {
        props.setNum(props.num);
      }}>
      {props.plus}
    </button>
  );
};

A: I would suggest avoiding initial component setup in beforeAll/beforeEach functions. Each test case should run in isolation and not be affected by operations executed in other tests.
Instead, create a helper function with that logic and call it on every test.
import React from 'react';
import Counter from './Counter';
import { render, fireEvent } from '@testing-library/react';

describe('Counter works', () => {
    let comp;
    let inp;
    let btnPlus;
    let val;

    const renderComponent = () => {
        comp = render(<Counter />);
        inp = comp.getByTestId('inp');
        btnPlus = comp.getByTestId('btn-+');
        val = comp.getByTestId('counter-value');
    }

    it('Counter exists', () => {
        renderComponent();
        expect(comp).toBeTruthy();
    });

    it('Input works', () => {
        renderComponent();
        expect(inp.value).toBe('');
        fireEvent.change(inp, { target: { value: 10 } });
        expect(inp.value).toBe('10');
        fireEvent.click(btnPlus);
        expect(val.textContent).toBe('10');
    });
});


Q: How is the btmgmt command used to set PHY? When I run the command: btmgmt phy LE2MTX LE2MRX
It returns:
Could not set PHY Configuration with status 0x0d (Invalid Parameters)
btmon shows:
@ MGMT Open: btmgmt
@ MGMT Command: Set PHY Configuration (0x0045) plen 4
        Selected PHYs: 0x1800
          LE 2M TX
          LE 2M RX
@ MGMT Event: Command Status (0x0002) plen 3
      Set PHY Configuration (0x0045)
        Status: Invalid Parameters (0x0d)
@ MGMT Close: btmgmt

I'm very unfamiliar with btmgmt, how do I specify that I want LE 2M PHY whenever possible?
If I run: btmgmt phy
I get the available PHYs which incudes the LE2MTX and LE2MRX (which I am after).
Supported phys: BR1M1SLOT BR1M3SLOT BR1M5SLOT EDR2M1SLOT EDR2M3SLOT EDR2M5SLOT EDR3M1SLOT EDR3M3SLOT EDR3M5SLOT LE1MTX LE1MRX LE2MTX LE2MRX
Configurable phys: BR1M3SLOT BR1M5SLOT EDR2M1SLOT EDR2M3SLOT EDR2M5SLOT EDR3M1SLOT EDR3M3SLOT EDR3M5SLOT LE2MTX LE2MRX
Selected phys: BR1M1SLOT BR1M3SLOT BR1M5SLOT EDR2M1SLOT EDR2M3SLOT EDR2M5SLOT EDR3M1SLOT EDR3M3SLOT EDR3M5SLOT LE2MTX LE2MRX

These can also be seen in btmon:
      Get PHY Configuration (0x0044) plen 12
        Status: Success (0x00)
        Supported PHYs: 0x1fff
          BR 1M 1SLOT
          BR 1M 3SLOT
          BR 1M 5SLOT
          EDR 2M 1SLOT
          EDR 2M 3SLOT
          EDR 2M 5SLOT
          EDR 3M 1SLOT
          EDR 3M 3SLOT
          EDR 3M 5SLOT
          LE 1M TX
          LE 1M RX
          LE 2M TX
          LE 2M RX
        Configurable PHYs: 0x19fe
          BR 1M 3SLOT
          BR 1M 5SLOT
          EDR 2M 1SLOT
          EDR 2M 3SLOT
          EDR 2M 5SLOT
          EDR 3M 1SLOT
          EDR 3M 3SLOT
          EDR 3M 5SLOT
          LE 2M TX
          LE 2M RX
        Selected PHYs: 0x19ff
          BR 1M 1SLOT
          BR 1M 3SLOT
          BR 1M 5SLOT
          EDR 2M 1SLOT
          EDR 2M 3SLOT
          EDR 2M 5SLOT
          EDR 3M 1SLOT
          EDR 3M 3SLOT
          EDR 3M 5SLOT
          LE 2M TX
          LE 2M RX


Q: find nth fibonacci number where n can vary till 10^9 //  i was trying to find (n^n)%1000000007 where n is the nth fibonacci term of the series.
     example : n=3  ans 4 (2^2)
 public class Sol_Big {
 public static void main(String args[])
{
       int n =10000000;
       BigInteger a = BigInteger.ZERO;
       BigInteger b = BigInteger.ONE;
       BigInteger c = BigInteger.valueOf(1);
       BigInteger MOD = BigInteger.valueOf(1000000007);

       for (int j=2 ; j<=n ; j++)
       {
           c =  a.add(b);
           c=c.mod( MOD);
           a = b.mod(MOD);
           b = c.mod(MOD);
       }
        System.out.println(c);
        BigInteger result = BigInteger.valueOf(1);
        result = c.modPow(c, MOD);
        int intval = result.intValue();
        System.out.println( intval);

      }
}

// my code is working for 10^7 input but for 10^8 and onward it is exceeding time limit....

A: The trick is to notice that you can calculate the Fibonacci numbers using matrix multiplication:
| 0 1 |   | a |   | b     |
| 1 1 | * | b | = | a + b |

With this knowledge, we can calulate the n-th Fibonacci number:
| 0 1 |^n   | 0 |
| 1 1 |   * | 1 |

Because matrix multiplication is associative, we can efficiently calculate m^n.

*

*If n is even, m^n = m^(n/2) * m^(n/2)

*If n is odd, m^n = m^((n-1)/2)) * m^((n-1)/2)) * m
Note that we need the same thing twice, but we only have to compute it once.
This makes it possible to calculate the n-th Fibonacci number in O(log n).
I leave it to you to write the code.


Q: Spring XD stream status failed After creating stream in Spring XD using the below command
*stream create foo --definition "jdbc --fixedDelay=1 --split=1 --url=jdbc:mysql://localhost:3306/test --query='select * from test_tutorials_tbl'|log" --deploy*
we have got the status as 'Created and deployed new stream 'foo'.
But when I checked with the stream list command, the status seems to be failed and no data. This is not with the case with MySql database alone but with a command like
'stream create --name stocks --definition "http --port=9090 | gemfire-json-server --regionName=Customers --keyExpression=payload.getField('lastname')" --deploy'
is too failing.
Could any one please help us as this work is very much critical.

A: I have a solution for the question that i have posted. Try starting the Spring XD single node too. Then you won't face any stream creation failure. Status will be in deployed (when we try create stream to fetch mysql data for example). But stream creation will be in failed, if we are pointing to gemfire. I am looking into it.


Q: Why don't Spring actuator requests display in log? I have 6 Springboot apps. Each one is slightly different from another. All of them include Actuator (so I can hit /health, /env, etc). The problem is that in 3 of the apps I can see in the logs where the request was processed for each endpoint (see example below). In the other 3 apps I do not get this log info. I have tried to copy some config code and dependencies from one app to the other but have not figured out what is different or how to change the logging configuration. Has anyone discovered how to solve this problem?
2016-12-15 20:02:04.962 DEBUG 1 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/health]


Q: Connections, edges, node: how to use a subtype of a node I'm following the Connection, Edges, Node, concept of relay in Apollo.
I use a Node { id: ID! } interface. I have a collection of entities that are all kind of 'groups', with small differences. I would like to model these as a single Connection, but not really sure how to do that:
     # simplified for example
    interface Group {
        id: ID!
        type: String!
    }
    type WallGroup implements Node & Group {
        id: ID!
        type: String!
    }
    type Event implements Node & Group {
        id: ID!
        type: String!
        dteStart: DateTime!
        dteEnd: DateTime!
    }
    type GroupEdge implements Edge {
        cursor: String!
        node: Group!
    }
    type GroupConnection implements Connection {
        edges: [GroupEdge!]!
        pageInfo: PageInfo!
        totalCount: Int!
    }

This will generate an error because GroupEdge expects node to a Node. It is, but the Group interface is not and it therefore fails.
Another thing I tried was
    union AllGroup = WallGroup | Event
    type GroupEdge implements Edge {
        cursor: String!
        node: AllGroup!
    }

But this leads to the same issue. Apparently, the union loses notion of the Node interface implemented on WallGroup and Event.
Any ideas on hwo to model this or should I just duplicate everything?

A: The Relay specification only requires that your schema include a Node interface -- when creating a Relay-compliant, normally you don't create interfaces for Connection and Edge.
The reason Relay requires a Node interface is to allow us to query for any Node by id. However, typically there's no need for a field that returns one of many edges or one of many connections. Therefore, typically there's no need to need to make an interface for edges or connections. This is what you would normally do:
interface Node {
  id: ID!
}

interface Group {
    id: ID!
    type: String!
}

type GroupA implements Node & Group {
    id: ID!
    type: String!
    # other fields
}

type GroupA implements Node & Group {
    id: ID!
    type: String!
    # other fields
}

type GroupEdge {
    cursor: String!
    node: Group!
}

type GroupConnection {
    edges: [GroupEdge!]!
    pageInfo: PageInfo!
    totalCount: Int!
}

According to the spec, "the [implementing] object type must include a field of the same name for every field defined in an interface." So, if an interface specifies that a field is of the type Foo, an implementing type cannot have the field be of type FooBar even if Foo is an interface and FooBar implements it. Unfortunately, that means it's not really possible to use interfaces like you're trying to do.
If you would like to utilize interfaces to provide a safety-net of sorts and ensure that the implementing types are consistent, you can do something like this:
interface Connection {
  pageInfo: PageInfo!
  # don't specify edges
}

interface Edge {
  cursor: String!
  # don't specify node
}

This way you can ensure that fields like pageInfo or cursor are present in the implementing types, have the correct type and are non-null. But this kind of schema-level validation is really the only benefit you get out adding and implementing these two interfaces.


Q: Executing server side code (node.js) on click of a button from within an HTML page generated through Jade I am trying to develop a web application and I am stuck at a point where I need some server side code to be executed on click of a button (through the onClick event handler and not the Submit button. I learnt how to route traffic that way through a form action). I am using Node.js, Express and Jade.
Can someone please help me. Here is my current code snapshot
I have made the following changes with respect to app.js to route the on-click traffic to this node.js function
app.post('/overview/delete-uni', uniappController.deleteUniversity);

Within the appropriate controller file I have added the deletion code
exports.deleteUniversity = function(req, res) {
  // Code logic
  // More code logic
  res.render('uniapp/university', {
  title: 'University'
  });

};
My Jade Template looks like this. Here when I click the Update button I need the deleteUniversity code to be executed
extends ../layout

block content

  .mdl-layout.mdl-js-layout.mdl-color--grey-100
      main.mdl-layout__content
        .mdl-grid
          #user
          for application in user.applications
            form.form-card.form-horizontal(action='/overview/update-uni', method='POST')
              input(type='hidden', name='_csrf', value=_csrf)
              .mdl-card.mdl-shadow--2dp
                .mdl-card__supporting-text
                  textarea#sample5.mdl-textfield__input(type='text', rows='1', name='universityName', readonly)
                    if application.university.name
                      | #{application.university.name}
                  .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label
                    textarea#sample5.mdl-textfield__input(type='text', rows='1', name='universityDescription')
                      if application.university.description
                        | #{application.university.description}
                    label.mdl-textfield__label(for='sample5') Description of university...
                .mdl-card__actions.mdl-card--border
                  button.mdl-button.mdl-button--colored.mdl-js-button.mdl-js-ripple-effect(type='submit')
                    | Update
                .mdl-card__menu
                  button.mdl-button.mdl-button--icon.mdl-js-button.mdl-js-ripple-effect
                    i.material-icons delete

P.S : I am a complete noob w.r.t Jade and hence please forgive me if this is something trivial.

A: Create a javascript file deleteUni.js (or whatever you want to call it) and add this to your template script(src="/Scripts/deleteUni.js")
//content of name.js
$(function(){

    var isButtonDisabled = false;
    $('#buttonId').click(function($event){

        //this part handles multiple button clicks by the user, trust me on this one, it's really important to have it
        if (isButtonDisabled){
            return $event.preventDefault();
        }
        isButtonDisabled = true;

        var formData = $('#formId').serialize(); //serialize form to a variable

        $.post( "/overview/delete-uni",formData)
         .success(function(response){
            //handle response

         })
         .fail(function(error){
            //handle error
         })
         .always(function(){
            //always execute
            .
            .
            .
            isButtonDisabled = false;
         });

        return $event.preventDefault();
    })
});


Q: Can dynamic import of @mdi/js icon work with tree-shaking in a vue template? I have the following component to dynamically import an icon from mdi/js. The only problem with this is that it doesn't do tree-shaking. Does anyone know how to make tree-shaking work with this kind of setup? I can use this anywhere like
<Icon name='mdiMagnify'>
Icon.vue
<template>
    <v-icon v-bind="$attrs">{{ icon }}</v-icon>
</template>

<script>
export default {
    name: 'Icon',
    props: {
        name: {
            required: true,
            type: String,
        },
    },
    data: () => ({
        icon: null,
    }),
    async created() {
        const { [this.name]: icon } = await import('@mdi/js')
        this.icon = icon
    },
}
</script>

The reason behind this is, I won't be needing to import each and every icon that i need in all my components and passing it to a data variable to be able to be utilized in vue template.

A: if you're using nuxt.js (which I suppose you do since you have the tag on your question), it's pretty easy, just add the following in your nuxt.config.js:
vuetify: {
  defaultAssets: false,
  treeShake: true,
  icons: {
    iconfont: 'mdiSvg',  // --> this should be enough

    // sideNote: you can also define custom values and have access to them
    // from your app and get rid of the imports in each component

    values: {
      plus: mdiPlus, // you have access to this like $vuetify.icons.values.plus from your component
    }
  }
}

for the values to work you just have to import the appropriate icon in the nuxt.config.js like:
import { mdiPlus } from '@mdi/js'

or if you don't like the custom values you can import the needed icons for each component in the component itself and use them there like:
import { mdiPlus } from 'mdi/js'
...
data() {
  return {
    plusIcon: mdiPlus
  }
}

A: What I ended up doing currently is to have all the svg in @mdi/svg package and use that as an img src. That way, I won't have to deal with dynamically importing it from @mdi/js and hoping for a treeshake.


Q: How do I configure my Route config to get a URL Pattern like localhost/Product (Controller)/List (Action)/Category (Id)? As the title says all about what I want but to be kind of specific I would like to have a URL pattern like localhost/Product/List/Category/Page but I couldn't succeed finding a solution for it. I am sure it's belong to routing and as it is difficult topic in MVC I would need your help to find a solution for it.
My route config is:
 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(null, "",
                new
                {
                    controller = "Home",
                    action = "Shop",

                });
            routes.MapRoute(null, "",
                new
                {
                    controller = "Product",
                    action = "list",
                    category = (string)null,
                    page = 1
                }
                );
            routes.MapRoute(null, "Page{page}",
            new
            {
                controller = "Product",
                action = "List",
                category = (string)null,
                subcategory = (string)null
            },
            new { page = @"\d+" }
            );

            routes.MapRoute(null,
            "{category}",
            new { controller = "Product", action = "List", page = 1 }
            );
            routes.MapRoute(null,
            "{category}/Page{page}",
            new { controller = "Product", action = "List" },
            new { page = @"\d+" }
            );
            routes.MapRoute(null, "{controller}/{action}");
        }
    }

My Controller product is:
 public class ProductController : Controller
    {
        EFDbContext db = new EFDbContext();
        private IProductsRepository repository;
        public int PageSize = 4;

        public ProductController (IProductsRepository productrepository)
        {
            this.repository = productrepository;
        }
        public ViewResult List(string category, int page = 1)
        {
            ProductsListViewModel model = new ProductsListViewModel()
            {
                Products = repository.Products
                .Where(p => category == null || p.ProductCategory == category || p.MenSubCategory == category)
                    .OrderBy(p => p.ProductID)
                    .Skip((page - 1) * PageSize)
                    .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = category == null ? repository.Products.Count():repository.Products.Where(e => e.ProductCategory == category).Count()
                },
                CurrentCategory = category
            };
            return View(model);
        }

        public PartialViewResult Menu(string subcategory = null )
        {
            ViewBag.SelectedCategory = subcategory;
            IEnumerable<string> categories = repository.MenSubCategories
                .Select(x => x.MenSubCategory)
                .Distinct()
                .OrderBy(x => x);
            return PartialView(categories);
        }
}

I hope I get answer for this as far as I really tried but couldn't find how to do it.

A: With attribute routing, you just need to decorate your action method with your specific route pattern.
public class ProductController : Controller
 {
     EFDbContext db = new EFDbContext();
     private IProductsRepository repository;
     public int PageSize = 4;

     public ProductController (IProductsRepository productrepository)
     {
          this.repository = productrepository;
     }
     [Route("Product/list/{category}/{page}")]
     public ViewResult List(string category, int page = 1)
     {
       // to do  : Return something
     }
}

The above route definition will send the request like yourSite/Product/list/phones and yourSite/Product/list/phones/1 to the List action method and the url segments for category and page will be mapped to the method parameters.
To enable attribute routing, you need to call the method MapMvcAttributeRoutes
method inside the RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

A: To generate an URL like you want: localhost/Product/List/Cars you can create a custom route like this:
routes.MapRoute(
    name: "ProductList",
    url: "Product/List/{category}",
    defaults: new { controller = "Product", action = "List" }
);

Remember that custom routes have to come before the most general route (the one that comes with the default template).
Regarding your page parameter, if you are comfortable with this URL: localhost:3288/Product/List/teste?page=10 the above already work. But if you want this: localhost:3288/Product/List/teste/10 10 meaning the page number, then the simplest solution would be create two different routes:
routes.MapRoute(
   name: "ProductList",
   url: "Product/List/{category}",
   defaults: new { controller = "Product", action = "List" }
);

routes.MapRoute(
   name: "ProductListPage",
   url: "Product/List/{category}/{page}",
   defaults: new { controller = "Product", action = "List" , page = UrlParameter.Optional}
);

Another cleaner way, is to create a custom route constraint for your optional parameter. This question has a lot of answers to that:
ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+


Q: how to make Angular service only module scooped if its not a lazy loaded module So i m trying to make a module have a service which is module scoped. I have implemented a shared module which i would like to have it with a utils service only singleton to its components. other modules can only have instances of the utils service.
when i import this shared module in the app module, than somehow the utils service becomes singleton eventhough its not provided inside of the app module.
what is the logic behind of it ? And how can i achieve this when its not a route module which is lazy loaded ?
@NgModule({
  declarations: [FilterComponent],
  imports: [
  ],
  exports: [
    FilterComponent
  ],
  providers: [DataService]
})
export class SharedModule {
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule,
    CommonModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

@Injectable({
  providedIn: SharedModule
})
export class UtilsService {
  constructor() {
   console.log("created")
  }
}


Q: Do I need JDK to work with Eclipse Helios and Tomcat 7.0.33? I want to develop dynamic web applications.
For this I am using Eclipse Helios and Tomcat 7.0.33. I have the JRE installed on my machine and I have provided the location of the JRE in the JAVA_HOME path.
But when I am running any servlet, I get the error:

" HTTP Status 404  " --     " The requested resource is not available
  "

Do I need a JDK in place of the JRE (meaning I have to set the path of the JDK in place of the JRE)? Or could there be another other reason why this error is happening?
Looking for Help!

A: If your servlets are already compiled then JRE will serve the purpose,
But they are compiled then you will JDK and other libraries( like servlet-api.jar, etc.) to compile you servlets.
In short JDK is for development where you want to develop something using Java.
And JRE is used when you already have compiled classes and you just want to run it.
You might want to refer to this :
What is the difference between JDK and JRE?

A: In theory, compiling with Eclipse's incremental compiler is sufficient. Running the application server with a JRE should be fine as well. I suppose your error is somewhere else. Anyway, I'd strongly recommend installing a JDK for developing a Java application. It comes with some handy tools and many 3rd party tools (Maven, e.g.) also require a real JDK compiler and can't work with Eclipse's built in compiler.

A: I had the same problem. The JDK was not the issue.  After you compile your servlet you have to restart your tomcat server so it can load your class files before you try to access it through the web browser.  No more 404 errors after that, servlets are running fine.


Q: Creating mapkit's showsUserLocation pin ripple animation Has any one successfully created user location pin that has a ripple like effect that 4.x (or higher) mapkit gives when we use mkMakkit.showUserLoaction = YES;
If any one has done it please guide me how to do it or past sample code that does that effect.
The user location in the mapkit is read-only property. Has anyone able to move the pin from user actual location. That is in my senario when the user location is not available for cases like iTouch user can select his location, I don't want to show user at Infinite Loop,CA but the location he prefers to choose.


Q: How to parse nested function calls using Pyparsing? I'm developing a css parser but cannot figure out how to parse nested function calls like alpha(rgb(1, 2, 3), 0.5).
Here is my code:
# -*- coding: utf-8 -*-

from pyparsing import * #, Word, alphas, OneOrMore, countedArray, And, srange, hexnums,  Combine, cStyleComment

from string import punctuation
from app.utils.file_manager import loadCSSFile, writeFile
from pyparsing import OneOrMore, Optional, Word, quotedString, delimitedList,  Suppress
from __builtin__ import len

# divide tudo por espaços, tabulações e novas linhas
words = ZeroOrMore(cStyleComment | Word(printables))

digit = '0123456789'; underscore = '_'; hyphen =  '-'
hexDigit = 'abcdefABCDEF' + digit
letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
az_AZ_underscore = underscore + letter;
az_AZ_09_underscore = az_AZ_underscore + digit;
az_AZ_hyphen = hyphen + letter;
az_AZ_09_hiphen = az_AZ_hyphen + digit;
LPAR = Suppress('('); RPAR = Suppress(')')

# identifiers
identifier = Combine(Word(az_AZ_underscore) + Optional(Word(az_AZ_09_underscore)))
# identifiers
identifier_reserved = Combine(Word(az_AZ_hyphen) + Optional(Word(az_AZ_09_hiphen)))

# numbers
hexadecimal = Word(hexnums, min=1)
integer = Word(digit, min=1)
decimal = Combine('.' + integer | integer + Optional('.' + integer))

# value values
color_hex = Combine('#' +  hexadecimal )
at_identifier =  Combine('@' + identifier)
arg = at_identifier | color_hex | decimal | quotedString

function_call = identifier + LPAR + Optional(delimitedList(arg)) + RPAR

value =  Group(color_hex | at_identifier | function_call)

print(value.parseString('a(b())'))

I whould like to do something like     arg = at_identifier | color_hex | decimal | quotedString | function_call  but it's not possible because the variable is function_call is not declared yet.
How could I parse nested function calls using Pyparsing?

A: You are really very close. To define a recursive grammar like this, you need to forward-declare the nested expression.
As you have already seen, this:
arg = at_identifier | color_hex | decimal | quotedString
function_call = identifier + LPAR + Optional(delimitedList(arg)) + RPAR

only parses function calls with args that are not themselves function calls.
To define this recursively, first define an empty placeholder expression, using Forward():
function_call = Forward()

We don't know yet what will go into this expression, but we do know that it will be a valid argument type. Since it has been declared now we can use it:
arg = at_identifier | color_hex | decimal | quotedString | function_call

Now that we have arg defined, we can define what will go into a function_call. Instead of using ordinary Python assignment using '=', we have to use an operator that will modify the function_call instead of redefining it. Pyparsing allows you to use <<= or << operators (the first is preferred):
function_call <<= identifier + LPAR + Optional(delimitedList(arg)) + RPAR

This is now sufficient to parse your given sample string, but you've lost visibility to the actual nesting structure. If you group your function call like this:
function_call <<= Group(identifier + LPAR + Group(Optional(delimitedList(arg))) + RPAR)

you will always get a predictable structure from a function call (a named and the parsed args), and the function call itself will be grouped.


Q: Gson not loading in properly - Null object reference I'm trying to load in a local file into my Android application using Gson. Loading in the file works just fine. Here is what the Json looks like:
{"heroes" : [
  {
    "hero": {
      "name": "Hanzo",
      "role": "Offense",
      "abilities": {
        "primary": "left click",
        "secondary": "right click",
        "ultimate": "dragons"
      },
      "strongAgainst": [
        "Bastion",
        "Mercy"
      ],
      "weakAgainst": [
        "Genji",
        "Tracer"
      ]
    },
    "hero": {
      "name": "Torbjorn",
      "role": "Defense",
      "abilities": {
        "primary": "left click",
        "secondary": "right click",
        "ultimate": "lava bastard"
      },
      "strongAgainst": [
        "Lucio",
        "Mercy"
      ],
      "weak_against": [
        "Widowmaker",
        "Junkrat"
      ]
    }
  }
]}

I have created 3 POJOs with getters and setters like so:
public final class Heroes {
    private List<Hero> hero;
}

public class Hero {
    private HeroAttr hero;
}

public class HeroAttr {
    private String name;
    private String role;
    private Abilities abilities;
    private List<String> strongAgainst;
    private List<String> weakAgainst;
}

public class Abilities {
    private String primary;
    private String secondary;
    private String ultimate;
}

And I load in using Gson like so:
Gson gson = new GsonBuilder().create();
Heroes h = gson.fromJson(byteArrayOutputStream.toString(), Heroes.class);

And whenever I try to get the size or print something from h it gives me a null object reference and I am unable to get anything from the arraylist.
I've even tried making the json file only an array and using
Hero[] h = gson.fromJson(byteArrayOutputStream.toString(), Hero[].class);
but I get the same issue -- null object reference.
Any ideas? Thanks.

A: UPDATED
You got a problem in your JSON:
{
    "hero": {
        "name": "Hanzo",
        "role": "Offense",
        "abilities": {
            "primary": "left click",
            "secondary": "right click",
            "ultimate": "dragons"
        },
        "strongAgainst": [
            "Bastion",
            "Mercy"
        ],
        "weakAgainst": [
            "Genji",
            "Tracer"
        ]
    },
    "hero": {
        "name": "Torbjorn",
        "role": "Defense",
        "abilities": {
            "primary": "left click",
            "secondary": "right click",
            "ultimate": "lava bastard"
        },
        "strongAgainst": [
            "Lucio",
            "Mercy"
        ],
        "weak_against": [
            "Widowmaker",
            "Junkrat"
        ]
    }
}

This is not sane. An object defining hero property twice.
The full version should be:
{
    "heroes" : [
        {
            "name": "Hanzo",
            "role": "Offense",
            "abilities": {
                "primary": "left click",
                "secondary": "right click",
                "ultimate": "dragons"
            },
            "strongAgainst": [
                "Bastion",
                "Mercy"
            ],
            "weakAgainst": [
                "Genji",
                "Tracer"
            ]
        },
        {
            "name": "Torbjorn",
            "role": "Defense",
            "abilities": {
                "primary": "left click",
                "secondary": "right click",
                "ultimate": "lava bastard"
            },
            "strongAgainst": [
                "Lucio",
                "Mercy"
            ],
            "weak_against": [
                "Widowmaker",
                "Junkrat"
            ]
        }
    ]
}

Full code (back to three POJOs):
import com.google.gson.Gson;

import java.util.List;

public class Test {
    String json = "{\n" +
                  "    \"heroes\" : [\n" +
                  "        {\n" +
                  "            \"name\": \"Hanzo\",\n" +
                  "            \"role\": \"Offense\",\n" +
                  "            \"abilities\": {\n" +
                  "                \"primary\": \"left click\",\n" +
                  "                \"secondary\": \"right click\",\n" +
                  "                \"ultimate\": \"dragons\"\n" +
                  "            },\n" +
                  "            \"strongAgainst\": [\n" +
                  "                \"Bastion\",\n" +
                  "                \"Mercy\"\n" +
                  "            ],\n" +
                  "            \"weakAgainst\": [\n" +
                  "                \"Genji\",\n" +
                  "                \"Tracer\"\n" +
                  "            ]\n" +
                  "        },\n" +
                  "        {\n" +
                  "            \"name\": \"Torbjorn\",\n" +
                  "            \"role\": \"Defense\",\n" +
                  "            \"abilities\": {\n" +
                  "                \"primary\": \"left click\",\n" +
                  "                \"secondary\": \"right click\",\n" +
                  "                \"ultimate\": \"lava bastard\"\n" +
                  "            },\n" +
                  "            \"strongAgainst\": [\n" +
                  "                \"Lucio\",\n" +
                  "                \"Mercy\"\n" +
                  "            ],\n" +
                  "            \"weak_against\": [\n" +
                  "                \"Widowmaker\",\n" +
                  "                \"Junkrat\"\n" +
                  "            ]\n" +
                  "        }\n" +
                  "    ]\n" +
                  "}";

    static class Heroes {
        public List<Hero> heroes;
    }

    static class Hero {
        public String name;
        public String role;
        public Abilities abilities;
        public List<String> strongAgainst;
        public List<String> weakAgainst;
    }

    static class Abilities {
        public String primary;
        public String secondary;
        public String ultimate;
    }

    void go() {
        Gson gson = new Gson();
        Heroes h = gson.fromJson(json, Heroes.class);
        System.out.println(h.heroes.size());
        System.out.println(h.heroes.get(0).name);
    }

    public static void main(String[] args) {
        new Test().go();
    }
}


Q: How to delete an existing embed in DiscordJS (v12) I'm working on a small private Discord bot (mainly for learning)
I've been working on a feature where the bot sends a message, the user sends a response and the bot will delete the initial embed and follow up with another embed. (creating a chain of embedded messages to collect user input and build a final result from it)
Thus far this is what my code consists of
const wait = 30000;
    let count;

    const embed = new Discord.MessageEmbed()
        .setColor('#9EFF9A')
        .setTitle('Question?')
        .setDescription('');

    message.channel.send(embed);
    message.channel.awaitMessages(m => m.author.id == message.author.id,
        { max: 1, time: `${wait}` }).then(collected => {
        message.delete(embed);
        count = collected.first().content;
            console.log(count);
    }).catch(() => {
        message.delete(embed);
        return message.reply('No reply after ' + `${wait / 1000}` + ' seconds, operation canceled.').then(m => {
            m.delete({ timeout: 15000 });
        });
    });

I have tried various iterations of message.delete(); with no useful results, the bot usually ends up deleting the commanding message sent by the user to start the embed chain.
I got a suggestion from a friend that I also ended up seeing online a few times which was the following:
.then(() => {
message.delete()
})

I can't come up with any way to implement this into my current code.
Is there something I am misunderstanding? I am very new to DiscordJS and Javascript and my friend did mention that .then() statements can get pretty tricky

I appreciate any help I can get!

A: Your code is very close to achieving what you want, except you are attempting to delete the Embed object that you created instead of the Message object of the embed. Here's a slight tweak that will achieve what you need:
const wait = 30000;
let count;

const embed = new Discord.MessageEmbed()
    .setColor('#9EFF9A')
    .setTitle('Question?')
    .setDescription('');

message.channel.send(embed).then(embedMessage => {
    embedMessage.channel.awaitMessages(m => m.author.id == message.author.id,
    { max: 1, time: wait }).then(collected => {
        embedMessage.delete();
        count = collected.first().content;
        console.log(count);
    }).catch(() => {
        embedMessage.delete();
        return message.reply('No reply after ' + (wait / 1000) + ' seconds, operation canceled.').then(m => {
            m.delete({ timeout: 15000 });
        });
    });
})

The secret here is using .then() on the method that sends the embed. This allows you to obtain the actual Message object of the embed that was sent, which you can then interact with. Now that you have the Message object for your embed, you can directly interact with the message using its methods, such as delete() and edit().

A: .then(() => {
   message.delete()
})

Is not working because you never passed in the message as a parameter, therefor your embed does not exist in the context of .then()
You can try using .then() or await to delete a send message.
then Method
// const embed = ...
message.channel.send(embed).then(msg => {
   msg.delete();
});

Await Method
// Make sure you're in an async function
//const embed = ...
const msg = await message.channel.send(msg);
msg.delete();

A: I am not to familiar with discordjs but from what I understand you create a message with the bot under the variable "message" which has the properties seen here:
https://discord.js.org/#/docs/main/master/class/Message
Then you use that message to send an embed to the message's channel. The embed ask's a question and you then await for ensuing messages. You then want to take the first response and put it into the count variable. Then you want to delete the original embed. If this is all true I would suggest deleting the original message that houses the embed itself like so:
message.channel.awaitMessages(m => m.author.id == message.author.id,
    { max: 1, time: `${wait}` }).then(collected => {
    message.delete();
    count = collected.first().content;
        console.log(count);
})

Or try this but I don't think this method will work:
message.channel.awaitMessages(m => m.author.id == message.author.id,
    { max: 1, time: `${wait}` }).then(collected => {
    embed.delete();
    count = collected.first().content;
        console.log(count);
})

I would check out these two pages of documentation:
https://discord.js.org/#/docs/main/master/class/Message?scrollTo=delete
https://discord.js.org/#/docs/main/master/class/MessageEmbed
Welcome to Stack Overflow tell me if one of these worked.


Q: Apache: Can't open .php files I want to start learning PHP, so I installed Apache2, MySQL and PHP5 on my Ubuntu 10.10 today. For some reason, when I try to open a file other than index.html from the default directory /var/www/, I either get a 404 error or I get a prompt to download the php file. I googl'd all over and I can't find a solution.
When I do http://localhost/index.html, it works, and displays whatever I write in index.html. When I change /index.html to /test.php, I get an error saying "The requested URL /test.php was not found on this server".
When I try /var/www/index.html or file:///var/www/index.html, again, index.html appears although it appears differently. When opened with http://localhost/index.html I only get "It works!", but with /var/www/index.html I get "It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet."
And then when I change /var/www/index.html to /test.php, I get a prompt to download test.php.
In my .conf files, the default directory is set to /var/www/, so this is very weird.
Edit:
Did some checking, and it seems that when I run http://localhost it's set to a directory in the httpd directory. I tried putting my test.php file there, and still I'm getting 404. But when I write the full path, again, I get a download prompt.
This problem is really confusing... thanks to all helpers.

A: Check to see if PHP has been enabled in the Apache httpd.conf file. See here for further details: http://www.devarticles.com/c/a/Apache/Using-Apache-and-PHP-on-Mac-OS-X/

A: Ok.. seems that I found the solution myself. For some weird reason, I have like 4 different localhost default folders. I had to search manually through each folder containing index.html and move test.php there. Eventually, I found an obscure folder somewhere in the /usr/ folder, moved test.php to there, and it worked. Apparently I have like 4 different versions for each .conf file, and each one states a different thing. Only one of them works.
Phew. What a relief.


Q: How to update profile picture for existing model instance? I'm trying to update a user's profile photo after they've already created their account. I'm using an abstract user model connected to a model called Person. For additional context, I have my application connected to AWS to deploy to Heroku.
I have a form, model, url and view set up but I'm sure I'm missing some piece to the puzzle.

<form action="{% url 'update-photo' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    {{ form|crispy }}

    <input type="submit" class="btn btn-lg custom-bg">

  </form>

class User(AbstractUser):

    is_active = models.BooleanField(default=False)

class Person(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    upload = models.FileField(default='core/static/images/default_avatar.png')

class UpdatePhotoForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = ('upload',)

@login_required
def update_photo(request):
    person = Person.objects.get(user=request.user)
    from core.forms import UpdatePhotoForm
    if request.method == "POST":
        form = UpdatePhotoForm(data=request.POST, instance=request.user.person)
        if form.is_valid():
            person = form.save(commit=False)
            person.save()
            return redirect('profile')
    else:
        form = UpdatePhotoForm()
    return render(request, 'core/edit_profile.html', {'form': form})

    path('update_photo/', core_views.update_photo, name='update-photo'),

The form submits without any error but does not actually update the user's photo. I can change the photo in the admin site but not via the form. Any help would be greatly appreciated!

A: You will have to fetch file field from request Object with following code:
form = UpdatePhotoForm(data=request.POST, files=request.FILES, instance=request.user.person)


Q: node.js redis smembers synchronously I wonder if it's possible to implement synchronous retrieval of smembers of redis with node_redis.
_.each(seeds, function(subseed, key, list){

    client.smembers(subseed, function (err, replies) {
        retrieved = retrieved.concat(replies)
    })
})
client.quit();
console.log("start")
console.log(retrieved.length)

OUTPUT:
start
0
10

So it looks like I need somehow to get to the point when smembers finishes it's run, ot alternatively to run smembers in synchronous mode.
How can I solve this problem?

A: Why do you want to make it synchronous?
If you want to do something after members, just do it in callback function.
var callback=function(res){
    retrived=retrieved.concat(res);
    //continue do other things
};

client.smembers("offer", function (err, replies) {
    if(!err){
        callback(replies);
    }
})

If you want to do something after a loop,you can try _.after of underscore.js,for example:
var times=10;

var arrayOfReplies=[]; //store all replies
var callback=function(){
    //do something with arrayOfReplies
}

var afterAll = _.after(times,callback); //afterAll's callback is a function which will be run after be called 10 times

for(var i=0;i<10;i++){
    client.smembers("offer", function (err, replies) {
        if(!err){
            arrayOfReplies=arrayOfReplies.concat(replies);
            afterAll();
        }
    })
}

see more:http://underscorejs.org/#after


Q: Recursive python script found = 0
def new(string):
    global found

    if found > len(string):
        return 0

    fish = string.find('x',found,len(string))
    found = fish + 1

    return new(string) + 1

text = 'onxonxoinxoinoxn'
final_text = text + 'x'
print new(final_text)

So I'm new to recursion and i know there is a much easier way to do this but can someone explain how to fix this.this is basically a recursive function to find the total number of times a letter 'x' can be found in the variable 'text'.
This is my error:
4
7
11
16
18
0
4
7
Traceback (most recent call last):
11
16
  File "/Users/Charana/Documents/Projects/untitled/Main.py", line 18,

in
        new(final_text)
    RuntimeError: maximum recursion depth exceeded
so it works but it continues to loop.how do i make it stop
thankyou in advance

A: found > len(string)

This condition will never be true, because str.find will always return a result < len(s).
The correct return value to check for when there was no result is -1. But you need to be careful with the increment, since that will change the invalid result -1 to 0 continuing the loop. So you should reorder your logic a bit:
def new(string):
    global found

    fish = string.find('x',found,len(string))
    if fish < 0:
        return 0

    found = fish + 1
    return new(string) + 1

Note that using global variables for such a function, especially for recursive functions, is a bad idea. You don’t have full control over it, and instead, you also need to make sure that you reset its value when you call the function. Instead, you should keep all the information inside, and pass it around to the recursive calls if necessary. You could change your function like this:
def new (string, found = 0):
    fish = string.find('x', found)
    if fish < 0:
        return 0
    return new(string, fish + 1) + 1

This uses default parameter values to make sure that found starts with 0. And for the recursive call, it just passes the new found value, so the next function can start there.
Finally note, that you should try to use descriptive names for your functions and variables. The function is supposed to count the number of occurrences of 'x', so maybe count_x would be better. Also, the variable found in that context conveys a meaning that it contains the number of occurrences of x that you have already found; but instead, it’s the start offset from which to continue the search; and fish is just bad, as it’s just the index of the next 'x':
def count_x (string, offset = 0):
    index = string.find('x', offset)
    if index < 0:
        return 0
    return count_x(string, index + 1) + 1

Finally, just in case you don’t know, there is also a built-in function str.count which does the same thing :)


Q: Pandas pivot table: Aggregate function by count of a particular string I am trying to analyse a DataFrame which contains the Date as the index, and Name and Message as columns.
df.head() returns:
            Name           Message
Date
2020-01-01  Tom            image omitted
2020-01-01  Michael        image omitted
2020-01-02  James          image Happy new year you wonderfully awfully people...
2020-01-02  James          I was waiting for you image
2020-01-02  James          QB whisperer image

This is the pivot table I was trying to call off the initial df, which the aggfunc being the count of the existence of a word (eg. image)
df_s = df.pivot_table(values='Message',index='Date',columns='Name',aggfunc=(lambda x: x.value_counts()['image']))

Which ideally would show, as an example:
 Name        Tom    Michael   James
 Date
 2020-01-01    1       1        0
 2020-01-02    0       0        3

For instance, I've done another df.pivot_table using
df_m = df.pivot_table(values='Message',index='Date',columns='Name',aggfunc=lambda x: len(x.unique()))

Which aggregates based off the number of messages in a day and this returns the table fine.
Thanks in advance

A: Use Series.str.count for number of matched values to new column added to DataFrame by DataFrame.assign and then pivoting with sum:
df_m = (df.reset_index()
          .assign(count= df['Message'].str.count('image'))
          .pivot_table(index='Date',
                       columns='Name',
                       values='count' ,
                       aggfunc='sum',
                       fill_value=0))
print (df_m)
Name        James  Michael  Tom
Date
2020-01-01      0        1    1
2020-01-02      3        0    0

A: This is for the fun of it, and an alternative to the same answer. It is just a play on the different options Pandas provides :
      #or df1.groupby(['Date','Name']) if the index has a name
res = (df1.groupby([df1.index,df1.Name])
          .Message.agg(','.join)
          .str.count('image')
          .unstack(fill_value=0)
      )

res

Name      James   Michael   Tom
Date
2020-01-01  0       1        1
2020-01-02  3      0         0


Q: Why it's not possible to reach nested type, declared in interface, through inheriting type in C#? Let's say we have a situation like this:
    // Declare `Nested` struct inside class and interface

    class Base {
        public struct Nested {}
    }
    interface IBase {
        public struct Nested {}
    }

    // Inherit them

    class ThroughClass: Base {}
    class ThroughInterface: IBase {}

    // Try reaching `Nested` class through above types

    class Test {
        ThroughClass.Nested c;     // OK
        ThroughInterface.Nested i; // Error CS0426: The type name 'Nested' does not exist in the type 'ThroughInterface'
    }

Why it's not possible to reach Nested here using ThroughInterface? Is this a compiler bug, or design choice (I can't find any documentation related to that)?


Q: jQuery '.each' and attaching '.click' event I am not a programer but I enjoy building prototypes. All of my experience comes from actionScript2.
Here is my question. To simplify my code I would like to figure out how to attach '.click' events to div's that are already existing in the HTML body.

dog

cat

mouse

My (failed) strategy was:
1) make an array of objects:
var props = {
"dog": "false",
"cat": "true",
"mouse": "false"
};

2) iterate through the array with '.each' and augment each existing div with a '.click' event. Lastly, construct a local variable.
here is a prototype:
$.each(props, function(key, value) {
$('#'+key+'-selected').click(function(){
var key = value;
});
});

A: No need to use .each. click already binds to all div occurrences.
$('div').click(function(e) {
    ..
});

See Demo
Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

A: One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.
For example:
HTML:

dog

cat

mouse

JS:
$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id');
    });
});


Q: Spread function in R with multiple fields which constitute the key Im working to transform my table in this way so i can join it on another table. Here is a sample of what my initial table looks like:
df1 <- data.frame(ID = c(1,1,1,2,2,2,3,3,3),
                  date=c('2021-11-01', '2021-11-01', '2021-11-02','2021-11-01',
                         '2021-11-01', '2021-11-02','2021-11-01', '2021-11-01', '2021-11-02'
                         ),
                  event_name = c('a', 'a', 'c', 'a', 'b', 'b','a', 'b', 'c'),
                  Time_duration = c(1, 3, 5, 9, 2, 4, 1, 6, 8))

And this is an example of how I'd like the data to look after spreading it:
df2 <- data.frame(ID = c(1,1, 2,2, 3,3),
                  date=c('2021-11-01', '2021-11-02',
                         '2021-11-01', '2021-11-02',
                         '2021-11-01', '2021-11-02'
                         ),
                  event_A_duration_sum = c(4, 0,
                                       9, 0,
                                       1,0),
                  event_B_duration = c(0, 0,
                                       2, 4,
                                       6,0),
                  event_C_duration = c(0, 5,
                                       0, 0,
                                       0,8))

In my final table, I need to have the data grouped by (ID, Date); a unique identified for my final table would be both the ID and date. Each ID and date can have multiple events of the same type, for instance.
I hope this makes sense. Should I concatenate my identifiers and then split them back, after? Or is there a better way to do this using DPLYR?
Cheers, appreciate any help.

A: library(data.table)

dcast(data.table(df1),
ID + date ~ event_name,value.var = 'Time_duration',
 fun.aggregate = sum)

Key: <ID, date>
      ID       date     a     b     c
   <num>     <char> <num> <num> <num>
1:     1 2021-11-01     4     0     0
2:     1 2021-11-02     0     0     5
3:     2 2021-11-01     9     2     0
4:     2 2021-11-02     0     4     0
5:     3 2021-11-01     1     6     0
6:     3 2021-11-02     0     0     8


Q: exit() doesn't work anymore (Python 3.10? New Pycharm version? Windows 11?) I used to close the console automatically when there was an error with:
exit()

However, I reinstalled everything on my new laptop (worth noting it's windows 11 maybe ?), exit() doesn't work anymore and returns :
To exit the PyDev Console, terminate the console within IDE.

Is it because I have a newer version of PyCharm (currently using 2021.3.1 community edition on my new laptop), Python 3.10.1 instead of Python 3.9, or Windows 11 instead of Windows 10 ?
I can use:
import sys
sys.exit()

in the meantime.
But it's longer and makes me import sys when I used to not have to.
Anyone knows what's happening?
Thank you very much!
EDIT : ON ANOTHER IDE (same laptop) exit() WORKS. I therefore assume it's a PyCharm related problem.


Q: oracle sql - missing dates from range I've created the following script ...
SELECT
  gr.RESERVATION_NO,
  gr.TITLE,
  gr.CATNR,
  gl.DUEDATE,
  gr.CRE_USR,
  gl.QTY,
  gl.WORK_CENTER_NO,
  gl.TEC_CRITERIA,
  gr.RESERVE_QTY,
  gl.PLANT,
  studate.dt
FROM GPS_RESERVATION gr,
    (Select first_date + Level-1 dt
    From
    (
        Select trunc(sysdate) first_date,
        trunc(sysdate)+60 last_date
        from dual
    )
        Connect By Level <= (last_date - first_date) +1 ) studate
  INNER JOIN GPS_RESERVATION_LOAD gl
          ON gl.work_center_no = 'ALIN'
         AND gl.duedate = studate.dt
         AND gl.plant = 'W'
WHERE gr.RESERVATION_NO = gl.RESERVATION_NO
  AND gr.ACTIVE_FLAG  =  'Y'
  AND gr.reservation_no = '176601'
ORDER BY
  gl.DUEDATE

I expected to see ALL DATES from sysdate to sysdate+60 but, I only get dates where duedate exists.
i.e.
I get...

I expected...

What am I doing wrong please ?
Thanks for your help.

A: You're mixing older Oracle join syntax with newer ANSI join syntax which is a bit confusing, and might trip up the optimiser; but the main problem is that you have an inner join between your generated date list and your gl table; and you then also have a join condition in the where clause which keeps it as an inner join even if you change the join type.
Without the table structures or any data, I think you want:
...
FROM (
    Select first_date + Level-1 dt
    From
    (
        Select trunc(sysdate) first_date,
        trunc(sysdate)+60 last_date
        from dual
    )
    Connect By Level <= (last_date - first_date) +1
  ) studate
  CROSS JOIN GPS_RESERVATION gr
  LEFT OUTER JOIN GPS_RESERVATION_LOAD gl
          ON gl.work_center_no = 'ALIN'
         AND gl.duedate = studate.dt
         AND gl.plant = 'W'
         AND gl.RESERVATION_NO = gr.RESERVATION_NO
WHERE gr.ACTIVE_FLAG = 'Y'
  AND gr.reservation_no = '176601'
ORDER BY
  gl.DUEDATE

The cross-join gives you the cartesian product of the generated dates and the matching records in gr; so if your gr filter finds 5 rows, you'll have 300 results from that join. The left outer join then looks for any matching rows in gl, with all the filter/join conditions related to gl within that on clause.
You should look at the execution plans for your query and this one, firstly to see the difference, but more importantly to check it is joining and filtering as you expect and in a sensible and cost-effective way. And check the results are correct, of course... You might also want to look at a version that uses a left outer join but keeps your original where clause, and see that that makes it go back to an inner join.


Q: Should I build my gradle project using the Dockerfile I'm reading about dockerization of Spring Boot applications and all (or almost all) tutorials are based on some simple Dockerfile like
FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

It usually work (however you may need to change some build target paths) but as far as I understand it requires us to build the application jar before the docker build command will be run.
I'm actually working with Gradle but for the Maven, I guess, it looks the same.
My question is: is it good convention?
If I'll download some repostitory and run docker build, regardless having proper Dockerfile, it will fail because there is no target/*.jar file (at least if someone did not commit the /build directory :P).
Should we then include some ./gradlew build commands in the Dockerfile?

A: https://github.com/palantir/gradle-docker
you should use this project
or
jar_path=$(find . |grep $APP_NAME|grep jar|grep -v original|grep -v repository|grep -v templates)
mv $jar_path ./app.jar


Q: PluginManager::get was unable to fetch or create an instance for getObjectManager So my problem is to use Doctrine 2 with Zend Framework 2. I installed Doctrine correctly and when I tried to use it in the controller I get this error :
C:\wamp2\www\zf2\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:518

and this :
Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for getObjectManager

This is my controller :
class BlogController extends AbstractActionController
{

    public function blogAction()
    {
        $article = $this->getObjectManager()->getRepository('\Application\Entity\Article')->findAll();

        return new ViewModel(array('article' => $article));
    }
}

This is my view:
<?php if (isset($article)) : ?>
    <?php foreach($article as $articles): ?>

<?php echo $articles->getTitle(); ?>

                <?php echo $articles->getDate(); ?>

<?php echo $articles->getContent(); ?>

            <a href="<?php echo $this->url('article') ?>" class="btn btn-default btn-lg">Read More

    <?php endforeach; ?>
<?php endif; ?>

For the configuration I followed this tutorial

A: Sadly you didn't follow the tutorial, otherwise you'd have noticed that inside the tutorial they define a function getObjectManager() inside the Controller. You don't define this function and therefore the Controller assumes this to be a ControllerPlugin and therefore asks the ControllerPluginManager to create an instance for this plugin. But no such Plugin was ever registered and that's why you see this error.
TL/DR -> do the tutorial step by step. Understand what you're doing, don't blindly copy paste the lines you think are important.

A: You forgot to implement the getObjectManager for your controller :
protected function getObjectManager()
    {
        if (!$this->_objectManager) {
            $this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
        }

        return $this->_objectManager;
    }

this method is included at the end of the IndexController in the tutorial you mentionned.


Q: Pig Changing Schema to required type I'm a new Pig user.
I have an existing schema which I want to modify. My source data is as follows with 6 columns:
Name        Type    Date        Region    Op    Value
-----------------------------------------------------
john        ab      20130106    D         X     20
john        ab      20130106    D         C     19
jphn        ab      20130106    D         T     8
jphn        ab      20130106    E         C     854
jphn        ab      20130106    E         T     67
jphn        ab      20130106    E         X     98

and so on. Each Op value is always C, T or X.
I basically want to split my data in the following way into 7 columns:
Name        Type    Date        Region    OpX    OpC   OpT
----------------------------------------------------------
john        ab      20130106    D         20     19    8
john        ab      20130106    E         98     854   67

Basically split the Op column into 3 columns: each for one Op value. Each of these columns should contain appropriate value from column Value.
How can I do this in Pig?

A: One way to achieve the desired result:
IN = load 'data.txt' using PigStorage(',') as (name:chararray, type:chararray,
       date:int, region:chararray, op:chararray, value:int);
A = order IN by op asc;
B = group A by (name, type, date, region);
C = foreach B {
  bs = STRSPLIT(BagToString(A.value, ','),',',3);
  generate flatten(group) as (name, type, date, region),
    bs.$2 as OpX:chararray, bs.$0 as OpC:chararray, bs.$1 as OpT:chararray;
}

describe C;
C: {name: chararray,type: chararray,date: int,region: chararray,OpX:
    chararray,OpC: chararray,OpT: chararray}

dump C;
(john,ab,20130106,D,20,19,8)
(john,ab,20130106,E,98,854,67)

Update:
If you want to skip order by which adds an additional reduce phase to the computation, you can prefix each value with its corresponding op in tuple v. Then sort the tuple fields by using a custom UDF to have the desired OpX, OpC, OpT order:
register 'myjar.jar';
A = load 'data.txt' using PigStorage(',') as (name:chararray, type:chararray,
      date:int, region:chararray, op:chararray, value:int);
B = group A by (name, type, date, region);
C = foreach B {
  v = foreach A generate CONCAT(op, (chararray)value);
  bs = STRSPLIT(BagToString(v, ','),',',3);
  generate flatten(group) as (name, type, date, region),
    flatten(TupleArrange(bs)) as (OpX:chararray, OpC:chararray, OpT:chararray);
}

where TupleArrange in mjar.jar is something like this:
..
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;

public class TupleArrange extends EvalFunc<Tuple> {

    private static final TupleFactory tupleFactory = TupleFactory.getInstance();

    @Override
    public Tuple exec(Tuple input) throws IOException {
        try {
            Tuple result = tupleFactory.newTuple(3);
            Tuple inputTuple = (Tuple) input.get(0);
            String[] tupleArr = new String[] {
                    (String) inputTuple.get(0),
                    (String) inputTuple.get(1),
                    (String) inputTuple.get(2)
            };
            Arrays.sort(tupleArr); //ascending
            result.set(0, tupleArr[2].substring(1));
            result.set(1, tupleArr[0].substring(1));
            result.set(2, tupleArr[1].substring(1));
            return result;
        }
        catch (Exception e) {
            throw new RuntimeException("TupleArrange error", e);
        }
    }

    @Override
    public Schema outputSchema(Schema input) {
        return input;
    }
}


Q: From Cider, in Emacs, is there a way to restart Figwheel to detect new dependencies? I added a new dependency to my Clojurescript app, and I want to know if I can run a function, maybe something like (restart-figwheel) to restart Figwheel. I read you have to restart Figwheel to detect new dependencies.

A: At this time, I don't think you can do this. You need to quit your current figwheel session and restart in order to pick up new dependencies added to your :dependencies in your project.clj file. In fact, the figwheel docs also recommend running lein clean before you restart figwheel to be sure you don't end up with some old code.
I think this functionality is on the roadmap, but is not a high priority. There is considerable complexity in being able to have this functionality work reliably - especially if you add in the complexity of different repl environments (such as using piggyback, and cider with figwheel).
Note that this limitaiton is just with :dependency items in the project.clj. You can add :require lines in your cljs files dynamically and have them picked up (asusming the library is already in the dependencies list of course).
I suspect part of the compicaiton is ensuring the classpath is updated and that all processes already running which use the classpath are somehow updated and making sure all loaded classes are reloaded in case the dependency changes the dependencies of those loaded classes to keep things consistent.


Q: How to get destination point? I am trying to navigation application on Mapbox with Unity. I want to get destination point from the user. I mean that user will write to where it wants to go and i will plot the road on the map according to destination point.
I tried reload map scrip, but it is just geolocate the map.
    namespace Mapbox.Examples
{
    using Mapbox.Geocoding;
    using UnityEngine.UI;
    using Mapbox.Unity.Map;
    using UnityEngine;
    using System;
    using System.Collections;

    public class ReloadMap : MonoBehaviour
    {
        Camera _camera;
        Vector3 _cameraStartPos;
        AbstractMap _map;

        [SerializeField]
        ForwardGeocodeUserInput _forwardGeocoder;

        [SerializeField]
        Slider _zoomSlider;

        private HeroBuildingSelectionUserInput[] _heroBuildingSelectionUserInput;

        Coroutine _reloadRoutine;

        WaitForSeconds _wait;

        void Awake()
        {
            _camera = Camera.main;
            _cameraStartPos = _camera.transform.position;
            _map = FindObjectOfType<AbstractMap>();
            if(_map == null)
            {
                Debug.LogError("Error: No Abstract Map component found in scene.");
                return;
            }
            if (_zoomSlider != null)
            {
                _map.OnUpdated += () => { _zoomSlider.value = _map.Zoom; };
                _zoomSlider.onValueChanged.AddListener(Reload);
            }
            if(_forwardGeocoder != null)
            {
                _forwardGeocoder.OnGeocoderResponse += ForwardGeocoder_OnGeocoderResponse;
            }
            _heroBuildingSelectionUserInput = GetComponentsInChildren<HeroBuildingSelectionUserInput>();
            if(_heroBuildingSelectionUserInput != null)
            {
                for (int i = 0; i < _heroBuildingSelectionUserInput.Length; i++)
                {
                    _heroBuildingSelectionUserInput[i].OnGeocoderResponse += ForwardGeocoder_OnGeocoderResponse;
                }
            }
            _wait = new WaitForSeconds(.3f);
        }

        void ForwardGeocoder_OnGeocoderResponse(ForwardGeocodeResponse response)
        {
            if (null != response.Features && response.Features.Count > 0)
            {
                int zoom = _map.AbsoluteZoom;
                _map.UpdateMap(response.Features[0].Center, zoom);
            }
        }

        void ForwardGeocoder_OnGeocoderResponse(ForwardGeocodeResponse response, bool resetCamera)
        {
            if (response == null)
            {
                return;
            }
            if (resetCamera)
            {
                _camera.transform.position = _cameraStartPos;
            }
            ForwardGeocoder_OnGeocoderResponse(response);
        }

        void Reload(float value)
        {
            if (_reloadRoutine != null)
            {
                StopCoroutine(_reloadRoutine);
                _reloadRoutine = null;
            }
            _reloadRoutine = StartCoroutine(ReloadAfterDelay((int)value));
        }

        IEnumerator ReloadAfterDelay(int zoom)
        {
            yield return _wait;
            _camera.transform.position = _cameraStartPos;
            _map.UpdateMap(_map.CenterLatitudeLongitude, zoom);
            _reloadRoutine = null;
        }
    }
}

In the direction example, it is just return geojson file. I could not able to plot the route on the map according to writing location. How can i define the destination point on the map by text.

A: For this you can use the directions API inside of the Unity SDK. Check out the traffic and directions example. You'll see how the response is being drawn as a line and rendered on a map. The DirectionsFactory.cs script draws a line along the route with the assigned material.