text:
Q: How can you switch includes on and off in Hotchocolate for EFCore So I'm trying to figure out how to tell EfCore when to apply an include to an IQueryable object based on whether the GraphQl request from the client actually includes the related object.
Example:

*

*2 Classes: Person, Payment

*Theses are kept in 2 different tables and related Person -> Payment in a one to many relationship

*I have 1 GraphQl Query set up to retrieve all people in the Database:
 [UseFiltering]
 [UseDbContext(typeof(DbAccess))]
 public IQueryable<Person> GetPeople([ScopedService] DbAccess db)
 {
     return db.People;
 }

*This returns just the fields in the People table
ex:
query:
{people{sso,payments{amount, recipient{compayName}}}}
response:
{
"data": {
"people": [
{
"sso": "000-00-0003",
"payments": null
}
]
}
}

*In order to get the payments my GetPeople func needs to be changed to
 [UseFiltering]
 [UseDbContext(typeof(DbAccess))]
 public IQueryable<Person> GetPeople([ScopedService] DbAccess db)
 {
     return db.People.Include(p => p.Payments);
 }

*This works but places an unneeded strain when the payments aren't part of the request (as the Include will run every time).
What I would like to do would be something like:
    var baseQuery = db.People;
        if (graphqlRequestIncludePayments)
        {
            baseQuery.Include(p => p.Payments);
        }
    return baseQuery;

But I cannot figure out how to check the GraphQl query to see if payments is requested. I know GraphQl will remove the excess data before returning to the consumer but that can be a lot of wasted bandwidth and memory on the server side.
I feel like there is a way to do this in the Hotchocolate ObjectType.Configure function but I cant see how.
Any help would be much appreciated, thanks :)

A: Tobias Tengler was correct this should be done through Projections


text:
Q: Extract diagonals of each 2D square sub-array from a larger 2D array This is my first programming class and I'm very excited to learn Python for Data Science. I cannot figure out how to write a loop that returns all diagonal numbers in the matrix. Below is the code, how close or far off am I? Thank you!
import numpy as np
cols = 0

matrixA = np.array([[2,0,0], [0,3,0], [0,0,4], [6,0,0], [0,7,0], [0,0,8]])

for rows in range(6):
    if rows == cols:
        print(matrixA[rows, cols])
    cols = cols + 1

A: Your current solution does not work because it does not take into account the fact that matrixA is not square. You will have to take care that your indices do not run out of bounds. Running it gives:
IndexError: index 3 is out of bounds for axis 1 with size 3

This is because the maximum value that cols is allowed to take here is 2.

As an alternative, you could use np.diag:
print(x)
array([[2, 0, 0],
       [0, 3, 0],
       [0, 0, 4],
       [6, 0, 0],
       [0, 7, 0],
       [0, 0, 8]])

res = np.array([np.diag(x, -offset) for offset in range(0, *x.shape)])

print(res)
array([[2, 3, 4],
       [6, 7, 8]])

If you want a 1D result, call np.ravel:
print(res.ravel())
array([2, 3, 4, 6, 7, 8])

A: You don't need heavy library like numpy to achieve this simple task. In plain python you can do it via using zip and itertools.cycle(...) as:
>>> from itertools import cycle

>>> my_list = [[2,0,0], [0,3,0], [0,0,4], [6,0,0], [0,7,0], [0,0,8]]
>>> for i, j in zip(my_list, cycle(range(3))):
...     print(i[j])
...
2
3
4
6
7
8

A: Why have cols at all? It's always the same as rows, right?
for rows in range(6):
    print(matrixA[rows,rows])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Troubleshooting s3 ajax uploader in Django I'm using: https://github.com/GoodCloud/django-ajax-uploader with AWS backend (s3 boto). My file uploads are all 0 bytes, but they upload and the correct filename shows up on the correct bucket. Any thoughts on why the files are all 0 bytes though? I am looking for some higher level considerations.
Here's s3 backend code:
https://github.com/GoodCloud/django-ajax-uploader/blob/master/ajaxuploader/backends/s3.py

A: I believe that if you write to StringIO like that, it positions the file pointer at the end, and there is nothing to upload. You ought to do
buffer = StringIO(chunk)

A: I just encountered something like this. Try calling the method seek(0) on the file to set its current position back to the beginning.

A: The s3 backend for this Ajax uploader is using MultiPart upload.  This will only work for files that are > 100MB and each part must be 5MB or larger.  So, I think what is happening is that it's initiating the Multipart upload and finalizing it but the individual parts are being rejected because they are too small.  So, the result is a zero-length file in S3.


text:
Q: How to access the image url inside a function app I am writing a function app to send emails and I want the email to include an embedded image which is hosted on my different website.
I am using AlternativeViews and adding it to my MailMessage object like so -
mailMessage.AlternateViews.Add(GetEmbeddedImage(@"https://some_domain/xmas.jpg"));
However, the LinkedResource in GetEmbeddedImage is the one throwing an error, if the filePath is an url address like this - https://some_domain/xmas.jpg -
        private AlternateView GetEmbeddedImage(string filePath)
        {
            LinkedResource res = new LinkedResource(filePath);
            res.ContentId = Guid.NewGuid().ToString();
            string imageMarkup = @"";

            string htmlBody = @"

Dear Mr. XYZ,
" + imageMarkup +
                      @"
some message here

Kind Regards,

                     ";

            AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
            alternateView.LinkedResources.Add(res);

            return alternateView;
        }

The error message is
The filename, directory name, or volume label syntax is incorrect. : 'C:\mylocal\EmailFunctionApp\FunctionAppEmailer\bin\Debug\netcoreapp3.1\https:\my_domain\xmas.jpg'


text:
Q: complex analysis(introduction) - locus on Argand diagram satisfying $z^{n-1}=\bar{z}$ ($z\in\mathbb{C}, n\in\mathbb{N}\setminus\{1\}$) Question: Determine on Argand diagram the locus in $\mathbb{C}^{2}$ satisfying: $z^{n-1}= \bar{z} \space (n\in\mathbb{N}\setminus\{1\})$
My attempt: Let: $z:=r(\cos\theta+i\sin\theta) (r:=|z|, \theta:=argz)$ Then:
$z^{n-1}= \bar{z} \iff r^{n-1}(\cos (n-1)\theta+i\sin(n-1)\theta)=r\cos\theta-ir\sin n \theta\iff \begin{cases}r^{n-1}\cos(n-1)\theta =r\cos\theta && (1)\\
r^{n-1}\sin(n-1)\theta=-r\sin\theta  && (2)\end{cases}$
If: $\cos(n-1)\theta \neq 0$ then: dividing $(2)$ by $(1)$ yields: $\tan(n-1)\theta=\tan(-\theta) \implies (n-1)\theta=-\theta+k\pi \space(k\in\mathbb{Z}) \implies \theta = \frac{k\pi}{n}$ In this case the locus is set of rays going from $(0,0)$ satisfying: $\theta=\frac{k\pi}{n} $($\theta$-angle between real line of Argand diagram and given ray)
If: $\cos(n-1)\theta=0$,then:
$\begin{cases}
r\cos(\theta)=0 && (3)\\
r^{n-2}\sin(n-1)\theta=-\sin\theta && (4)
\end{cases}$
$(3)$implies: $\theta=\frac{(2k+1)\pi}{2}\space(k\in\mathbb{Z})$ implying that $(4)$ then yields: $r=1$ (since then sine functions are equal to $(-1)^{l},(-1)^{m}$, where: $l,m\in\mathbb{Z}$ but modulus of complex number is positive). In this case the locus is set of point lying on unit circle centred at $(0,0)$, where angle between real line and segment joining origin and k-th distinct point is $\frac{(2k+1)\pi}{2}$
Troubles: My analysis is incorrect since I think that I should obtain only set of points, while at some point set of rays pops out. Besides, I intuitively feel that my reasoning is incomplete...
Request: Could anyone state gaps in my reasoning, please?
Thanks for help in advance.

A: Here is a different solution to the problem -- if I have more time later, I will try to correct your solution.
We want to solve $z^{n-1} = \bar z$. Multiply both sides by $z$ to get
$$z^n = z \bar z = \left|z\right|^2,$$
so then $\left|z^n\right| = \left|z\right|^2$, so $\left|z\right|^n = \left|z\right|^2$. If $\left|z\right| \neq 0$, then by taking logs we get
$$n \log \left|z\right| = 2 \log \left|z\right|,$$
and if $\left|z\right| \neq 1$ then $\log\left|z\right| \neq 0$, so $n = 2$ by cancellation. In this case, then we are solving $z^{2-1} = z = \bar z$, which has the entire real line as solutions.
Otherwise (if $\left|z\right| = 1$) then we want to solve $z^n = \left|z\right|^2 = 1$; here we see that $z$ must be an $n$-th root of unity.
Thus here are the possible solutions:

*

*If $n = 1$, then $z^{n-1} = \bar z$ if and only if $z = 1$.

*If $n = 2$, then $z^{n-1} = \bar z$ if and only if $z \in \mathbb R$.

*If $n > 2$, then $z^{n-1} = \bar z$ if and only if

*

*$z = 0$, or

*$z^n = 1$ ($z$ is an $n$-th root of unity).

A: Your analysis seems to be correct as is, but you have not proven what you actually want to prove. What you have shown is that if $z^{n-1} = \bar z$, then either

*

*$z$ lies in a ray extending from $0 + 0i$ with angle $\theta = \frac{k\pi}{n}$, or

*$z$ has angle ("argument") $\theta = \left(k + \frac{1}{2}\right)\pi$ and distance from the origin $\left|z\right| = 1$. (Note that then $z$ must be $i$ or $-i$, since only the angle mod $2\pi$ matters.)

This is, in fact, true, but we want a converse. For example, if $n = 4$ then we may consider $z = \frac{1}{2}i$; it certainly lies on the ray from the origin with angle $\theta = \frac{2\pi}{4}$ ($k = 2$), but it is not a solution to $z^{n-1} = \bar z$, since $z^3 = -\frac{1}{8}i \neq -\frac{1}{2}i = \bar z$. What I did in my other answer is show a bidirectional implication: $z$ is a solution to $z^{n-1} = \bar z$ if and only if certain conditions apply to $z$. You proved a half of this: that if $z$ is a solution to $z^{n-1} = \bar z$ then certain conditions apply. You need the other half: if certain conditions apply to $z$, then $z$ is a solution.


text:
Q: Highlight text in nattable cell I have a nettable with different columns and rows filled with data. I want to highlight specific text in cells when some text is searched in a text field.
After lookin into https://www.eclipse.org/nattable/nandn/nandn_150.php
I tried the following but nothing is highlighted when I press the apply button
this.applyButton = new Button(parent, SWT.PUSH);
this.applyButton.addSelectionListener(getSelectionListener());

private SelectionListener getSelectionListener(){
    return new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            String text = textBox.getText();
            if(!text.trim().isEmpty()) {
                applyHighlighting(text);
            }
        }
    };
}

