text:
Q: MPLABX macro expansion I am using MPLABX v2.25 and XC32 compiler v1.33 on a Mac.
Maybe I am not fluent with the use of the preprocessor, but the macro expansion window in MPLABX seems to produce rather unexpected results.
Example-1:
#define PIBO TEST
void ftest(void)
{
#if (PIBO == TEST)
  printf("Hello");
#endif
}

Expected Result: printf() should appear in the macro expansion window
Result: printf() does appear in the macro expansion window
So far so good.
Example-2:
#define PIBO FOOTEST
void ftest(void)
{
#if (PIBO == TEST)
    printf("Hello");
#endif
}

Expected Result: printf() should NOT appear in the macro expansion window
Result: printf() does appear in the macro expansion window
Example-3:
void ftest(void)
{
#if (0)
    printf("Hello");
#endif
}

Expected Result: printf() should not appear in the macro expansion window
Result: printf() does not appear in the macro expansion window
Is the MPLAB X macro expansion window showing faults or is it my code or understanding of how this is supposed to work?

A: In C, undefined symbols in the preprocessor evaluate as 0. Therefore, your first two examples all evaluate as 0 == 0 which is true.
If you
#define x 1

then
#define y 2

then (x == y) evaluates as (1 == 2) which is false.


text:
Q: C# DllImport - number of parameters doesn't match I try to reverse a C# assembly with .NET Reflector. I'm interessted in the external function func which is declared like this:
[SuppressUnmanagedCodeSecurity]
public class Class
{
...
[DllImport("extern.dll")]
public static extern uint func(IntPtr a, ulong b, int c, int d, int e);
...
}

So I opened extern.dllwith IDA and searched for the function func. The decompilation looks like this:
int __fastcall func(__int64 a1, __int64 a2, unsigned int a3) {...}

In the C# Code the function is invoked with 5 parameters:
uint ret = Class.func(this.a, b, this.c, this.d, e);

In the C# assembly there are 5 parameters and in the external dll are only 3 parameters. So my question is how can this work?
I have absolutely no idea how the 5 parameters are mapped to only 3.
I hope someone can help me so i can continue reversing the external dll.
Thanks in advance and best regards
Markus

A: So i looked into the assembly of func and noticed that only 3 parameters are used by the function. Thats the reason why IDA recognized only 3 params.
To verify this i wrote a little function with 5 params which uses only the first 3 params. Then i call that function with 5 params. I decompiled it and the result was the same: IDA only recognized 3 params.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sympy not handling float numbers Basically i wrote this code ..
import sympy
number = 5.62527e-11;
f = sympy.Symbol('f');
answer = sympy.solve(Eq(f,number),f);
print(answer);

and as expected the answer is "5.62527e-11"
but when i change "5.62527e-11" to "5.62527e-67" and run the same code ...i am getting
[0.0] as output which is awkward ...it is working for "e-11" but fails for "e-67" can someone please exp-lain why this is happening ..and can someone show me the solution ...i need a solution for this problem
Note : the above code is just a piece of the actual code ...and i have to run it in the same way ...so can anyone please help me dealing with that number ?
thanks in advance

A: This is a bug in SymPy. See https://stackoverflow.com/a/22574099/161801 and https://github.com/sympy/sympy/issues/7322.

A: The limitation of floating point numbers is that they are only accurate to a certain about of decimal places. I was curious about your question myself and found https://docs.python.org/3/tutorial/floatingpoint.html

A: Use a symbol instead of the number (and substitute it in at the end if necessary):
>>> from sympy import *
>>> number = Symbol('5.62527e-11')
>>> f = sympy.Symbol('f');
>>> sympy.solve(Eq(f,number),f)
[5.62527e-11]


text:
Q: "Segemented" foreign keys in MySQL? I have a problem with foreign keys in MySQL or probably I am just thinking in the wrong direction... I have an activity log table where I need to reference key values from currently 2 other tables. So I am using a field that contains that foreign key value along with an indicator stating which table that foreign key value is from.
Table activitylog
    ...
    RefID INT NOT NULL,
    RefType INT NOT NUL,
    ...

Table offers
    OfferID INT NOT NULL,
    ...

Table orders
    OrderID INT NOT NULL,
    ...

If the user created an offer, the value of OfferID from table Offers would be writtten to RefID of activity log and RefType is set to 1. If it was an order then the value of OrderID goes into RefID and RefType is set to 2.
Of course I could add an additional field, name it OrderID, rename RefID to OfferID and discard RefType and use these fields. But if in future an new entity will be used I would have to add an additional field holding the key values of the new entity instead of just invent RefType 3 and continue having the key values in RefID.
I am now struggling with the definition of the foreing key constraints. The logic would be if RefType = 1 lookup the key in Offers, if RefType = 2 go into Orders.
Does anybody know if there is a way to achieve my current concept or do I have to add additional fields to the activitylog?

A: No. MySQL doesn't support enforcement of FOREIGN KEY constraints like you explain, a single column referencing multiple tables.
You could define the constraints with the MyISAM engine, but the FK constraints wouldn't be enforced.
If you define the FK constraints for tables using the InnoDB engine, then ALL of the foreign key constraints would be enforced, no matter what values are stored in other columns.
To have FK constraints on a table to reference two (or more) different, independent parent tables, you'd need two (or more) foreign keys columns, one for each table.
With your table design with InnoDB, you'd have to forgo declarative FOREIGN KEY constraints.
It might be possible for you to roll-your-own constraints by writing some messy triggers; have the trigger throw an exception when one of your constraint rules is violated.


text:
Q: Show calendar for a Many2many field How can I display each employee on the calendar view

    employee_id0 = fields.Many2many('hr.employee', string='Employee', index=True)

<record id="calendar_planning_working_dashboard" model="ir.ui.view">
    <field name="model">my_model</field>
    <field name="arch" type="xml">
        <calendar date_start="date_r1" date_stop="date_r2" color="employee_id0" mode="month" avatar_model="hr.employee" quick_add="False">
            <field name="display_name" />

        </calendar>
    </field>
</record>


text:
Q: Hiding and showing a span Here is my HTML code that is generated by PHP.

CompanyRO
XXXXXX

<input name="first_row" type="radio">AAAAAAAAAA

<input class="f_det" value="Details" onclick="ShowDetails(resp19)" type="button">
<input class="f_det" value="Share" type="button">

Detalii

After this, I'm hidding this span $('.details_content').hide();.
I want that when I press the Details button, the span with details_content is shown, only for this
.
How can I do that ?

A: You need to pass string to function onclick="ShowDetails(resp19)":
onclick="ShowDetails('resp19')"

Then in function ShowDetails write:
function ShowDetails(someId) {
    $('#' + someId + ' span.details_content').show();
}

Also as you use jQuery better to attach click events using click() method:
Html:
<input id="details_button" class="f_det" value="Details" type="button">

JS:
$('#details_button').click(function() {
    ShowDetails('resp19');
});

Note that you using
 element that is for paragraphs and they are inline elements. Better usage will be
 or other block elements.


text:
Q: The degree of the hypersurface of pfaffian cubic fourfolds Let $\Pi:=\mathbb{P}(H^0(\mathbb{P}^5,\mathcal{O}_{\mathbb{P}}(3)))$ be the space of cubic fourfolds in $\mathbb{P}^5$. It is well-known that those cubics which are pfaffian, i.e. defined by the pfaffian of a 6-by-6 skew-symmetric
matrix of linear forms, form a hypersurface in $\Pi$. Does anyone know the degree of that hypersurface?

A: According to Example 3, p. 319 of
Li, Zhiyuan; Zhang, Letao: Modular forms and special cubic fourfolds, Adv. Math. 245, 315-326 (2013). ZBL1290.11077,
the degree of $\mathcal{C}_{14}$ should be 915678.

A: Just a remark: the Pfaffian locus is not quite the $\mathcal{C}_{14}$ divisor, but rather a constructible dense subset of $\mathcal{C}_{14}$, see
https://link.springer.com/article/10.1007/s00208-018-1707-7.
The divisor $\mathcal{C}_{14}$ is rather the locus of cubic fourfolds containing a quartic rational normal scroll $T$ (or a deformation of such $T$ with $T\cdot H^2=4$ and $T\cdot T=10$).


