Q: can not resolve method getProjection() and getMapCenter() i am implementing long click to get latlang on mapview,
i referred this tutorial. but i am getting error
here is my code:
import com.google.android.gms.vision.barcode.Barcode;
public class MyCustomMapView extends MapView {

    public interface OnLongpressListener {
        public void onLongpress(MapView view, Barcode.GeoPoint longpressLocation);
    }
    static final int LONGPRESS_THRESHOLD = 500;
    private Barcode.GeoPoint lastMapCenter;
    private Timer longpressTimer = new Timer();
    private MyCustomMapView.OnLongpressListener longpressListener;

    public MyCustomMapView(Context context) {
        super(context);
    }

    public void setOnLongpressListener(MyCustomMapView.OnLongpressListener listener) {
        longpressListener = listener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        handleLongpress(event);

        return super.onTouchEvent(event);
    }
    private void handleLongpress(final MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // Finger has touched screen.
            longpressTimer = new Timer();
            longpressTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Barcode.GeoPoint longpressLocation = getProjection().fromPixels((int)event.getX(),
                            (int)event.getY()); <--here -->

                    longpressListener.onLongpress(MyCustomMapView.this, longpressLocation);
                }

            }, LONGPRESS_THRESHOLD);

            lastMapCenter = **getMapCenter()**;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {

            if (!getMapCenter().equals(lastMapCenter)) {
                longpressTimer.cancel();
            }

            lastMapCenter = getMapCenter();<-- here -->
        }

        if (event.getAction() == MotionEvent.ACTION_UP) {
            longpressTimer.cancel();
        }

        if (event.getPointerCount() > 1) {
            longpressTimer.cancel();
        }
    }
}

here my getProjection() and getMapCenter() cant resolve, i want to know why its happening, is this method deprecated, or what method i have to use instead,
and i also want to know that why its barcode.GeoPoint,
why my program importing
import com.google.android.gms.vision.barcode.Barcode;     instead of
import com.google.maps.GeoPoint;

A: You can implement GoogleMap.OnMapClickListener and  GoogleMap.OnMapLongClickListener to achieve this
public class CreateFenceActiviy extends AppCompatActivity implements GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener{
    private GoogleMap mGoogleMap;
    private SupportMapFragment mMapFragment;
    private ArrayList<double[]> mLatLongArray =null;
    private Polygon mPolygon;
    private PolygonOptions mPolygonOptions;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_fence_activity);
        mLatLongArray = new ArrayList<double[]>();
        if (mGoogleMap == null) {
                mMapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_create_fence));
                mGoogleMap = mMapFragment.getMap();
                mGoogleMap.setOnMapClickListener(this);
                mGoogleMap.setOnMapLongClickListener(this);
                mGoogleMap.setOnMarkerClickListener(this);
                isMarkerClicked = false;
            }

    }
    @Override
    public void onMapClick(LatLng point) {
        if(mGoogleMap != null){
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
            isMarkerClicked = false;
        }
    }

    @Override
    public void onMapLongClick(LatLng point) {
        if(mGoogleMap != null) {
            mGoogleMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
            double latitudeNew = point.latitude;
            double longitude = point.longitude;
            mLatLongArray.add(new double[]{latitudeNew, longitude});
            isMarkerClicked = false;
        }
    }
}

XML for Map view will contain this component
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map_create_fence"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


Q: Get list of values from grandchildren records I'm trying to access the grandchildren records in a list to avoid duplicate records.  In this example, a tag can only be used once across articles for a given author.  I will use the resulting list of grandchildren records in my clean function to return validation errors.
class Article(models.Model):
    tag = models.ManyToManyField(Tag)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Tag(models.Model):

class Author(models.Model):

Right now I can do this:
print(author.articles.first().tag.first())
Travel

I'd like to be able to use something like author.articles.tags.all() to return the list and check the submitted form against it to raise a ValidationError message to the user.
How can this be done efficiently with the basic Many-to-Many setup without creating an intermediate table for the tag relationships?  This is solely in the Admin interface, in case that matters at all.

A: i come from the link you posted on upwork,
the way i understand your question,
what you want to achieve seems to be impossible ,
what i think can work , is to fetch articles related to the author, with their corresponding tags,
after that they are retrieved you do filtering and remove duplicates.
otherwise the tag has nothing to connect it with the author,,

A: The Django ORM is pretty cool when you get used to it, but regular SQL is pretty cool too
# created_at, updated_at, name and tag_val are variables I
# added due to my slight ocd lol

class Author(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Tag(models.Model):
    tag_val = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Article(models.Model):
    author = models.ForeignKey(Author,related_name='articles', on_delete=models.CASCADE)
    tags = models.ManyToManyField(Tag, related_name='articles')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

I can write my query like this, assuming the variable 'author' has been assigned an Author object instance, and get a list of dictionaries [{'tags':1},{'tags':2}] where the value is the auto generated primary key id of the Tag object instance
author.articles.values('tags').distinct()

A: I'm so jealous that's a great answer @since9teen94
Be aware, I will not base my answer in the easiest solution but how we model reality (or how we should do it).
We put tags after things exists right?
In that order I will make your life horrible with something like this:
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=30, null=False)

class Article(models.Model):
    name = models.CharField(max_length=30, null=False)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Tag(models.Model):
    name = models.CharField(max_length=30, null=False, unique=True)
    articles = models.ManyToManyField(Article)

but believe me you don't want to follow this approach it will make your work harder.
You can search for Articles based on Tags directly
Tag.objects.filter(name='Scify').first().articles.all() # name is unique

The real issue with this is that the reverse lookup is really complex (I mean.. get ready for debug)
Article.objects.filter(
    id__in=list(
        Tag.objects.filter(name='Scify').first().articles.values_list('id', flat=True)
    )
)

I am sure this does not solve your problem and I don't like complex code for no reason but if you're open to suggestions I don't mind to think different and add some options
Edit:
About the author and clean repeated tags.. well you don't have to deal with that and if you want to find all Tag your author has you could loop the tags
for tag in Tag.objects.all():
    if tag.articles.filter(author__name='StackoverflowContributor'):
        print(tag.name)
# > Scify

I am just saying that there are options not that this is the best for you but don't be afraid of the terminal, it's really cool


Q: Multiple filter in single function using angularjs I try to filter two values like this | filter:{voucher_type: selectedName } | filter:{voucher_type: both }
Here both is "B" and selectedName "P or R". Below code work only one filter only.
I want to combine this two filter values together and show the result like voucher_type B + P (Or) R.

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
    <title>search</title>

            <form class="form-search" ng-controller="autocompleteController">
              Selected Ledger: {{selectedLedgers}}

              <input type="text" ng-model="both">

select voucher :<select ng-model="selectedName" ng-options="x for x in names">
                </select>

              <input type="text" ng-model="selectedLedgers" placeholder="Search Ledger" typeahead="c as c.ledger_id +  '-'+ c.ledger_name for c in producers | filter:$viewValue| limitTo:20 | filter:{voucher_type: selectedName1 } | filter:{voucher_type: both }" typeahead-min-length='2' typeahead-on-select='onSelectPart($item, $model, $label)' typeahead-template-url="search" class="form-control" style="width:350px;">

            </form>

Find my demo project here https://jsfiddle.net/basilbkodakk/sk549x4m/2/ .there have 3 company x,y,z .list box show x and y . z is common for x,y .that filter method in angularjs


Q: Should I still respond to html if view is rendered with javascript? I have a Rails application integrated with react, my views are rendered with react, including the html (JSX). I noticed that I had a few format.html responses from back when my views were regular erb views, now that they are not, should I still respond to html just in case (even  though I don't see how a user can use my app if they javascript have disabled)?
Example :
 def destroy
    @comment.destroy
    respond_to do |format|
      format.json { head :no_content }
      format.html { redirect_to @question, notice: 'Comment was deleted.' }
    end
  end

Can I get rid of the html responses?

A: Whether to keep it or not is a personal choice. I sometimes do, but fewer LOC makes for cleaner code. To remove it you have several options. You can leave the respond_to as is and just remove the html eg:
def destroy
  @comment.destroy
  respond_to do |format|
    format.json { head :no_content }
  end
end

but you can also remove the respond_to from each action (even fewer LOC) with something like this:
# put this LOC at the top of your controller, outside of any action
respond_with :json

# then each action is much simpler... you just assume it's always json
def destroy
  @comment.destroy
  head :no_content
end


Q: Python: how to deal with several .pyd dependencies with the same name? I have in my python workspace two Modules which need sip.pyd
Module1.pyd needs sip.pyd (which implements v 8.0-8.1)
Module2.pyd needs sip.pyd (another file, that implements v6.0)
So I can't just choose the newer one, it doesn't work: I have to keep them both!
(RuntimeError: the sip module implements API v6.0 but the fbx module requires API v8.1)

How can I import a module in .pyd extension (a python dll, not editable), and specify which sip.pyd to source?
As for a workaround, I manage to do that:

*

*One sip.pyd is in my root site-packages location.

*If I have to import the module that need the other sip.pyd, I remove root path form sys.path, and I append the precise folder path where the other sip.pyd are.

*I can import my Module and restore previous sys.path.

A: VirtualEnv is done to handle those case.

virtualenv is a tool to create isolated Python environments.

Using virtualenv, you will be able to create 2 environements, one with the sip.pyd in version 8.x another in version 6.0

A: Assuming you don't have a piece of code needing both files at once. I'd recommend the following:

*

*install both files in 2 separate directories (call them e.g. sip-6.0 and sip-8.0), that you'll place in site-packages/

*write a sip_helper.py file with code looking like
sip_helper.py contents:
import sys
import re
from os.path import join, dirname
def install_sip(version='6.0'):
    assert version in ('6.0', '8.0'), "unsupported version"
    keep = []
    if 'sip' in sys.modules:
       del sys.modules['sip']
    for path in sys.path:
        if not re.match('.*sip\d\.\d', path):
            keep.append(path)
    sys.path[:] = keep # remove other paths
    sys.path.append(join(dirname(__file__), 'sip-%s' % version))

*

*put sip_helper.py in site_packages (the parent directory of the sip-6.0 and sip-8.0 directories)

*call sip_helper.install_sip at the startup of your programs

A: I don't know if that works (if a module's name has to match its contents), but can't you just rename them to sip6.pyd resp. sip8.pyd and then do
if need6:
    import sip6 as sip
else:
    import sip8 as sip

?


Q: Draw polygon with hole inside I need to draw a rectangle polygon with a rectangle hole inside. I found this piece of code but I couldn't manage to understand how I can modify to meet my requirement.
 figure()
 p  = [0 0; 0 1; 1 1; 1 0]; %ccw
 pp = [0 0; 1 0; 1 1; 0 1]; %cw
 ph = p + [1.2 0];
 # add hole
 ph(end+1,:) = nan;
 ph = [ph; (pp-[0.5 0.5])*0.5+[1.7 0.5]];
 po = polygon2patch (ph);
 patch (po(:,1), po(:,2), 'b', 'facecolor', 'c');
 axis image