public void applyHighlighting(String text) {
    RegexMarkupValue regexMarkup = new RegexMarkupValue("", "",
            "");
    natTable.addConfiguration(new DefaultNatTableStyleConfiguration() {
        {
            this.cellPainter = new BackgroundPainter(new PaddingDecorator(new RichTextCellPainter(), 2));
        }

        @Override
        public void configureRegistry(IConfigRegistry configRegistry) {
            super.configureRegistry(configRegistry);
            // markup for highlighting
            MarkupDisplayConverter markupConverter = new MarkupDisplayConverter();
            markupConverter.registerMarkup("highlight", regexMarkup);
            // register markup display converter for normal display mode in the body
            configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, markupConverter,
                    DisplayMode.NORMAL, GridRegion.BODY);
        }
    });
    regexMarkup.setRegexValue(text.isEmpty() ? "" : "(" + text + ")");
}

so with this I assumed when I type something in the text field and click on apply button text in the cells provided in the text field should be highlighted but nothing is changed. Any help?
Thanks

A: If you only want to highlight parts of a text inside a cell, you need the Nebula Extension. It is described in the New & Noteworthy of 1.5
https://www.eclipse.org/nattable/nandn/nandn_150.php
There is also a pointer to the corresponding example.


text:
Q: ubuntu with win7 I have ubuntu 13.04 installed on my computer.  Ubuntu on 130gb partition. Ubuntu swap on 10gb separate partition. In addition 300gb partition for data. now i want to:

*

*resize the data partition from 300gb to 250gb.

*live the ubunt os but resize the ubuntu partition from 130gb to 50gb.

*install win7 64 bit on a new partition 130gb (50gb from data + 80gb from ubuntu).

*enable dual boot - ubuntu and win7.
Thank you for help,
David.

A: First you need an Ubuntu Live CD or USB drive and make a live boot.
Then start GParted app.
You can easily make changes in the partition for Ubuntu and other data using this app (Answer for Qn.1 & Qn.2).  For any clarifications , try the following link:
http://www.howtogeek.com/114503/how-to-resize-your-ubuntu-partitions/.
You may easily install windows on the partition you prefer (Qn.3).
After installation,  if you don't get the GRUB (Boot menu) try the following link :
How can I repair grub? (How to get Ubuntu back after installing Windows?) (Qn.4).


text:
Q: Create a custom layout - Magento1.9 I have installed Magento1.9.3.2, I need to create a custom page layout like 1column,2columns,etc... I have tried something but he doesn't work properly.My frontend design displaying a white page.
My codes
app\design\frontend\MyPackage\MyTheme\layout\page.xml
    <page_home translate="label">
        Home Main
        <reference name="root">
            <action method="setTemplate"><template>pages/home.phtml</template></action>

            <action method="setIsHandle"><applied>1</applied></action>
        </reference>
    </page_home>

app\design\frontend\MyPackage\MyTheme\template\pages\home.phtml

test

Any one help.Advance thanks

A: To create a new layout page, you have to create a new module like this:
Lets say that your new layout page call 1column-fullwidth
app/etc/modules/Custom_Column1Fullwidth.xml
<?xml version="1.0"?>
   <config>
    <modules>
      <Custom_Column1Fullwidth>
        <active>true</active>
        <codePool>local</codePool>
        <depends>
            <Mage_Page />
        </depends>
    </Custom_Column1Fullwidth>
    </modules>
   </config>

app/code/local/Custom/Column1Fullwidth/etc/config.xml
<?xml version="1.0"?>
    <config>
         <modules>
            <Custom_Column1Fullwidth>
            <version>0.1.0</version>
            </Custom_Column1Fullwidth>
         </modules>
               <global>
                   <page>
                     <layouts>
                        <Column1Fullwidth translate="label">
                               1Column-fullWidth
                                 <template>page/1column-fullwidth.phtml</template>
                               <layout_handle>1column_full_width</layout_handle>
                        </Column1Fullwidth>
                     </layouts>
                   </page>
              </global>
     </config>

app/design/frontend/{package}/{theme}/page/1column-fullwidth.phtml
<!DOCTYPE html>
    <html lang="<?php echo $this->getLang() ?>">

    <?php echo $this->getChildHtml('head') ?>

    <body<?php echo $this->getBodyClass()?' class="'.$this->getBodyClass().'"':'' ?>>
    <?php echo $this->getChildHtml('after_body_start') ?>

        <?php echo $this->getChildHtml('global_notices') ?>

            <?php echo $this->getChildHtml('custom_notice') ?>
            <?php echo $this->getChildHtml('header') ?>
            <?php echo $this->getChildHtml('topContainer') ?>

                        <?php echo $this->getChildHtml('global_messages') ?>
                        <?php echo $this->getChildHtml('content') ?>

            <?php echo $this->getChildHtml('footer') ?>
            <?php echo $this->getChildHtml('global_cookie_notice') ?>
            <?php echo $this->getChildHtml('before_body_end') ?>

    <?php echo $this->getAbsoluteFooter() ?>

A: app/etc/modules/Custompage_Templates.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Custompage_Templates>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Page />
            </depends>
        </Custompage_Templates>
    </modules>
</config>

A: change your layout as below
app\design\frontend\MyPackage\MyTheme\layout\page.xml
<cms_index_index translate="label">
    Home Main
    <reference name="root">
        <action method="setTemplate"><template>pages/home.phtml</template></action>

        <action method="setIsHandle"><applied>1</applied></action>
    </reference>
</cms_index_index>


text:
Q: NEAR Lake Indexer - Stuck on "#9820210 - Waiting for peers" So I was trying to use the Near Lake Indexer but after completing every step, when I ran
./target/release/near-lake --home ~/.near/mainnet run --endpoint https://my-endpoint  --bucket my-bucket --region us-east-1 --stream-while-syncing sync-from-latest

there is nothing other than
INFO stats: # 9820210 Waiting for peers 0 peers ⬇ 0 B/s ⬆ 0 B/s 0.00 bps 0 gas/s CPU: 0%, Mem: 32.8 MB

Why is it trying to fetch block 9820210 but not the latest one, even though I passed in "sync-from-latest"?

A: You need to follow the standard nearcore network sync procedures: https://github.com/near/near-lake-indexer#syncing
INFO stats: # 9820210 Waiting for peers 0 peers ⬇ 0 B/s ⬆ 0 B/s 0.00 bps 0 gas/s CPU: 0%, Mem: 32.8 MB

This means that your node does not have the network state backup, and it waits to get synced (why it is not happening is not clear to me, and needs to be asked on https://github.com/near/nearcore by providing them with the means to reproduce the issue running neard instead of the indexer).

Why is it trying to fetch block 9820210 but not the latest one, even though I passed in "sync-from-latest"?

stats log is reported by nearcore, which reports the most recent synced block on the node.


text:
Q: How to align log messages using java.util.logging Can someone post how to achieve alignment in log messages:
[10:14:31 main     package1.Class1 <init>  INFO]: initializing data..
[10:14:31 Thread-0 package2.Class2 method1 INFO]: log message

I know I can use log4j but I want to know how to achieve this with JUL.
I tried using MessageFormat, FieldPosition but to no avail.
Thanks

A: You can create you own java.util.logging.Formatter. For that you can extend it this way:
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public final class MyFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();

        // Build output the way you want
        sb.append(new Date(record.getMillis()))
            .append(" \t")
            .append(record.getThreadID())
            .append(" \t")
            .append(record.getSourceMethodName())
            .append(" \t")
            .append(record.getSourceClassName())
            .append(" \t")
            .append(record.getLevel().getLocalizedName())
            .append(": ")
            .append(formatMessage(record))
            .append(System.getProperty("line.separator"));

        return sb.toString();
    }
}

You get the idea.
This is just an example of how you can handle the output and align it using \t. This is not a perfect solution because you don't know beforehand what's the length of SourceMethodName or SourceClassName or any other output field and only one \t may not be enough to align them all, perfectly.
The solution may be in use as many \t as necessary to cover almost all situations you can think of.
That being said, the perfect solution is to save all output infos and, at the end, calculate how many \t to use depending on the lenght of each field.
EDIT:
Instead of \t you can use StringBuilder together with String.format() to a cleaner and easier to read code:
sb.append(String.Format("[%1$-10s %2$-10s %3$-10s]: %4",
    new Data(record.getMillis(),
    record.getSourceMethodName(),
    record.getSourceClassName(),
    formatMessage(record)
));

Check this page on how to use String.format() to format string into tables.


text:
Q: How to check if array of object's properties are empty or not in javascript I want to check the following array have any empty value or not
Example
The following should return true
[
    {
        "price": "12",
        "number": "1"
    },
    {
        "price": "12",
        "number": "1"
    }
]

The following should return false
[
    {
        "price": "12",
        "number": "1"
    },
    {
        "price": "12",
        "number": ""
    }
]

A: You can use Array.some and Object.values to check whether one of the property value's length of an item in the array is smaller than 1:

const arr=[{price:"12",number:"1"},{price:"12",number:"1"}];

const isValid = !arr.some(e => Object.values(e).some(f => f.length < 1))

console.log(isValid)

A:

function isNonEmptyValue(value) {
  return (
    (value != null)
    && (value !== '')
  //&& any other *empty* value constraint
  );
}
function hasEntriesAndNoEmptyValues(item) {
  const values = Object.values(item);
  return (
    values.length >= 1 &&
    values.every(value => isNonEmptyValue(value))
  );
}

console.log(
  [{
    "price": "12",
    "number": "1",
  }, {
    "price": "12",
    "number": "",

  }].every(hasEntriesAndNoEmptyValues)
);
console.log(
  [{
    "price": "12",
    "number": "1",
  }, {
    "price": "12",
    "number": " ",

  }].every(hasEntriesAndNoEmptyValues)
);
console.log(
  [{

  }, {
    "price": "12",
    "number": " ",

  }].every(hasEntriesAndNoEmptyValues)
);


text:
Q: Array not in correct format in Javascript for use by HighChart Hi i'm passing a List object from my controller to Javascript where it is put back into an array and used as a data source for HighChart bar graph.
In my code below if i comment back in the raw data it WORKS. If I use my array variable called 'result' I get nothing
If I step into Javascript with debugger and output result to immediate window it looks like:
?result[0]
{...}
    [0]: "2"
    [1]: {...}
?result[0][1]
{...}
    [0]: 0
    [1]: 0
    [2]: 0
    [3]: 0
    [4]: 0
    [5]: 0
    [6]: 1
    [7]: 0
    [8]: 0
    [9]: 0
    [10]: 0
    [11]: 0
HERE IS THE CODE :
function CreateChart3(surl) {

    // Code block for fetching Array as jsonResult (js)
    var url = $("#AbsolutePath").val() + "Complaint.mvc/GetChartData_MonthlyByType/" + surl;

    var chart;

    $.getJSON(url, null, function(data) {

        var result = [];
        jQuery.each(data, function(i, val) {
            result[i] = [val.Type, val.Count];
        });

        //            var seriesData = [];
        //            for (var i = 0; i < result.length; i++) {
        //                seriesData.push({ data: result[i][1] ,name: result[i][0]});
        //            }

        debugger;
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart3',
                defaultSeriesType: 'column',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: 'Stacked Bar Monthly By Type'
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Total No Of Complaints'
                },
                xAxis: {
                    categories: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
                    title: 'Month'
                },
                stackLabels: {
                    enabled: true,
                    style: {
                        fontWeight: 'bold',
                        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                    }
                }
            },
            legend: {
                backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
                borderColor: '#CCC',
                borderWidth: 1,
                shadow: false
            },
            tooltip: {
                formatter: function() {
                    return '' + this.x + '
' +
            this.series.name + ': ' + this.y + '
' +
            'Total: ' + this.point.stackTotal;
                }
            },
            plotOptions: {
                column: {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                    }
                }
            },
            //                            series:
            //                                 [{
            //                                    name: "2",
            //                                    data: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
            //                                        }, {
            //                                    name: "3",
            //                                    data: [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0]

            //                                    }]
            series: [{
                data: result
                }]
            });
        });
    };