text:
Q: Equivalence of Sobolev norm with infinity norm Let $f\in C^1[a,b]$ be a function. The Sobolev norm is defined as follows:
$$\|f\|_{1,2}=\left[\int_a^b \left(f(x)^2 +f'(x)^2\right)dx\right]^{1/2}$$
I want to find a constant $C$ such that $\|f\|_\infty\le C\|f\|_{1,2}$ for all $C^1[a,b]$.
How do I do so? I've tried some approaches with inequalities, but didn't succeed. Would appreciate a hint.
Also, does the existence of such a constant imply that the norms are equivalent? (Of course, we also need to find $c$ so that $\|f\|_\infty\ge c\|f\|_{1,2}$, but just curious. Since $(C^1[a,b], \|\cdot\|_\infty$ is complete and $(C^1[a,b], \|\cdot\|_{1,2})$ is incomplete, can the norms be possibly equivalent?

A: Let $f\in E={\mathcal C}^1([a,b])$. Then there exists $m\in I=[a,b]$ such that $|f(t)|\geq |f(m)|$ for all $t\in I$. We have also $$f(x)=\int_m ^x f^{\prime}(t)dt+f(m)$$
hence $$|f(x)|\leq |f(m)|+\int_{a}^{b}|f^{\prime}(t)|dt\leq \frac{1}{b-a}\int_a^b|f(t)|dt+\int_{a}^{b}|f^{\prime}(t)|dt$$
By Cauchy-Schwarz, we have $(\int_a^b|f(t)|dt)^2\leq (b-a)\int_a^b|f(t)|^2dt$ and $(\int_{a}^{b}|f^{\prime}(t)|dt)^2\leq (b-a)\int_a^b|f^{\prime}(t)|^2dt$, and so there exists a constant $c_1>0$ such that $$|f(x)|\leq c_1((\int_a^b|f(t)|^2dt)^{1/2}+(\int_a^b|f^{\prime}(t)|^2dt)^{1/2}) $$
for all $x\in I$. To finish, use that if $u,v\geq 0$, we have $u+v\leq \sqrt{2}\sqrt{u^2+v^2}$.


text:
Q: How does cast work with Set Returning Functions (SRF) like generate_series? I got to wondering about how we would best use generate_series if we only want a series of dates. As a note, generate_series returns setof timestamp or setof timestamp with time zone (same as argument type). For example, observe this..
SELECT generate_series(
  '2018-01-01'::date,
  '2019-01-01'::date,
  '1 day'
);
    generate_series
------------------------
 2018-01-01 00:00:00-06
 2018-01-02 00:00:00-06
 2018-01-03 00:00:00-06

In the above you'll notice the time portion. In order to generate dates, I tried,
SELECT cast(
  generate_series(
    '2018-01-01'::date,
    '2019-01-01'::date,
    '1 day'
  )
  AS date
);
 generate_series
-----------------
 2018-01-01
 2018-01-02
 2018-01-03

To my surprise that worked! But, that raises the question, is this supported? If it is, is this documented. Even more awkward, in the above you'll see that cast is returning a setof, but if you move it to the from condition like this,
SELECT *
FROM cast(
  generate_series(
    '2018-01-01'::date,
    '2019-01-01'::date,
    '1 day'
  )
  AS date
);

You'll get back,

ERROR:  set-valued function called in context that cannot accept a set

As a side note, it works in sub-selects and the dynamic can also be seen with int/reals
SELECT x/5 FROM (SELECT CAST(generate_series(1,10) AS real)) AS t(x);
SELECT x/5 FROM (SELECT CAST(generate_series(1,10) AS int)) AS t(x);

Question inspired from this answer

A: Cast the actual value, not the set.
SELECT v::date
FROM generate_series('2018-01-01'::date, '2019-01-01'::date, '1 day') as t(v);


text:
Q: Why WebResponse.StatusCode == HttpStatusCode.OK returns false? I use this code to verify Twitter email and password in c# but it return false and I do not know why?
also, I want to return the xml to read the username from it.
bool Result = false;

// A try except block to handle any exceptions
try
{
    // Encode the user name with password
    string UserPass = Convert.ToBase64String(
        System.Text.Encoding.UTF8.GetBytes(email + ":" + password));

    // Create our HTTP web request object
    HttpWebRequest Request =
        (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml");

    //Request.Proxy = WebProxy;
    //Request.Timeout = Timeout.Infinite;
    //Request.ReadWriteTimeout = Timeout.Infinite;
    //Request.KeepAlive = false;
    //Request.AllowAutoRedirect = false; // was true
    //Request.CookieContainer = cc;
    //Request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";

    // Set up our request flags and submit type
    Request.Method = "GET";
    Request.ContentType = "application/x-www-form-urlencoded";

    // Add the authorization header with the encoded user name and password
    Request.Headers.Add("Authorization", "Basic " + UserPass);

    // Use an HttpWebResponse object to handle the response from Twitter
    HttpWebResponse WebResponse = (HttpWebResponse)Request.GetResponse();

    string SourceCode = new StreamReader(WebResponse.GetResponseStream()).ReadToEnd();

    // Success if we get an OK response
    Result = WebResponse.StatusCode == HttpStatusCode.OK;
}
catch (Exception Ex)
{
    System.Diagnostics.Debug.WriteLine("Error: " + Ex.Message);
}

// Return success/failure

return Result;

A: Actually your code returns 404 not found, which comes to the catch , so by default you are setting the result to false, it never reaches this line
result = WebResponse.StatusCode == HttpStatusCode.OK;

so the result is false;
Also to make it good practice declare your Result like this,
bool result = false;

Instead of
  result = WebResponse.StatusCode == HttpStatusCode.OK;

just do
if(WebResponse.StatusCode == HttpStatusCode.OK;)
{
  result =true;
}


text:
Q: How to handle word in the middle using "look ahead" and "look behind" in Regex? From answer of @skyfoot at this question
regex-lookahead-lookbehind-and-atomic-groups
He said that:
given the string `foobarbarfoo`

    bar(?=bar)     finds the first bar.
    bar(?!bar)     finds the second bar.
    (?<=foo)bar    finds the first bar.
    (?<!foo)bar    finds the second bar.

you can also combine them

    (?<=foo)bar(?=bar)    finds the first bar.

What's happened suppose i have string "barfoobarbarfoo"
And i want to find these bold text
"barfoobarbarfoo"
The regex might be: (?<=bar)foo(????)bar(?=foo)
The question is that what expression should be in the middle (look ahead or look behide)?

A: try this pattern
foo(?=bar)|(?<=bar)bar

Demo

A: To complete your example:
bar(?=bar)     finds the `bar` followed by `bar`
bar(?!bar)     finds the `bar` NOT followed by `bar`
(?<=foo)bar    finds the `bar` preceeded by `foo`
(?<!foo)bar    finds the `bar` NOT preceeded by `foo`

So, in your case, you want the foo preceeded by bar AND followed by bar. Using the example above, this should give:
(?<=bar)foo(?=bar)
Then, to find the bar preceeded by bar AND followed by foo you should use:
(?<=bar)bar(?=foo)
Finally, to combine those two patterns, you should use the OR operator and you end up with the following:
(?<=bar)foo(?=bar)|(?<=bar)bar(?=foo)

DEMO


text:
Q: Why is the following command inconsistent in my repository? In my repository, which has mixed line endings.
I am using Mac OS X, and git 1.8.3.1
I would like to renormalize this repository so that every file has line endings that agree with the .gitattributes file.
To this end, I have checked out the latest change:
git checkout origin/develop
git reset --hard
git rm -rf .
git rm --cached -rf .
rm .git/index
git checkout HEAD .gitattributes
git reset --hard
git status

Now, git rm --cached -rf . will cause an error, but I am being very paranoid with the above command. (On my machine, those commands were on one line, ignoring exit codes)
I repeat the command many times. (Ie, UP; ENTER; UP; ENTER; UP; ENTER;...)
Most of the time, I have a clean check out, which is not what I am expecting.
However, roughly once every ten times, I find that  I get three files (which seem to be correctly renormalized).  The remaining times there is no renormalization.
The output of such a file that gets renormalized (Ie, is 'modified') is:
$ file source/RemoveDuplications.cs
source/RemoveDuplications.cs: UTF-8 Unicode (with BOM) C++ program text, with CRLF line terminators

My git attributes file has a fair number of entries, but the relevant one is here:
* text=auto
*.cs text eol=crlf

What might be going wrong here?

A: It looks like what you are doing may be overly complex. You shouldn't need to remove all files from the repo or delete the index by hand. Have you tried:
git rm --cached -r .  # remove everything from the index
git reset --hard      # replace files w/ corrected line endings
git add .             # stage all changes
git commit -m "Normalize line endings"

If this isn't working for you I'd re-check the values of your core.autocrlf and .gitattributes. You may need to clear those, reset your shell, check out the repo again and then reset them to get the behavior you want.
Here are some other resources that might help:

*

*Github - dealing w/ line endings

*A similar question here with multiple answers to consider

*A good post about the pros/cons of this approach vs git filter-branch

A: You could always use something like a sed script to edit the files and then recommit them to see if this keeps happening.  If you do this from the command line, you should, using the proper regex, be able to pull out any hidden characters that might be causing your problem.


text:
Q: How to crop and resize Images without chaning the original coordinates I have bunch of images with it's X and Y Coordinates which are markers for training. I have to resize the images to 500 X 500. Without affecting the original position how to change the size?
I have tried tf.image.resize_with_crop_or_pad but when I plot the dots using its x and Y to the cropped image it shows wrong coordinates which is left top.

newImage = tf.image.resize_with_crop_or_pad(
        image,
        500,
        500
    )

I want the original Image to be unaffected of it's original coordinates adn have space so when I plot the original points on the image it perfectly fits.

A: You can move the dots with
x += (500 - image.shape(0)) / 2
y += (500 - image.shape(1)) / 2

This should work because the function always crops and pads the image keeping it centered. You might have to check how it works when the original image has an odd size because this would give a float number and it could be half a pixel away from the intended point.


text:
Q: Is there a way to copy text from verbose startup sequence macOS High Sierra without Terminal? I have a mid-2011 Mac mini running High Sierra (I think) that gets ~60% through startup, then simply quits and restarts. Hard drive sounds normal, not hunting.
I can see verbose startup sequence on screen (option V), but can't find a way to copy/pipe/access text after the fact since Mac never finishes booting, therefore no Terminal.app. The best I can do is take a lame video with another device.
I've tried starting from bootable High Sierra USB flash drive, but same problem.
Thoughts?


text:
Q: Phpmyadmin error 200 when loading table structure we have been using phpmyadmin for about 10 years, but since 3-4 days ago, when I click on a table and then on the Structure menu, PMA gives me this error in a red popup:

Error in Processing Request Error code: 200 Error text: OK
MySQL version is 4.5.1 PHP version is: 5.5.30 Microsoft-IIS/7.5
  Database client version: libmysql - mysqlnd 5.0.11-dev - 20120503 PHP
  extension: mysqli Server charset: UTF-8 Unicode (utf8) Server version:
  5.1.73-community - MySQL Community Server (GPL) Server: xxx.xxx.xxx.xx via TCP/IP

I have searched the other questions, but I didn't find a solution.

A: Thank you all for the answers.
It was the language file that was the cause of the error. The error doesn't show anymore if i use other language than italian.
Thanks a lot.


text:
Q: What can cause a node project to work on one machine but fail on another? (both are using the same versions of node) In this case, we have 5 developer machines, and it's working on 3 and not on 2. All are pretty new macs.  All are using node 9.4 (via nvm.  Also I get the same error with node 10).
The main error we are getting when running yarn start is
.../server/start.js:74
    );
    ^
SyntaxError: Unexpected token )

NOTE 1: The problem is related to trailing commas in babel
https://babeljs.io/docs/en/babel-plugin-syntax-trailing-function-commas/
This comma is automatically inserted by Prettier, I believe!
NOTE 2:
I found the problem is this yarn
=> which yarn
/Users/otto/.anyenv/envs/ndenv/shims/yarn

And when I run yarn in VScode, it works, because it's using a different yarn.


text:
Q: VB 2010 : Add items in first menustrip i want to add a new toolstripmenuitem, but at the first/beginning of menustrip

item "a" named from visual design and item "1" named from code (as new toolstripmenuitem)
how to put item "1" at the beginning / first position of menustrip ?
thanks :) (sorry for my english :( )

A: When you need to Add an item at position you need to use Insert as in
ts.Items.Insert (0, item)

And please, don't call everything "item" and "subitem".


text:
Q: Как правильно задавать зависимостей в pom.xml на дочерних модулях? Есть maven проект. К примеру есть pom.xml родительского проекта parentProject с зависимостью junit, и есть модуль child в нём зависимость от mysql.
Вопрос в том, как обозначать зависимости в многомодульном maven проекте? Прописывать их в модулях по мере необходимости или сразу все разместить в pom.xml проекта parentProjects?
Я думаю, что разница есть, потому что если я размещу mysql зависимость в pom.xml родительского проекта parentProjects, то все остальные модули унаследуют её, даже те которые в ней не нуждаются. Хотя наверное можно как-то исключить зависимость из потомка.
Но зачем исключать если можно и не наследовать её!? Верно ли я размышляю? И если нет, то как это делается в реальных многомодульных проектах?

A: Общие зависимости можете включить в родительском pom.xml, а другие в каждый дочерний pom.xml. Этот вариант лучше чем исключать зависимостей потом на дочерний pom.xml'ах.
Но если скажем у вас есть 5 модулей и только в одном из них не повторяется одна зависимость, то в этом случае лучше включить эту зависимость в родительском pom.xml и потом исключить в том модуле где она не повторяется.


text:
Q: java.lang.OutOfMemoryError: Java heap space My result set is too large. If its returning a huge data set which consumes memory, then it displaying OutOfMemory error in server. How can I handle this problem apart from increasing the heap size?

A: Try don't put so many data per one time, use paginator or something like this.

A: Check your query for the resultset is correct/ optimised in the first place.
And in most databases you can restrict the number of rows returned anyway with something like
SELECT top(1000) * FROM mytable;

A: Use a paginator pattern: instead of getting everything at once, periodically get only partf of the data. For example, instead of getting 100 results, you can get 20 results 5 times: 0-19, then 20-39, then 40-59, etc...

A: If you can't load the entire resultset into memory .... then don't!  I can think of three alternatives, depending on the situation:

*

*Only read part of the resultset at a time; e.g. get it in "pages".

*Reduce the resultset as you read it; e.g. by extracting the fields you need, tabulating, or whatever.

*Restructure your query so that the data reduction can be done in the database.

If you provided more details of what the resultset contains and what you are doing with it, we may be able to offer concrete suggestions.

A: If you can structure your query so that a single query can return everything you need then with result set streaming you can get the database to return results to you one row at a time. Your memory use is then drastically reduced at the expense of increased data traffic between your client software and the database. In my own company we find this very effective when working with result sets with millions of rows returned. This functionality is database dependant, for MySQL it is described at
http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-implementation-notes.html


text:
Q: Pubsubhubbub library for NodeJs I have a system where various rss feeds are added. I want to follow the content and be notified when new content is added in the feeds without having to check them one by one.
I found out there is a pubsubhubbub protocol and that publishers can use various hubs which implement this protocol in their feeds. This is how I found out about superfeedr and I'm trying to work with their XMPP API. I installed their nodejs library and made a few subscribe tests that worked fine.

*

*Is it possible to use the node superfeedr module to subscribe to a feed that doesn't use superfeedr? For example I found one that has:
link rel='hub' href='http://pubsubhubbub.appspot.com/'

*Do I have to handle each hub separately or I can just send them the same requests based on the protocol?

A: Alex, I created Superfeedr.
Yes, of course it is possible to subscribe to a feed that doesn't use Superfeedr. Superfeedr acts as a default hub. You can add any feed, and you should get notifications for it. The only difference is that you may see delays. We poll feeds every 15 minutes, so, unless there are strong caches, you should see messages no later than 15 minutes after they've been published.
2 and 3 are probably not relevant given 1. However, I believe there are a couple other PubSubHubbub libraries, but they all require that your endpoint is outside the firewall... and all of them will only work for feeds that use the pubsubhubbub protocol. Even though your application will use each hub separately, the code should be the same, so that's transparent for you.
I hope this helps.


text:
Q: How to create a function that returns the sum of each character code(ASCII value) of the given string? The question is as followed:
Define a class Append.
Use the parameterized constructor used to initialize the input string a.
Define a method that returns the sum of each character code(ASCII value) of the given string a.
Sample test case:
input(string):
CodeTantra

output:
997

A: Try something like:
s = sum(ord(x) for x in "CodeTantra")

This sums up the ASCII value of every character in the string CodeTantra, which yields 997.

A: You can use this:
print(sum(map(ord, "CodeTantra"))) # 997

A: This should work:
class Append:
    def __init__(self, a: str):
        self.a = a

    def sum_char_codes(self):
        sum = 0
        for char in self.a:
            sum += ord(char)
        return sum

# Test the Append class
test = Append("CodeTantra")
print(test.sum_char_codes())


text:
Q: UDP Packet loss when sending possible? My professor gave me the task to realize a file transfer via UDP, which implements the protection mechanisms for reliability like as TCP (CRC check, correct packet order, ACK/NACK). I got some default classes from him (Socket & Channel) to simulate packet loss and delay on local machine. A packet loss when sending the packets is also simulated in its classes. However, this means that if an ACK is not sent correctly i can't notice it either, since an ACK from server to client is not confirmed with an ACK for an ACK from client to server.
I thought that packet loss can only happen when receiving packets.
Is it possible in real cases that an packet can be lost while sending without getting a code exception?
Greetings

A:
Is it possible in real cases that an packet can be lost while sending without getting a code exception?

Easy. Simply send the packets from your application faster than the network interface can forward these. Of course any intermediate systems on the way (i.e. switches, routers) might also get overloaded and loose packets.
But at the end it does not actually matter how the packet is lost, i.e. if one the local system while sending, on the remote system while receiving or in between while forwarding. One simply cannot assume that a successful send will be matched by a successful recv.

A: IP packets contain the transport protocol (TCP, UDP, etc.) in their payload, and you lose IP packets all the time due to things like oversubscription at some point in the path. QoS, controls can also use something like RED that purposely discards packets in order to keep queues from filling and doing tail-drop. TCP can realize that TCP segments (not packets) are lost and resend them, but UDP has no mechanism to realize that its datagrams (not packets) are lost. UDP is a fire-and-forget protocol.


text:
Q: How to build char* from array of char* Please have a look at the following code:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
        const char * cmd;
        const char * help;
} CmdEnum;

static CmdEnum cmd_enum[] = {
        {"help", "This help..."},
        {"first", "The first command"},
        {"second", "The second command"},
};

void main()
{
    int i,n;
    char *out = "";

        n = sizeof(cmd_enum) / sizeof(CmdEnum);
        for (i=0; i<n; i++)
        {
            char *oldOut = out;
            CmdEnum cmd = cmd_enum[i];
            asprintf(&out, "%s%s -> %s\n", oldOut, cmd.cmd, cmd.help);
            if(i>0) free(oldOut);
        }

    printf("%s", out);
    printf("Done.\n");
}

Is this a good way to build a text from the CmdEnum?
Is there a "nicer" way do define cmd in the first place as to avoid the if(i>0) free...?
Or am I doing something entirely wrong?
EDIT:
After reading larsmans' answer I modified main to:
int main()
{
    int i,n, copied, siz;
    char *out, *cursor;
    siz = 1;// 1 for NUL char
    n = sizeof(cmd_enum) / sizeof(CmdEnum);

    for (i=0; i<n; i++)
    {
        siz += strlen(cmd_enum[i].cmd) + strlen(cmd_enum[i].help) + strlen(":\n\t\n\n");
    }

    out = malloc(siz);
    if(!out)
    {
        printf("Could not alloc!\n");
        return 1;
    }

    cursor = out;
    for (i=0; i<n; i++)
    {
        copied = snprintf(cursor, siz, "%s:\n\t%s\n\n", cmd_enum[i].cmd, cmd_enum[i].help);
        if(copied < 0 || copied >= siz)
        {
            printf("snprintf failed: %i chars copied.\n", copied);
            return 1;
        }

        cursor += copied;
        siz -= copied;
    }

    printf("%s", out);
    printf("Done.\n");
    free(out);
    return 0;
}

(Note: I also changed the output format...)

A:
Is this a good way to build a text from the CmdEnum?

Yes, except that asprintf is not portable (although you can define it easily in terms of snprintf for platforms that don't have it) and you're not checking error returns. void main isn't valid C btw.

Is there a "nicer" way do define cmd in the first place as to avoid the if(i>0) free...?

You could allocate the whole string beforehand.
size_t i, siz = 1;  // 1 for NUL char
for (i=0; i<n; i++)
    siz += strlen(cmd_enum[i].cmd) + strlen(cmd_enum[i].help) + strlen(" -> \n");

char *out = malloc(siz);
// check for errors

then build the string with snprintf. This saves you some malloc'ing and error checking in the loop.


text:
Q: Getting total amount of memory, available in Adobe Flash from ActionScript I have to load a lot of data from BlazeDS and/or Livecycle DS service to Adobe Flex and would like to find out what's available from memory stand point.  This is similar to querying in java: long heapSize = Runtime.getRuntime().totalMemory()

A: You can't find the available memory, but you can find the memory currently in use via the System.totalMemory property.
http://livedocs.adobe.com/flex/3/langref/flash/system/System.html#totalMemory


text:
Q: nested forms in rails 3 I'm trying to setup a nested form and the main thing I can't get working is knowing when to do the build method. Here are my models:
class User < ActiveRecord::Base
  belongs_to :address
  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  has_one :user
end

In all the examples I've found, which appear to be pre-rails 3, I see the following two methods:
user.address.empty?
user.address.build

I have managed to winnow out with my semi-asleep Google-Fu that the build has been replaced with:
user.build_address

What I'm trying to figure out is what's the replacement for empty? It doesn't appear to exist when I try things at the console, but user.build_address is wonderful.
Any ideas?
thanks...

A: For the has_one relation build_address will create an empty address instance or will load already existing instance. So you don't need to call user.address.empty?.


text:
Q: Android - Adding item to array.xml with String[] Array I am trying now for days to add item (String) into array.xml (string-array) file in values folder. The added item must be stored there, because i want to use this strings in another activity, too.
my array.xml looks like this
<string-array name="Array">
    <item>Example</item>
</string-array>

I have tried it in different ways, but as the last it looks in my MainActivity like this
private void addArray(){
    String [] array = getResources().getStringArray(R.array.Array);
    ArrayList<String> lst = new ArrayList<String>(Arrays.asList(array));
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);
    adapter.add("Hello");
}

But that did not work either. This don't adds an item to my array.xml file.


text:
Q: Setting up multiple cores for apache solr for Ubuntu 12.04 and Drupal 7 I'm setting up solr locally for my development purposes and integration with Drupal 7. I'm not very familiar with tomcat. My background has primarily been LAMP setups.
So I went and installed the package provided by ubuntu for apache solr following this guide.

*

*sudo apt-get install tomcat6 tomcat6-admin tomcat6-common tomcat6-user tomcat6-docs tomcat6-examples

*sudo apt-get install solr-tomcat
I've got that working. The apt-get package manager does a great job and allows me to setup solr but with one core.
What steps need to be taken to enable multi core setup for apache solr?
And below is my solr.xml file:
sudo nano /var/lib/tomcat6/conf/Catalina/localhost/solr.xml
<!--
    Context configuration file for the Solr Web App
-->

<Context path="/solr" docBase="/usr/share/solr"
   debug="0" privileged="true" allowLinking="true" crossContext="true">
  <!-- make symlinks work in Tomcat -->
  <Resources className="org.apache.naming.resources.FileDirContext" allowLinking="true" />

  <Environment name="solr/home" type="java.lang.String" value="/usr/share/solr" override="true" />
</Context>

A: The guide in OP is a quick start quide and does not touch on multi-core configuration.
There is an official guide in solr site: http://wiki.apache.org/solr/CoreAdmin
It is very long. I will quote the initial setup portion.
Partial Quote
Configuration
To enable support for dynamic SolrCore administration, place a file named solr.xml in the solr.home directory. Here is an example solr.xml file:
<solr persistent="true" sharedLib="lib">
 <cores adminPath="/admin/cores">
  <core name="core0" instanceDir="core0" />
  <core name="core1" instanceDir="core1" />
 </cores>
</solr>

You can also specify properties in solr.xml which can be used in the solrconfig.xml and schema.xml files.
<solr persistent="true" sharedLib="lib">
 <property name="snapshooter" value="/home/solr-user/solr/bin/snapshooter.sh" />
 <cores adminPath="/admin/cores">
  <core name="core0" instanceDir="core0">
    <property name="dataDir" value="/data/core0" />
  </core>
  <core name="core1" instanceDir="core1" />
 </cores>
</solr>

The properties can be container scope (i.e. specified after < solr > but outside of a < core > element) in which case it is automatically inherited by each core. Therefore, they can be used in any of the cores' configuration files.
The properties can also be defined in a core's scope (inside the < core > element) in which case they can be used only in that core's scope. If a property by that name already exists in the container scope then it will be overridden.
Besides them, a few properties are automatically added in the core scope. They are:
solr.core.name -- The core's name as defined in solr.xml

solr.core.instanceDir -- The core's instance directory (i.e. the directory under which that core's conf/ and data/ directory are located)

solr.core.dataDir -- The core's data directory (i.e. the directory under which that core's index directory are located)