A: The polygon2patch function certainly seems useful, but maybe for only drawing two rectangles, you could also use just two patch commands, and simply set the inner rectangle, i.e. the hole, to white foreground color, like so:
outer = [0 0; 2 0; 2 1; 0 1];
inner = [0.4 0.2; 1.6 0.2; 1.6 0.8; 0.4 0.8];
patch(outer(:, 1), outer(:, 2), 'c');
patch(inner(:, 1), inner(:, 2), 'w');
axis equal;

This will produce such an output:

Hope that helps!


Q: Grouping and Aggregating on multiple time series Im new to python and pandas and have some basic question about how to write a short function which takes a pd.Dataframe and returns relative values grouped by month.
Example data:
import pandas as pd
from datetime import datetime
import numpy as np

date_rng = pd.date_range(start='2019-01-01', end='2019-03-31', freq='D')
df = pd.DataFrame(date_rng, columns=['date'])
df['value_in_question'] = np.random.randint(0,100,size=(len(date_rng)))
df.set_index('date',inplace=True)
df.head()

       value_in_question
date
2019-01-01  40
2019-01-02  86
2019-01-03  46
2019-01-04  75
2019-01-05  35

def absolute_to_relative(df):
    """
    set_index before using
    """
    return df.div(df.sum(), axis=1).mul(100)

relative_df = absolute_to_relative(df)

relative_df.head()

       value_in_question
date
2019-01-01  0.895055
2019-01-02  1.924368
2019-01-03  1.029313
2019-01-04  1.678228
2019-01-05  0.783173

Rather than taking the column sum and devide each row by that,
I would like to have the sum groupby each month. The final df should have the same
shape and form but the row values relate to sum of the month.
old:
             value_in_question
date
"2019-01-01" value/colum_sum * 100

new:
            value_in_question
date
"2019-01-01" value/month_sum * 100

So I tried the following, which returns NA for value_in_question:
def absolute_to_relative_agg(df, agg):
    """
    set_index before using
    """
    return df.div(df.groupby([pd.Grouper(freq=agg)]).sum(), axis=1)

relative_df = absolute_to_relative(df, 'M')
      value_in_question
date
2019-01-01  NaN
2019-01-02  NaN
2019-01-03  NaN
2019-01-04  NaN
2019-01-05  NaN

A: Use GroupBy.transform instead aggregation for Series/DateFrame with same DatatimeIndex like original, so possible division:
def absolute_to_relative_agg(df, agg):
    """
    set_index before using
    """
    return df.div(df.groupby([pd.Grouper(freq=agg)]).transform('sum'))

relative_df = absolute_to_relative_agg(df, 'M')

Another way for call function is DataFrame.pipe:
relative_df = df.pipe(absolute_to_relative_agg, 'M')

print (relative_df)
           value_in_question
date
2019-01-01           0.032901
2019-01-02           0.045862
2019-01-03           0.048853
2019-01-04           0.008475
2019-01-05           0.041376
                      ...
2019-03-27           0.062049
2019-03-28           0.002165
2019-03-29           0.048341
2019-03-30           0.007937
2019-03-31           0.015152

[90 rows x 1 columns]

A: For the sums, you can groupby the index month:
In [31]: month_sum = df.groupby(df.index.strftime('%Y%m')).sum()
    ...: month_sum
    ...:
Out[31]:
        value_in_question
201901               1386
201902               1440
201903               1358

You can then use .map to align the month with the correct rows of your DataFrame:
In [32]: map_sum = df.index.strftime('%Y%m').map(month_sum['value_in_question'])
    ...: map_sum
    ...:
Out[32]:
Int64Index([1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386,
            1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386,
            1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1440, 1440,
            1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440,
            1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440,
            1440, 1440, 1440, 1440, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
            1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
            1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
            1358, 1358],
           dtype='int64')

Then you just need to do the division:
In [33]: df['value_in_question'].div(map_sum)
Out[33]:
date
2019-01-01    0.012987
2019-01-02    0.018759
2019-01-03    0.000000
2019-01-04    0.056277
2019-01-05    0.019481
                ...
2019-03-27    0.031664
2019-03-28    0.007364
2019-03-29    0.050074
2019-03-30    0.033873
2019-03-31    0.005155
Name: value_in_question, Length: 90, dtype: float64

A: Use Grouper with freq='M'.
The code is:
relative_df = df.groupby(pd.Grouper(freq='M'))\
    .value_in_question.apply(lambda x: x.div(x.sum()).mul(100))

It returns a Series with index the same like in original DataFrame
and values equal to relative value_in_question for the current month.


Q: Can anyone solve the error in Spark databricks My SQL request:
SELECT Incident Number FROM fireIncidents where Incident Date='04/04/2016'

Error in SQL statement:

ParseException:
mismatched input 'Date' expecting {, ';'}(line 1, pos 57)