EXTRACT FROM CONTROLLER CODE IF IT HELPS......
         var qry = from i in _db.Complaints
                  where i.Site.SiteDescription.Contains(searchTextSite)
                       && (i.Raised >= startDate && i.Raised <= endDate)
                  group i by i.ComplaintNatureTypeId.ToString()
                      into grp
                      select new
                          {
                              Type = grp.Key,
                              Count = new int[] {
                                  grp.Where(c => c.Raised.Month == 1).Count(),
                                      grp.Where(c => c.Raised.Month == 2).Count(),
                                      grp.Where(c => c.Raised.Month == 3).Count(),
                                      grp.Where(c => c.Raised.Month == 4).Count(),
                                      grp.Where(c => c.Raised.Month == 5).Count(),
                                      grp.Where(c => c.Raised.Month == 6).Count(),
                                      grp.Where(c => c.Raised.Month == 7).Count(),
                                      grp.Where(c => c.Raised.Month == 8).Count(),
                                      grp.Where(c => c.Raised.Month == 9).Count() ,
                                      grp.Where(c => c.Raised.Month == 10).Count() ,
                                      grp.Where(c => c.Raised.Month == 11).Count(),
                                      grp.Where(c => c.Raised.Month == 12).Count() }

                          };

        return Json(qry.ToArray(), JsonRequestBehavior.AllowGet);

A: As I remember data property of series is array of

*

*y-values

*pair of x-y values

*point objects

As I understand every element of your array is array where element[0] is name and element[1] is array of y-values. So you have some number of series. You have to convert manually you result into array of { name: ..., data: ...} objects and pass it to HighCharts constructor. Use for loop:
var seriesData = [];
for (var i = 0; i < result.length; i++){
    seriesData.push({ name: result[i][0], data: result[i][1] });
}

And use series data like:
series: seriesData

A: Looking at the debugger output the JSON isn't what you're expecting.
Hard to say for definite but are you returning the correct object from the controller? It looks like you're returning qry when you should be using grp.


text:
Q: package-lock.json resolution urls are incorrect I have scoped dependencies and npm is configured such that it finds those packages at our private repo:
@kw:registry=https://slug.jfrog.io/artifactory/api/npm/main/
//slug.jfrog.io/artifactory/api/npm/main/:_auth=***
//slug.jfrog.io/artifactory/api/npm/main/:email=***
//slug.jfrog.io/artifactory/api/npm/main/:always-auth=true
registry=https://registry.npmjs.com/

However, in my package-lock.json there remains hundreds of public packages with resolved url values of my private repo, not npmjs.org:
},
    "@babel/runtime": {
      "version": "7.20.0",
      "resolved": "https://slug.jfrog.io/artifactory/api/npm/main/@babel/runtime/-/runtime-7.20.0.tgz",

We previously had all dependencies (scoped and not scoped) resolving to our private repository which proxied requests to npmjs.org. Since defining our scope and configuring it in .npmrc I would expect unscoped packages resolve to the default of npmjs.org.
I'm on an older version of npm, 6.14.15. I've tried purging the lock file and rebuilding with npm i.
Is there a way to change npm 6 behavior so that urls in package-lock.json resolve or default to the public npm registry?


text:
Q: Printing Vec2 x value I am new on c++, I try to print Vec2 value but it prints 0 always.
My code:
Vec2 v[2] = {Vec2(12, 330), Vec2(122, 313) };
for (auto value : v ) {
    CCLOG("x: %d", value.x );
}

How can I fix this

A: x, y values are float
CCLOG("x: %f", value.x );
I though it was int


text:
Q: Jquery get width/height after adjustment I'm trying to get the width or height (depending on the size of a screen) of a image after it's been resized. It's for a gallery and I'm trying to make the outer div to wrap tightly around it however it's not getting the size of image, it's only getting 0px. The value it's trying to get is set as "auto" in CSS so why can't it get the actual value after that's been set?
Any ideas? Here's what I've got at the moment.
Javascript:
function resizeDiv() {
vpw = $(window).width();
vph = $(window).height();
$("#image_holder_main").css({"height": (vph - 30) + "px", "width" : (vpw - 30) + "px"});
if(vpw > vph){
    $("#image_main").css({"height": (vph - 30) + "px", "width" : "auto"});
    $("#image_large").css({"height": (vph - 30) + "px", "width" : $("#image_main").outerWidth() + "px"});
}else if(vph > vpw){
    $("#image_main").css({"height": "auto", "width" : (vpw - 30) + "px"});
    $("#image_large").css({"height": $("#image_main").outerHeight() + "px", "width" : (vpw - 30) + "px"});
}
//$("#image_large").css({"height": $("#image_main").outerHeight() + "px", "width" : $("#image_main").outerWidth() + "px"});

HTML:

X

CSS:
#image_large{
    position: fixed;
    top: 15px;
    left: 15px;
    width: 50px;
    height: 50px;
    z-index: 1000;
}
#image_holder_main{
    width: 100%;
    height: 100%;
}


text:
Q: Why does the red div not float right next to the yellow one? I want to place the red div right next to the yellow one, without removing anything from the code below. It is not possible, is it? By the way, what is this behaviour called, that is caused by the transform, similar to the effect of relative positioning? It would be great to at least know how to call it, if I can't turn it off.

div {
  float: left;
  padding: 20px;
}
div:first-child {
  background: yellow;
  margin-left: 50%;
  transform: translateX(-100%);
}
div:nth-child(2) {
  background: red;
}

This is the first div.

2nd div.

A: Your first div is being transformed left by its width.  You're hoping that the second div can also be transformed left by the first div's width, but that's not possible in CSS.
Instead, you could give the first div absolute positioning, and give the second div a 50% margin-left:

div {
  float: left;
  padding: 20px;
}
div:first-child {
  position: absolute;
  background: yellow;
  margin-left: 50%;
  transform: translateX(-100%);
}
div:nth-child(2) {
  margin-left: 50%;
  background: red;
}

This is the first div.

2nd div.


text:
Q: Sort django admin column by __str__ method I have a Folder model and I want to display the columns in the admin page ordered alphabetically following the __str__ method.
I looked over several similar questions like this one, this one and also this one, but didn't manage to really understand the answers, or at least enough to adapt them to my problem (even though I've been trying for quite some time).
Here is my Folder class, with the str method I want to sort with :
class Folder(models.Model):
    folder_name = models.CharField(max_length=200)
    parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        if self.parent_folder:
            return f'{self.parent_folder}/{self.folder_name}'
        else:
            return self.folder_name

And my FolderAdmin class :
class FolderAdmin(admin.ModelAdmin):
    ordering = ('str',) #I want it to do like that but don't know how to do it

    fieldsets = [
        (None,            {'fields': ['folder_name']}),
        ('Parent Folder', {'fields': ['parent_folder']}),
    ]

    list_display = ('folder_name', '__str__')

I feel dumb for not understanding a question already answered multiple times but if you could help me understand it I'd be grateful.
Thank you in advance !


text:
Q: Opera, jQuery - prevent notice popup on key up I'm trying to build a selector box with search results which can be selected using the keyboard. It's not too hard to do - except when it comes to Opera which I can't prevent from popping up an own selector box (wand form settings) on key down, making it impossible to make a choice from mine.
Here's a little demo: Type something into the box and try to select from my popup with the arrow down... will work as intended in latest Chrome, for example - won't work in latest Opera.
Opera's my favorite, so I need to find a solution just to satisfiy myselve ;-)
http://jsfiddle.net/ujFvn/13/
Thanks for sharing ideas...

A: See jQuery keyup keyCode doesn't work in Opera
Soloution: use autocomplete="off"
<input id="test" value="" autocomplete="off" >

Or if you wan't to keep it clean in JS:
e.preventDefault();

Inside your keyup function.
Hope it helps :)


text:
Q: Binding dropdownlist with database table and get selected item n MVC I am new to asp.net mvc.
I have a employee registration view, where i have a dropdown-list for for department, I want to bind the dropdown-list with a database table tblDepartment and i have did it. But I don't know how to get the select item of the list on post-back.
Employee Controller
[HttpGet]
public ActionResult AddEmployee()
{
    ViewBag.Departments = new SelectList(_department.GetAll(), "id", "name");
    return View(_employee.Get());
}

[HttpPost]
public ActionResult AddEmployee(FormCollection data)
{
    var emp = _employee.Get();
    emp.name = data["name"];
    emp.age = Convert.ToInt32(data["age"]);
    emp.dept_id = Convert.ToInt32(data["dept_id"]); // return dept_id 0 always.
    emp.city = data["city"];
    _employee.Insert(emp);
    return RedirectToAction("Index");
}