solr.core.configName -- The name of the core's config file (solrconfig.xml by default)

solr.core.schemaName -- The name of the core's schema file (schema.xml by default)

Such properties can be used inside solrconfig.xml and schema.xml files by specifying an expression with optionally, a default value.
// Without a default value
${snapshooter}
// With a default value
${snapshooter:./solr/bin/snapshooter.sh}

The above expression will evaluate to the value specified in solr.xml for the property name "solr.snapshooter". If no value is defined in solr.xml, it will check if a system property by that name exists otherwise it will use the specified default value. If no default value is specified, a runtime exception will be thrown and the core may fail to startup.


text:
Q: How to handle Custom listview item clicks? I have a problem with custom listview item click.
In my activity I have a button and a custom ListView such that on clicking the button, checkboxes appear to left of each item, and again on clicking the button, checkboxes disappear.By default on clicking the item, it should display Toast1, and on clicking the button(when checkboxes enabled), it should display Toast2.So the button acts like a toggle button.
So I have written ListView.onitemclickListener in Activity to display Toast1 and convertView.setOnClickListener in getView to display Toast2.
In getView(), I have written :
if(myFlag)
{
  convertView.setOnClickListener ...
  {
      display Toast2
  }
}

here myFlag will be set true/false based on the toggle button.
But when after clicking toggle button and clicking on listview item, sometimes its displays Toast1 and sometimes Toast2.