A: You have a space in Incident Date column.
If you want spark to know the column has space, use ` symbol in start and end of col.
Same as Incident Number col.
SELECT `Incident Number` FROM fireIncidents where `Incident Date`='04/04/2016'

If your Incident Date col is a date, you can cast it to spark format, use
select `Incident Date`, to_date(`Incident Date`, 'dd/MM/yyyy') FROM fireIncidents""").show()

which yields
+-------------+----------------------------------+
|Incident Date|to_date(Incident Date, dd/MM/yyyy)|
+-------------+----------------------------------+
|   04/04/2016|                        2016-04-04|
|   04/04/2016|                        2016-04-04|
|   04/04/2016|                        2016-04-04|
+-------------+----------------------------------+


Q: How to use window lag function to partition the data with multiple sensor types I'm, trying to use the postgres LAG function to calculate a difference in absolute time between two sampling dates for each sensor in the system.
The best I have come up with is to use WINDOW LAG function to calculate a difference from earlier line. However there are two problems with this. The first value is always null. I'd guess I can solve this using a CASE function. Second is that it does not take each sensor value explicitly.
SELECT
    seq_id, stream_id, sensor, "timestamp", oper_value
    "timestamp" - LAG("timestamp",1) OVER (ORDER BY "timestamp") delta
    FROM public.mt_events
    where "type" = 'operational_value_event'
    limit 100;

The data is logged when threshold breached (including hysteresis) and therefore some values are changed more often than other. There are no fixed intervals in when the data is logged.
The end goal to to get a value that have atleast a certain amount of time difference.
Example data:
id stream_id sensor oper_value timestamp
44 100000000    GT1         17 2018-05-16 13:36:21.899821+00
45 100000000    GT2         44 2018-05-16 14:36:21.000000+00
88 100000000    GT1         26 2018-05-18 12:33:22.000000+00
94 100000000    GT1         99 2018-05-18 12:33:23.002000+00

For example if a selection of data with at least time difference of 5 minutes I would like to get the following values:
id stream_id sensor oper_value timestamp
44 100000000    GT1         17 2018-05-16 13:36:21.899821+00
45 100000000    GT2         44 2018-05-16 14:36:21.000000+00
88 100000000    GT1         26 2018-05-18 12:33:22.000000+00

The last GT1 is filtered out since the difference was less than 5 minutes.
Is there any way of doing this effectively using a SQL statement or do I need to write a stored procedure?
Cheers,
 Mario

A: You can use the three-argument form of lag() with partition by:
("timestamp" -
 LAG("timestamp", 1, "timestamp") OVER (PARTITION BY sensor ORDER BY "timestamp")
) as delta

For your ultimate problem, the NULL value for the first row doesn't matter.  You can solve the problem using a subquery:
select *
from (select seq_id, stream_id, sensor, "timestamp", oper_value ,
             lag("timestamp") over (partition by sensor order by timestamp) as prev_timestamp
      from public.mt_events
      where "type" = 'operational_value_event'
     ) t
where delta is null or
      prev_timestamp < timestamp - interval '5 minute';


Q: add typings for missing method (from a npm package) I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)
I tried to merge the definitions from node_modules with my own declaration.
declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;

the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)
Here's how I import cropper in an angular component.
import * as Cropper from 'cropperjs';
Here's my tsconfig.json (parts of it)
 "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs"
]

I tried it with my custom typings folder an with the tripple slash reference notation.
But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module
P.S.
I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).

A: As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here.
If the @types/cropperjs would have been written using interfaces, you could have extended that interface using your own declaration.
Here is an ugly hack you can do for now:
import * as Cropper from 'cropperjs';

interface MyCropper extends Cropper {
  scale(scaleX: number, scaleY?: number): void;
}

function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper {
  return new Cropper(dom, options) as MyCropper;
}

casting is always ugly, but at least you hide it in one place, I think it's reasonable...

A: Just wanted to add another possible "solution". I say "solution" because it's in my opinion quite ugly but then again it's a workaround.
After seeing and reading (see Aviad Hadad's answer) that class merging is not possible and read about typescripts node module resolution
Basically if you import an non-relative path like import * as Cropper from 'cropperjs typescript will look for the appropriate files in a folder named node_modules and it starts in the directory in which the file with the import statement resides. It then traverses up (example taken from the typescript documentation)

*

*/root/src/node_modules/moduleB.ts

*/root/node_modules/moduleB.ts

*/node_modules/moduleB.ts (I assume that's the global node_modules directory)

Since typescript will also look for d.ts files I copied the whole index.d.ts from the @types/cropperjs package, renamed it to cropperjs.d.ts and put it in a folder named /root/src/node_modules. (and added the missing method)
if you trace the resolution with tsc --traceResolution you'll see that typescript will take the d.ts file from the custom node_modules directory.
The advantage with this solution is that you don't have to touch your code. As soon as @types/cropperjs has updated the missing method you can just delete your custom node_modules directory and everything will still work.
Disadvantage is you have to copy and paste code around.


Q: How to remove unused blocks of code from a source code file? Let’s suppose I have a bunch of source code files (C or Delphi, i.e., *.c or *.pas). I want to purge them of blocks of text which are not used in the compilation. Those blocks are:

*

*Comments. They can be removed with regexp. (But, for example, Delphi
uses the preprocessor directives which look like comments (“{ is it
a comment or a directive? }”), so the regexp would not be trivial.)

*But the most tricking part is the blocks of code which are excluded
from the compilation with #ifdef. These blocks have to be removed
too.

So, the question is: “Is there a way to do it with some program or script?” Let’s suppose there is a program that can be given a source code file and a list of defined symbols to distinguish unused blocks of code, and it would spit out the cleansed file I want to get.


Q: Quasar Vue: Set static width content on Grid Style I'm very new in dynamic web programming but I get a little problem with Quasar Grid Gutter.
I have string on array with different word and length, I want to show them in Button with grid style. So I use Grid Gutter to build this. But I want the size of card is always static (etc width: 200), so add style="width: 100px". But if width too small and text length too long, the height is getting weird. If add height:50px the width is not work. Here is a codepen sample.
I try the Offset too but I can set the padding between Button.


Q: Blackberry SQLite optimal performance I've overcome many hurdles while trying to work with SQLite on Blackberry. Now I've reached the point where everything seems to work fine and I'm looking for ways to speed up my queries.
Sometimes my app retrieves a lot of data from a web service call, this data is parsed and stored into my database. A lot of DELETE, INSERT and UPDATE going on. The database calls seem to be taking a lot of time.
I would like to know some best practices when dealing with SQLite. Preferably from people who have experience with it on the Blackberry platform specifically. Any tricks to speed up DELETEs or INSERTs etc....
Links to good tutorials would be great. Or some snippets of useful code even better.
Thanks in advance.
EDIT:
Here is some sample code from Blackberry using transactions.
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.*;
import net.rim.device.api.io.*;
public class UsingTransactions extends UiApplication
{
public static void main(String[] args)
{
    UsingTransactions theApp = new UsingTransactions();
    theApp.enterEventDispatcher();
}
public UsingTransactions()
{

}
}

class UsingTransactionsScreen extends MainScreen
{
    Database d;
public UsingTransactionsScreen()
{
   LabelField title = new LabelField("SQLite Using Transactions Sample",
   LabelField.ELLIPSIS |
   LabelField.USE_ALL_WIDTH);
   setTitle(title);
   add(new RichTextField(
          "Updating data in one transaction in MyTestDatabase.db."));
   try
   {
      URI myURI = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
          "MyTestDatabase.db");
      d = DatabaseFactory.open(myURI);

      d.beginTransaction();
      Statement st = d.createStatement("UPDATE People SET Age=7 " +
          "WHERE Name='Sophie'");
      st.prepare();
      st.execute();
      st.close();
      st = d.createStatement("UPDATE People SET Age=4 " +
          "WHERE Name='Karen'");
      st.prepare();
      st.execute();
      st.close();
      d.commitTransaction();
      d.close();
 }
 catch ( Exception e )
 {
      System.out.println( e.getMessage() );
      e.printStackTrace();
 }
  }
}

Is there a reason why they're closing the statement every time?? Isn't it better just to close it once at the end (in a Finally block perhaps??).

A: The standard technique is to use a prepared insert statement, inside a loop inside a transaction. That will give you almost optimal efficiency in most instances. It will speed things up by at least an order of magnitude.

A: I personally don't know many blackberry-specific practices, but these seem to be helpful (sorry I couldn't find code snippets):
"Top 8 SQL Best Practices"
"Best Practice: Optimizing SQLite Database Performance"
Hope these help!

A: You should do one thing is that, create different methods for database handling code.
and simply call these methods from your main code and open and close database also in each and every block. It will reduce redundancy and will be better for your future. This will also helps you in your App performance.


Q: Contact form not sending email and no notification working on contact form for my website. All tree form fields are validating correctly somehow the email is not send but looks page is loading again. Can anyone check my code and tell me where could be a problem here. Would like temail to be sent and notification to the user shown.
Contact form:
<form role="form" id="contactForm">

                 <input type="text" class="form-control" name="name" id="name" placeholder="Wpisz swoje imię, nazwisko" required="required">

                <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" required>

            <textarea id="message" name="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>

        <button type="submit" id="form-submit" class="btn-block">Wyślij wiadomość</button>

Message Submitted!

    </form>

Java sripts within same html file as form:

PHP file (process.php) :
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$EmailTo = "roger@gth.com.pl";
$Subject = "New Message Received";

// send email
$success = mail($EmailTo, $Subject, $message, $email);

// redirect to success page
if ($success){
   echo "success";
}else{
    echo "invalid";
}

?>

for further dicussion:
my top code:
<!DOCTYPE html>

            <meta http-equiv="content-type" content="text/html; charset=UTF-8">

            <title>my site</title>
            <link rel="shortcut icon" href="img/ico.png">

            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="description" content="jakiś wyraz">
            <meta name="keywords" content="">
            <meta name="author" content="strona">

            <link href="bootstrap-assets/css/bootstrap.min.css" rel="stylesheet">

            <link href="plugins/owl-carousel/owl.carousel.css" rel="stylesheet">
            <link href="plugins/owl-carousel/owl.theme.css" rel="stylesheet">
            <link href="plugins/owl-carousel/owl.transitions.css" rel="stylesheet">
            <link href="plugins/Lightbox/dist/css/lightbox.css" rel="stylesheet">
            <link href="plugins/Icons/et-line-font/style.css" rel="stylesheet">
            <link href="plugins/animate.css/animate.css" rel="stylesheet">
            <link href="css/main.css" rel="stylesheet">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

i notice couple errors in console please help me also to fix it.:
error type: SCRIPT5009: '$' is undefined
on this line:
$("#contactForm").validator().on("submit", function (event) {

error type: SCRIPT5009: '$' is undefined
at the end on own.carousel script here:
});

A: You haven't loaded the jQuery library (or at least prior to attempting to use it based on your  tag from above), add:

before useing the $ function.
After jQuery has resolved, remove the syntax error cased by the extra } in your submitForm function -right in between the ) and the ;.


Q: Nested 'for' loop in Racket shows error 'not a procedure' I have the following code lines to do bubble sort in Racket. I find the syntax correct but it is still showing error:
(define List (list 1 3 5 7 9 2 4 6 8 0))
(define Left  0)
(define Right 0)

(for ([I (range (- (length List) 1))])
  (for ([J (range (+ I 1) (length List))])
    (set! Left  (list-ref List I))
    (set! Right (list-ref List J))

    (when (> Left Right)
      [(set! List (list-set List I Right))
       (set! List (list-set List J Left ))]
    )
  )
)

The error is:
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: #<void>
  arguments...:
   #<void>
  context...:
   /home/jdoodle.rkt:6:2: for-loop
   /home/jdoodle.rkt:5:0: for-loop
   top-level: [running body]
   eval-one-top12
   begin-loop
   loop

Can't guess it out why. I tested it on https://www.jdoodle.com/execute-racket-online but it didn't work.

A: I found the answer, sorted it out. I must add the expression begin for multiple statements after when. Not the double parentheses.
(for ([I (range (- (length List) 1))])
  (for ([J (range (+ I 1) (length List))])
    (set! Left  (list-ref List I))
    (set! Right (list-ref List J))

    (when (> Left Right)
      (begin
        (set! List (list-set List I Right))
        (set! List (list-set List J Left ))
))))

Or just a series of forms after when:
(for ([I (range (- (length List) 1))])
  (for ([J (range (+ I 1) (length List))])
    (set! Left  (list-ref List I))
    (set! Right (list-ref List J))

    (when (> Left Right)
      (set! List (list-set List I Right))
      (set! List (list-set List J Left ))
)))


Q: Phoenix - client requested channel transport error While running my Phoenix app, I suddenly noticed an error being logged:
The client's requested channel transport version "2.0.0" does not match server's version requirements of "~> 1.0"
It appears after starting the server with mix phoenix.server:
[info] Running MyApp.Endpoint with Cowboy using http://localhost:4000
21 Nov 13:47:19 - info: compiled 4 files into app.js, copied robots.txt in 2.3 sec
[error] The client's requested channel transport version "2.0.0" does not match server's version requirements of "~> 1.0"

and then continues to log the error message every 10 seconds or so, regardless of whether or not I'm making any requests to the server.  Despite this, the app seems to run fine, but it'd be great to resolve this.
Can anyone shed any light on why this would've suddenly started happening, and what I can do to fix it?
Here's some config info from mix.exs:
def application do
 [mod: {MyApp, []},
  applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext,
                :phoenix_ecto, :postgrex, :comeonin]]
end

defp deps do
  [{:phoenix, "~> 1.2.1"},
   {:phoenix_pubsub, "~> 1.0"},
   {:phoenix_ecto, "~> 3.0"},
   {:postgrex, ">= 0.0.0"},
   {:phoenix_html, "~> 2.6"},
   {:phoenix_live_reload, "~> 1.0", only: :dev},
   {:gettext, "~> 0.11"},
   {:cowboy, "~> 1.0"},
   {:cors_plug, "~> 1.1"},
   {:comeonin, "~> 3.0"},
   {:guardian, "~> 0.14"},
   {:guardian_db, "~> 0.8.0"}]
end


Q: How to convert short array to BitSet with 2 bit precision in Java? I have a short array {0,2,3,1,…} which I would like to convert to a BitSet.
Expected bits in bitset: 00 10 11 01 …
Every two bit in the bitset should represent a short. (2-bit precision)
This should work fine for short values (0,1,2,3).
I know that I can use ByteBuffer and BitSet to access the bits of the numbers but those are formatted into 2 bytes (16 bit). I assume I need to bitshift the values to access the correct bits but I don't know how.
int nBit = 0;
BitSet result = new BitSet();
for (int i = 0; i < numbers.length; i++) {
  ByteBuffer buffer = ByteBuffer.allocate(2);
  buffer.putShort(number);
  BitSet bits = BitSet.valueOf(buffer.array());

  result.set(nBit++, bits.get(?));
  result.set(nBit++, bits.get(?));
}

It there maybe an easier way?

A: My current pragmatic solution which may be okay since only 4 values need to be handled:
public static BitSet transformToBitSet(short[] numbers) {
        BitSet data = new BitSet();
        int nBit = 0;
        for (int i = 0; i < numbers.length; i++) {
            short number = numbers[i];
            switch (number) {
            case 0:
                data.set(nBit++, false);
                data.set(nBit++, false);
                break;
            case 1:
                data.set(nBit++, true);
                data.set(nBit++, false);
                break;
            case 2:
                data.set(nBit++, false);
                data.set(nBit++, true);
                break;
            case 3:
                data.set(nBit++, true);
                data.set(nBit++, true);
                break;
            default:
                throw new RuntimeException("Invalid number encountered. Can't map values >4");
            }
        }
        return data;
    }

A: Here is one way to do it.

*

*set the desired bitLength (used for padding on the left with zero bits);

*initialize the BitSet index to 0.

*The iterate over the values.

*convert each to a bit string.

*pad on the left to achieve the desired bit length

*then set the bits based on the numeric value of the bit

BitSet b = new BitSet();
short[] vals = { 0, 2, 3, 1 };

int bitLength = 2;
int idx = 0;
for (short v : vals) {
    String bits = Integer.toBinaryString(v);
    bits = "0".repeat(bitLength - bits.length())+bits;
    for (char c : bits.toCharArray()) {
        b.set(idx++, c - '0' == 1);
    }
}
System.out.println(b)

prints
2,4,5,7


Q: Direct X 11 Texturing FX file error X3004 undiclared identifier "input" I am trying to texture a cube but when i try to run the progam the fx file thows error X3004 undiclared identifier "input" but input is declared near the top so i don't understand whats going wrong. I have tried for 4 day's plz help.
This code includes diffuce lighting as well as texturing. i believe that output.tex=input.tex is the problem but im not sure.
Texture2D txDiffuse : register(t0);
SamplerState samLinear : register(s0);

float4 textureColour = txDiffuse.Sample(samLinear, input.Tex);

struct VS_INPUT
{

    float4 Pos : POSITION;
    float2 Tex : TEXCOORD0;

};

struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : TEXCOORD0;
};

//--------------------------------------------------------------------------------------
// Constant Buffer Variables
//--------------------------------------------------------------------------------------
cbuffer ConstantBuffer : register( b0 )
{
    matrix World;
    matrix View;
    matrix Projection;

    float4 DiffuseMtrl;
    float4 DiffuseLight;
    float3 LightVecW;

}

//--------------------------------------------------------------------------------------
struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float4 Color : COLOR0;
    float2 Tex : TEXCOORD0;
};

//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
//guroud shading with diffuse lighting
VS_OUTPUT VS(float4 Pos : POSITION, float3 NormalL : NORMAL)
{
    VS_OUTPUT output = (VS_OUTPUT)0;

    output.Pos = mul(Pos, World);
    output.Pos = mul(output.Pos, View);
    output.Pos = mul(output.Pos, Projection);

    // Convert from local space to world space
    // W component of vector is 0 as vectors cannot be translated
    float3 normalW = mul(float4(NormalL, 0.0f), World).xyz;
        normalW = normalize(normalW);

    // Compute Colour using Diffuse lighting only
    float diffuseAmount = max(dot(LightVecW, normalW), 0.0f);
    output.Color.rgb = diffuseAmount * (DiffuseMtrl * DiffuseLight).rgb;
    output.Color.a = DiffuseMtrl.a;

    return output;

    output.Tex = input.Tex;
}

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( VS_OUTPUT input ) : SV_Target
{
    return input.Color;
}

error
Framework.fx(12,53-57): error X3004: undeclared identifier 'input'

A: You're trying to sample a texture (on line 4) outside of any function. Where do you expect this code to run, in the vertex shader (VS) or the pixel shader (PS)?
Remove line 4 and change your pixel shader to:
return txDiffuse.Sample(samLinear, input.Tex);

You seem to have some structures that aren't used at all (VSINPUT, PSINPUT). The last line of the vertex shader won't compile either because you're using "input.Tex" and the vertex shader has no variable called "input". If you're not going to use them, change the first line of the VS to:
VS_OUTPUT VS(float4 Pos : POSITION, float3 NormalL : NORMAL, float2 Tex : TEXCOORD0)

and the end of the shader to be:
output.Color.a = DiffuseMtrl.a;
output.Tex = Tex;
return output;


Q: Intelij uses 100% of CPU -> vmware is extremely slow I'm getting an usage 100% when the Intelij is running. After 20 min I cannot do anything on VMWARE and then I am forced to supsend or restart VM.
I tried to remove rm /var/crash/* but it did not help.
May you please advice me how to resolve the slowness problems?


Q: Deduping a StringBuilder List of Items in C# I have a situation where I need to dedupe a list of columns in a SQL select statement that is being generated with a StringBuilder. I need to return a StringBuilder object as well.
The solution I came up with works but it looks like a dang nightmare. Can someone suggest a cleaner way to achieve this?
//The SQL statement is being passed to my code as a StringBuilder
//This is just scaffolding to fake that input.
StringBuilder items = new StringBuilder();
items.Append("SELECT ");
items.Append("Apple,");
items.Append("Carrot,");
items.Append("Pear,");
items.Append("Orange,");
items.Append("Apple");
items.Append(" From fruit_table");
//End scaffolding

//My code start:
//Chop off the non-important parts
items.Replace("SELECT ", "");
items.Replace(" From fruit_table", "");

//Convert string to list, seperating on commas
List<string> itemList = items.ToString().ToUpper().Split(',').ToList<string>();

//Found a handy "distinct" method in LINQ library
itemList = itemList.Distinct().ToList();

//Wipe out the original stringbuilder. For clarity and consistency with some other code, I'd like to reuse the same stringBuilder that was passed to me.
items.Clear();

//Rebuild my stringbuilder, now deduped
items.Append("SELECT ");
itemList.ForEach(x => items.Append(x + ","));
//Remove that comma after last fruit item
items.Remove((items.Length - 1), 1);
items.Append(" FROM fruit_table");

//Not really going to output to console, but you
//get the idea.
Console.WriteLine(items.ToString());
Console.ReadLine();

Thank you in advance for any assistance!

A: If you are stuck with starting with the StringBuilder then I think you've pretty much worked out what you need to do.
I would make it a little cleaner like this though:
var prefix = "SELECT ";
var suffix = " From fruit_table";
var result =
    String.Format("{0}{2}{1}",
        prefix,
        suffix,
        String.Join(",",
            items
                .ToString()
                .Replace(prefix, "")
                .Replace(suffix, "")
                .Split(',')
                .Select(x => x.Trim())
                .Distinct()));
items.Clear();
items.Append(result);

Before:
SELECT Apple,Carrot,Pear,Orange,Apple From fruit_table

After:
SELECT Apple,Carrot,Pear,Orange From fruit_table

If you know that there are no spaces between the names of the columns, then this is slightly cleaner:
var result =
    String.Format("{0}{2}{1}",
        prefix,
        suffix,
        String.Join(",",
            items
                .ToString()
                .Split(' ')[1]
                .Split(',')
                .Distinct()));

A: Here's another way to do it without having to hard-code the prefix and suffix elements:
// Encapsulate the behavior in an extension method we can run
// directly on a StringBuilder object
public static StringBuilder DeduplicateColumns(this StringBuilder input) {
    // Assume that we can split into large "chunks" on spaces
    var sections = input.ToString().Split(' ');
    var resultSections = new List<string>();

    foreach (var section in sections) {
        var items = section.Split(',');

        // If there aren't any commas, spit this chunk back out
        // Otherwise, split on the commas and get distinct items
        if (items.Count() == 1)
            resultSections.Add(section);
        else
            resultSections.Add(string.Join(",", items.Distinct()));
    }

    return new StringBuilder(string.Join(" ", resultSections));
}

Test code:
var demoStringBuilder = new StringBuilder
    ("SELECT Apple,Carrot,Pear,Orange,Apple From fruit_table");
var cleanedBuilder = demoStringBuilder.DeduplicateColumns();

// Output: SELECT Apple,Carrot,Pear,Orange From fruit_table

Here's a fiddle: link


Q: MySQL to google charts PHP         <?php
        $con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!");
        mysql_select_db("data", $con);

        $sth = mysql_query("SELECT * FROM data");

        $data = array (
      'cols' => array(
        array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'),
        array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'),
        array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number')
    ),
    'rows' => array()
);

while ($res = mysql_fetch_assoc($sth))
    // array nesting is complex owing to to google charts api
    array_push($data['rows'], array('c' => array(
        array('v' => $res['date']),
        array('v' => $res['temp1']),
        array('v' => $res['temp2'])
    )));
}
?>

I am having problem finishing this, echo count($bar_chart_rows_arr) AND echo count($task_submissions_arr) is showing corresponding good results (number of rows in table). The chart frame is showing but there are no table/chart data. Any suggestions ?
output html:
   6060

A: Your PHP code is producing JSON in an incorrect format for the Google Visualization API.  Try this instead:
<?php
$con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!");
mysql_select_db("data", $con);

$sth = mysql_query("SELECT * FROM data");

$data = array (
    'cols' => array(
        array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'),
        array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'),
        array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number')
    ),
    'rows' => array()
);

while ($res = mysql_fetch_assoc($sth))
    // array nesting is complex owing to to google charts api
    array_push($data['rows'], array('c' => array(
        array('v' => $res['date']),
        array('v' => $res['temp1']),
        array('v' => $res['temp2'])
    )));
}
?>

and then in your javascript:
var bar_chart_data = new google.visualization.DataTable(<?php echo json_encode($data); ?>);

A: From the code you've originally posted - change
$task_submissions_arr[][] = $res;

to
$task_submissions_arr[] = $res;

A: Thanks for all your help in the design, I had several mistakes but the crucial mistake was that I used the wrong format for date, datetime from MySQL database, when I changed it from date / datetime to string the code was complete!
$table['cols']=array(
        array('label' => 'Date', type=>'string'),
        array('label' => 'Temp 1', type=>'number'),
        array('label' =>'Temp 2', type=>'number'),
);

Jason result:
new google.visualization.DataTable({"cols":[{"label":"Date","type":"string"},{"label":"Temp 1","type":"number"},{"label":"Temp 2","type":"number"}],"rows":[{"c":[{"v":"2013-10-05 20:41:00"},{"v":10.75},{"v":4}]}


Q: How do I access the value of a slot in a Svelte 3 component? I've been playing around with Svelte 3. I'm trying to create a basic Link component that's used like this:
<Link to="http://google.com">Google</Link>

My component renders a normal HTML  tag with a favicon in front of the link text:

  <img src={imageURL} alt={`${title} Icon`} />
  <slot />

The title variable I'm showing in the alt attribute for my  tag needs to be the text value of the unnamed slot. This is a really basic example, but is there any way to get the value of a slot like this?

A: In the mean time I found another (even better and not so hacky) way:

  <slot/>

A: This hack will work.
Add a hidden span or div to bind the slot text:

    <slot/>

And update your code like this:

  {text}


Q: How do I specify a type bound for Float and Double on a generic type in Scala? I am  writing some simple Vector and Matrix classes. They look like this:
// Vector with Floats
case class Vector3f(x: Float, y: Float, z: Float) {
  def +(v: Vector3f) = Vector3f(x + v.x, y + v.y, z + v.z)
}

// Vector with Doubles
case class Vector3d(x: Double, y: Double, z: Double) {
  def +(v: Vector3d) = Vector3d(x + v.x, y + v.y, z + v.z)
}

If I go on with further methods and classes like Point3f/d, Vector4f/d, Matrix3f/d, Matrix4f/d ... this is going to be a lot of work. Uff...
So I thought generics could possible help here and remove redundancy from my code base. I thought of something like this:
// first I define a generic Vector class
case class Vector3[@specialized(Float, Double) T](x: T, y: T, z: T) {
   def +(v: Vector3[T]) = new Vector3[T](x + v.x, y + v.y, z + v.z)
}

// than I use some type aliases to hide the generic nature
type Vector3f = Vector3[Float]
type Vector3d = Vector3[Double]

The idea is that the scala compiler generates specialized classes for Vector3[Float] and Vector3[Double] similar as a C++ template would do. Unfortunately I have to put some type bound on the type parameter [T] of class Vector3 such that the operator + is defined on T. My question: How can I write Vector3[Float] that it has the same performance characteristics as Vector3f?
Context: I would like to use the Vector3f / Vector3d classes in collision detection code ... so performance does matter for me.

A: Use a context bound of Fractional:
case class Vector3[@specialized(Float, Double) T : Fractional](x: T, y: T, z: T)  { ...

then within the body of the class, get an instance of the arithmetic operators:
  val fractOps = implicitly[Fractional[T]]

lastly import its members into the scope of the class:
  import fractOps._

Thereafter you can write ordinary infix operations on values of type T used within the class. Sadly, you will have to use fractOps.div(a, b) instead of a / b for division.


Q: calculating how many lines of code in ipython notebook just for curiosity sake - is there a way to find how many lines of code you've written in your ipython notebook? I have multiple lines per box, so I can't just count the number of boxes I have...


Q: XSLT to sum product of two attributes I have the following XML source structure:
<turnovers>
    <turnover repid="1" amount="500" rate="0.1"/>
    <turnover repid="5" amount="600" rate="0.5"/>
    <turnover repid="4" amount="400" rate="0.2"/>
    <turnover repid="1" amount="700" rate="0.05"/>
    <turnover repid="2" amount="100" rate="0.15"/>
    <turnover repid="1" amount="900" rate="0.25"/>
    <turnover repid="2" amount="1000" rate="0.18"/>
    <turnover repid="5" amount="200" rate="0.55"/>
    <turnover repid="9" amount="700" rate="0.40"/>
</turnovers>

I need an XSL:value-of select statement that will return the sum of the product of the rate attribute and the amount attribute for a given rep ID. So for rep 5 I need ((600 x 0.5) + (200 x 0.55)).

A: <xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:template match="/turnovers">
    <val>
      <!-- call the sum function (with the relevant nodes) -->
      <xsl:call-template name="sum">
        <xsl:with-param name="nodes" select="turnover[@repid='5']" />
      </xsl:call-template>
    </val>
  </xsl:template>

  <xsl:template name="sum">
    <xsl:param name="nodes" />
    <xsl:param name="sum" select="0" />

    <xsl:variable name="curr" select="$nodes[1]" />

    <!-- if we have a node, calculate & recurse -->
    <xsl:if test="$curr">
      <xsl:variable name="runningsum" select="
        $sum + $curr/@amount * $curr/@rate
      " />
      <xsl:call-template name="sum">
        <xsl:with-param name="nodes" select="$nodes[position() > 1]" />
        <xsl:with-param name="sum"   select="$runningsum" />
      </xsl:call-template>
    </xsl:if>

    <!-- if we don't have a node (last recursive step), return sum -->
    <xsl:if test="not($curr)">
      <xsl:value-of select="$sum" />
    </xsl:if>

  </xsl:template>
</xsl:stylesheet>

Gives:
<val>410</val>

The two <xsl:if>s can be replaced by a single <xsl:choose>. This would mean one less check during the recursion, but it also means two additional lines of code.

A: In plain XSLT 1.0 you need a recursive template for this, for example:
  <xsl:template match="turnovers">
    <xsl:variable name="selectedId" select="5" />
    <xsl:call-template name="sum_turnover">
      <xsl:with-param name="turnovers" select="turnover[@repid=$selectedId]" />
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="sum_turnover">
    <xsl:param name="total" select="0" />
    <xsl:param name="turnovers"  />
    <xsl:variable name="head" select="$turnovers[1]" />
    <xsl:variable name="tail" select="$turnovers[position()>1]" />
    <xsl:variable name="calc" select="$head/@amount * $head/@rate" />
    <xsl:choose>
      <xsl:when test="not($tail)">
        <xsl:value-of select="$total + $calc" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="sum_turnover">
          <xsl:with-param name="total" select="$total + $calc" />
          <xsl:with-param name="turnovers" select="$tail" />
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

A: This should do the trick, you'll need to do some further work to select the distinct repid's
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <xsl:variable name="totals">
            <product>
                <xsl:for-each select="turnovers/turnover">
                    <repid repid="{@repid}">
                        <value><xsl:value-of select="@amount * @rate"/></value>
                    </repid>
                </xsl:for-each>
            </product>
        </xsl:variable>
        <totals>
            <total repid="5" value="{sum($totals/product/repid[@repid='5']/value)}"/>
        </totals>
    </xsl:template>

</xsl:stylesheet>

A: In XSLT 1.0 the use of FXSL makes such problems easy to solve:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:f="http://fxsl.sf.net/"
 xmlns:ext="http://exslt.org/common"
 exclude-result-prefixes="xsl f ext"
 >
 <xsl:import href="zipWith.xsl"/>
 <xsl:output method="text"/>

  <xsl:variable name="vMultFun" select="document('')/*/f:mult-func[1]"/>

    <xsl:template match="/">
      <xsl:call-template name="profitForId"/>
    </xsl:template>

    <xsl:template name="profitForId">
      <xsl:param name="pId" select="1"/>

      <xsl:variable name="vrtfProducts">
          <xsl:call-template name="zipWith">
            <xsl:with-param name="pFun" select="$vMultFun"/>
            <xsl:with-param name="pList1" select="/*/*[@repid = $pId]/@amount"/>
            <xsl:with-param name="pList2" select="/*/*[@repid = $pId]/@rate"/>
          </xsl:call-template>
      </xsl:variable>

      <xsl:value-of select="sum(ext:node-set($vrtfProducts)/*)"/>
    </xsl:template>

    <f:mult-func/>
    <xsl:template match="f:mult-func" mode="f:FXSL">
     <xsl:param name="pArg1"/>
     <xsl:param name="pArg2"/>

     <xsl:value-of select="$pArg1 * $pArg2"/>
    </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the originally posted source XML document, the correct result is produced:
310
In XSLT 2.0 the same solution using FXSL 2.0 can be expressed by an XPath one-liner:
sum(f:zipWith(f:multiply(),
          /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.),
          /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.)
          )
     )

The whole transformation:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:f="http://fxsl.sf.net/"
 exclude-result-prefixes="f xs"
>
 <xsl:import href="../f/func-zipWithDVC.xsl"/>
 <xsl:import href="../f/func-Operators.xsl"/>

 <!-- To be applied on testFunc-zipWith4.xml -->
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
   <xsl:value-of select=
   "sum(f:zipWith(f:multiply(),
              /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.),
              /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.)
              )
         )
    "/>
 </xsl:template>
</xsl:stylesheet>

Again, this transformation produces the correct answer:
310
Note the following:

*

*The f:zipWith() function takes as arguments a function fun() (of two arguments) and two lists of items having the same length. It produces a new list of the same length, whose items are the result of the pair-wise application of fun() on the corresponding k-th items of the two lists.

*f:zipWith() as in the expression takes the function f:multiply() and two sequences of corresponding "ammount" and "rate" attributes. The sesult is a sequence, each item of which is the product of the corresponding "ammount" and "rate".

*Finally, the sum of this sequence is produced.

*There is no need to write an explicit recursion and it is also guaranteed that the behind-the scenes recursion used within f:zipWith() is never going to crash (for all practical cases) with "stack overflow"

A: <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      exclude-result-prefixes="xs"
      version="2.0">

   <xsl:variable name="repid" select="5" />

   <xsl:template match="/">
      <xsl:value-of select=
         "sum(for $x in /turnovers/turnover[@repid=$repid] return $x/@amount * $x/@rate)"/>
   </xsl:template>

</xsl:stylesheet>

You can do this if you just need the value and not xml.

A: The easiest way to do it in XSLT is probably to use programming language bindings, so that you can define your own XPath functions.


Q: Code API default signature gsuite email in admin I am not sure how to input the code and location input the code for gsuite. So it is set up as default for each employee


Q: passing data to dynamically created ascx user control I want to display user control which produces different set of data depending on values which are being passed to it.
No. of UserControls are decided at run-time

*

*Now it dint Hit in Page_Load of ascx.cs
Default.aspx
<%@ Register Src="~/UserControl/SquareEUA.ascx" TagName="Square" TagPrefix="EUA" %>

Default.aspx.cs
    protected void Page_Load(object sender, EventArgs e)
    {
    string[] Property;
    foreach (string sPropID in Property)
    {
SquareEUA userControl = (SquareEUA)Page.LoadControl("~/UserControl/SquareEUA.ascx");
        userControl.ID = "MyControl_" + sPropID.Trim();
        userControl.sCustID = CustomerID;
        userControl.sCustPropID = sPropID.Trim();
        userControl.Visible = true;
        divControls.Controls.Add(userControl);
        userControl.Dispose();
    }
    }

SquareEUA.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SquareEUA.ascx.cs" Inherits="UserControl.SquareEUA" %>

     // Some HTML Markup

SquareEUA.ascx.cs
public partial class SquareEUA : System.Web.UI.UserControl
{
public string sCustID { get; set; }
public string sCustPropID { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Some Code
        // Didnt Hit Breakpoint Here;
    }
}

A: you need to cast your usercontrol as the actual class SquareEUA to access that class's properties
SquareEUA userControl = (SquareEUA)(Page.LoadControl("~/UserControl/SquareEUA.ascx"));

that should do the trick (you should add some error handling, null check, etc.)
edit: seems I missed a parenthesis around (Page...


Q: Linux: Join two lines with an equal value in the SAME file I have a file that looks like this:
1 51 Brahui A C A A T
1 51 Brahui A C A G T
3 51 Brahui A C A G C
3 51 Brahui A C G A T
5 51 Brahui A C G A T
5 51 Brahui A C G G C
7 51 Brahui A C G A T
7 51 Brahui A C G G T
9 51 Brahui A C G G T
9 51 Brahui A C G G T
And I want to generate an output file whereby if the first column/field are of equal value then I want to merge the two lines together with a "/" character as a delimiter. For example:
1 51 Brahui A/A C/C A/A A/G T/T
3 51 Brahui A/A C/C A/G G/A C/T
Is there a way that I can do that?
P.S.The columns starting from $4 are actually 2,834 long (i.e. $4-$2841) so I don't think it will be practical to physically enter $4, $5, $6, etc.. Is there a way to do this?

A: pearl.229>awk '{a=$1;
          b=$4;
          c=$5;
          d=$6;
          e=$7;
          f=$8;
          getline;
          if(a==$1)
          print a,$2,$3,b"/"$4,c"/"$5,d"/"$6,e"/"$7,f"/"$8}' file3
    1 51 Brahui A/A C/C A/A A/G T/T
    3 51 Brahui A/A C/C A/G G/A C/T
    5 51 Brahui A/A C/C G/G A/G T/C
    7 51 Brahui A/A C/C G/G A/G T/T
    9 51 Brahui A/A C/C G/G G/G T/T
    pearl.230>

A: I like using fmt.  It makes the code prettier.
[ghoti@pc ~]$ cat doit
#!/usr/bin/awk -f

BEGIN {
  fmt="%s %s %s %s/%s %s/%s %s/%s %s/%s %s/%s\n";
}

one == $1 {
  split(last,a);
  printf(fmt, $1,$2,$3, a[4],$4, a[5],$5, a[6],$6, a[7],$7, a[8],$8);
}

{ last = $0; one = $1; }

[ghoti@pc ~]$ ./doit input.txt
1 51 Brahui A/A C/C A/A A/G T/T
3 51 Brahui A/A C/C A/G G/A C/T
5 51 Brahui A/A C/C G/G A/G T/C
7 51 Brahui A/A C/C G/G A/G T/T
9 51 Brahui A/A C/C G/G G/G T/T
[ghoti@pc ~]$


Q: Explain Traverse[List] implementation in scalaz-seven I'm trying to understand the traverseImpl implementation in scalaz-seven:
def traverseImpl[F[_], A, B](l: List[A])(f: A => F[B])(implicit F: Applicative[F]) = {
  DList.fromList(l).foldr(F.point(List[B]())) {
     (a, fbs) => F.map2(f(a), fbs)(_ :: _)
  }
}

Can someone explain how the List interacts with the Applicative? Ultimately, I'd like to be able to implement other instances for Traverse.

A: An applicative lets you apply a function in a context to a value in a context. So for instance, you can apply some((i: Int) => i + 1) to some(3) and get some(4). Let's forget that for now. I'll come back to that later.
List has two representations, it's either Nil or head :: tail. You may be used to fold over it using foldLeft but there is another way to fold over it:
def foldr[A, B](l: List[A], acc0: B, f: (A, B) => B): B = l match {
   case Nil => acc0
   case x :: xs => f(x, foldr(xs, acc0, f))
}

Given List(1, 2) we fold over the list applying the function starting from the right side - even though we really deconstruct the list from the left side!
f(1, f(2, Nil))

This can be used to compute the length of a list. Given List(1, 2):
foldr(List(1, 2), 0, (i: Int, acc: Int) => 1 + acc)
// returns 2

This can also be used to create another list:
foldr[Int, List[Int]](List(1, 2), List[Int](), _ :: _)
//List[Int] = List(1, 2)

So given an empty list and the :: function we were able to create another list. What if our elements are in some context? If our context is an applicative then we can still apply our elements and :: in that context. Continuing with List(1, 2) and Option as our applicative. We start with some(List[Int]())) we want to apply the :: function in the Option context. This is what the F.map2 does. It takes two values in their Option context, put the provided function of two arguments into the Option context and apply them together.
So outside the context we have (2, Nil) => 2 :: Nil
In context we have: (Some(2), Some(Nil)) => Some(2 :: Nil)
Going back to the original question:
// do a foldr
DList.fromList(l).foldr(F.point(List[B]())) {
  // starting with an empty list in its applicative context F.point(List[B]())
  (a, fbs) => F.map2(f(a), fbs)(_ :: _)
  // Apply the `::` function to the two values in the context
}

I am not sure why the difference DList is used. What I see is that it uses trampolines so hopefully that makes this implementation work without blowing the stack, but I have not tried so I don't know.
The interesting part about implementing the right fold like this is that I think it gives you an approach to implement traverse for algebric data types using catamorphisms.
For instance given:
trait Tree[+A]
object Leaf extends Tree[Nothing]
case class Node[A](a: A, left: Tree[A], right: Tree[A]) extends Tree[A]

Fold would be defined like this (which is really following the same approach as for List):
def fold[A, B](tree: Tree[A], valueForLeaf: B, functionForNode: (A, B, B) => B): B = {
  tree match {
    case Leaf => valueForLeaf
    case Node(a, left, right) => functionForNode(a,
        fold(left, valueForLeaf, functionForNode),
        fold(right, valueForLeaf, functionForNode)
      )
  }
}

And traverse would use that fold with F.point(Leaf) and apply it to Node.apply. Though there is no F.map3 so it may be a bit cumbersome.

A: This not something so easy to grasp. I recommend reading the article linked at the beginning of my blog post on the subject.
I also did a presentation on the subject during the last Functional Programming meeting in Sydney and you can find the slides here.
If I can try to explain in a few words, traverse is going to traverse each element of the list one by one, eventually re-constructing the list (_ :: _) but accumulating/executing some kind of "effects" as given by the F Applicative. If F is State it keeps track of some state. If F is the applicative corresponding to a Monoid it aggregates some kind of measure for each element of the list.
The main interaction of the list and the applicative is with the map2 application where it receives a F[B] element and attach it to the other F[List[B]] elements by definition of F as an Applicative and the use of the List constructor :: as the specific function to apply.
From there you see that implementing other instances of Traverse is only about applying the data constructors of the data structure you want to traverse. If you have a look at the linked powerpoint presentation, you'll see some slides with a binary tree traversal.

A: List#foldRight blows the stack for large lists. Try this in a REPL:
List.range(0, 10000).foldRight(())((a, b) => ())

Typically, you can reverse the list, use foldLeft, then reverse the result to avoid this problem. But with traverse we really have to process the elements in the correct order, to make sure that the effect is treated correctly. DList is a convenient way to do this, by virtue of trampolining.
In the end, these tests must pass:
https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/TraverseTest.scala#L13
https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/std/ListTest.scala#L11
https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Traverse.scala#L76


Q: Issue with deploying Azure project using Powershell 2 I used the Azure training kit command
New-Deployment
    -serviceName <YOUR_SERVICE_NAME_LOWER_CASE>
    -subscriptionId <YOUR_SUBSCRIPTION_ID>
    -certificate (get-item cert:\CurrentUser\MY\<YOUR_CERTIFICATE_THUMBPRINT>)
    -slot staging
    –package <PACKAGE_LOCATION>
    -configuration <CONFIGURATION_LOCATION>
    -label "v2.0"
    –storageServiceName <YOUR_STORAGE_SERVICE_NAME_LOWER_CASE>

to deploy my Azure app. It was able to upload package to the blob but when Create a new deployment it shows error as:
New-Deployment : Cannot access a closed Stream.
At line:1 char:15
+ New-Deployment <<<<  -serviceName mytodo -subscriptionId xxxxxxxxx
8ad-360cdbdc361f -certificate (get-item cert:\CurrentUser\MY\xxxxxxxx
6DD27E3DFF5F7FE24A3FBF) -slot staging -package MyTodo.cspkg -configuration Serv
iceConfiguration.cscfg -label "v1.0" -storageServiceName xxxxx
    + CategoryInfo          : CloseError: (:) [New-Deployment], ObjectDisposed
   Exception
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Samples.ManagementTools.P
   owerShell.Services.HostedServices.NewDeploymentCommand

A: Do you have a local proxy (e.g. Fiddler) running? If so, you'll need to disable it.
Also, check the certificate is installed properly and in the right place: follow, to the letter, the instructions here:
http://msdn.microsoft.com/en-us/gg271300
in particular noting there are no line breaks or spaces in the path for (get-Item cert:\CurrentUser\MY\XXXXX).


Q: can not create virtual environment for a django project I'm trying to create a Django project from scratch.
I executed django-admin startproject autoshine in my zsh terminal.
Then I opened pycharm and run pipenv install in its local terminal to create a virtual environment for this project. But I got this error:
 raise child_exception_type(errno_num, err_msg, err_filename)

FileNotFoundError: [Errno 2] No such file or directory: '/home/mohsen/.local/share/virtualenvs/autoshine-YDp111VE/bin/python'
I realized that in the above directory, it can create a virtual environment but unfortunately it doesn't have any bin file.
I don't know how to solve this problem.
Thank you for your answers in advance.

A: You can try the default way of creating a venv. For more information look here
python3 -m venv tutorial-env

and activate it with
source/tutorial-env/bin/activate


Q: How do you get Ember Data to recognize that the server is returning IDs for hasMany relationships? My server returns JSON responses that look like this:
{
  'book': {
    'id': 252,
    'name': 'The Hobbit',
    'tag_ids': [1, 2, 3, 5, 6, 7]
   }
}

I'm using Ember Data's DS.RESTSerializer, which I've extended to include a keyForRelationship function that recognizes that keys ending in "_ids" are really hasMany relationships. Thus, the above code should match up just fine with my model code, which looks like this:
App.Book = DS.Model.extend({
    name: DS.attr('string'),
    tags: DS.hasMany('tag')
});

The problem is that whenever I create a new book and the server returns its JSON response, Ember Data's store gets it wrong. It fails to convert the IDs into actual tag instances. Instead, the tags property on the model is literally set to an array of IDs.
Any ideas?

A: You should consider using DS.ActiveModelAdapter instead of DS.RESTAdapter. See also https://stackoverflow.com/a/19209194/1345947


Q: Can I use Django templatetags on Google App Engine? My Django site has many templatetags directories, can I use Django templatetags on Google App Engine?

A: Yes.


Q: check which names have the same field in a database i have this table:
id name     lastname   id_op  time
0  Richard  Touch        5    8.00
1  Mattew   Cast         6    9.00
2  Carl     Cappai       7   10.00
3  Mario    Bros         8   10.00
4  Luigi    Same         9    8.00

I want to print in page ex:
"Richard and Luigi have the sames time: 8.00"
"Carl and Mario have the same time: 10.00"
i tryed with this choice:
   $link=connect_db();
$query_count="SELECT * FROM table";
$result_count=mysql_query($query_count,$link);

while($var = mysql_fetch_assoc($result_count)){

foreach ($var as $key => $value){
        $i=0;
        $var[$i];
        $row_count[$i][$key] = $value;

        //echo $content[$index][$key];
    echo $key.' '.$value.', ';

    }

    $i++;

}

 for($i=0;$i<count($row_count);$i++) {
for($j=$i+1;$j<count($row_count);$j++) {
if($row_count[$i]['time']==$row_count[$j]['time']) {
        echo ' '.$row_count[$i]['name'].' and '.$row_count_lun[$j]['name'].'have the same time:'.$row_count_lun[$i]['time'].'';
        }
}
 }

Final Result = Carl Carl Richard Richard.. -__-

A: How about this:
select group_concat(name) as names, time
from table t
group by time
having count(*) > 1;

This will give you output such as:
Names               Time
Richard,Luigi       8:00
. . .

Which can then format on the application side.


Q: Android: Handling screens that are the same dpi level but different I have gone through all of the Android docs about handling multiple screen sizes but I still haven't been able to find an answer to this question or how to handle this.
If there are two phones that have the same dpi level (such as both being hdpi) I can provide one resource for them and set the layout parameters as such:
<ImageView
android:id="@+id/icon"
android:layout_width="94dp"
android:layout_height="94dp"
>

The "icon" in this instance is large enough so that it will scale down to fit that layout in all cases. In an ideal world, I would assume that the icon would appear the exact same size on all hdpi devices, however when I tested it out on a LG G2x and a HTC Sensation, the image is smaller on the Sensation. So is Android always just using a factor of 1.5x when calculating the size the hdpi image? Is there something I can do to guarantee the size will be the exact same on all hdpi devices? Thanks.

A: You can use this to help you out with the proyect
http://developer.android.com/training/multiscreen/screensizes.html

A: The answer was that the system does use a standard multiplier for each dpi level (1.5x for hdpi for example). In order to get around this I just used the .xdpi and .ydpi values of DisplayMetrics and do my calculations off of those real values.

A: Usually when ever we want to do like this we usually use wrap_content. so once try layout_width = "wrap_content",layout_height = "wrap_content". Such that ANdroid SDK will look.


Q: I installed scott user creating file but It wasn't the scott It mentioned like USER is ""
as u know it usually downloads together with scott.sql file but Idk why but It couldn't download it so, eventually, I did it by myself. even directory wasn't created so I made it those by myself as well. anyway, even though I did it and succeeded to create user, it didn't have the name like that pic and as u know we don't have any way to change user's name so I couldn't. How can I change it to scott like normal?


Q: whats wrong in my code? why the error msg The following code works just fine I can get the results I want if I ignore the error message once I run it. the error I get is: Debug Error!
Program:c:\qt\qt5.5.1\5.5\msvc2013_64\bin\Qt5Cored.dll
Module: 5.5.1
File: global\qglobal.cpp
Line: 2966
.....
if I chose to ignore error the console app displays all data correctly it shows the correct bits array it also shows correct character for the binary array and last it gives also the correct byte decimal value for the byte char...
this is the error in console:
 ASSERT: "uint(i) < uint(size())" in file c:\work\build\qt5_workdir\w\s\qtbase\sr
c\corelib\tools\qbytearray.h, line 464
this is correct output:
Bits are: QBitArray(0110 0011)
Byte Char is "c"
Decimal format Bytes are:  99
Code used:
    QBitArray Alphabits(8);
    Alphabits[0] = false;
    Alphabits[1] = true;
    Alphabits[2] = true;
    Alphabits[3] = false;
    Alphabits[4] = false;
    Alphabits[5] = false;
    Alphabits[6] = true;
    Alphabits[7] = true;

    QByteArray Alphabytes;
    // Convert from QBitArray to QByteArray
    for(int b=0; b<Alphabits.count();++b) {
        Alphabytes[b/8] = (Alphabytes.at(b/8) | ((Alphabits[b]?1:0)<<(7-(b%8))));
    }

    qDebug() << "Bits are:" << Alphabits;
    qDebug() << "Byte Char is" << Alphabytes;
    qDebug() << "Decimal format Bytes are: "<< static_cast<quint8>(Alphabytes[0]);

A: Ok, i figure out where is the problem. This is because when  you inside for make call Alphabytes.at(b/8) for the first time, the size of Alphabytes is zero, so you try get index that is out of array range. Replace this with Alphabytes[b/8] = (Alphabytes[b/8] |.......

A: It seems that in release mode everything compiles and even no errors or warnings etc are detected so this is strange it only happens in debug mode so I think ill report this in QT bug tracking maybe...
Unless anyone can figure out why this error only happens when debugging...


Q: ThreadLocal garbage collection From javadoc

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

from that it seems that objects referenced by a ThreadLocal variable are garbage collected only when thread dies. But what if ThreadLocal variable a is no more referenced and is subject for garbage collection? Will object references only by variable a be subject to garbage collection if thread that holds a is still alive?
for example there is following class with ThreadLocal variable:
public class Test {
    private static final ThreadLocal a = ...; // references object b
}

This class references some object and this object has no other references to it. Then during context undeploy application classloader becomes a subject for garbage collection, but thread is from a thread pool so it does not die. Will object b be subject for garbage collection?

A: TL;DR : You cannot count on the value of a ThreadLocal being garbage collected when the ThreadLocal object is no longer referenced. You have to call ThreadLocal.remove or cause the thread to terminate
(Thanks to @Lii)

Detailed answer:

from that it seems that objects referenced by a ThreadLocal variable are garbage collected only when thread dies.

That is an over-simplification.  What it actually says is two things:

*

*The value of the variable won't be garbage collected while the thread is alive (hasn't terminated), AND the ThreadLocal object is strongly reachable.

*The value will be subject to normal garbage collection rules when the thread terminates.
There is an important third case where the thread is still live but the ThreadLocal is no longer strongly reachable. That is not covered by the javadoc.  Thus, the GC behaviour in that case is unspecified, and could potentially be different across different Java implementations.
In fact, for OpenJDK Java 6 through OpenJDK Java 8 (and other implementations derived from those code-bases) the actual behaviour is rather complicated.  The values of a thread's thread-locals are held in a ThreadLocalMap object.  The comments say this:

ThreadLocalMap is a customized hash map suitable only for maintaining thread local values. [...] To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys. However, since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space.

If you look at the code, stale map entries (with broken WeakReferences) may also be removed in other circumstances.  If stale entry is encountered in a get, set, insert or remove operation on the map, the corresponding value is nulled.  In some cases, the code does a partial scan heuristic, but the only situation where we can guarantee that all stale map entries are removed is when the hash table is resized (grows).

So ...

Then during context undeploy application classloader becomes a subject for garbage collection, but thread is from a thread pool so it does not die. Will object b be subject for garbage collection?

The best we can say is that it may be ... depending on how the application manages other thread locals the thread in question.
So yes, stale thread-local map entries could be a storage leak if you redeploy a webapp, unless the web container destroys and recreates all of the request threads in the thread pool.  (You would hope that a web container would / could do that, but AFAIK it is not specified.)
The other alternative is to have your webapp's Servlets always clean up after themselves by calling ThreadLocal.remove on each one on completion (successful or otherwise) of each request.

A: ThreadLocal variables are hold in Thread
ThreadLocal.ThreadLocalMap threadLocals;

which is initialized lazily on first ThreadLocal.set/get invocation in the current thread and holds reference to the map until Thread is alive. However ThreadLocalMap uses WeakReferences for keys so its entries may be removed when ThreadLocal is referenced from nowhere else. See ThreadLocal.ThreadLocalMap javadoc for details

A: If the ThreadLocal itself is collected because it's not accessible anymore (there's an "and" in the quote), then all its content can eventually be collected, depending on whether it's also referenced somewhere else and other ThreadLocal manipulations happen on the same thread, triggering the removal of stale entries (see for example the replaceStaleEntry or expungeStaleEntry methods in ThreadLocalMap). The ThreadLocal is not (strongly) referenced by the threads, it references the threads: think of ThreadLocal<T> as a WeakHashMap<Thread, T>.
In your example, if the classloader is collected, it will unload the Test class as well (unless you have a memory leak), and the ThreadLocal a will be collected.

A: ThreadLocal contains a reference to a WeakHashMap that holds key-value pairs

A: It depends, it will not be garbage collected if your are referencing it as static or by singleton and your class is not unloaded, that is why in application server environment and with ThreadLocal values, you have to use some listener or request filter the be sure that you are dereferencing all thread local variables at the end of the request processing. Or either use some Request scope functionality of your framework.
You can look here for some other explanations.
EDIT: In the context of a thread pool as asked, of course if the Thread is garbaged thread locals are.

A: Object b will not be subject for garbage collection if it somehow refers to your  Test class. It can happen without your intention. For example if you have a code like this:
public class Test {
    private static final ThreadLocal<Set<Integer>> a =
     new ThreadLocal<Set<Integer>>(){
            @Override public Set<Integer> initialValue(){
                return new HashSet<Integer>(){{add(5);}};
            }
    };
}

The double brace initialization {{add(5);}} will create an anonymous class which refers to your Test class so this object will never be garbage collected even if you don't have reference to your Test class anymore. If that Test class is used in a web app then it will refer to its class loader which will prevent all other classes to be GCed.
Moreover, if your b object is a simple object it will not be immediately subject for GC. Only when ThreadLocal.ThreadLocalMap in Thread class is resized you will have your object b subject for GC.
However I created a solution for this problem so when you redeploy your web app you will never have class loader leaks.


Q: How do you find duplicated elements of a vector that outputs the integer appearance of that duplicate instead of a logical? We know that the duplicated() function outputs a vector of logicals. What I want, however, is a vector of integers such that, if this is the (n+1)th time that this particular element appears, the corresponding element of the output vector is n.
For example, if we call the function that I'm looking for "intDuplicate()" then I would want the following output:
> x <- sample(c('a','b','c'),10,replace=T)
> y <- intDuplicate(x)
> x
[1] "c" "b" "b" "a" "a" "b" "c" "b" "b" "c"
> y
[1] 0 0 1 0 1 2 1 3 4 2

So, for example, y[9] = 4 because this is the fifth occurrence of 'b' (i.e. fourth duplication).
Is there a vectorized way to do this?

A: Here's a possible solution using base R (not sure if vectorized enough for you)
as.numeric(ave(x, x, FUN = seq)) - 1L
## [1] 0 0 1 0 1 2 1 3 4 2

Or something similar using data.table package
library(data.table)
as.data.table(x)[, y := seq_len(.N) - 1L, by = x][]
#     x y
#  1: c 0
#  2: b 0
#  3: b 1
#  4: a 0
#  5: a 1
#  6: b 2
#  7: c 1
#  8: b 3
#  9: b 4
# 10: c 2

Or maybe a dplyr option
library(dplyr)
data.frame(x) %>%
  group_by(x) %>%
  mutate(y = row_number() - 1L)
# Source: local data frame [10 x 2]
# Groups: x
#
#    x y
# 1  c 0
# 2  b 0
# 3  b 1
# 4  a 0
# 5  a 1
# 6  b 2
# 7  c 1
# 8  b 3
# 9  b 4
# 10 c 2


Q: Access a ViewModel from another ViewModel I'm developing an WPF using MVVM pattern, C# and .NET Framework 4.6.1.
I have a Window that contains an UserControl (Control1) and that UserControl contains another UserControl (Control2). I have chosen this way to do it instead of using a Dialog Window (Control2 acts as Dialog Window).
Both user controls have a Viewmodel (Control1VM and Control2VM).
I use Control2 as a form to let users input some data that I need to start the application.
This is the MainWindow with Control1:

And this is Control2 over Control1.

My problem is that I don't know how to hide Control2 when I click on OK or Cancel button.
This is how Control2 is set on Control1:
<Grid x:Name="gridControl2" Margin="30" Grid.RowSpan="6" Grid.ColumnSpan="3" Visibility="{Binding GridControl2Visibility}">
    <local:Control2 x:Name="userControlControl2" />
</Grid>

To show Control2 and set GridControl2Visibility to Visible in Control1VM:
public Visibility GridControl2Visibility
{
    get { return gridControl2Visibility; }
    set
    {
        if (gridControl2Visibility != value)
        {
            gridControl2Visibility = value;

            RaisePropertyChangedEvent("GridControl2Visibility");
        }
    }
}

How can I hide Control2 when I click on Ok or Cancel button in Control2? My problem is that GridControl2Visibility is on Control1VM and I can't access that class from Control2VM.

A: Use a service that both view models can access and that stores the info whether Control2 should be visible or not. Ideally, the service would be registered as singleton with your di-container and injected into the view models.
Alternatively, you can use an event aggregator, which is basically a singleton service, too, but focused on distributing events rather than holding a state.

A: You can use events, You can raise event from Control2VM and hadnle it in Control1VM and set GridControl2Visibility to false.


Q: Python or Matlab rotate with spline interpolation order higher than 5 I need to do a rotation with a spline interpolation of high order >5. I insist on the fact that it is for interpolating rotated data, not upsampling.
I found : https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rotate.html?highlight=rotate#scipy.ndimage.rotate
but only up to splines order 5. (I know orders > 3 are unusual, nevertheless I do need it).
any idea of a Python/Matlab or way to implement higher order spline interpolation for rotation ?


Q: Wilcoxon test with chicken's weight data(ChickWeight)
head(ChickWeight)
plot( ChickWeight$Time, ChickWeight$weight, col=ChickWeight$Diet)
chick = reshape(ChickWeight, idvar=c("Chick","Diet"), timevar="Time",
                direction="wide")
head(chick)
chick = na.omit(chick)

Perform a t-test of x and y, after adding a single chick of weight 200
grams to x (the diet 1 chicks). What is the p-value from this test?
The p-value of a test is available with the following code:
t.test(x,y)$p.value

Do the same for the Wilcoxon test. The Wilcoxon test is robust to the outlier. In addition, it has less assumptions that the t-test on the distribution of the underlying data.
When I try do Wilcoxon test:
wilcox.test(c(x, 200), y)

I get this error:
Warning message:
In wilcox.test.default(c(x, 200), y) :
  cannot compute exact p-value with ties

A: Use exactRankTests::wilcox.exact:
If x is a weight for example time 0 e.g. chick$weight.0 and
y is a weight for example time 2 e.g. chick$weight.2
Then you could do it this way:
With wilcox.test you will get a warning message:
> wilcox.test(c(chick$weight.0, 200), chick$weight.2)$p.value
[1] 6.660003e-14
Warning message:
In wilcox.test.default(c(chick$weight.0, 200), chick$weight.2) :
  cannot compute exact p-value with ties

Use exactRankTests::wilcox.exact() that can handle ties:
t.test(chick$weight.0,chick$weight.2)$p.value
6.660003e-14

exactRankTests::wilcox.exact(c(chick$weight.0, 200), chick$weight.2)$p.value
[1] 5.889809e-18


Q: Repeating text in Processing language So I need to repeat text 40 times, I figured out how to do a line a certain amount of times, but using the same process for text is not working, ive tried messing around with different code but I am stuck.
Any help would be great.
I just need to repeat the word "text" 40 times in the program.
Here is my current code:
void setup() {
    size(640, 360);
    textFont(createFont("Georgia", 24));
}

void draw() {
    background(102);
    textAlign(RIGHT);
    drawType(width * 0.10);
}

void drawType(float x) {

    fill(0);

    float y = 35;
    int spacing = 50;
    int endLine = 640;

    while (x <= endLine){
        text("text", x, y, 50, 50);
        x = x + y + spacing;
    }
}

I'm using the language Processing, (processing.org), which is a type of JAVA.

A: Just thought i would be clear with my comment:
try
String var="";
 for(int i=0;i<40;i++)
    {
       var=var+"text";
     }

//Then use the variable got

 text(var, x, y, 50, 50);

There may be built in functions to do this in a better way, but this would be a simple way to solve your problem.
This method though is in-efficient as String operations are costly in Java because they are immutable.
The above example would print the same string 40 times in a single line(depending upon the length of the line).
If the horizontal length of the line is not sufficient, either increase the line size or decrease the spacing or decrease the number of times you are repeating the string.


Q: SQL - Select MAX or TOP 1 FROM each month I have a query that literally does nothing helpful, but hopefully paints the picture of what I am trying to accomplish.
SELECT *
FROM Tbl_StockData
WHERE Date <= DateSerial(YEAR(Date), MONTH(Date) + 1, 1) - 1);

Which basically gets all values where the date is <= the end of the month. From here, I want to select the top (or latest) day from each month of the query. I.e, the current query produces
CodeName    Date
----------------------
14D         2018-09-12
14D         2018-09-13
14D         2018-09-14
14D         2018-09-17
14D         2018-09-18
14D         2018-09-19
14D         2018-09-20
14D         2018-09-21
14D         2018-09-24
14D         2018-09-25
14D         2018-09-26
14D         2018-09-27
14D         2018-09-28
14D         2018-10-01
.
.
.

And note that it is not just 14D listed here, there are many more. What you can see here is that the end of month data is not always the 31'st or 30'th, so for each new month, for each new CodeName, I want to obtain the last value in the given month, for all months.
Something that achieves this would look like
CodeName    Date
----------------------
14D         2018-09-28
14D         2018-10-31
14D         2018-11-30
14D         2018-12-31
14D         2019-01-31
14D         2019-02-28
.
.
.

Okay, well I got a bit unlucky with that one given then last 5 dates are, in fact, the EOM date, but hopefully the point is clear. If I were to select the MAX or TOP of the days in a given month, I would like it to return me the last date in the data set of the month, for all months, for all CodeNames.


Q: Error when calling classroom PHP API method: courses.courseWork.list So I use the Google Classroom PHP API to integrate it with my project. When the user is requested to logging with the google account, I request the following scopes.
Google_Service_Classroom::CLASSROOM_COURSES_READONLY,     Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY,           Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS,           Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY,
Google_Service_Classroom::CLASSROOM_ANNOUNCEMENTS_READONLY
Interesting enough, the accessToken generated returns the following scopes:
Google_Service_Classroom::CLASSROOM_COURSES_READONLY,     Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY,           Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS,           Google_Service_Classroom::CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY,             Google_Service_Classroom::CLASSROOM_ANNOUNCEMENTS_READONLY
The problem is that courses.courseWork.list specifically requires Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY, as stated in the API reference.
So as a result I'm getting an error:
{
   "error":{
      "code":403,
      "message":"The caller does not have permission",
      "errors":[
         {
            "message":"The caller does not have permission",
            "domain":"global",
            "reason":"forbidden"
         }
      ],
      "status":"PERMISSION_DENIED"
   }
}

Am I doing something wrong or this might be an API bug?

Adding further details on the code.
First the frontend request the Authorization URL, that one where the user will login and accept the scopes being requested. This is done with the following methods: Frontend > getAuthorizationURL > getGoogleAuthorizationURL.
public function getAuthorizationURL($parameters) {

    $classroomIntegration = new classroomIntegration();
    $asyncState = $classroomIntegration->generateGoogleAsyncState(classroomIntegration::$CLASSROOM_INTEGRATION, $parameters->userID);
    $resultUrl = googleLogin::getGoogleAuthorizationURL("callback.php",
                                                        $asyncState,
                                                       [Google_Service_Classroom::CLASSROOM_COURSES_READONLY,
                                                        Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY,
                                                        Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS,
                                                        Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY,
                                                        Google_Service_Classroom::CLASSROOM_ANNOUNCEMENTS_READONLY,
                                                        Google_Service_Oauth2::USERINFO_PROFILE]);

    $this->respond(TRUE, $resultUrl);
}

public static function getGoogleAuthorizationURL($callbackRelativePath, $asyncState, $scopes){

    $client = new Google_Client();
    $httpHost = constant("httpHost");

    $client->setAuthConfig("credentials.json");
    $client->setRedirectUri("http://" . $httpHost . $callbackRelativePath);

    $client->setApplicationName("Dummy App");
    $client->setPrompt("consent");
    $client->setApprovalPrompt("consent");
    foreach($scopes as $scope){
        $client->addScope($scope);
    }

    $client->setAccessType("offline");
    $client->setIncludeGrantedScopes(true);
    $client->setState($asyncState);

    $authUrl = $client->createAuthUrl();

    return filter_var($authUrl, FILTER_SANITIZE_URL);
}

Than in the callback file I just get the access code, which contains the tokens and the scopes that were granted:
$client->setAccessType("offline");
$code = filter_input(INPUT_GET, "code");
$accessToken = $client->fetchAccessTokenWithAuthCode($code);

So basically on the list of scopes that were granted, instead of getting the Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY as requested I'm being granted the Google_Service_Classroom::CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY. Problem is that courses.courseWork.list requires the first one.


Q: How to run a memory intensive spark streaming job using the smallest memory usage possible I am running a job that joins two kafka topics into one topic using a value. The environment I am using only allow me to assign less than 10g ram per job, the data I am trying to join is around 500k record per topic.
I am pretty new to Spark, so I'd like to know if there is a way to minimize the memory consumption
the code:
val df_person: DataFrame = PERSONINFORMATION_df
      .select(from_json(expr("cast(value as string) as actualValue"), schemaPERSONINFORMATION).as("s")).select("s.*").withColumn("comsume_date", lit(LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss.SS")))).as("dfperson")

val df_candidate: DataFrame = CANDIDATEINFORMATION_df
      .select(from_json(expr("cast(value as string) as actualValue"), schemaCANDIDATEINFORMATION).as("s")).select("s.*").withColumn("comsume_date", lit(LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss.SS")))).as("dfcandidate")

Join topics:
val joined_df : DataFrame = df_candidate.join(df_person, col("dfcandidate.PERSONID") === col("dfperson.ID"),"inner").withColumn("join_date", lit(LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss.SS"))))

Re-structure the data
val string2json: DataFrame = joined_df.select($"dfcandidate.ID".as("key"),to_json(struct($"dfcandidate.ID".as("candidateID"), $"FULLNAME", $"PERSONALID",$"join_date",$"dfcandidate.PERSONID".as("personID"),$"dfcandidate.comsume_date".as("candidate_comsume_time"),$"dfperson.comsume_date".as("person_comsume_time"))).cast("String").as("value"))

write them to a topic
string2json.writeStream.format("kafka")
      .option("kafka.bootstrap.servers", "xxx:9092")
      .option("topic", "mergedinfo")
      .option("checkpointLocation", "/tmp/producer/checkpoints")
      .option("failOnDataLoss", false)
      .start()
      .awaitTermination()

the run command:
spark-submit --class taqasi_spark.App --master yarn ./spark_poc-test_memory.jar --executor-memory 10g --driver-memory 10g --executor-memory 10g  --deploy-mode cluster