View
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.name, "Name", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.age, "Age", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.dept_id, "Department", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("Departments", "Select Department")

            @Html.LabelFor(model => model.city, "City", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

A: You are defining your dropdownlist with name DropDownLists i.e. @Html.DropDownList("Departments" which will be the name of the drop-down list so it will be rendered like:
<select name="Departments">
</select>

and in form post the values are posted in key value pair and the key is the name of the input element.
But in post request you are finding the posted value in dept_id, you need to read from correct key in FormCollection which would be:
emp.dept_id = Convert.ToInt32(data["Departments"]);

Side Note:
You should be using strongly typed helpers to post values directly to model and let the model binder do the magic for you, instead of populating the model manually.
For that your helper method would be DropDownListFor :
@Html.DropDownListFor(x=>x.dept_id ,ViewBag.Departments as SelectList, "Select Department")

and in action method set the parameter to be mode object:
[HttpPost]
public ActionResult AddEmployee(Employee employee)
{
     If(ModelState.IsValid)
     {
        _employee.Insert(employee);
        return RedirectToAction("Index");
     }
     else
     {
         return View(employee);
     }
}


text:
Q: Como criar um modelo no Android? A respeito sobre essa resposta desta pergunta, fiz pergunta para o autor da resposta

Se ele escolhesse armazenar num Array de Objetos, essa
  pergunta tivesse uma imagem o que poderia ser feito.

resposta dele

você pode criar um modelo chamado Pergunta, por exemplo, e ter um
  objeto Bitmap (ou qualquer outra tipagem da sua imagem) dentro do
  modelo. Aí é só criar um List<Pergunta>

A pergunta é o que seria esse modelo e como cria-lo ?

A: Esse modelo é uma classe normal, ela agrupa as informações do que você quiser, nesse caso o Bitmap por exemplo.
É basicamente a ideia de orientação a objetos.
public class Pergunta {

    private String nome;
    private Bitmap imagem;

    public Pergunta() {
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Bitmap getImagem() {
        return imagem;
    }

    public void setImagem(Bitmap imagem) {
        this.imagem = imagem;
    }
}


text:
Q: People Picker, User profile, and AD Sync - small clarification I am a beginner SharePoint developer, here is my question
The people picker fields in SharePoint, fetches data from user profile or AD?
How do I sync user profile to AD?

A: Answering your questions specifically:

*

*The people picker pulls from AD. It can be configured to filter on specific OU and Forest, but by default it searches AD.

*The User Profile Synchronization service in SharePoint 2013 uses a build of ForeFront Identity Manager or direct AD synchronization. The default is to IMPORT from AD to SharePoint UPS. Your question is directional, "sync User Profile to AD" that would be an EXPORT and can be configured in SharePoint 2013 provided you follow the guidance and allow the UPS Service account WRITE permissions on AD. If you are using SharePoint 2016/2019 you must use and external Identity Manager or roll your own synchronization back to AD. It is not provided out of the box.

A: By default SharePoint doesn't get a lot of profile information for the AD and only when a use first accesses the SharePoint Farm.
If you want to have full profile information, you need to configure the User Profile service. And this is not always en easy thing to do. Depending on your SharePoint version, I would opt for AD import if you need only info from the AD. If you need to write back data to the AD you need to configure a sync.
Your options all depend on the version you are running and can be very different between 2010, 2013 and 2016.
This gives you an idea how to properly configure the sync for 2010 (and I think most of it applies to 2013 as well) http://www.harbar.net/articles/sp2010ups.aspx
And for the AD import: http://www.harbar.net/archive/2012/07/23/sp13adi.aspx
I'm only referencing this site http://www.harbar.net, as he is the guru regarding User Profiles.


text:
Q: problema con http get angular 5 el problema es que el método me está retornando undefinded el código es
    getLugares() {
    this._http.get(this.url + 'lugar')  //usar la url que corresponda
      .map(res => res)
      .subscribe(
        res => this.lugares=res,
        err => console.error(err),
        () => console.log('Funciona!')
      );
  }

No es problema del web service ni de la URL porque ya los probé. Además al cambiar la linea 5 así res => console.log(res), en el log me aparece el array  de forma correcta

A: El problema parece ser this.lugares, en ese scope this ya no se refiere a tu objeto original, por lo que utilizar una variable that puede ayudarte:
 getLugares() {
    const that = this
    that._http.get(that.url + 'lugar')  //usar la url que corresponda
      .map(res => res)
      .subscribe(
        res => that.lugares=res,
        err => console.error(err),
        () => console.log('Funciona!')
      );
  }


text:
Q: Exclude files when using "Find Usages" in IntelliJ IDEA In Java source files, when I select a class or a method, then click the right button of mouse, in the pop up context menu, and run Find Usages, the files that use the class or methods are searched out.
But I would like to exclude certain files (e.g. JUnit test files) from the search results.
Where could I configure this?

A: From the docs; you can confgure the Find Usages scope by clicking on the tools icon in the top left hand corner of the Find Usages results.
Here are some screenshots:

*

*Click on the tools icon here:

*

*Click on the build button (... next to the Scope field) to create a Scope and define it like so (in this examples I have included production classes and excluded test classes):

*

*Choose that scope in the Find Usages dialog:

Notes:

*

*You can also chose the precanned scope named Project Production Files from the Scope dropdown

*All subsequent searches will use this scope by default until you choose a different scope.


text:
Q: Ruby to get the value from HTML table which has same elements I have a HTML file code which is shown below:

            Plans
            Basic
            Plus
            Prime

            www.test.com

            <input name="upgrade" type="radio">
           //this span element is hidden

            <input name="upgrade" value="plus www.test.com" type="radio">
           //this span element is hidden

            <input name="upgrade" value="prime www.test.com" checked="" type="radio">
            current

I want to check which plan is the current plan in the page through Ruby Watir. Below is the script:
require 'watir'

browser = Watir::Browser.new(:chrome)

browser.goto('file:///C:/Users/Ashwin/Desktop/new.html')

browser.table(:id, 'plans').tds.each do |table_row|
    if table_row.input(:value, 'plus www.test.com').text =~ /current/i
        p 'current plan status is plus'
    elsif table_row.input(:value, 'prime www.test.com').text =~ /current/i
        p 'current plan status is prime'
    else
        p 'current plan status is basic'
    end
end

But I am getting the output as:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/elements/element.rb:513:in `assert_exists': unable to locate element, using {:value=>"plus www.test.com", :tag_name=>"input"} (Watir::Exception::UnknownObjectException)
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/elements/element.rb:86:in `text'
        from C:/Users/Name/Documents/NetBeansProjects/RubyApplication6/lib/new_main15.rb:8:in `block in '
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/element_collection.rb:29:in `each'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/element_collection.rb:29:in `each'
        from C:/Users/Name/Documents/NetBeansProjects/RubyApplication6/lib/new_main15.rb:7:in `'

But I want the output to be as:
current plan status is prime

Can anyone please help?
Thanks in advance

A: Instead of checking which td element has the "current" text, I would suggest checking which radio has the checked attribute. This reduces the number of elements you have to worry about interacting with.
You can find the selected radio using:
table_row.radios.find(&:set?).value

You can then check the value of the radio to see if it starts with the word "plus" or "prime":
# Note that we scope to the tbody to ignore the header row.
# Also make sure you do `trs` not `tds` for the rows.
table_rows = browser.table(id: 'plans').tbody.trs

# Iterate through the rows and check the checked radio button
table_rows.each do |table_row|
  case table_row.radios.find(&:set?).value
  when /^plus/
    p 'current plan status is plus'
  when /^prime/
    p 'current plan status is prime'
  else
    p 'current plan status is basic'
  end
end

Note that for older versions of Ruby (ie v1.9), you will need to find the selected radio using:
table_row.radios.find { |r| r.set? }.value


text:
Q: How to speed up external merge sort in Java I am writing code for the external merge sort. The idea is that the input files contain too many numbers to be stored in an array so you read some of it and put it into files to be stored. Here's my code. While it runs fast, it is not fast enough. I was wondering if you can think of any improvements I can make on the code. Note that at first, I sort every 1m integers together so I skip iterations of the merging algorithm.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class ExternalSort {

    public static void sort(String f1, String f2) throws Exception {
        RandomAccessFile raf1 = new RandomAccessFile(f1, "rw");
        RandomAccessFile raf2 = new RandomAccessFile(f2, "rw");
        int fileByteSize = (int) (raf1.length() / 4);
        int size = Math.min(1000000, fileByteSize);
        externalSort(f1, f2, size);
        boolean writeToOriginal = true;
        DataOutputStream dos;
        while (size <= fileByteSize) {
            if (writeToOriginal) {
                raf1.seek(0);
                dos = new DataOutputStream(new BufferedOutputStream(
                        new MyFileOutputStream(raf1.getFD())));
            } else {
                raf2.seek(0);
                dos = new DataOutputStream(new BufferedOutputStream(
                        new MyFileOutputStream(raf2.getFD())));
            }
            for (int i = 0; i < fileByteSize; i += 2 * size) {
                if (writeToOriginal) {
                    dos = merge(f2, dos, i, size);
                } else {
                    dos = merge(f1, dos, i, size);
                }
            }
            dos.flush();
            writeToOriginal = !writeToOriginal;
            size *= 2;
        }
        if (writeToOriginal)
        {
            raf1.seek(0);
            raf2.seek(0);
            dos = new DataOutputStream(new BufferedOutputStream(
                    new MyFileOutputStream(raf1.getFD())));
            int i = 0;
            while (i < raf2.length() / 4){
                dos.writeInt(raf2.readInt());
                i++;
            }
            dos.flush();
        }
    }

    public static void externalSort(String f1, String f2, int size) throws Exception{

        RandomAccessFile raf1 = new RandomAccessFile(f1, "rw");
        RandomAccessFile raf2 = new RandomAccessFile(f2, "rw");

        int fileByteSize = (int) (raf1.length() / 4);

        int[] array = new int[size];
        DataInputStream dis = new DataInputStream(new BufferedInputStream(
                new MyFileInputStream(raf1.getFD())));
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
                new MyFileOutputStream(raf2.getFD())));

        int count = 0;
        while (count < fileByteSize){
            for (int k = 0; k < size; ++k){
                array[k] = dis.readInt();
            }
            count += size;
            Arrays.sort(array);
            for (int k = 0; k < size; ++k){
                dos.writeInt(array[k]);
            }
        }
        dos.flush();
        raf1.close();
        raf2.close();
        dis.close();
        dos.close();
    }

    public static DataOutputStream merge(String file,
            DataOutputStream dos, int start, int size) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        RandomAccessFile raf2 = new RandomAccessFile(file, "rw");

        int fileByteSize = (int) (raf.length() / 4);
        raf.seek(4 * start);
        raf2.seek(4 *start);
        DataInputStream dis = new DataInputStream(new BufferedInputStream(
                new MyFileInputStream(raf.getFD())));
        DataInputStream dis3 = new DataInputStream(new BufferedInputStream(
                new MyFileInputStream(raf2.getFD())));
        int i = 0;
        int j = 0;
        int max = size * 2;

        int a = dis.readInt();

        int b;
        if (start + size < fileByteSize) {
            dis3.skip(4 * size);
            b = dis3.readInt();
        } else {
            b = Integer.MAX_VALUE;
            j = size;
        }
        while (i + j < max) {
            if (j == size || (a <= b && i != size)) {
                dos.writeInt(a);
                i++;
                if (start + i == fileByteSize) {
                    i = size;
                } else if (i != size) {
                    a = dis.readInt();
                }
            } else {
                dos.writeInt(b);
                j++;
                if (start + size + j == fileByteSize) {
                    j = size;
                } else if (j != size) {

                    b = dis3.readInt();
                }
            }
        }
        raf.close();
        raf2.close();
        return dos;
    }

    public static void main(String[] args) throws Exception {
        String f1 = args[0];
        String f2 = args[1];

        sort(f1, f2);

     }
}

A: You might wish to merge k>2 segments at a time. This reduces the amount of I/O from n log k / log 2 to n log n / log k.
Edit: In pseudocode, this would look something like this:
void sort(List list) {
    if (list fits in memory) {
        list.sort();
    } else {
        sublists = partition list into k about equally big sublists
        for (sublist : sublists) {
            sort(sublist);
        }
        merge(sublists);
    }
}

void merge(List[] sortedsublists) {
    keep a pointer in each sublist, which initially points to its first element
    do {
        find the pointer pointing at the smallest element
        add the element it points to to the result list
        advance that pointer
    } until all pointers have reached the end of their sublist
    return the result list
}

To efficiently find the "smallest" pointer, you might employ a PriorityQueue.

A: I would use memory mapped files. It can be as much as 10x faster than using this type of IO.  I suspect it will be much faster in this case as well.  The mapped buffers use virtual memory rather heap space to store data and can be larger than your available physical memory.

A: We have implemented a public domain external sort in Java:
http://code.google.com/p/externalsortinginjava/
It might be faster than yours. We use strings and not integers, but you could easily modify our code by substituting integers for strings (the code was made hackable by design). At the very least, you can compare with our design.
Looking at your code, it seems like you are reading the data in units of integers. So IO will be a bottleneck I would guess. With external memory algorithms, you want to read and write blocks of data---especially in Java.

A: You are sorting integers so you should check out radix sort.  The core idea of radix sort is that you can sort n byte integers with n passes through the data with radix 256.
You can combine this with merge sort theory.


text:
Q: Disabled PrintScreen from a windows service Is there any way to prevent user log into a computer to use the printscreen key. I looked all over the net and can't really find any way to make it work. Only way I see is using a windows form , which isn't really an option here.
either c# of vb is fine with me.
Any help will be greatly appreciated.

A: Ok, so something like this...
From http://go4answers.webhost4life.com/Example/monitor-keys-53505.aspx
    Module Keyboard
<DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
Public Function GetModuleHandle(ByVal lpModuleName As String) As IntPtr
End Function
Public Declare Function UnhookWindowsHookEx Lib "user32" _
  (ByVal hHook As Integer) As Integer
Public Declare Function SetWindowsHookEx Lib "user32" _
  Alias "SetWindowsHookExA" (ByVal idHook As Integer, _
  ByVal lpfn As KeyboardHookDelegate, ByVal hmod As IntPtr, _
  ByVal dwThreadId As Integer) As Integer
Private Declare Function GetAsyncKeyState Lib "user32" _
  (ByVal vKey As Integer) As Integer
Private Declare Function CallNextHookEx Lib "user32" _
  (ByVal hHook As Integer, _
  ByVal nCode As Integer, _
  ByVal wParam As Integer, _
  ByVal lParam As KBDLLHOOKSTRUCT) As Integer
Public Structure KBDLLHOOKSTRUCT
    Public vkCode As Integer
    Public scanCode As Integer
    Public flags As Integer
    Public time As Integer
    Public dwExtraInfo As Integer
End Structure
' Low-Level Keyboard Constants
Private Const HC_ACTION As Integer = 0
Private Const LLKHF_EXTENDED As Integer = &H1
Private Const LLKHF_INJECTED As Integer = &H10
Private Const LLKHF_ALTDOWN As Integer = &H20
Private Const LLKHF_UP As Integer = &H80
' Virtual Keys
Public Const VK_TAB As Integer = &H9
Public Const VK_CONTROL As Integer = &H11
Public Const VK_ESCAPE As Integer = &H1B
Public Const VK_DELETE As Integer = &H2E
Private Const WH_KEYBOARD_LL As Integer = 13
Public KeyboardHandle As Integer
' Implement this function to block as many
' key combinations as you'd like
Public Function IsHooked( _
  ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean
    Debug.WriteLine("Hookstruct.vkCode: " & Hookstruct.vkCode)
    Debug.WriteLine(Hookstruct.vkCode = VK_ESCAPE)
    Debug.WriteLine(Hookstruct.vkCode = VK_TAB)
    'MessageBox.Show(Hookstruct.vkCode.ToString)
    If (Hookstruct.vkCode = VK_ESCAPE) And _
      CBool(GetAsyncKeyState(VK_CONTROL) _
      And &H8000) Then
        Call HookedState("Ctrl + Esc blocked")
        Return True
    End If
    If (Hookstruct.vkCode = VK_TAB) And _
      CBool(Hookstruct.flags And _
      LLKHF_ALTDOWN) Then
        Call HookedState("Alt + Tab blockd")
        Return True
    End If
    If (Hookstruct.vkCode = VK_ESCAPE) And _
      CBool(Hookstruct.flags And _
        LLKHF_ALTDOWN) Then
        Call HookedState("Alt + Escape blocked")
        Return True
    End If
    '' disable PrintScreen here
    If (Hookstruct.vkCode = 44) Then
        Call HookedState("Print blocked")
        Return True
    End If
    Return False
End Function
Private Sub HookedState(ByVal Text As String)
    Debug.WriteLine(Text)
End Sub
Public Function KeyboardCallback(ByVal Code As Integer, _
  ByVal wParam As Integer, _
  ByRef lParam As KBDLLHOOKSTRUCT) As Integer
    If (Code = HC_ACTION) Then
        Debug.WriteLine("Calling IsHooked")
        If (IsHooked(lParam)) Then
            Return 1
        End If
    End If
    Return CallNextHookEx(KeyboardHandle, _
      Code, wParam, lParam)
End Function
Public Delegate Function KeyboardHookDelegate( _
  ByVal Code As Integer, _
  ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) _
               As Integer
<MarshalAs(UnmanagedType.FunctionPtr)> _
Private callback As KeyboardHookDelegate
Public Sub HookKeyboard(ByRef f As Form)
    callback = New KeyboardHookDelegate(AddressOf KeyboardCallback)
    KeyboardHandle = SetWindowsHookEx(WH_KEYBOARD_LL, callback, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0)
    MessageBox.Show(KeyboardHandle.ToString)
    Call CheckHooked()
End Sub
Public Sub CheckHooked()
    If (Hooked()) Then
        Debug.WriteLine("Keyboard hooked")
    Else
        Debug.WriteLine("Keyboard hook failed: " & Err.LastDllError)
    End If
End Sub
Private Function Hooked() As Boolean
    Hooked = KeyboardHandle <> 0
End Function
Public Sub UnhookKeyboard()
    If (Hooked()) Then
        Call UnhookWindowsHookEx(KeyboardHandle)
    End If
End Sub

End Module
Also, I looked at this and a few others, seems to be stuff you are looking for
Global System  Hooks in .NET
 http://www.codeproject.com/KB/system/globalsystemhook.aspx


text:
Q: jQuery Submit is not working? I used modal of bootstrap and when i click Add Changes button, nothing happens.. :(
Script in head:

My modal in body:

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Confirm your change

Are you sure you need to add these ?

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button id="addBtn" class="btn btn-primary">Add changes</button>

and my form in same body
<form id="programFormDropDown" action="../hDashBoard/project">

.....

can you give some idea?

A: You seem to have forgoten a # in your selectors, unless you are using Mootools which gets the ID with $('id') try this:
$("#addBtn").click(function() {
   ^
    $("#programFormDropDown").submit(function(event) {
       ^
    });
});

A: You seem to be missing the '#' reference from your selector.

A: you have miss # in two selector jquery
try this:
$("#addBtn").click(function() {
    $("#programFormDropDown").submit(function(event) {
    });
});

instead of this:
$("addBtn").click(function() {
    $("programFormDropDown").submit(function(event) {
    });
});

A: Looks like you are not looking for ajax submit, in that case change the button type to submit like
<button id="addBtn" class="btn btn-primary" type="submit">Add changes</button>

if you want to use script
/add script in dom ready handler
jQuery(function () {
    //use id selectors - # in front of id
    $("#addBtn").click(function () {
        //call the dom elements submit method
        $("#programFormDropDown")[0].submit();
    });
})


text:
Q: Download and display html files I have to download contents of an HTML file (which uses image) via REST API. Then store them for offline use. When needed I want to display the HTML page with a WebView (of course with image). The REST result should look something like:
{
"id": 45,
"html": "<!DOCTYPE html>
My Heading

My paragraph.
",
"imagePath": "abc.com/images/54289847.jpg",
"moreData": "something more"
}

So, what will be the most efficient way to do this?
I'm planning encrypted contents of HTML will go to local storage in any file. Same thing for the images. And then decrypt, and load to WebView. But will it work for images?
I don't need any code, just suggest me a way.

A: in this example string is loaded to webview
String summary = "You scored 192 points.";
       webview.loadData(summary, "text/html", null);
what if you get string from input stream  and pass it to web view      IOUtils.toString(context.getResources().openRawResource())

A: Im not an android developer, but can't you get the "image data-url" and use as the image itself?
For example your avatar's data-url is:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADYUlEQVRYhe2W7UtTYRjGj2VqZSFC4AtSS+d8Wa5pKaWbnql7dVMsxEjDisjMVAoKkvxgUEFZhJVT6MWioBeCvkX0j/SxP0D6srOzuZ1zdZ9ztnl0x9cZEvjh5kx39jy/+7qv+34ehhnwYUtjG+D/AbiqipX+t+kA0uLDPhT2enCxw4VJuwNTLXb4Ke46HXCddiPzQtvCu5sKMOJDTbcH362tEA02oJgFypdECYs/lc2453Ag+3Lb+iGW/WLIi3HKEBUW2sQC7jCLQIV2CDGYOWMznKSIBJ4awDUvPrJ2oJBFuLMckTs54L1GBHQOBKoalwWRFdHb0N/uTAGA6MdclLmOBVdmQfRJBvCVgTiVicjoAYROlSNQbltZDYKwdLnXVo6lhjOf8QClNnDSgpVN4FkThIls4A0DfGIQ7tMhkOdBoMy2OFRQkhK/Tc1IG/CuE4Dc/oMMJy0gLyY9i5wItZohTmQCMwyio7ngm46BbzCDt1I0VNOzGsH6Ohk4AUGGvd7mXF0Fdfa6HsreEMuegjNbMD9cBFHK3p8GTDMyBGbTFEVmGeX5gcAIkKs9qUDHVPhV1wJmcBUV1ACDPie5fiF7ru4EhGc7gXeMsrlWzMRK01NCJl3wgpSEVEo9JbWiCuo/pmm4JOSPL6RvQWQoX9lIA0Cc3I35/iJwpc2J7NVl6O10rRHgig8/La1JAIGDDgXgrcbmM+ngJdmLXOCO1Ce3JcWljlQBaADN3yhILgMpIvozECSFeHcVIg+zwBmsKQAsUwKpvXjrUYgv0xcD+CneM7I6kZE8iGRITuoCdTuuqwRLTagC4IxNEJ9nLfjgxQ4I4/sRpQkZvZ0L8RUjl4i3mZSZsCETarRhwohkMOHRPgVgilrwdRqEx9kIn9XTHKhFdCwH+EydcJ6G1CHbBttQaxAljMgicitf3kR4sAfC010IdRkQtB6nDR0ItRuAL1SOwQL53Y0NIq1RrJoJvMuE8Lli2XBBtkbZSALV2RDyGYFvBHAzn4BSGcXqw6iYTSqF1BGyydSHEX2WgKL39yLcXQpB35jCYRSP+HGsBaEVZFLebqb3rfJvUjuO4xG/kFA2kqQrgchHsMmCORO7SRcSVTlqut1rv5L1beaVTGXMrbuULgXZkmv5v45tgK0G+At38NtPjlXm2AAAAABJRU5ErkJggg==

If you paste this in your computer's browser(as url) and/or in  tag, you'll see your avatar.


text:
Q: Guide to good text file IO C/C++ on linux I often find myself needing to write functions to load/save from/to ASCII (or similar) text files; such as config files or data. I can and have done so many times but never feel like I do it well. ie the results are not very tolerant of minor changes to the file format.
Can anyone point me to a good guide to writing robust text file io or even better some libraries to make it easier?

A: Off the top of my head, there's:

*

*Glib's key-value file parser

*YAML
Both of these are pretty standard under linux.

A: YAML is a really good choice. Here we use yaml-cpp
my2c


text:
Q: how to manage dynamics crm Solution Programmatically? I want to create a windows Form App to do This :

*

*Create a new dynamics CRM solution Publisher.

*Create 5 Solution with this Publisher .

*I have two managed Solution in my SharePoint and I want to import it
to dynamics CRM.

Can anyone tell me how much time I will need to achieve This.
I will be gratefully if you can give me some tips or links to this topic.

A: i have to give you some bad news
Dynamics SRM has deprecated their API and so the only way currently to create and manage environment is through PowerShell.
here is a link to the modules you are going to need in order to create and manage you Dynamics CRM:
Microsoft.PowerApps.Administration.PowerShell
Microsoft.Xrm.Data.Powershell
Microsoft.Xrm.Tooling.ConfigurationMigration
the last one is a bit tricky so you are looking for the cmdlet - Import-CrmDataFile


text:
Q: Automation for selecting dropdown items in the webpage I am trying to automate the process of filling the webpage which has lot of selection list.
can anyone suggest how to get start with it.
Can i use javascript.
Additional info:
Website is not hosted by me, third party site.
Regards
Su

A: As an example of how to select a menu item from a drop down list, go to this website: http://nzbindex.com. See the "Maximum age" drop down? If I wanted to select the first menu item under that (30 days), with the web page frontmost in Safari I can run the following. Of course you have to look at the html code of the web page to figure out the name of that drop down menu (in this case "age"). I hope that helps.
tell application "Safari"
   tell document 1
      do JavaScript "document.getElementById(\"age\").selectedIndex = 1;"
   end tell
end tell


text:
Q: RedirectToAction in ASP.Net MVC I'm using ASP.net MVC 4
I have a controller following:
public class PersonController : Controller
{
    public ActionResult Edit(int id)
    {
        //todo something.........
    }

    [HttpPost]
    public ActionResult Edit(PersonModel model)
    {
        //todo something.........
        return RedirectToAction("Edit", model.Id); // => Okay
    }

    public ActionResult Create()
    {
        //todo something............
    }

    [HttpPost]
    public ActionResult Create(PersonModel model)
    {
        //todo something........

        return RedirectToAction("Edit", new { id = model.Id } ); //=>Okay
        //return RedirectToAction("Edit", model.Id); // => exception???, but Edit Action is Okay**
    }
}

A: I think you got the exception because the RedirectToAction Method has 6 signatures and when you write RedirectToAction("Edit", model.Id); it can be considered as a string and will search for a controller with the name model.Id.
Have a look here MSDN:RedirectToAction. Hope it will help you

A: By default MVC supports 'ID' andnot 'id' or any other:
In your code ::
public ActionResult Edit(int id)
{
    //todo something.........
}

here you have declared int id
because of that ::
return RedirectToAction("Edit", model.Id);

this is not working.
If you have been declared your Edit action as::
public ActionResult Edit(int ID)
{
    //todo something.........
}

then you can use this::
return RedirectToAction("Edit", new { @Id = model.Id } );


text:
Q: How do I open the root.disk in linux? When doing a wubi install of linux from windows, the place/file where all linux info is saved is inside a "root.disk" file.
I am intending on formatting my laptop to run linux only and I can't seem to find a way to open this root.disk file from linux itself (to extract some of the files from my previous installation). Of course, it does and is able to open in windows using a certain software, but because I will only have linux on my system now, does anybody know how to open this file in linux itself? It's kind of strange that it isn't able to open with the default linux tools.
Specs:
I am using Linux Mint 12 (via wubi install). Intending on moving to a 'lighter' version of linux.

A: You need to mount this image before you can access it, try the following:
mkdir olddisk
sudo mount -o loop /path/to/root.disk olddisk

You should now be able to access the data inside this container.


text:
Q: read each cell values and store result in another column VBA i have set of values in column A
need to select each cell value up to end of values entered
and after some operation i need to add the result in column B
A1 result to be stored in B1
A2  in B2
please help

A: Sub LearnVBA()

    Dim c As Range
    For Each c In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
        ' do something with each row
        ' for example add todays date to each cell
        Range("B" & c.Row) = Range("A" & c.Row) & Chr(32) & Now
    Next

End Sub


text:
Q: Google Play Store - Unable to Install App on Tablet Device. While trying to install it show this error- Your device isn't compatible with this version Android Tablet - Your Device isn't compatible with this version
I have my android app published in google play store with considerable number of installations. Recently i have released a new version(Update).
For Mobile device users everything was fine. They were able to update / install the latest version without any issues.
The problem is with Tablet Users - After this update the tablet device users were unable to install the latest version of my app from google play store. The installation screen shows Your device isn't compatible with this version error message for new tablet users(Attached Screenshot for reference).
For existing tablet users the update is not available , they are still using the previous version.
I have searched for solutions and tried the most common solutions posted in the internet. I already tried the below solutions and none of them fixed the issue

*

*Restarting Device

*Clear cache & Clear Data of Google Play Store App

*Uninstall Google play updates

*Updating the Android OS

*Clear cache & Clear Data of Google Services Framework

*Side loading the app (Downloading the APK file using a browser from other place like google drive) -  This one works but still i need my app available for tablet users in Google play store.

Below are some of the key changes i have made in the application code in the new build

*

*In this update i have Migrated to AndroidX.

*In this update, i have updated to Java 11.
My Project Level Gradle File :
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.4'
        classpath 'com.google.gms:google-services:4.3.10'
    }
}
allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io"}
        maven { url "https://maven.google.com" }
    }
}

My Application Level Gradle File :
apply plugin: 'com.android.application'
android {

    lintOptions {abortOnError false}

    compileSdkVersion 29

    //buildToolsVersion '27.0.3'
    //buildToolsVersion '25.0.0'

    useLibrary 'org.apache.http.legacy'

    defaultConfig {

        applicationId "app id here"

        versionCode "version code here"

        versionName "version name here"

        minSdkVersion 21

        targetSdkVersion 31

        multiDexEnabled true

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }

    dexOptions {
        javaMaxHeapSize "2g"
    }

    buildTypes {
        release {
            minifyEnabled true
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }

    sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } }
}

dependencies {

    implementation files('libs/picasso-2.5.2.jar')

    implementation files('libs/radial-menu-v4.jar')

    implementation files('libs/YouTubeAndroidPlayerApi.jar')

/**
    compile('abbi.io:abbisdk:+')
    {
        exclude module: 'support-v4'
        exclude module: 'appcompat-v7'
    }
**/

    implementation 'androidx.appcompat:appcompat:1.0.0'

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation 'com.google.android.gms:play-services-base:15.0.0'

    implementation 'com.google.android.gms:play-services-maps:15.0.0'

    implementation 'com.google.android.gms:play-services-location:15.0.0'

    implementation 'com.google.android.gms:play-services-auth:15.0.0'

    implementation 'com.facebook.android:facebook-android-sdk:4.+'

    implementation 'com.github.QuadFlask:colorpicker:0.0.10'

    implementation 'com.github.clans:fab:1.6.3'

    implementation 'androidx.cardview:cardview:1.0.0'

    implementation 'androidx.recyclerview:recyclerview:1.0.0'

    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'

    implementation 'com.github.devlight:infinitecycleviewpager:1.0.2'

    implementation 'com.github.arimorty:floatingsearchview:2.0.3'

    implementation 'com.androidadvance:topsnackbar:1.1.1'

    implementation 'com.google.maps.android:android-maps-utils:0.5'

    implementation 'io.branch.sdk.android:library:4.3.0'

    implementation 'androidx.browser:browser:1.0.0'

    implementation 'com.google.android.gms:play-services-ads:15.0.0'

    //compile 'com.google.android.gms:play-services-appindexing:9.0.0'

    implementation 'com.google.firebase:firebase-appindexing:15.0.0'

    implementation 'com.google.firebase:firebase-messaging:18.0.0'

    implementation 'com.google.android.material:material:1.0.0'

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'

    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'

    //compile 'abbi.io:abbisdk:+'

    implementation 'com.google.code.gson:gson:2.8.0'

    implementation 'androidx.multidex:multidex:2.0.0'

    //implementation 'com.google.android.gms:play-services-places:11.4.0'

    implementation 'com.elconfidencial.bubbleshowcase:bubbleshowcase:1.3.1'

    implementation 'com.getkeepsafe.taptargetview:taptargetview:1.13.3'

    implementation 'com.wdullaer:materialdatetimepicker:3.6.4'

    implementation 'com.google.code.gson:gson:2.8.5'

    implementation 'com.google.android.libraries.places:places:1.1.0'

    testImplementation 'junit:junit:4.12'

    testImplementation 'org.mockito:mockito-core:1.10.19'

    implementation 'fr.bmartel:jspeedtest:1.32.1'

    implementation 'com.facebook.spectrum:spectrum-default:1.1.0+'

    //BEGIN AWS DEPENDENCIES
    def aws_version = "2.16.+"

    implementation "com.amazonaws:aws-android-sdk-s3:$aws_version"

    implementation "com.amazonaws:aws-android-sdk-sqs:$aws_version"

    implementation ("com.amazonaws:aws-android-sdk-mobile-client:$aws_version") { transitive = true }

    implementation 'info.hoang8f:android-segmented:1.0.6'

    implementation 'de.hdodenhof:circleimageview:3.1.0'

    implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

    implementation 'org.apache.httpcomponents:httpcore:4.4.1'

    implementation 'org.apache.httpcomponents:httpclient:4.5'

    implementation 'org.apache.commons:commons-lang3:3.12.0'
}

apply plugin: 'com.google.gms.google-services'

Note :

*

*I'm still using java language for my coding.

*My Application is working fine for mobile users with Android 13 also.


text:
Q: Unreal Engine Gravity, AddImpulse & Physics Hey guys I wanted to know if the physics in unreal engine aka gravity, Addimpulse are frame rate dependent meaning the output will be affected by the machine's current FPS in-game. if that is the case how can I make a Ball fall down on every machine equally how to use Getworlddeltaseconds with gravity or Addimpulse will be greatly appreciated.

A: Well, it is a little context-dependent question. By default physics updates every frame so yes, it is framerate-dependent, but at the same time it takes into count time between updates so in most cases that dependency is not noticable.
However, if you still need more acurate and determinable physics you may want to tweak physics sub-stepping parameters (documentation) to achieve what you need. What this feature basically does is it forces engine to call additional physics updates between rendering ticks once every time interval. Be careful tough as if your simulation takes longer to process then defined time interval whole physics update sequence may break.
Hope that answers your question.


text:
Q: R summary() equivalent in numpy Is there an equivalent of R's summary() function in numpy?
numpy has std, mean, average functions separately, but does it have a function that sums up everything, like summary does in R?
If found this question which relates to pandas and this article with R-to-numpy equivalents, but it doesn't have what I seek for.

A: 1. Load Pandas in console and load csv data file
import pandas as pd

data = pd.read_csv("data.csv", sep = ",")

2. Examine first few rows of data
data.head()

3. Calculate summary statistics
summary = data.describe()

4. Transpose statistics to get similar format as R summary() function
summary = summary.transpose()

5. Visualize summary statistics in console
summary.head()

A: If you are looking for details like summary() in R i.e

*

*5 point summary for numeric variables

*Frequency of occurrence of each class for categorical variable

To achieve above in Python you can use df.describe(include= 'all').

A: No. You'll need to use pandas.
R is for language for statistics, so many of the basic functionality you need, like summary() and lm(), are loaded when you boot it up. Python has many uses, so you need to install and import the appropriate statistical packages. numpy isn't a statistics package - it's for numerical computation more generally, so you need to use packages like pandas, scipy and statsmodels to allow Python to do what R can do out of the box.


text:
Q: Async custom validators mongoose I'm trying to do some async custom validations in mongoose@6.6.1
`
const courseSchema = new mongoose.Schema({
  tags: {
    type: Array,
    validate: {
      validator: async function (v) {
        return await validateTags(v);
      },
      message: "A Course should have atleast one tags.",
    },
  }
});

const validateTags = async (v) => {
  setTimeout(() => {
    return v && v.length > 0;
  }, 2000);
};

`
This is to check whether the given input has atleast one value in it's array. But I am not getting validated properly. Reffered Mongoose: the isAsync option for custom validators is deprecated. Can anyone help?

A: Have you tried to call the validateTags to see what it returns?
Aswer: undefined and also it returns immediately, it does not wait for the timeout to fire.
The setTimeout with return does not work the way you think.
const validateTags = async (v) => {
  setTimeout(() => {
    // the result of the line bellow is returned to the caller of this function
    // and that is the setTimeout not the validateTags !!!
    return v && v.length > 0;
  }, 2000);
};

Try this instead:
const validateTags = async (v) => {
  return new Promise(function(resolve, reject){
      setTimeout(() => {
        resolve(v && v.length > 0);
      }, 2000);
  });
};


text:
Q: Where to throw exception handles? I'm trying to write a class that does data validation as the user enters data for the instance variables. There is no main method in this class only constructors. User input is done in a test harness. My question is do I do the exception handling in the set methods as I have done here? or should I do a try and catch in one of the constructors?
public class Customer
{
  private String fName;
  private String lName;
  private String custTIN;
  private int custNbr;
  private int custHonor;

  public Customer(String first, String last, String tin, int cust, int honor)
  {
    setFName(first);
    setLName(last);
    setCustTIN(tin);
    setCustNbr(cust);
    setCustHonor(honor);
  }

  public Customer(String first, String last, int cust, String tin)
  {
    setFName(first);
    setLName(last);
    setCustTIN(tin);
    setCustNbr(cust);
  }
  /**************************************************************************************************************
    * Set & Get Methods
   **************************************************************************************************************/

  public void setFName(String first) throws InvalidCustomerException
  {
    if(first == "null")
    {
     throw new InvalidCustomerException("You did not enter any data");
    }
       else
       {
        fName = first;
       }
  }

  public void setLName(String last)
  {
   lName = last;
  }

  public void setCustTIN(String tin)
  {
   custTIN = tin;
  }

  public void setCustNbr(int cust)
  {
   custNbr = cust;
  }

  public void setCustHonor(int honor)
  {
   custHonor = honor;
  }

  public String getFName()
  {
   return fName;
  }

  public String getLName()
  {
   return lName;
  }

  public String getCustTIN()
  {
   return custTIN;
  }

  public int getCustNbr()
  {
   return custNbr;
  }

  public int getCustHonor()
  {
   return custHonor;
  }

  /****************************************************************************************************************
    * toString Methods
   ****************************************************************************************************************/
  //public String createSalutaion()
  {
  }//end createSalutation()

  public String toString()
  {
    return String.format ("%d %s %s, Customer number %d, with Tax Id: %s", getCustHonor(), getFName(), getLName(), getCustNbr(), getCustTIN());
  }//end toString()

}

Here is my exception class.....
/**
 * Auto Generated Java Class.
 */
public class InvalidCustomerException extends Exception
{
  private String inputValue = "null";

  public InvalidCustomerException(String message)
  {
   super(message);
  }

  public InvalidCustomerException(String message, Throwable cause)
  {
   super(message,
        cause);
  }

  public InvalidCustomerException(String message, String inputValue)
  {

  }

  public InvalidCustomerException(String message, String inputValue, Throwable cause)
  {

  }

} // end of invalid customer exception

A: Personally, I like to make sure that bad data never gets passed in the first place, with try-catches and throwing of errors (IllegalArgumentException, generally, because it is, after all) in whatever is collecting the data passed to the constructor.
But to answer your question, it would probably be best to intercept the errors as soon as possible to avoid undefined behavior or garbage in garbage out in later functions that rely on input data being correct, with, and this is the thing here, the ability to resubmit input that got messed up.  But as you don't directly set your instance variables, your setup works well enough, as long as you can get data from the user to rectify whatever got messed up.


text:
Q: How to find the size of these RAM sticks? Some time ago I cleaned up mess in my room and found 2 RAM chips. Can I find out somehow how much memory it contains without pluging it in the computer?
p.s It seems, both of the chips are DDR.

*

*One of it is Samsung and has the following text on each subchip it contains:
SAMSUNG     428
K4H560838E-TCCC
H56 8 BEF986BA

*The second one is HYNIX and has this text on each subchip:
HYNIX 147A
HY5DU28822AT-H
KOREA 7E80256M

A: Google'd the part numbers:

*

*K4H560838E-TCCC for Samsung and found 256 MB from here and here

*HY5DU28822AT-H for Hynix and found 128 MB
from here
and here
With older memory there may be wrong data on the Internet. Only sure way would be to install in a system and check on the BIOS screen.


text:
Q: Not sure why my code to check if a number is prime is not working? I need to create a program to check whether a number is prime that first prompts the user to enter a number and then input a string of up to 3 characters. If more than 3 characters are entered via the keyboard, the program should output the message and exit. If a non-numeric character is entered via the keyboard, the program should output the message Invalid input and exit. If the input is valid, the program should display either the
message number entered is a prime number or the message number entered is not a prime number.
I currently have the code to determine whether the number is prime but it does not seem to work, it does not give an output of "is a prime number" when the number entered is prime. Can anyone see where I have gone wrong with the prime number code?
def isPrime(n):
    for i in range(2, n):
            if (num % i) == 0:
                print("is not a prime number")
                break
    else:
            print("is a prime number")

str = input('Please enter a decimal number: ')
try:
    n = int(str)

    if len(str) > 3:
        print ('Invalid input')
    sys.exit()

    if isPrime(n):
        print ('Number entered is a prime number')
    else:
        print ('Number entered is not a prime number')
except:
    print ('Number is not a prime number')

A: with the input() command you prompt the user to give u an input. What u get is an string.
Then u can turn this to an integer and make different cases.
NOTE: if u enter a float number the int(str) will blow up and u will get a message
invalid input. Maybe u should also include a case where u check out if the input is a number, but not an integer.
import sys

def isPrime(n):

    for i in range(2, n):
        if (n % i) == 0:
                return False

    return True

str = input('Give an integer, with no more than 3 digits: ')
try:
    n = int(str)

    if len(str) > 3:
        print ('Invalid input! Up to three digits!')
        sys.exit()

    if isPrime(n):
        print ('Is prime')
    else:
        print ('Not prime')

except:
    print ('Invalid input! Not a number')


text:
Q: Proof for a property of a triangle In the below image, $H$ is orthocenter of the $\triangle ABC$ and I need to show that quadrilateral
$ACDF$ is cyclic.

I am able to conclude that $\angle 1 =\angle 2 =90^{\circ}$  suggesting that $AC$ can be diameter of such a circle. So If I say that since line $AC$ subtends right angle at points $F$ and $D$ therefore it can be diameter of circle passing through points $A,C,D,F$. Hence these points can be concyclic if $AC$ is taken as diameter of such a circle. This question was asked to me in a class test and I wrote above proof but got a zero for it.
Can I proof this in some other better way?


text:
Q: python performance of subsequent call to os.listdir I'm performing a heavy glob operation on a network drive (a CIFS share on a NAS) from a windows machine.
(CPython, v2.7.6)
The folder "Project" contains 1 To for 15 840 files and 1232 folders.
(I'm usinf the glob module which is calling os.listdir() recursively)
The following script is loaded in IDLE and I'm doing "Run Module" multiple times
import timeit
import glob

globPath = u'Z:/Project/*/*/*/*'

def native_glob():
    glob.glob(globPath))

print timeit.timeit(native_glob, number=1)

first call:
>>> 64.4641505602

next and every other call (+- .5 sec):
>>> 2.07747177124

(The command returns 4125 files)
The first call highly depends on the network charge, it was in a range from 100 sec to 40 sec, but subsequent calls are always around 2 sec each.
It looks like there is a caching mechanism behind this.

*

*Can anyone reproduce this behavior ?

*Is this only related to windows or is this coming from python ?

A: Python doesn't do any caching of os.listdir() calls, this is entirely down to Windows.
Any network directory listing is going to be slow until cached, and folder listings on a remote network-shared drive are no exception.


text:
Q: global python lists in external module replacing each other's values I have a file config.py with two values
score_param = [-3.24097637368454,0,0,0,0,0]
p = [-3.24097637368454,
 0.587524975207248,
 0.630901213219356,
 0.647563874895472,
 -0.547490987136909,
 -0.851756955173558,
 -0.840787900229345,
 -0.230491995673875]

When I import this module to another one called config_beta.py and call in a loop config.score_param, it takes values of config.p
EDIT (importing config.py in config_beta.py):
congif_beta.py
from config import *

importing config_beta.py
import importlib
import sys
#import parameters

env = sys.argv[1]

config = importlib.import_module('config_'+env)
param = config.score_param

for i in range(1,100):
    print param

Offcourse, the above code was in a class with multiple objects being initited. I can't share the entire code for confidentiality.
To combat this I created a new list for score_param as
param = [config.p[0],0,0,0,0,0]

Is this because the first value of p and score_param the same and both are global in the config.py
It could also be some other issue but I would like to know if I am getting wrong some basic practice of declaring global variables in external modules.


text:
Q: Closest value in DataTable I am currently trying to find the value of a column by comparing the value of another column with a reference number.
Let me explain:
I have a DataTable with 2 columns.
ID    DATA
1     120
2     200
3     -60
4     478

I want to find the ID of the DATA closest from 0.
In this case the correct value will be -60 and the ID 3
I actually do that
int closestId = dtQueryLambda.AsEnumerable().Where(x => x.Field<double> ("DATA") > 0 ||
                                                        x.Field<double>("DATA") < 0)
    .Select(x => x.Field<Int32>("ID"))
    .First();

Can someone help me?

A: You can use Aggregate method like this:
double baseValue = 0; // or something else
int closestId = dtQueryLambda.AsEnumerable()
    .Select(dr => new
    {
        Id = dr.Field<int>("ID"),
        Diff = Math.Abs(dr.Field<double>("DATA") - baseValue)
    })
    .Aggregate((a, b) => b.Diff < a.Diff ? b : a).Id;

The above is an efficient standard LINQ To Objects approach. With MoreLINQ it's even simpler:
int closestId = dtQueryLambda.AsEnumerable()
    .MinBy(dr => Math.Abs(dr.Field<double>("DATA") - baseValue))
    .Field<int>("ID");

A: Sort by the absolute value and then select the first
var closestId = dtQueryLambda.AsEnumerable()
    .OrderBy(x => Math.Abs(x.Field<double>("DATA")))
    .Select(x => x.Field<Int32>("ID"))
    .First();


text:
Q: Получения значения по ключу в HashMap,LinkedHashMap,Map Всем привет,у меня закрался довольно интересный вопрос в ходе роботы с Map. Итак, у меня есть массив который заполняется случайными числами, позже я сравниваю эти числа с другим массивом ( также заполнятся случайными числами ), если числа совпадают True, иначе False.Вопрос: я хочу посчитать чего больше True или False ( +1 если совпадает условия ).
P.s в ходе написания вопроса я решил данную задачу, решил оставить вопрос, для тех кому ( возможно ) понадобится. Но также буду рад вашим вариантам решения задачи. Возможно кто-то знает способ который лучше/быстрее/эффективней решает задачу
Код:
package Collections;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

public class lalaalal {
    public static void main(String[] args) {

        int numbers ;
        Integer randomNumber;
        ArrayList<String> arrayListmain = new ArrayList<>();
        ArrayList<String> arrayListmain2 = new ArrayList<>();

        Map<Integer,String> linkedHashMapArray= new LinkedHashMap<>();

        for (int i = 0; i < 100; i++) {
            // randomNumber =20+ (int) ( Math.random() * 80 );
            randomNumber =1+ (int) ( Math.random() * 10 );

            arrayListmain.add(randomNumber.toString());

        }
        for (int i = 0; i < arrayListmain.size(); i++) {

            randomNumber =1+ (int) ( Math.random() * 10 );
            arrayListmain2.add(randomNumber.toString());

        }
        int countNumberFalse =0;
        int countNumberTrue = 0;

        System.out.println("Welcome to Create second array and Compare with first");

        System.out.println(arrayListmain + "First Array\n");

        System.out.println(arrayListmain2 + "Second Array\n");

        for (int  i =0  ; i < arrayListmain.size(); i++) {

            if (arrayListmain.get(i).equals(arrayListmain2.get(i))){
                linkedHashMapArray.put(i,"True");
            }
            if (!arrayListmain.get(i).equals(arrayListmain2.get(i))){
                linkedHashMapArray.put(i,"False");
            }

        }

        System.out.println("linkedHashMapArray: "+linkedHashMapArray);
        System.out.println("Size:"+linkedHashMapArray.size());

        // Собственно то самое получения значения ( value ), сначала я добавляю значения в linkedHashMapArray (
        // циклом выше ) позже при linkedHashMapArray.get достаю значения по номеру ( который
        // я циклом выше добавляю ) ключа и сравниваю его с значения String

        for (int i = 0; i < arrayListmain.size(); i++) {
//                                System.out.println("I="+i);

            if (linkedHashMapArray.get(i)== "True"){

                countNumberTrue +=1;

            }
            else if(linkedHashMapArray.get(i)== "False") {

                countNumberFalse +=1;

            }

        }
//
        System.out.println("True:"+countNumberTrue +"False:"+countNumberFalse);

    }
}

A: Да, есть способы решить данную задачу более правильно.

*

*Вам для решения задачи не нужно использовать список из строк. Вы работаете с целыми числами - объявите ArrayList и сразу отпадет необходимость преобразовывать числа в строки.

*Для генерации целых чисел вместо Math.random() можно использовать nextInt() класса java.util.Random.

*Для подсчета числа совпадающих элементов достаточно использовать один цикл и переменную-счетчик.

Прикрепляю свой вариант для примера:
final int NUM_OF_ELEMENTS = 100;

ArrayList<Integer>
    firstList = new ArrayList<>(),
    secondList = new ArrayList<>();

Random random = new Random();

// Заполнение коллекций случайными числами
for(int i = 0; i < NUM_OF_ELEMENTS; i++){
    firstList.add(random.nextInt(10) + 1);
    secondList.add(random.nextInt(10) + 1);
}

// Подсчет количества совпадений
int count = 0;
for(int i = 0; i < NUM_OF_ELEMENTS; i++){
    if(firstList.get(i).equals(secondList.get(i))) count++;
}

// Вывод результата:
System.out.println(
    String.format("Совпало: %s, не совпало: %s", count, NUM_OF_ELEMENTS - count)
);


text:
Q: Prove that $X$ is uniformly distributed Let $(X_n)_{n \geq 1}$ be a independent sequence of (on $\{0,...,9\}$) uniformly distributed random variables.
Show that  $X = \sum\limits_{n \geq 1} \frac{X_n}{10^n}$ is uniformly distributed on the unit interval.
I don't quite know how to start here, so any help would be appreciated!

A: Using the moment-generating function of a discrete uniform distribution:
$$M_X(t)=\mathbf{E} \left[\mathrm{e}^{tX} \right]=\mathbf{E}\left[ \mathrm{e}^{t \sum_{n \geq 1} \frac{X_n}{10^n}}  \right] = \prod_{n \geq 1} M_{X_n} \left( \frac{t}{10^n} \right) = \prod_{n \geq 1} \frac{1-\mathrm{e}^{\frac{t}{10^{n-1}}}}{10(1-\mathrm{e}^\frac{t}{10^n})}=\frac{e^t-1}{t}. $$
That is indeed the MGF of a continuous uniform distribution over $[0,1]$.


text:
Q: Matlab builder NE / MCR on Windows 8 I have compiled some matlab functions using Matlab R2012a into .net DLL files. and everything is working as it should. i am using WPF/C# .net 4.5 on windows 7 64bit and my program works ok.
however we are now transferring and testing our program on windows 8 pro. we have a problem in runtime - we are using of course MCR R2012a in order to run the .dll files.
we can't load the classes or functions in win8 and our program crashes.
have anyone came across this problem? will it help if we will compile the functions using Matlab R2013a?

A: The solution to the matlab problem with windows 8 is to add
[assembly: MathWorks.MATLAB.NET.Utility.MWMCROption("-nojit")]

in the assembly file.
I do not know why this works. nojit- means no just in time compiler which creates binary file.
however when I have added this. it worked on windows 8 x64 as well. with the same MCR

A: Most of the problems I had with MCR had to do with wrong value of the PATH variable. This can happen when you install more than one MCR on a computer, or sometimes even when you install just one. Since you get an access violation error, i guess that the system can find the MCR dlls, but it finds the wrong ones (for example 32 bit instead of 64 bit). Check carefully your PATH environment var and make sure it points to the correct location of MCR dlls.


text:
Q: Sorting array based on player position I have a singular situation where I am trying to sort football players based on their positions.
Let's say I have 10 players and I need to sort them based on their positions:
John | Position 1
Bill | Position 1
Gael | Position 2
Phil | Position 2
Joao | Position 2
Cale | Position 3
Bruu | Position 4
Aron | Position 5
Jimm | Position 5
Carl | Position 5

I need to try to sort them as equal as possible, in this case:
Team 1 - John, Gael, Cale, Jimm, Carl
Team 2 - Bill, Phil, Joao, Bruu, Aron
I started trying dividing the positions and then sort them in one or another team, but it didn't work as expected because sometimes I have only one player on a position and 3 on the other position.

A: Seems like the only reasonable way to do it if you don't have enough players in each position is to sort the players by position, and then go through the list, assigning the next player to the next team. That is, given your list and two teams, you'd write code that does this:
John | Position 1 | Team 1
Bill | Position 1 | Team 2
Gael | Position 2 | Team 1
Phil | Position 2 | Team 2
Joao | Position 2 | Team 1
Cale | Position 3 | Team 2
Bruu | Position 4 | Team 1
Aron | Position 5 | Team 2
Jimm | Position 5 | Team 1
Carl | Position 5 | Team 2

The code is pretty simple:
int numTeams = 2
int team = 0
for each player
{
    Assign player to teams[team]
    team = team + 1
    if (team == numTeams) then
    {
        team = 0
    }
}

If you have other restrictions, like a team ideally has x number of position y, then the algorithm would change somewhat to accommodate those restrictions. But you'd have to give me more information before I could supply a suggestion.


text:
Q: Combining multiple IndexOf Is there a way to combine multiple indexOf() to make this more succinct?
Dim UserAgent As String = HttpContext.Current.Request.UserAgent

If Not (UserAgent.IndexOf("Chrome") > -1) OrElse Not (UserAgent.IndexOf("Safari") > -1) Then

    ' do this

End If

A: You can use Contains instead of IndexOf and a collection to lookup:
Dim browsers = {"Chrome", "Safari"}
if Not browsers.Any(Function(b) UserAgent.Contains(b)) Then

End If

or with query syntax:
Dim matchingBrowsers = From browser In browsers
                       Where UserAgent.Contains(browser)
If Not matchingBrowsers.Any() Then

End If

A: Try the following regex (Chrome|Safari)
Not familiar with VB but it should be similar to if (Regex.Match(@"(Chrome|Safari)") != null)


text:
Q: Linux: procedure to keep as much from previous settings in home directory I'm setting up a new Linux (Mint Cinnamon 19.1) on a new machine. My old machine is very similar hardware-wise and also runs Linux (Mint Cinnamon 16). I have a ton of settings for the system and individual programs (zsh, Sublime Text, Double Commander and and and) amassed over time; this got me thinking:

*

*Can I just so copy everything in the home directory from the old to new computer?

*Is there any best practice that makes this migration less of a painful chore?

*Given that this is happening on a netbook with tiny internal SSD, I want to put all my personal stuff on a removable SD (that I plan to always have inserted); can I symlink my homedirectory? Or mount a removable disk as home directory? What would happen if I removed the disk? Would it help if setup a secondary user with home on the internal disk for that case?

*Is there such a concept as a 'portable home directory' in Linux (one that is kept on an SD/USB medium to be used in more than a single machine)?

*An alternative procedure would be to keep the primary user that is set up during system installation as a fallback and to log in as a secondary user.

A: Given both systems are the same architecture(x86-64, I assume) and running close versions of the same distro, you shouldn't have a problem just doing the install with the same username as the previous machine and copying over the whole home directory onto the new machine.
As you may be aware, Linux frequently makes use of dotfiles to manage user-specific configuration to programs, which are stored in the user's home directory. You may also consider implementing some form of dotfile management to facilitate the move.
On the whole, this question has a broad nature to it since your personalized machine could hold individual configuration in the tiniest cracks of every file on the system. You may have personalized etc files, custom binaries in /usr/local/bin, etc. Only you know your system in its entirety. Further, there isn't really a standardized best practice when it comes to migrating from one system to another. Although, in particular, I would advise against having the home directory on an external SSD since this may cause you a lot more headache than it's worth, unfortunately. See first answer here.
Ultimately, when it comes to the home directory, copying and moving it should be a trivial affair if it's to a near-identical machine that has the same kind of CPU and a relatively similar distro version. You might wish to peruse the Ubuntu docs article on home directory migrations since it touches on a lot of relevant points like custom partitioning, mounting, etc. though not with the exact same goal as yourself.