A: Adding different OnClickListeners at runtime can cause some Problems, especially if you tie it to the getView() Method.
If you use a single onClickListener and check for your flag there, it should be working the way you want to.
Pseudocode:
    convertView.setOnClickListener ...
  {
       if(myFlag){
       hide checkbox;
       display Toast2;
       myFlag =false;
     }
      else {
       show checkbox;
       display Toast 1;
       myFlag =true;
     }

}

A: Finally I got solved this myself.
Just set the setclickable() of convertView to true/false in getView() method. If set to true Toast2 will displayed() and if set to False Toast1 will be displayed.

A: I use setTag()/getTag() methods for getting the position of the item. In the getView() method of the list adapter set position of the item as the tag of the row items(in your case button) using setTag("position") method.
When the button in any row is clicked the onClick() method will be called for that button and in the onClick() method you can use getTag() method to get the position. Use same method as the onClick routine for all the rows button.
sample code: List item could be something like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
    android:id="@+id/button1"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="117dp"
    android:background="@drawable/grad"
    android:onClick="onButtonClick" />

getView() method could be something like this:
public View getView (int position, View convertView, ViewGroup parent) {
    ...
    ...
    button.setTag(position);
    ...
}

onClick routine could be something like this:
public void onButtonClick(View v) {
    String tag = v.getTag().toString();
    if(tag != null) {
         int position = Integer.parseInt(tag);
    }
    ...
    ...
}


text:
Q: Method of coefficients quotient variable power Divide $15+2m^4-31m+9m^2+4m^3+m^5$ by $3-2m-m^2$
I use the method of coefficients. I first arrange the dividend and divisor coefficients in descending powers then proceed to the operation:
$-1, -2, 3$ $
\begin{vmatrix}
1 & 2 & 4 &9&-31 &15 \\
1 & 2 & -3 \\
 &  & 7 &9&-31& \\
 &  & 7 &14&-21 \\
 &  &  &-5&-10 &15 \\
 &  &  &-5&-10 &15 \\
\end{vmatrix}
$ $-1,-7,5$
The quotient coefficients are $-1, -7, 5$. Since the entire operation is in descending order of powers, I naturally assumed the quotient is $-m^2-7m+5$. But it isn't. The correct quotient is $-m^3-7m+5$. Here is my question. How can I tell what the correct power is? Obviously I can look back at the problem statement and see $-m^2$ and $m^5$ and determine the quotients' first coefficient has to be to the third power,  but then since there is only three terms in this quotient how do I determine the power of the second and third terms? Thank you.


text:
Q: how to install the latest version of ansible by pip OFFLINE we are working on linux redhat 7.2
first we download the ansible pkgs on machine
pip download ansible
Collecting ansible
  Downloading https://files.pythonhosted.org/packages/00/5d/e10b83e0e6056dbd5b4809b451a191395175a57e3175ce04e35d9c5fc2a0/ansible-2.9.9.tar.gz (14.2MB)
    100% |████████████████████████████████| 14.2MB 73kB/s
  Saved ./ansible-2.9.9.tar.gz
Collecting jinja2 (from ansible)
  Downloading https://files.pythonhosted.org/packages/30/9e/f663a2aa66a09d838042ae1a2c5659828bb9b41ea3a6efa20a20fd92b121/Jinja2-2.11.2-py2.py3-none-any.whl (125kB)
    100% |████████████████████████████████| 133kB 2.7MB/s
  Saved ./Jinja2-2.11.2-py2.py3-none-any.whl
Collecting PyYAML (from ansible)
  Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)
    100% |████████████████████████████████| 276kB 2.0MB/s
  Saved ./PyYAML-5.3.1.tar.gz
Collecting cryptography (from ansible)
  Downloading https://files.pythonhosted.org/packages/5f/fc/a92bad2460d349ee9eb868f9f9dcddb7c8f42a45677d53a5c663fa251e75/cryptography-2.9.2-cp27-cp27mu-manylinux1_x86_64.whl (2.7MB)
    100% |████████████████████████████████| 2.7MB 371kB/s
  Saved ./cryptography-2.9.2-cp27-cp27mu-manylinux1_x86_64.whl
Collecting MarkupSafe>=0.23 (from jinja2->ansible)
  Downloading https://files.pythonhosted.org/packages/fb/40/f3adb7cf24a8012813c5edb20329eb22d5d8e2a0ecf73d21d6b85865da11/MarkupSafe-1.1.1-cp27-cp27mu-manylinux1_x86_64.whl
  Saved ./MarkupSafe-1.1.1-cp27-cp27mu-manylinux1_x86_64.whl
Collecting cffi!=1.11.3,>=1.8 (from cryptography->ansible)
  Downloading https://files.pythonhosted.org/packages/08/29/8001b940ef40e7a25ffe8f3188bc9b118934b513d64f769dbf461e46f4ed/cffi-1.14.0-cp27-cp27mu-manylinux1_x86_64.whl (387kB)
    100% |████████████████████████████████| 389kB 1.9MB/s
  Saved ./cffi-1.14.0-cp27-cp27mu-manylinux1_x86_64.whl
Collecting six>=1.4.1 (from cryptography->ansible)
  Downloading https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
  Saved ./six-1.15.0-py2.py3-none-any.whl
Collecting ipaddress; python_version < "3" (from cryptography->ansible)
  Downloading https://files.pythonhosted.org/packages/c2/f8/49697181b1651d8347d24c095ce46c7346c37335ddc7d255833e7cde674d/ipaddress-1.0.23-py2.py3-none-any.whl
  Saved ./ipaddress-1.0.23-py2.py3-none-any.whl
Collecting enum34; python_version < "3" (from cryptography->ansible)
  Downloading https://files.pythonhosted.org/packages/6f/2c/a9386903ece2ea85e9807e0e062174dc26fdce8b05f216d00491be29fad5/enum34-1.1.10-py2-none-any.whl
  Saved ./enum34-1.1.10-py2-none-any.whl
Collecting pycparser (from cffi!=1.11.3,>=1.8->cryptography->ansible)
  Downloading https://files.pythonhosted.org/packages/ae/e7/d9c3a176ca4b02024debf82342dab36efadfc5776f9c8db077e8f6e71821/pycparser-2.20-py2.py3-none-any.whl (112kB)
    100% |████████████████████████████████| 112kB 3.3MB/s
  Saved ./pycparser-2.20-py2.py3-none-any.whl
Successfully downloaded ansible jinja2 PyYAML cryptography MarkupSafe cffi six ipaddress enum34 pycparser
You are using pip version 8.1.2, however version 20.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

now we disconnect the machine from network
and we intend to install the following files by pip
# ls -ltr
total 17508
-rw-r--r-- 1 root root 14222889 May 25 20:36 ansible-2.9.9.tar.gz
-rw-r--r-- 1 root root   125774 May 25 20:36 Jinja2-2.11.2-py2.py3-none-any.whl
-rw-r--r-- 1 root root   269377 May 25 20:36 PyYAML-5.3.1.tar.gz
-rw-r--r-- 1 root root  2728298 May 25 20:36 cryptography-2.9.2-cp27-cp27mu-manylinux1_x86_64.whl
-rw-r--r-- 1 root root    24348 May 25 20:36 MarkupSafe-1.1.1-cp27-cp27mu-manylinux1_x86_64.whl
-rw-r--r-- 1 root root   387834 May 25 20:36 cffi-1.14.0-cp27-cp27mu-manylinux1_x86_64.whl
-rw-r--r-- 1 root root    10963 May 25 20:36 six-1.15.0-py2.py3-none-any.whl
-rw-r--r-- 1 root root    18159 May 25 20:36 ipaddress-1.0.23-py2.py3-none-any.whl
-rw-r--r-- 1 root root    11223 May 25 20:36 enum34-1.1.10-py2-none-any.whl
-rw-r--r-- 1 root root   112041 May 25 20:36 pycparser-2.20-py2.py3-none-any.whl

how to install the ansible pkgs/file by pip without network ?


text:
Q: Definition of Specific Heat: Molar Specific or Mass Specific Quantity? Five kilograms of air, initially at 0 °C, are heated until the temperature reaches 50 °C. The internal energy increases by 180 kJ during this process. Find the specific heat of air.
I know this is a basic question, but I am confused on the dimensional analysis. The answer provided is $0.72 \ kJ/kg$. From my textbook we defined specific heat of an ideal gas as:
$$u_1 - u_2 = c (T_2 - T_1)$$
Where $u$ is the specific internal energy (ie: kJ/kmol). They call it a molar specific internal energy.  Thus, the units for specific heat should be $\frac{[kJ]}{[kmol \cdot K]}$. Are these two valid definitions for specific heat? How can I tell which one is of interest ?

A: Specific values are those normalized to the amount of material (mass in kg or quantity in moles) and are thus useful as material properties. "Specific heat" typically means the heat capacity normalized to the mass, but if "molar" is specified, it means the heat capacity normalized to the number of moles ("molar heat capacity" is also used for the latter). One can easily convert from one to the other for a certain material (e.g., the molar mass of air is 0.02897 kg/mol).


text:
Q: Test a property only if it exists? The following test generates an error if the response does not have a msgs[0] property.
if response.msgs[0] === "published" { ... }

The error is:
Uncaught TypeError: Cannot read property '0' of undefined

How can I rewrite the test to generate an error? If there is no msgs[0] property, I want the test to evaluate to false.

A:
response does not have a msgs[0] property

This is incorrect. It throws an error because it doesn't have a msgs property, not because there is no 0 property on it.
You need to test if msgs exists before testing what 0 is.
if (response.msgs && response.msgs[0] === "published") { ... }

A: Test if response.msgs is defined first:
if response.msgs && response.msgs[0] === "published" { ... }


text:
Q: An error occurred while installing pg (1.4.1), and Bundler cannot continue - Ruby on rails When I run bundle install I get this error:
An error occurred while installing pg (1.4.1), and Bundler cannot
continue.

I then run gem install pg and get this:
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen - /Users/name/.rbenv/versions/2.7.5/lib/ruby/gems/2.7.0/gems/pg-1.4.5/.appveyor.yml

I thought it was a permission is so I ran : sudo gem install pg then I got this:
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [pg_ext.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/name/.rbenv/versions/2.7.5/lib/ruby/gems/2.7.0/gems/pg-1.4.5 for inspection.
Results logged to /Users/name/.rbenv/versions/2.7.5/lib/ruby/gems/2.7.0/extensions/arm64-darwin-22/2.7.0/pg-1.4.5/gem_make.out

gcc is installed and up to date.
Postgres 14.7
I followed most of the solutions on here and got nowhere. Does anyone know how to fix this?
I am on a M1 with MacOS Ventura


text:
Q: SQL - Selecting master IDs where there is at least one copy on every platform My apologies if this has been asked before. I wasn't sure what terms to use that broadly address this sort of issue.
I have this datatable containing master versions of videos (master) and copies illegally uploaded by other people (copy). Each copy is uploaded to a particular platform.
In this case the only possible values for platform are:

*

*facebook

*youtube

*instagram

*twitter

╔════════╤══════╤═══════════╗
║ master │ copy │ platform  ║
╠════════╪══════╪═══════════╣
║ 1      │ 1    │ facebook  ║
╟────────┼──────┼───────────╢
║ 1      │ 2    │ youtube   ║
╟────────┼──────┼───────────╢
║ 1      │ 3    │ instagram ║
╟────────┼──────┼───────────╢
║ 1      │ 4    │ twitter   ║
╟────────┼──────┼───────────╢
║ 1      │ 5    │ youtube   ║
╟────────┼──────┼───────────╢
║ 1      │ 6    │ twitter   ║
╟────────┼──────┼───────────╢
║ 2      │ 1    │ facebook  ║
╟────────┼──────┼───────────╢
║ 2      │ 2    │ instagram ║
╟────────┼──────┼───────────╢
║ 2      │ 3    │ twitter   ║
╚════════╧══════╧═══════════╝

What query would I write to pull only the master that has at least one copy on each possible platform?
In this case, the only master that should be returned is 1 because it has at least one copy on each of the 4 possible platforms. 2 should not be returned because it does not have a copy on youtube.

A: You could use aggregation and filter with a having clause:
select master
from mytable
group by master
having count(distinct plaform) = 4

Since you mentioned that there are only 4 possible platforms, it is enough to just ensure that the count of distinct platform values per master is 4.


text:
Q: Merge rows by ID in excel I've got a set of columns like this in excel:
ID                                      sizeAndColourAndSku_Value
2ff0d3d7-8c18-4386-83be-1b2485fb4ea9    Select size
2ff0d3d7-8c18-4386-83be-1b2485fb4ea9    Extra Small - Available (only 1 left)
2ff0d3d7-8c18-4386-83be-1b2485fb4ea9    Small - Available (only 2 left)
2ff0d3d7-8c18-4386-83be-1b2485fb4ea9    Medium - Available (only 2 left)
2ff0d3d7-8c18-4386-83be-1b2485fb4ea9    Large - Available (only 1 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    Select size
4697ce05-2e50-4e67-85d5-ad733e15ae95    6 - Available (only 2 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    8 - Available (only 4 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    10 - Available (only 6 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    12 - Available (only 6 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    14 - Available (only 4 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    16 - Available (only 2 left)
4697ce05-2e50-4e67-85d5-ad733e15ae95    Select size

I need to combine merge them by their ID so the results become like this:
2ff0d3d7-8c18-4386-83be-1b2485fb4ea9   Extra Small  Small  Medium  Large
4697ce05-2e50-4e67-85d5-ad733e15ae95   6      8      10     12      14

I read here that the quickest and easiest way to do this is with a pivot table in excel
http://www.excelbanter.com/showthread.php?t=235727
However I'm using excel 2010 and the method they've provided doesn't really work, anyone able to help me out with this?
Thanks

A: If you pivot on this data range and apply the ID field to 'Row Labels' and the sizeAndColourAndSku_Value field to both 'Column Labels' and 'Values' you will get something similar, except it will give you a count of the occurrences rather than the values themselves.

A: There is already an answer to this somewhere on SE (I wrote it but can't find it!) however:

*

*Parse your sizeAndColourAndSku_Value column with Text to Columns and - as the delimiter.

*Delete rows with Select size.

*Assuming the  Extra Small part of Extra Small- Available (only 1 left) is now in B2 put:

=IF(COLUMN()<COUNTIF($A:$A,$A2)+3,IF($A2=$A3,INDIRECT("$B"&ROW()+COLUMN()-3),""),"")
in  C2 and copy across and down to suit.

*Select entire sheet and Paste Special Values over the top.

*In B2 put: =A1=A2 and copy down to suit.

*Filter ColumnB for TRUE and delete visible rows.

*Delete ColumnB.

Edit to add image:


text:
Q: Return value in a class from another class and method Note that I am new with Java. I have a class and and a method in this class hat computes some values and I want to return them in the first class. I have a code but it returns 0.
That's in class that computes the values
public class ImageProcessing{
int i,j;
int R[][]=new int[640][320];
int G[][]=new int[640][320];
int B[][]=new int[640][320];

public double meanR[]=new double[320];
public double meanG[]=new double[320];
public double meanB[]=new double[320];
public double varianceR[]=new double[320];
public double varianceG[]=new double[320];
public double varianceB[]=new double[320];
public double skewnessR[]=new double[320];
public double skewnessG[]=new double[320];
public double skewnessB[]=new double[320];

public double round(double value){
    //  int decimalPlace = 2;

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2,BigDecimal.ROUND_UP);
    return (bd.doubleValue());
}

public void Mean(Bitmap image){

    int width = image.getWidth();
    int height = image.getHeight();
    int pixel = 0;

    for (i=0; i<width;i++){
        for (j=0; j<height; j++){
            pixel = image.getPixel(i,j);
            R[i][j] = Color.red(pixel);
            G[i][j]= Color.green(pixel);
            B[i][j] = Color.blue(pixel);

            meanR[j]=meanR[j]+R[i][j];
            meanG[j]=meanG[j]+G[i][j];
            meanB[j]=meanB[j]+B[i][j];
        }
    }

In the main class I have:
    method.Mean(rescaledBitmap1);

    meanR1=method.meanR;
    meanG1=method.meanG;
    meanB1=method.meanB;
    System.out.println(meanR1);

A: You must specify what you want to return in the definition of the method and actually return a value using the keyword return:
public int sum(int a, int b){
 int result = a + b;
 return result;
}

You've declared Mean() as void public void Mean(Bitmap image) and thus it returns no value.
Also, you can only return 1 variable so you should either put those 3 values in some sort of array or create a new class and encapsulate the variables inside an object. Here is an example:
public class MeanResult(){
private double meanR[]=new double[320];
private double meanG[]=new double[320];
private double meanB[]=new double[320];
//Maybe declare more stuff here

 public MeanResult(Bitmap image){
  //... code n stuff here to calculate width, height and pixel
 }
 public double getMeanR(){ return this.meanR[]; }
 public double getMeanG(){ return this.meanG[]; }
 public double getMeanB(){ return this.meanB[]; }
}

And you can use it like this:
MeanResult mean = new MeanResult(image);
meanR1=mean.getMeanR();
meanG1=mean.getMeanG();
meanB1=mean.getMeanB();

A: The method mean(Bitmap image) is void. For it to return something, you must change void to what it will return, and at the end of the method return the variable.
Example:
public int add(int x, int y)
{
    return x + y;
}

Then if you called add(1,2) it would have a value of 3.


text:
Q: 3x3 submatrix with only $0$ or $1$ entries I decided to cross-post the question here from math.stackexchange.com because I got no answer from there.
It is a quick question on bipartite Ramsey numbers (I'm not an expert on the subject, so perhaps the question is trivial).
What is the least positive integer $r$ such that, any $r \times r$ 0-1 matrix contains at least one $3 \times 3$ submatrix filled with only 0 or only 1 entries ?
I found some articles with upper/lower bounds, but not a clear chart with the particular values I need.

A: According to this:
MR1622032 (99c:05139)
Hattingh, Johannes H.(SA-RAND); Henning, Michael A.(SA-NTL2)
Bipartite Ramsey theory. (English summary)
Util. Math. 53 (1998), 217–230.
the answer is $17$, not $15.$
Addition A proof is contained in Irving's paper "A bipartite Ramsey problem and the Zarankiewicz numbers" (available on line). In the later paper with an almost identical title:
Bipartite Ramsey Numbers and Zarankiewicz Numbers (by Goddard et al) they seem to indicate that the Irving paper is slightly buggy, but that the result holds anyhow.


text:
Q: Alternative for shortest_path algorithm I have a network consisting of 335 nodes. I computed the weighted shortest.paths between all of the nodes.
Now I would like to see which path sequences where used to travel between the nodes.
I use the the shortest_path command in igraph and iterate through all combinations of nodes in my network (335² combinations - 335(path from/to same node is 0)/2 (graph is undirected). So all in all I have to iterate over 55.945 combinations.
My approach looks like this:
net is my network
sp_data is a df with all combinations of links in the network
results1 <- sapply(sp_data[,1], function(x){shortest_paths(net, from = x, to = V(net), output="epath"})

Unfortunately this needs ages to compute and at the end I don't have enough memory to store the information. (Error: cannot allocate vector of size 72 Kb).
Basically I have two questions:

*

*How can it be that the shortest.paths command needs seconds to compute the distance between all nodes of my network whereas extracting the path sequences (not just it length) needs days and exceeds the memory capacity?

*Is there an alternative to get the desired output (path sequences of shortest path)? I guess that the sapply Syntax should already be faster than a for::loop?

A: you could try cppRouting package.
It provides get_multi_paths function which return a list containing the node sequence for each shortest path.
library(igraph)
library(cppRouting)

#random graph
g <- make_full_graph(335)

#convert to three columns data.frame
df<-data.frame(igraph::as_data_frame(g),dist=1)

#instantiate cppRouting graph
gr<-cppRouting::makegraph(df)

#extract all nodes
all_nodes<-unique(c(df$from,df$to))

#Get all paths sequence
all_paths<-get_multi_paths(Graph=gr,from=all_nodes,to=all_nodes)

#Get path from node 1 to 3
all_paths[["1"]][["3"]]


text:
Q: How to retrieve all users of Active Directory? I use following code to retrieve all users of active directory but not all users retrieved. Should I include something else in Filter?
 this is simplified code.
DirectoryEntry entry = new DirectoryEntry("LDAP://" + Bous.DomainName, Bous.UserName, Bous.Password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(&(objectCategory=person)(objectClass=user))");

foreach (SearchResult result in mySearcher.FindAll())
{
     dr = dt.NewRow();
     ResultPropertyCollection myResultPropColl = result.Properties;
     dr[0] = myResultPropColl["samaccountname"][0].ToString() + "@" + Bous.DomainName;
     dt.Rows.Add(dr);
}

A: Try this one:
DirectoryEntry entry = new DirectoryEntry("LDAP://" + Bous.DomainName, Bous.UserName, Bous.Password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.PageSize = 1000;   // <--- Important!
mySearcher.Filter = ("(&(objectCategory=person)(objectClass=user))");

foreach (SearchResult result in mySearcher.FindAll())
{
     dr = dt.NewRow();
     ResultPropertyCollection myResultPropColl = result.Properties;
     dr[0] = myResultPropColl["samaccountname"][0].ToString() + "@" + Bous.DomainName;
     dt.Rows.Add(dr);
}

A: If you're on .NET 3.5 or newer, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for UserPrincipal (users)
   UserPrincipal qbeUser = new UserPrincipal(ctx);

   // create your principal searcher passing in the QBE principal
   PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
   }
}

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.

A:     using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    ...
    protected static UserPrincipal QueryFilterUsers(string FilterFullName, string FilterDescription, string FilterLogin, string FilterPhone, string FilterEmail)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, _Domain);
        UserPrincipal _UserPrincipal = new UserPrincipal(ctx);

        _UserPrincipal.SamAccountName = "*" + ((!string.IsNullOrEmpty(FilterLogin)) ? FilterLogin.Trim() + "*" : "");
        if (!string.IsNullOrEmpty(FilterFullName)) _UserPrincipal.DisplayName = "*" + FilterFullName.Trim() + "*";
        if (!string.IsNullOrEmpty(FilterDescription)) _UserPrincipal.Description = "*" + FilterDescription.Trim() + "*";
        if (!string.IsNullOrEmpty(FilterPhone)) _UserPrincipal.VoiceTelephoneNumber = "*" + FilterPhone.Trim() + "*" ;
        if (!string.IsNullOrEmpty(FilterEmail)) _UserPrincipal.EmailAddress = "*" + FilterEmail.Trim() + "*";
        return _UserPrincipal;
    }

    //Получение списков
    public static List<Principal> GetUsersPrincipalList(string FilterFullName, string FilterDescription, string FilterLogin, string FilterPhone, string FilterEmail)
    {
        PrincipalSearcher _PrincipalSearcher = new PrincipalSearcher();
        _PrincipalSearcher.QueryFilter = QueryFilterUsers(FilterFullName, FilterDescription, FilterLogin, FilterPhone, FilterEmail);
        (_PrincipalSearcher.GetUnderlyingSearcher() as DirectorySearcher).PageSize = _PageSize;
        (_PrincipalSearcher.GetUnderlyingSearcher() as DirectorySearcher).SizeLimit = _SizeLimit;

        return _PrincipalSearcher.FindAll().ToList();
    }


text:
Q: Cant get access to service I have the second problem: cloud sql proxy pod wrapped onto service and must provide access to database.
And I have a job which must create new database for every branch.
But when this job runs the second error appears. I cant get access to the cloudsql-proxy-service.
I cant understand why its happens. Thanks.

E  psql: could not connect to server: Connection timed out
E     Is the server running on host "cloudsql-proxy-service"
  (10.43.254.123) and accepting
E     TCP/IP connections on port 5432?

apiVersion: apps/v1
kind: Deployment
metadata:
    name: cloudsql-proxy
    labels:
        type: backend
        name: app
    annotations:
        "helm.sh/created": {{ .Release.Time.Seconds | quote }}
        "helm.sh/hook": pre-install
        "helm.sh/hook-weight": "-20"
spec:
    replicas: 1
    selector:
        matchLabels:
            name: cloudsql-proxy
    template:
        metadata:
            labels:
                name: cloudsql-proxy
        spec:
            containers:
            -   name: cloudsql-proxy
                image: gcr.io/cloudsql-docker/gce-proxy:1.11
                command:
                - "/cloud_sql_proxy"
                - "-instances={{ .Values.testDatabaseInstanceConnectionName }}=tcp:5432"
                - "-credential_file=/secrets/cloudsql/credentials.json"
                securityContext:
                    runAsUser: 2  # non-root user
                    allowPrivilegeEscalation: false
                volumeMounts:
                -   name: cloudsql-instance-credentials
                    mountPath: /secrets/cloudsql
                    readOnly: true
                ports:
                  - containerPort: 5432
            volumes:
            -   name: cloudsql-instance-credentials
                secret:
                    secretName: {{ .Values.cloudSqlProxySecretName }}
---
apiVersion: v1
kind: Service
metadata:
  name: cloudsql-proxy-service
  labels:
    type: backend
    name: app
  annotations:
      "helm.sh/created": {{ .Release.Time.Seconds | quote }}
      "helm.sh/hook": pre-install
      "helm.sh/hook-weight": "-20"
spec:
  selector:
      name: cloudsql-proxy
  ports:
      - port: 5432

apiVersion: batch/v1
kind: Job
metadata:
    name: create-test-database
    labels:
        type: backend
        name: app
    annotations:
        "helm.sh/created": {{ .Release.Time.Seconds | quote }}
        "helm.sh/hook": pre-install
        "helm.sh/hook-weight": "-10"
spec:
    template:
        metadata:
          name: create-test-database
        spec:
            containers:
            -   name: postgres-client
                image: kalumkalac/postgresql-client
                env:
                    -   name: PGUSER
                        value: {{ .Values.testDatabaseCredentials.username }}
                    -   name: PGPASSWORD
                        value: {{ .Values.testDatabaseCredentials.password }}
                    -   name: PGDATABASE
                        value: {{ .Values.testDatabaseCredentials.defaultDatabaseName }}
                    -   name: PGHOST
                        value: cloudsql-proxy-service
                command:
                    - psql
                    - -q
                    - -c CREATE DATABASE {{ .Values.testDatabaseCredentials.name|quote }}
            restartPolicy: Never
    backoffLimit: 0 # Deny retry job


text:
Q: How to subtract two timestamps with SQL command to get minutes I am trying to get the minutes from each workout from a column and add them up to get the total minutes completed.
I have the command line below:
SELECT sum(timefinished - timestarted) AS minutesBetween FROM workouts WHERE id = 'id'

My SQL database column is formatted as 'time'.
My result to this query is 5239. This is incorrect as the times I need to get a minute value between are:
timefinished: 12:35:02 - timestarted 12:20:19 and timefinished: 12:55:07 - timestarted 12:17:51
The result I am looking for is: 53

A: I think TIMEDIFF should work in this case. You'll have to use it in conjunction with TIME_TO_SEC:
SELECT SUM(
    TIME_TO_SEC(
        TIMEDIFF(timefinished, timestarted)
    ) / 60) AS minutesBetween
FROM workouts
WHERE id = 'id';


text:
Q: How to Implement in a ModelAdmin Form in Django a Inline inside a Inline? Basic explanation:
I'm working on a catalog app that has Product as a model that has a 1-N relationship with  Galleries. Each Gallerie has N Photos.
I need to customize the add/edit form of my model Product as follows:

*

*In the same form can add/edit Galleries (as Inlines, easy, implemented). [1]

*But in each Gallerie Inline i can add Photos in the same Product Form

Is that possible?
[1]:
class GallerieInline(admin.StackedInline):
    model = Gallerie
    extra = 1

class ProductAdmin(admin.ModelAdmin):
    inlines = [GallerieInline,]

A: in the inline you must put a list_display with related object :S
Other way its create a view and with javascript get the images and append to inlines


text:
Q: Storing empty arrays in firebase I have my firebase app working with React whereby I sign users up and then log there information to the database. I am creating a "dating app" and I would like some way to store empty arrays. e.g, matchers: [] etc
I tried something liket this:
firebase.database().ref('users/' + userId).set({
      id: userId,
      username: name,
      email: email,
      matchers: [],
      likedUsers: [],
      disLikedUsers: []
    });

but then read that firebase doesn't really handle arrays as such and now am not sure how to do this. I want the empty array so then when the user starts using the app they can add to their various arrays.
any ideas?

A: Firebase has always recommended against using arrays. Instead of re-iterating the reasons, I'll point you to the blog post Best Practices: Arrays in Firebase.
But your bigger problem seems to be having empty arrays: the . If a property doesn't have a value, the Firebase Database doesn't store that property. That means that an empty array is not stored in the database and thus not read back.
You'll have to re-create those properties yourself after you read the data back. If you're having problems with this, update your question to show how you read the data.

A: You don't need to create those fields, they are initialized with the first item and the recommended way to indexed collections is to use the push and later to map it to an array.


text:
Q: How do you remove the x-axis from a bar chart produced by Google's Visualization API? Referring to the kind of chart shown here:
http://code.google.com/apis/visualization/documentation/gallery/barchart.html
There doesn't seem to be a simple switch, and changing the axis color to white (on a white background) didn't seem to do anything. I even tried jquery to hide the selectors produced by the api output but no dice.

A: You can set hAxis.textPosition to the value of 'none'
For example:
var options = {

                hAxis: { textPosition: 'none' },
            };

chart.draw(data, options);

See https://developers.google.com/chart/interactive/docs/gallery/barchart#Configuration_Options

A: I was able to remove the label in the material version of the chart by removing the string in my datatable.
Before:
data.addColumn('string', 'Date');

After:
data.addColumn('string', '');

A: let options = {legend: { position: 'none' }};

A: Their API has no function for this indeed, but:
chart.draw( data,
    {
        width: 400,
        height: 240,
        is3D: true,
        legend :'none',
        axisFontSize : 0
    });

Setting axisFontSize to 0 will remove your x-axis data. :)

A: Google changes the API so fast, this is what works today:
chart.draw(daily, {
    hAxis : {textColor: '#ffffff'},
    [... your other options here ...]
});

A: axisFontSize : 0 will remove x-axis and y-axis data

A: Check out http://code.google.com/apis/chart/docs/gallery/bar_charts.html#axis_label_styles
Axis Label Styles chxs "axis_or_tick"
You'll notice this documentation: "_ - (Underscore) Draw neither axis line nor tick marks. If you want to hide an axis line, use this value."
Example: 'chxs=0,,0,0,_'

A: Use this to remove axis from chart
hAxis: { textPosition: "none", gridlines: { count: 0 } },
  vAxis: { textPosition: "none", gridlines: { count: 0 } },
  baselineColor:"transparent",


text:
Q: c# No error but unresponsive program? My project to to create a c# windows,that simulates a fake GPS,that sometimes doesnt receive data,and most of the time receives data.
I have simulated that using Random class of c#.
It stores all this in sql server table m in db ex_1.
the program starts once i click GPS ON!,gps starts,and collects fake data,simulates periods of no data,meanwhile,I should be able to query the database,using other text boxes and buttons:

*

*One text box take the time and the object(I shud track several objects,for now i track just A)
and give me the location at the time.

*Another text box take the location and object name,and give the time at which it was at that     location.
The retreival of information from DB works fine on its own, the problem is the button GPSON! once it works nothing else does!
Now I am aware that I have an infinite loop in the program,so I was wondering,is it not possible to have other button working simulatenously,and this works infinitely UNTIL I press close,which ends the program?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public class GPS
        {
            public String ObjName;
            private Int32 Loc;
            private DateTime date;

            public void setLoc(Int32 Location)
            {
                Loc=Loc+Location;
            }

            public Int32 getLoc()
            {
                return Loc;
            }

            public void setDate(DateTime s)
            {
                date = s;
            }

            public DateTime getDate()
            {
                return date;
            }

            public GPS(String n)
            {
                ObjName =String.Copy(n);
                Random rnd1 = new Random();
                Loc = rnd1.Next(50);
            }
        }

        SqlConnection cs = new SqlConnection("Data Source=RAMAPRIYASR17A6;Initial Catalog=ex_1; Integrated Security=TRUE");
        System.Data.SqlClient.SqlCommand cmd=new System.Data.SqlClient.SqlCommand();

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            cs.Open();
            SqlCommand SelectCommand = new SqlCommand("select TIME from m where NAME=@name and LOCATION=@location",cs);
            SelectCommand.Parameters.Add("@name", tb2.Text);
            SelectCommand.Parameters.Add("@location", tb3.Text);
            SelectCommand.ExecuteNonQuery();

            SqlDataReader reader = SelectCommand.ExecuteReader();
            if (reader.Read())
            {
                answerlabel.Text = reader.GetString(0);
            }

            cs.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cs.Open();
            SqlCommand SelectCommand = new SqlCommand("select LOCATION from m where NAME=@name and TIME=@time", cs);
            SelectCommand.Parameters.Add("@name", tb2.Text);
            SelectCommand.Parameters.Add("@time", tb1.Text);
            SelectCommand.ExecuteNonQuery();

            SqlDataReader reader = SelectCommand.ExecuteReader();

            if (reader.Read())
            {
                answerlabel.Text = reader.GetString(0);
            }

            cs.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GPS a = new GPS("A");

            Random rnd = new Random();
            Random time_skip = new Random();

            while(true)
            {
                Int32 skip_or_not = time_skip.Next(-61, 600);//if <0 then GPS off

                //We check if skip_or_not < 0

                if(skip_or_not<0)//GPS off or off radar
                {
                    Int32 tChangePos = rnd.Next(-50, 50);
                    a.setLoc(tChangePos);

                    DateTime w = DateTime.Now;
                    TimeSpan timew = new TimeSpan(0, 0, 20, 0,0);//20 mins off radar
                    DateTime combined = w.Add(timew);
                    a.setDate(combined);
                }
                else
                {
                    Int32 ChangePos = rnd.Next(-6, 6);
                    a.setLoc(ChangePos);

                    a.setDate(DateTime.Now);
                }

                string stmt = "INSERT INTO m(TIME,LOCATION,NAME) VALUES(@time, @location,@name)";

                SqlCommand cmd = new SqlCommand(stmt, cs);
                cmd.Parameters.Add("@time", SqlDbType.VarChar, 100);
                cmd.Parameters.Add("@location", SqlDbType.VarChar, 100);
                cmd.Parameters.Add("@name", SqlDbType.VarChar, 100);

                cmd.Parameters["@time"].Value = a.getDate().ToString("t");
                cmd.Parameters["@location"].Value = a.getLoc().ToString();
                cmd.Parameters["@name"].Value = a.ObjName.ToString();

                cs.Open();
                cmd.ExecuteNonQuery();
                cs.Close();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

This is the shot of the program:

I am a beginner in c#, so Im not sure what I am doing wrong. I do think it has something to do with that infinite loop,not sure how to do it another way.
Thank you :)

A: You are blocking the main thread with your infinite loop. You should use another thread for that part of your software. Also, if you ever want to stop that functionality (a GPSOFF button for example) you should change while(true) to while(some_var) and before starting the thread set some_var to true and when you want to stop the thread do some_var = false. This will end the loop gracefully.
using System.Threading;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public class GPS
        {
            public String ObjName;
            private Int32 Loc;
            private DateTime date;

            public void setLoc(Int32 Location)
            {
                Loc=Loc+Location;
            }

            public Int32 getLoc()
            {
                return Loc;
            }

            public void setDate(DateTime s)
            {
                date = s;
            }

            public DateTime getDate()
            {
                return date;
            }

            public GPS(String n)
            {
                ObjName =String.Copy(n);
                Random rnd1 = new Random();
                Loc = rnd1.Next(50);
            }
        }

        SqlConnection cs = new SqlConnection("Data Source=RAMAPRIYASR17A6;Initial Catalog=ex_1; Integrated Security=TRUE");
        System.Data.SqlClient.SqlCommand cmd=new System.Data.SqlClient.SqlCommand();
        private Thread myThread;

        public Form1()
        {
            InitializeComponent();
            myThread = new Thread(trackGPS);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            cs.Open();
            SqlCommand SelectCommand = new SqlCommand("select TIME from m where NAME=@name and LOCATION=@location",cs);
            SelectCommand.Parameters.Add("@name", tb2.Text);
            SelectCommand.Parameters.Add("@location", tb3.Text);
            SelectCommand.ExecuteNonQuery();

            SqlDataReader reader = SelectCommand.ExecuteReader();
            if (reader.Read())
            {
                answerlabel.Text = reader.GetString(0);
            }

            cs.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cs.Open();
            SqlCommand SelectCommand = new SqlCommand("select LOCATION from m where NAME=@name and TIME=@time", cs);
            SelectCommand.Parameters.Add("@name", tb2.Text);
            SelectCommand.Parameters.Add("@time", tb1.Text);
            SelectCommand.ExecuteNonQuery();

            SqlDataReader reader = SelectCommand.ExecuteReader();

            if (reader.Read())
            {
                answerlabel.Text = reader.GetString(0);
            }

            cs.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            myThread.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void trackGPS()
        {
            GPS a = new GPS("A");

            Random rnd = new Random();
            Random time_skip = new Random();

            while(true)
            {
                Int32 skip_or_not = time_skip.Next(-61, 600);//if <0 then GPS off

                //We check if skip_or_not < 0

                if(skip_or_not<0)//GPS off or off radar
                {
                    Int32 tChangePos = rnd.Next(-50, 50);
                    a.setLoc(tChangePos);

                    DateTime w = DateTime.Now;
                    TimeSpan timew = new TimeSpan(0, 0, 20, 0,0);//20 mins off radar
                    DateTime combined = w.Add(timew);
                    a.setDate(combined);
                }
                else
                {
                    Int32 ChangePos = rnd.Next(-6, 6);
                    a.setLoc(ChangePos);

                    a.setDate(DateTime.Now);
                }

                string stmt = "INSERT INTO m(TIME,LOCATION,NAME) VALUES(@time, @location,@name)";

                SqlCommand cmd = new SqlCommand(stmt, cs);
                cmd.Parameters.Add("@time", SqlDbType.VarChar, 100);
                cmd.Parameters.Add("@location", SqlDbType.VarChar, 100);
                cmd.Parameters.Add("@name", SqlDbType.VarChar, 100);

                cmd.Parameters["@time"].Value = a.getDate().ToString("t");
                cmd.Parameters["@location"].Value = a.getLoc().ToString();
                cmd.Parameters["@name"].Value = a.ObjName.ToString();

                cs.Open();
                cmd.ExecuteNonQuery();
                cs.Close();
            }
        }
    }
}

A: Your problem is that the infinite loop is in the GUI thread, thus making the GUI unresponsive. Read up on BackgroundWorkers. You neeed to move your processing to a background thread, and BackgroundWorker is an easy way to do that.


text:
Q: Using Plupload with amazon s3 and asp.net MVC C# I am trying to use plupload http://www.plupload.com/ to upload images to an amazon s3 bucket and I want to also store the images urls in a sql server using asp.net MVC to be able to use them in the future. I am incredibly lost on exactly what to do. All the articles have really confused me.
Please help me in:
1) Re-size images to a maximum width and height on client size.
2) Upload images directly to amazon s3 (showing a progress bar).
3) Store image location in a database.
(How to link with plupload with MVC C# given that files are uploaded to s3 directly)

A: I can help with the post directly the S3 part.
I created a sample MVC3 app and put it on Github. It's currently setup for videos but if you change the content-type and some of the plupload settings it will easily work for images. This Ruby on Rails examples is configured for images:
https://github.com/iwasrobbed/Rails3-S3-Uploader-Plupload
Details on my blog:
http://blog.cdeutsch.com/2011/07/aspnet-mvc3-app-using-plupload-to.html
Github:
https://github.com/crdeutsch/MVC3PluploadToAmazonS3


text:
Q: Mongo select conversations based on messages I have a document for a message:
{ sender: ObjectId, receiver: ObjectId, message: string, createdAt: Date }

where sender and receiver refer to User.
The problem is selecting unique ids of the users with who provided user had at least one common message.
Something like this, but only distinct ids:
async getConversations(id) {
return this.personalMessageModel.find({
    $or: [
      { sender: Types.ObjectId(id) },
      { receiver: Types.ObjectId(id) },
    ],
  })
  .sort({ createdAt: 'asc' })

}


text:
Q: Problem adding .ics file to Iphone X Calendar I had a problem adding .ics files to my Iphone X calendar. I created an .ics file on my other Android phone and I am able to add this .ics-file-event to my Google calendar and many others. But when I send it to my Iphone X via Whatsapp, I can't add it to my default IOS calendar. It always says:
This invite is outdated

And there is no button to add it to my calendar. I am not sure, if it is a coding issue in my .ics file or something else. Surprisingly it's perfectly working on the Iphone 6 calendar.
That's my .ics file code.
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-Nick//0.6.3//EN
BEGIN:VEVENT
UID:dabfe592-49f3-4428-93cd-1026b90c0004
DTSTAMP:20190728T143648Z
SUMMARY:Test
DESCRIPTION:Test
LOCATION:Test
DTSTART;VALUE=DATE:20190914
DURATION:P1D
END:VEVENT
END:VCALENDAR

Thanks for help


text:
Q: Writing $\beta$ and X for a qualitative model Express the following model in matrix form, ie: specify $\beta$ and $X$ so that the model can be written as $Y = X \beta + \epsilon$.
The model $Y_{ij} = \mu_i + \epsilon_i$ where $Y_{ij}$ represents the $j$-th observation observed at level $i$ of a qualitative explanatory variable $T$, for $i=0,...,4$ and $j=1,2$.
I know how to write the vector $\beta$ (just a column of $\mu_0$ to $\mu_4$), but how do you write the matrix X?

A: Write $\tilde{Y}$ as a vector of length $10,$ by stacking $Y_{01},Y_{02},Y_{11},Y_{12},...,Y_{42}.$ Similarly define $\tilde{\varepsilon}.$ You are now  looking for a $10\times 5$ matrix $X$.
$\beta^T=(\mu_0,\mu_1,\mu_2,\mu_3,\mu_4)$
$$X=\begin{bmatrix}1&0&0&0&0\\
1&0&0&0&0\\
0&1&0&0&0\\
0&1&0&0&0\\
0&0&1&0&0\\
0&0&1&0&0\\
0&0&0&1&0\\
0&0&0&1&0\\
0&0&0&0&1\\
0&0&0&0&1\end{bmatrix}$$
Then $\tilde{Y}=X\beta+\tilde{\varepsilon}$ is an expression of $Y_{ij}=\mu_i+\varepsilon_{ij}.$
If instead you had $Y_{ij}=\mu_0+\mu_i+\varepsilon_{ij},$ $\tilde{Y}$ and $\tilde{\varepsilon}$ will have length $8.$ Then
$$X=\begin{bmatrix}1&1&0&0\\
1&1&0&0\\
1&1&0&0\\
1&1&0&0\\
1&0&1&0\\
1&0&1&0\\
1&0&0&1\\
1&0&0&1\end{bmatrix}$$
will be your design matrix so that $\tilde{Y}=X\beta+\tilde{\varepsilon}.$


text:
Q: Session Management in iPhone I need to manage server sessions in iPhone. As I researched there are many ways. One way is to use the apple native method calls by make use of the NSURLConnection and NSHTTPCookieStorage classes. However using the 3rd party libraries like ASIHttpRequest can also be helpful cos it already has implemented the above scenarios. So what will be the best approach for me to maintain the server session in my iPhone. I need to track the following,
1) Login, Logout mechanisms in server.
2) Sever session timeout.
Also does this cookie work as a normal browser cookie? Does it get invalidated after the life time of cookie has expired?
Regards,
Dilshan

A: Well, the best approach is the one which works best for you.
I like ASIHTTPRequest, personally. It can be setup to use the global cookie store for session management.
Your server-side code will have some ramifications here, as well. So bear that in mind with things like your timeouts, etc.


text:
Q: Tkinter: Display an image on top of other I'm trying to do a game based on Mario, and I wanna first, print 2 images on the screen with the code:
from tkinter import *
import time
janela = Tk()

janela.geometry("1920x1080")
janela.title("Mario")

mario = PhotoImage(file = "cenario.png")

label = Label(janela, image = mario).place(x=0,y=0)
photo = PhotoImage(file = "mario.png")
label = Label(janela, image = photo).place(x=3,y=600)

janela.mainloop()

And what I get was:

How can I display without this grey background?
Thank you


text:
Q: Is there a way to retrieve an existing notification_key based on a registration id or a notification key name? Assuming that one has created a device group in Firebase Cloud Messaging, is there a way to retrieve an existing notification_key for a device group after it's been created?
Is there a way to look up the notification_key based on either notification key name or by registration id?
It seems the notification key is only returned on the create method and if the key is ever lost or errors on saving to the the database - it would be impossible to add another registration id to the the key name without a notification_key since it already exists.

A: You can retrieve the notification_key for a device group if you know the notification_key_name that was used when you created it. Ref: https://firebase.google.com/docs/cloud-messaging/android/device-group
Use this:
https://android.googleapis.com/gcm/notification?notification_key_name=your-key-name

Ref: https://groups.google.com/forum/#!topic/firebase-talk/ytovugx8XNs
For example:
let options = {
    url: 'https://android.googleapis.com/gcm/notification?notification_key_name=the_name',
    method: 'GET',
    headers: {
        "Content-Type": "application/json",
        "Authorization": "key=" + authorizationKey,
        "project_id": projectId
    }
};

request(options, function (error, response, body) {
    if (!error) {
        res.json(body);
    }
    else {
        res.json(error);
    }
});

One thing I found when using this call was that the notification_key returned was always different, but I was able to use it successfully to add or remove registration_ids.
I'll add some additional information from comments I made earlier:

*

*I've had quite a bit of trouble with device groups. The only way to delete a device group is to remove all the notifications keys it contains. If you lose track of a notification key that you have added to the device group then deleting that device group is impossible, as there is no way currently to get a list of the notification keys in a device group.

*The device group is a very good mechanism for sending messages to multiple devices (see @AL.'s comment for another method). I also store in the database the registration_ids for each device group. The reason for that is if the user deletes their account for my app I also delete their device group so that the device group name can be reused.

A: There is currently no API to retrieve the Device Groups (notification_keys) associated with a given Registration Token. AFAIK, managing/mapping relationships of Device Groups and its associated registration tokens are the developers responsibility.
For your scenario, I would suggest to temporarily store the notification_key until it is successfully stored in your App Server.
Some possibly helpful posts:

*

*Firebase Cloud Messaging - Managing Registration Tokens

*Managing FCM device groups


text:
Q: Tools > Import Wordpress does not allow XML file over 2 MB How do I change the Import Wordpress limit of 2 MB for uploading an XML file?  Searched everywhere - most people talk about increasing limits in php.ini or .htaccess.  Both are unrelated to this issue, and do nothing to the screen which looks like this in Wordpress 3.8.1:

This video is the only apparent fix: http://www.youtube.com/watch?v=lZsXQ1KrObU
It shows exactly my problem, and how to solve it.  Unfortunately - it doesn't change anything in WP 3.8.1. I'm amazed this hasn't been addressed.

A: Found the answer. Create a php.ini file in the /wp-admin directory with the following code:
upload_max_filesize = 64M
post_max_size = 64M

It won't work if the file is in the root directory.

A: you may want to try asking your hosting provider they may have set the upload limit at 2mb and can change it quite easily


text:
Q: Get client SSL handshake data using IIS When working with IIS, is it possible to get information about SSL handshake?
I want to extract all the info the client is sending in it's "HelloMessage":

*

*highest TLS protocol version it supports

*a list of suggested cipher suites

*a list of suggested compression methods

*a list of supported application protocols(for clients who use ALPN)


text:
Q: Load a class to Java classpath dynamically using Eclipse and OSGi Combining the information from many posts on this site and many others, I got the following code to dynamically add (at run time) a directory containing classes to the classpath and load a class within that directory.
I'm using OSGi bundles and running from eclipse an "Eclipse Application" (a kind of Run Configuration).
This is the code I'm using:
CASE 1: (both cases are different things I've tried to do the same thing.)
File file = new File("/Users/alek/fastFIX/myJPass/");
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class  cls = cl.loadClass("GuiLauncher");    //the file GuiLauncher.class is in the /Users/alek/fastFIX/myJPass/ directory
Class[] argTypes = new Class[] { String[].class };
Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class
main.invoke(null, (Object) args);

I don't get any error, and nothing happens.
I've also tryied the following, as I actually need the loaded class to interact with other (already loaded) classes.
CASE 2:
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {  new File("/Users/alek/fastFIX/myJPass/").toURL() }, currentThreadClassLoader);
Thread.currentThread().setContextClassLoader(urlClassLoader);

then i load like this:
 Class<?> c = Class.forName("GuiLauncher");

or like this:
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("GuiLauncher");

and try to invoke the main function like this:
Class[] argTypes = new Class[] { String[].class };
Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class
main.invoke(null, (Object) args);

here also nothing happens.
Any clue of what could be happening? I've read all related posts here and many places else with no luck.

A: In OSGI framework it is necessary to add the OSGI class loader as a parent, something like this:
    ...
    ClassLoader cl = new URLClassLoader(new URL[]{file.toURI().toURL()}, this.getClass().getClassLoader());
    ...

A: In case 1, I suspect that the GuiLauncher class is already on the classpath, so may get loaded by the default classloader. Try doing Class.forName() before setting up the dynamic classloader, to confirm that there's no class available. If you are in Eclipse, you need to be careful that the class is not included on the Eclipse classpath, which is what would normally happen. You might need to compile it once then move the .java and .class files elsewhere to hide them from Eclipse!
In case 2:
Class.forName("GuiLauncher");

will not work as you expect, because this will use the system classloader. This should fail, hence my suspicion above. You need use the other version of this method that specifies your dynamic classloader:
Class.forName("GuiLauncher", true, urlClassLoader)

The following code works for me.
import java.net.*;
import java.lang.reflect.*;
import java.io.File;

public class Main{

public static void main(String[] args)
{
    try{
      Class  cls = Class.forName("Plugin");
    }
    catch(Exception e){
      System.out.println("Nothing there!");
    }

    try{
      File file = new File("plugin");
      ClassLoader cl = new URLClassLoader(new URL[]{file.toURI().toURL()});
      Class  cls = Class.forName("Plugin", true, cl);
      Method main = cls.getDeclaredMethod("main", new Class[] { String[].class });
      main.invoke(null, (Object) args);
    }
    catch(Exception e){
      e.printStackTrace();
    }
  }
}

The Plugin class is compiled in the plugin subfolder, so it's not on the classpath used to run Main, as shown by the first Class.forName().
public class Plugin{
  public static void main(String[] args)
  {
    System.out.println("Plugin was invoked!");
  }
}

and prints out:
Nothing there!
Plugin was invoked!