Q: F# - Return a value from for .. do I have a (random) set of numbers and I want to decide for any given number, whether the number is a composite one (meaning it can be created by two other numbers in the same given set).
Mathematical definition of my function:

Current code:
let task1 (M : seq<'T>, r : 'T) : bool =
    if not(Seq.exists((=) r) M) then
        failwith "nope!"
    else
        for s in M do
            for t in M do
                if s + t = r then
                    true         // error
        false

Issue:
I cannot return a boolean result from my iteration, when the element r has been 'found' as sum of the two elements s and t.

How could I solve the given problem as efficiently as possible?

If somebody finds an algorithm with a total run-time smaller than O(n²), then it is also fine by me.

[all called methods must also be faster than O(n²)]

A: You can't do what you're trying to do because F# is a language that uses expressions rather than statements.  F# expressions always evaluate to a value (although that value might be unit: ()).
The code you originally posted doesn't compile because something of type unit is expected, that's because your if/then expression has no else branch.  Consider the following:
let a = if x > 5 then 10

This code will produce a compiler error, that's obvious because we haven't specified what the integer value of a might be if x is not greater than 5.
Of course, this code will compile:
let a = if x > 5 then 10 else 5

If you provide and if without an else, the F# compiler will assume the type is unit so this is also valid code:
let a = if x > 5 then ()

This is because both cases still just return unit, there is no type mismatch.
Because F# uses expressions, everything has to be bindable to a value.

Anyway, you can solve this by using nested Seq.exists statements, this way you can check every combination of values.
let inline task1 items r =
    items |> Seq.exists (fun s ->
        items |> Seq.exists(fun t -> s + t = r))

I've changed some of your naming conventions (it's idiomatic for F# function parameters to be camelCased) and have made your function inline so it will work on any type that supports addition.

A: Generally, you don't want to use loops to implement complicated iterations / recursive functions in F#. That's what tail recursive functions are good for.
To get the computational complexity below O(n²), how about this: consider the set of candidate summands, which is the complete set of numbers at first. Now look at the sum of the largest and smallest number in this set. If this sum is larger than the target number, the largest number won't sum to the target number with anything. The same goes the other way around.
Keep dropping the smallest or largest number from the set of candidates until either the set is empty or a match has been found.
The code could look like this:
let rec f M x =
    if Set.isEmpty M then false else
    let biggest, smallest = Set.maxElement M, Set.minElement M
    let sum = biggest + smallest
    if   sum > x then f (Set.remove biggest M)  x
    elif sum < x then f (Set.remove smallest M) x
    elif sum = x then true
    else failwith "Encountered failure to compare numbers / NaN"

When I look at the mathematical definition, it doesn't seem to be a requirement that the target number is in the set. But if this matters, just check beforehand:
let fChecked M x =
    if Set.contains x M then f M x
    else invalidArg "x" "Target number is not contained in set."

Tom make this generic over the comparable type, the function could be marked inline.
Set operations are O(log n), we go over the whole thing once, multiplying O(n), making the total complexity O(n log n) (where n is the number of elements in the set).

Effective speed version
If it's about actual speed rather than "just" the computational complexity, arrays are probably faster than immutable sets. Here's a version that uses array indices:
/// Version where M is types as an unsorted array we're allowed to sort
let f M x =
    Array.sortInPlace M
    let rec iter iLow iHigh =
        if iLow > iHigh then false else
        let sum = M.[iLow] + M.[iHigh]
        if   sum > x then iter iLow (iHigh - 1)
        elif sum < x then iter (iLow + 1) iHigh
        elif sum = x then true
        else failwith "Encountered failure to compare numbers / NaN"
    iter 0 (M.Length - 1)

Note that we could pre-sort the array if the same set is used repeatedly, bringing down the complexity for each call on the same set down to O(n).


Q: Generating first n prime numbers using dynamic programming How can I generate first n prime numbers using dynamic programming ? (Code is not required just the concept would be enough)

A: We can use Memoization technique for generating prime numbers using dynamic programing. You can write a function which accepts the number to be checked(say x) for primality and another parameter which accepts divisor(say the variable is i). Inside the function check for the conditions like i==1 then return 1 and x%i==0 then return 0 and again call the function recursivly with decrementing i and the result shoiud be stored in to an array.

A: If you will google it, you will find the solution very easily:
BTW solution is
Use method described here:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes


Q: Run Once Code: Beyond Boolean? I'm struggling for a pattern here. I have quite a few tasks that need to be run, but only need to be run once if they haven't been run before. Everything right now is handled by if/then, booleans and a hashtable. There are also nested children of the same effect (if/then, boolean) so their parent if/then, boolean isn't set to true until the very end.
In .NET, is there some kind of code pattern or class for this that makes it simplier/clearer/less code, or am I over-thinking it and this is exactly the way needs to be done?
P.S. feel free to add better tags to this post, I wouldn't know what to add to make it more descriptive if there is a term out there

A: I don't know how your tasks are coded, but it seems that they could be encapsulated in commands, which would then be put in a queue, or some other data structure. Once they are dequeued, their logic is checked. If they need to run, they are executed, and they're not put back in the queue. If their logic says that they shouldn't run, they're just put back in the queue to be able to run later.
Your interface would be something like:
public interface ITaskSink {
  void AddTask(ICommandTask task);
}

public interface ICommandTask {
  bool ShouldRun();
  void Run(ITaskSink sink);
}

Tasks could also be able to add other tasks to the data structure (so Run takes an ITaskSink as a parameter), covering your subtask creation requirement. A task could even add itself back to the sink, obviating the need for the ShouldRun method and simplifying your task processor class.

A: If you're using .NET 4.0, the Lazy<T> generic might be the solution to what you're describing, because it evaluates its value at most once.
I'm not sure I exactly understand your use case, but there's no reason you couldn't nest Lazys together to accomplish the nested children issue.

A: I'm not exactly sure what you're talking about, but a helpful pattern for complex chained logic is the rules engine.  They're really simple to code, and can be driven by simple truth tables, which are either compiled into your code or stored as data.

A: Create a private static variable, create a read only property to check for null on the private variable, if the variable is null instantiate/initialize and just return the private variable value.  In your implementation code reference the property, never the private variable.


Q: How to pass Post (variable) info to a second page I have an HTML order form that collects info and then on submission passes that to a PHP form which sends an email. Then I have the PHP form forwarding to a PHP confirmation page.

*

*I am using the POST method on my HTML form.

*I am forwarding to the PHP confirmation page with header() after it sends the email.

Everything is working fine, but I need to know how to pass the variables along to the confirmation page. I can use them on the email page, but they are dropped on the page forwarding. I'm sure it's easy, but I have a lot to learn yet. :-) Do I have to create a file to store the variables, or can I pass them along?
I know I could display the confirmation page with the PHP page that sends the email (I did have it setup that way) but we have had users bookmark that page which will resend the order every time they visit that bookmark. So I'm separating the pages so if they bookmark the confirmation page it will at least not resend an order.
Make sense? Thanks for your help!

A: You can keep the parameter sent in POST in session variables. This way on your second page, you can still access them.
For example on your first page :
<?php
session_start();

// ... //

$_SESSION['value1'] = $_POST['value1'];
$_SESSION['value2'] = $_POST['value2'];

header('Location: youremailpage.php');
die();

// ... //
?>

And on your second page :
<?php
session_start();

// ... //

$value1 = $_SESSION['value1'];
$value2 = $_SESSION['value2'];

// ... //
?>


Q: Windows 7 hung during installation -- why and what can I do? I am upgrading from Windows Vista to Windows 7, and the installation process has gone into a loop during the "Expanding Windows Files" step. It is 17% through that step, and just alternates between a message saying "378 of 2224 MB installed" and one saying "please wait."
I would like to save my old files if possible.
Any idea why it may have hung or advice on what to try?

A: See this for backing up your data, it may be in the original location, but more than likely it is in a folder called windows.old
http://www.howtogeek.com/howto/windows-vista/use-ubuntu-live-cd-to-backup-files-from-your-dead-windows-computer/
.


Q: What does "alternate tone or mood" exactly means in  tag definition in HTML 5? In the docs(MDN), it is written:"Use the  element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages".
What does "alternate tone or mood" means in the above definition? Can someone explain it in simple terms.
It would be quite helpful if someone can explain this by providing an example.

A: Perhaps a good way to answer your question is from the same reference:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em
New developers are often confused at seeing multiple elements that
produce similar results. <em> and <i> are a common example, since
they both italicize text. What's the difference? Which should you use?
By default, the visual result is the same. However, the semantic
meaning is different. The <em> element represents stress emphasis of
its contents, while the <i> element represents text that is set off
from the normal prose, such a foreign word, fictional character
thoughts, or when the text refers to the definition of a word instead
of representing its semantic meaning. (The title of a work, such as
the name of a book or movie, should use <cite>.)
This means the right one to use depends on the situation. Neither is
for purely decorational purposes, that's what CSS styling is for.

To "emphasize" something is to express "alternate tone or mood".
If you want to "emphasize" a certain word or phrase in a paragraph, you can use italics.
In editors like MS-Word, you can highlight the text, and select "Italicize".
Older versions of HTML provided the <i> element.  HTML 5 introduced the "semantic" equivalent, <em>.  Distinguishing it from other semantic elements, like <cite>.


Q: Finding a subvariety that is finite over the target. Given a surjective homomorphism of abelian varieties like $f:A\rightarrow B$ where $\text{dim}(A)>\text{dim}(B)$, is it possible to find a subvariety $Z$ of $A$ such that restriction of $f$ to $Z$ induces a finite surjective morphism $f|_Z:Z\rightarrow B$? (this is equivalent to asking whether there is a cycles $Z$ such that $f_*[Z]$ is an integer in the grothendieck group of $B$)

A: Claim: "(this is equivalent to asking whether there is a cycles Z such that $f_∗[Z]$ is an integer in the grothendieck group of $B$)"
Comment: If $f: A \rightarrow B$ is a proper morphism of abelian varieties, there is an induced push forward map at the level of Chow groups
$$f_*: A_k(A) \rightarrow A_k(B)$$
and for any cycle $[Z]\in A_k(A)$ it follows $f_*[Z]\in A_k(B)$ is an algebraic cycle and not an integer. The group $A_k(B)$ is an abelian group that is not finitely generated in general. Similarly for the Grothendieck group: The push forward will be a class $\sum_i n_i[E_i]\in K_0(B)$. You must specify what you are talking about.
It seems you want $B$ to be irreducible with $d:=dim(B)$ and hence $A_d(B)$ is generated by $[B]$.
There is if $B:=B_1 \cup \cdots \cup B_l$ are the irreducible components of $B$
with $dim(B_i)=d$ for all $i$ an isomorphism of abelian groups
$$A_d(B)\cong\mathbb{Z}[B_1]\oplus \cdots \oplus \mathbb{Z}[B_l]\cong \mathbb{Z}^l,$$
hence you may not in general identify $A_d(B)$ and $\mathbb{Z}$.
Note: There is the "etale overing lemma" (Mumford, Abelian Varieties page 167) saying that if $f:Y \rightarrow X$ is an etale cover with $X$ an abelian variety, then $Y$ has the structure of abelian variety and $f$ is a separable isogeny. In your case this puts conditions on $Z$ if the induced map $f_Z$ is etale.


Q: Approximating matrix multiplication with integer arithmetic The following question is inspired with approximation of matrix multiplication computations occurring in numerical simulations and machine learning algorithms with a use of efficient integer arithmetic.
There are many possible variants of the question. For concreteness I'll propose one particular, but I am not very attached to this particular formulation.
How well can we approximate real matrix multiplication operation:
$$ \_ \cdot \_ :  \mathbb{R}_{\geq 0}^{I\times J} \times \mathbb{R}_{\geq 0}^{J\times K} \longrightarrow \mathbb{R}_{\geq 0}^{I\times K} $$
using matrix multiplication on a given (by $k$) finite prefix of natural numbers:
$$ \_ \odot \_ :  \mathbb{N}_{\leq k}^{I\times J} \times \mathbb{N}_{\leq k}^{J\times K} \longrightarrow \mathbb{N}^{I\times K} $$
where:
$$\mathbb{N}_{\leq k} = \{i \in \mathbb{N} \mid i \leq k \}$$
Of course in order to be precise we need to constrain the "remaining computation" that we might be allowed to do. One way to do it is to specify all allowed operations, another is to limit computational complexity. I'd like to avoid doing that explicitly and hope that the spirit of the question is clear.
The family of solutions I am thinking about is the family of approximations:
$$ A \cdot B \approx r ([ r^{-1} A s] \odot [s^{-1} B t]) t^{-1} $$
where $r, s, t$ are diagonal matrices that scale rows and columns of $A$ and $B$ and
$$[\_] : \mathbb{R}_{\geq 0} \longrightarrow \mathbb{N}_{\leq k}$$
is some projection operator e.g. round (or floor) and clip.
I have a hard time defining a metric to minimize and finding optimal $r,s,t$.
Some questions:
Is my formulation generic enough to capture the problem?
How to more precisely model the problem to find suitable $r, s, t$?
Are there any references that might help with the task?
I'll be grateful for all and any help. Thank you.


Q: How to structure a Python package so others can add modules easily I have a component-oriented Python (3.3) project.  I have a base Component class.  I want others to be able to add modules that contain subclasses of Component just by copying their .py file(s) into some folder, without having to edit anything.  Running the main program should then simply import all the .py files found in that folder.  All accesses from my main program to these subclasses are via Component.__subclasses__(), not by explicit name.  I am not especially worried about name clashes between code in different user-written modules, but of course I would like to avoid it if possible without screwing up the simple drop-file-into-folder inclusion.
How do I structure a package to achieve this?

A: I would structure the package like this:
myPackage
+ -- __init__.py
+ -- Component.py
+ -- user_defined_packages
     + -- __init__.py # 1
     + -- example.py

Ideas:

*

*let the users drop into a different folder so that they do not mix up your code and theirs

*The init file in user_defined_packages can load all the subpackages once user_defined_packages is imported. It must print all errors.

__init__.py # 1
import os
import traceback
import sys

def import_submodules():
    def import_submodule(name):
        module_name = __name__ + '.' + name
        try:
            __import__(module_name)
        except:
            traceback.print_exc() # no error should pass silently
        else:
            module = sys.modules[module_name]
            globals()[name] = module # easier access

    directory = os.path.dirname(__file__)
    for path_name in os.listdir(directory):
        path = os.path.join(directory, path_name)
        if path_name.startswith('_'):
            # __pycache__, __init__.py and others
            continue
        if os.path.isdir(path):
            import_submodule(path_name)
        if os.path.isfile(path):
            name, extension = os.path.splitext(path_name)
            if extension in ('.py', '.pyw'):
                import_submodule(name)

import_submodules()


Q: Windows Phone 8 URI associations and the mail client I have an application that has a registered URI association (my-prefix://) as per http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987(v=vs.105).aspx however I have noticed a difference between how the emulator works and how a device works.
Within the emulator I can send myself a HTML email containing a link with the above URI prefix (e.g. my-prefix://my-data).  The link appears blue and clicking it opens my app as expected.
On a Lumia 920 (accessing the same mail on the same mailbox), the link appears black (as per other text) and clicking it highlights the entire link but doesn't launch the app.  It does nothing.
Interestingly, accessing the same mail on a WP7 device (Lumia 900) does show it as a blue link, but WP7 doesn't support the URI associations so it obviously doesn't actually work.
Reading the documentation that I've found, there is nothing specific that says that this should or should not work from within an email.  The documentation states that "A URI association allows your app to automatically launch when another app launches a special URI", and various articles state that Bing Vision doesn't support them directly (although opening a web page which redirects to the URI apparently works).
My main question is: am I doing something wrong, or is this the expected behaviour?
(Unfortunately the links with the custom URI prefix aren't generated by me so can't be altered to be http with a redirect).
Craig.

A: Apparently, the "Safe HTML policy" on Exchange can lead to some URIs with "non-standard" schemes being just treated as plain text.
If this is the case and you can't control the policy on the server, the only option is to wrap in a HTTP redirect. :(


Q: Better way to handle asynchronous log writing public static class LogWriter
{
    private static ReaderWriterLockSlim writeLock = new ReaderWriterLockSlim();
    public static void WriteExceptionLog(string content)
    {
        #if DEBUG
        MessageBox.Show(content);
        #endif
        WriteLog(content, Constant.EXCEPTION_LOG_PATH);
    }
    public static void WriteLog(string content, string path)
    {
        try
        {
            writeLock.EnterWriteLock();
            string directory = Path.GetDirectoryName(path);
            if (!Directory.Exists(Path.GetDirectoryName(directory)))
                Directory.CreateDirectory(directory);
            using (StreamWriter writeFile = new StreamWriter(path, true))
            {
                content = DateTime.Now + " : " + content;
                writeFile.WriteLine(content);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            writeLock.ExitWriteLock();
        }
    }
}

I have a class that writes logs. Because I am writing to a log asynchronously, I need to put a lock and release it when write is done but this seems to be somewhat of a clunky solution and maybe even bad for performance.
What is a better way to handle this?

A: For performance reason and also to avoid a very different behavior between log-ON and log-OFF, I suggest to run one buffered log file per thread.

*

*One per thread to avoid locking: no contention

*Buffered to avoid disk latency

The counterparts are:

*

*a merging tools based on time (milliseconds) is needed to see application activity as a whole (vs thread activity)

*buffering may hide last log records in case of brutal termination

To go one step more to real-time, you have to log in memory, and to develop a dedicated interface to extract log on request  but this kind of log is generally reserved to hard real-time embedded application.
Other solution for safe logging with low CPU consumption (low level C programming):

*

*place a log record buffer into shared memory

*the observed process act as log record producer

*create a log manager process, with higher priority, which acts as log record consumer

*manage the communication between consumer and producer behind a flip/flop mechanism: a pointer assignment under critical section.

If the observed process crash, no log record will be lost since shared memory segment is attached to log manager process.

A: Opening, writing to, and then closing the file on each log request is both redundant and inefficient.
On your log class, use a buffer, and write that buffer's contents to the file, either every X requests, shutdown, or every Y minutes.


Q: Parsing information from a jQuery POST request? I have been trying for 2 weeks to get and parse information from an API of this site:
http://www.imei.info/api/imei/docs/
I'm new to web development (RT C++ developer), I can't seem to get is to work.
my code here:
<!DOCTYPE html>

Start typing a name in the input field below:

    First name:

    <input type="text" />

A: It's returning a JSON response. You can do var responseObj = JSON.parse(data) and access the fields like responseObj.imei or responseObj.brand


Q: why validate content-type header in REST request The OWASP website suggest to validate the content-type header. But it does not specify the rational for the same. What is the reason that I should validate the content-type header, even though I am not reading or using it?

When POSTing or PUTting new data, the client will specify the
  Content-Type (e.g. application/xml or application/json) of the
  incoming data. The server should never assume the Content-Type; it
  should always check that the Content-Type header and the content are
  the same type. A lack of Content-Type header or an unexpected
  Content-Type header should result in the server rejecting the content
  with a 406 Not Acceptable response.

A: One example that comes to mind is in a cross-site ajax request, it is easy to send a text/html request which will not generate a pre-flight request, but it is not possible with applictaion/json. So if you have a service with a POST action that expects json and changes server state, it may be possible to exploit CSRF if text/html is accepted for the content type, but there is some basic protection if application/json is verified, because the browser will not send the request from a different domain if the response to the pre-flight does not explicitly allow a CORS post.
So some properties of cross-domain ajax requests depend on the content type. I think this may be the main reason.
Also from a more theoretical standpoint, the format of the data is needed to parse it. I cannot think of an actual exploit, but at least in theory, trying to parse data in a wrong format may lead to the wrong results, things parsed different from what they were supposed to be. It's best to just validate that the client is actually sending what it claims, and what it should be.


Q: Include argument in NAnt executable call if property is not null or empty For a build script, part of my process is to deploy files using an in-house executable.  We call this with a number of parameters.
On an application I'm working on, it turns out we need to add a parameter.  This isn't something that retroactively applies to anything else I've previously worked on, so the idea is that I would only include the new argument if the corresponding property is not null or empty.
Relevant NAnt Call:
<property name="deploy.NewArg" value="" />
<echo message="deploy.NewArg = ${deploy.NewArg}" />

<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
    <arg value="AppTitle=${deploy.AppTitle}" />
    <arg value="Environment=${deploy.Environment}" />
    <!-- Here's the problem argument... -->
    <arg value="MyNewProperty=${deploy.NewArg}" if="${deploy.NewArg}" />
</exec>

The reason what I have is not working, is because of the if clause on the new <arg> tag - the deploy.NewArg string doesn't convert to a boolean statement.
Question: In what way can I perform an "Is Null or Empty" check on an <arg if> parameter?  As noted above, I want the MyNewProperty=... argument added if deploy.NewArg is anything but nothing or an empty string.
I checked a number of other StackOverflow questions, as well as the official NAnt arg tag documentation, but could not find how to do this.

A: It turns out, I needed to get back to the basics, and check out some of my fundamentals and functions.  The way to do an 'is empty' check on a property is as below:
<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
    <!-- Other args... -->
    <arg value="MyNewProperty=${deploy.NewArg}" if=${string::get-length(deploy.NewArg) > 0}" />
</exec>

For someone who hasn't yet done the research, if only works with a boolean.  That being said, booleans can be generated in one of two ways: either an explicit true or false, or by using an expression.  Expressions are always contained in ${} brackets.  The use of string::get-length() should be obvious.
Bring it all together, and you only include an argument if it's specified.


Q: Render props with typescript I am trying to create a render props wrapper component. It is working, but I am getting type errors. Here is my link to a code sandbox as well. link to sandbox

*

*the first error I am getting is children is an expression that is not callable.

*the second error is "hello" has implicitly any type.

Looking for a react/typescript guru for help
type Props = {
  children: JSX.Element;
};

const ControlledWrapper: FC<Props> = ({ children }) => {
  const state: { hello: string } = { hello: 'hello' };

  return children(state);
};

export default function App() {
  return (
    <ControlledWrapper>
    {({ hello }) =>
{hello}
}
  </ControlledWrapper>
  );
}

A: Change the type of children to a function that returns a React element:
type Props = {
  children: (ctx: { hello: string }) => ReactElement;
};

Now when you use the component you get the right types:
    {({ hello }) =>
{hello}
} // 'hello' is a string

Try this out here.


Q: extension 'GL_ARB_shading_language_420pack' is not supported, how to load this extension in QT? I'm using QT on a mac pro to run a demo of opengl.
But I got a message like this:
:: OpenGL initialized ( 4.1 INTEL-14.7.8 )
QOpenGLShader::compile(Fragment): WARNING: 0:1: extension 'GL_ARB_shading_language_420pack' is not supported
ERROR: 0:6: '{' : syntax error: syntax error

Does anyone know how to make this extension "GL_ARB_shading_language_420pack" supported in Qt?

A:
I'm using QT on a mac pro

MacOS does not support any OpenGL version higher than 4.1. It doesn't support 4.20 or most post-4.1 OpenGL extensions. And since OpenGL support is already deprecated in MacOS, no such support will be forthcoming.
If you want to use OpenGL on MacOS, then you're going to have to limit everything to 4.1 functionality.


Q: Average in dataframes with subsets of rows - Python I have a dataframe as the following:
Member Category Total
1001      1       5
1001      2       4
1001      3       9
1003      1       7
1003      2       5
1003      3       2
1005      1       2
1005      3       5

I need to get:
  Member Category Total  Average
    1001      1       5     0.27
    1001      2       4     0.22
    1001      3       9     0.5
    1003      1       7     0.5
    1003      2       5     0.35
    1003      3       2     0.15
    1005      1       2     0.28
    1005      3       5     0.72

That is, the average of totals for each member. For instance, the member 1001 has a total of 18, in which the category 1 represents 27% of the total. Therefore the average would be 0.27.
What I tried was:
average = []
for member in df[df["Member"].unique():
    total_member = df[df["Member"] == member]["Total"].sum()
    for category in df["Category"].unique():
        total_category = df[(df["Member"]==member) & (df["Category"]==category)]["Total"]
        average.append(total_category/total_member)

df["Average"] = average

However, not only does it not work, but since I have a very large amount of data, it is too slow.

A: Use transform for sum for divide by column Total:
df['Average'] = df['Total'] / df.groupby('Member')['Total'].transform('sum')
print (df)
   Member  Category  Total   Average
0    1001         1      5  0.277778
1    1001         2      4  0.222222
2    1001         3      9  0.500000
3    1003         1      7  0.500000
4    1003         2      5  0.357143
5    1003         3      2  0.142857
6    1005         1      2  0.285714
7    1005         3      5  0.714286

Detail:
print (df.groupby('Member')['Total'].transform('sum'))
0    18
1    18
2    18
3    14
4    14
5    14
6     7
7     7
Name: Total, dtype: int64

Alternative solution:
df['Average'] = df['Total'] / df['Member'].map(df.groupby('Member')['Total'].sum())

Timings:
np.random.seed(123)
N = 100000

L = ['AV','DF','SD','RF','F','WW','FG','SX']
dates = pd.date_range('2015-01-01', '2015-02-20')
df = pd.DataFrame(np.random.randint(100, size=(N, 3)), columns=['Member','Category','Total'])
df = df.sort_values(['Member','Category']).reset_index(drop=True)

#Wen solution
In [395]: %timeit df.groupby('Member').Total.apply(lambda x : x/sum(x))
10 loops, best of 3: 31.2 ms per loop

In [396]: %timeit df['Total'] / df.groupby('Member')['Total'].transform('sum')
100 loops, best of 3: 5.11 ms per loop

#alternative a bit slowier solution
In [397]: %timeit df['Total'] / df['Member'].map(df.groupby('Member')['Total'].sum())
100 loops, best of 3: 9.92 ms per loop

A: df['ave']=df.groupby('Member').Total.apply(lambda x : x/sum(x))
df
Out[318]:
   Member  Category  Total       ave
0    1001         1      5  0.277778
1    1001         2      4  0.222222
2    1001         3      9  0.500000
3    1003         1      7  0.500000
4    1003         2      5  0.357143
5    1003         3      2  0.142857
6    1005         1      2  0.285714
7    1005         3      5  0.714286


Q: display different under IE6 and other browers i know  IE6 is dead,but in china, there are lots of people still using it. so expect someone can do me a favor about this problem.
this is the page.the even line's background color is not the same length, under IE6, which is shorter
the display under IE6. (http://run.xxmn.com/ie6.jpg). the bgcolor displays different  from other browers.
the display under IE7,FF,CHROME  (http://run.xxmn.com/ie7.jpg). it displays ok.
how to make it under IE6 displays the same result as other browers?
ps:the problem is solved. thanks all the guys.

A: The problem in IE6 is probably due to negative margins on the views-field-title class (though I don't have IE6 installed to check).
You don't actually need negative margins to achieve the effect you want. So suggest removing them like this:

*

*Remove margin-left: -4px; from #left_cplist .cplist-bg .view-content .views-field-title

*Remove margin-left: 5px; form #left_cplist .cplist-bg .views-row


Q: Flex: Passing object to save back to server freezes application I have a NavigatorContent which is displayed when the user selects an item in a DataGrid.
This NavigatorContent contains a form and an accordion displaying the related objects.
When the user presses the Save button in the NavigatorContent the form and the children should be saved to the database by calling the server through BlazeDS:
saveObjectToDB()
{
  //Map the form values to the object
  object.field1 = object_field1.text;
  object.field2 = object_field2.selectedDate as Date;
  object.relatedobject3 = comboBox.selectedItem as RelatedObject3;
  //etc.....

  //Loop through accordion to save the child objects
  for(var i:int= 0; i < accordion.numChildren; i++ )
  {
    if(accordion.getChild(i) is RelatedObject1Form)
    {
      var formRelated1:RelatedObject1Form = accordion.getChild(i) as RelatedObject1Form;
      //Map the form values to the related object
      object.relatedobject1.field1 = formRelated1.relatedobject1_field1.selectedDate;
      //etc...
    }
    if(accordion.getChild(i) is RelatedObject2Grid)
    {
      var gridRelated2:RelatedObject2Grid = accordion.getChild(i) as RelatedObject2Grid;
      //Get dataProvider for the datagrid of the relatedObject
      object.relatedobject2 = gridRelated2.object.relatedobject2;
    }
  }

  // Call the remoting object's saveObject method
  var saveObjectOperation:Operation = new Operation();
  saveObjectOperation.name = "saveObject";
  saveObjectOperation.arguments=[object];
  ro.operations = [saveObjectOperation];
  saveObjectOperation.send();

  if(isNewObject)
    //dispatchEvent new object
  else
    //dispatchEvent object updated
}

My problem is as the question states that my application freezes for a few seconds when the user presses the save button that calls this method. I guess that is because Flex is single threaded, but still i dont quite get why this method would be so computational expensive? It doesnt seem to matter if i comment out the loop that loops over the accordion children.
I tried setting the objects related objects to null before calling the remote save method, and this seemed to speed up the save method, but it provided me with some troubles later.
My conclusion is that the remote call is whats freezing up the application, and if i set the related objects to null this seems to fix the issue. But is this really necessary? The related objects aren't really that big, so i don't quite get why the remote call should freeze the application for a few seconds.
This is how i create the accordion children when the NavaigatorContent is intialized:
    var relatedObjectForm:RelatedObject1Form= new RelatedObject1Form();
    accordion.addChild(relatedObjectForm);
    relatedObjectForm.object= object;
    relatedObjectForm.ro = this.ro;

The object that i pass to the accordion children is public and [Bindable] in the NavigatorContent and in the accordion children and is initially passed from the main DataGrid. May this be a problem relating to this issue?
Any help/comments is much appreciated. This issue is starting to affect my beauty sleep ;)

A: My guess would be that you're spending a lot of time in the serializer. Put a trace target in the app and watch the console when it runs to see what's being sent.
The most likely problems are from DisplayObjects - if they've been added to the application they will have a reference to the application itself, and will cause some serializers to start serializing the entire app. The bindable object might have some odd events attached that eventually attach to DisplayObjects - try copying the relevant values in it into your object instead of just taking a reference to the existing object.


Q: Representations and classes of square group $D4$ (I post this in physics because its about an excercise in the Thinkman book of theory group for  quantum physics).
The Group of symmetries of the square (D4) has an order of 8.
There are 2 classes in the group (correct me if Im wrong). These classes are: One class made of rotations in the plane of the square, of $0$ (identity), $\pi/2$, $\pi$ and $3 \pi /2$. Also 4 rotations with axis inside the plane: two across the diagonals of the square and two perpendicular to the sides by the middle.
Using the "dimensionality theorem", which says that the order is equal to the sum of the square of the dimensionalities of the possible representations, I get $2^2+2^2=8$, meaning that there are 2 representations of order 2.
One of this representations has the first class represented with these matrices:
$\begin{bmatrix}
    1 & 0 \\0 & 1
\end{bmatrix}$,
$\begin{bmatrix}
    0 & -1 \\1 & 0
\end{bmatrix}$,
$\begin{bmatrix}
    -1 & 0 \\0 & -1
\end{bmatrix}$,
$\begin{bmatrix}
    0 & -1 \\1 & 0
\end{bmatrix}$
And the second class represented as:
$\begin{bmatrix}
    -1 & 0 \\0 & 1
\end{bmatrix}$,
$\begin{bmatrix}
    1 & 0 \\0 & -1
\end{bmatrix}$,
$\begin{bmatrix}
    0 & 1 \\1 & 0
\end{bmatrix}$,
$\begin{bmatrix}
    0 & -1 \\-1 & 0
\end{bmatrix}$
But my problem is that the traces of a same class should be the same (correct me again if im wrong), and the first class has 1 matrix of $Tr=2$, 1 of $Tr=-2$ and two of $Tr=0$. The second class has every matrix with $Tr=0$.
I immediately thought that the classes I choose were wrong, and that I have 3 classes. But it doesn't have sense for me because, if I have 3 classes I cant fulfill the dimensionality theorem, as there isn't any sum of square integers which is equal to 8.
What I am missing? There are 2 or 3 classes? Im choosing wrong the members of the classes?


Q: How to weave AspectJ java project into Spring boot project I have java project named Test which have all aspects in it. I wan to use these aspects in another spring boot project. I am working on a poc to weave aspects in Test project into a spring boot application. What is the efficient way to do so and how it can be done, can some one who implemented please suggest.
Code for Java project Test with aspects
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Secured {
    public boolean isLocked() default false;
}

@Aspect
public class SecuredMethodAspect {

    @Pointcut("@annotation(secured)")
    public void callAt(Secured secured) {}

    @Around("callAt(secured)")
    public Object around(ProceedingJoinPoint pjp, Secured secured) throws Throwable {
        if (secured.isLocked()) {
             System.out.println(pjp.getSignature().toLongString() + " is locked");
            return pjp.proceed();
        } else {
            return pjp.proceed();
        }
    }
}

        <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>aspect</groupId>
        <artifactId>test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>AspectJ-POC</name>
        <url>http://maven.apache.org</url>

        <properties>
            <maven.compiler.source>11</maven.compiler.source>
            <maven.compiler.target>11</maven.compiler.target>
            <java.version>11</java.version>
        </properties>

        <!-- nickwongdev aspectj maven plugin, this is for weaving of aspects -->
        <build>
            <plugins>
                <plugin>
                    <groupId>com.nickwongdev</groupId>
                    <artifactId>aspectj-maven-plugin</artifactId>
                    <version>1.12.6</version>
                    <configuration>
                        <source>11</source>
                        <target>11</target>
                        <complianceLevel>11</complianceLevel>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>compile</goal>
                                <goal>test-compile</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>

        <!-- aspectj runtime dependency -->
        <dependencies>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>1.9.6</version>
            </dependency>
        </dependencies>

    </project>

A: Some quick first impressions I got when browsing your projects before cloning them:

*

*You should not use Lombok + native AspectJ together in a compile-time weaving scenario, see my answer here.

*Possible workarounds would be multi-phase compilation, i.e. first Java + Lombok and then post-compile-time weaving with AspectJ, see my answer here. Alternatively, use delombok in order to first generate source code with Lombok annotations expanded into equivalent source code and then compile the generated sources with AspectJ.

*On a second look, your sample aspect module does not seem to use any Lombok, so you do not need that dependency. But probably your real project does, hence my remarks above.

*Of course, you can use compile-time weaving in order to weave your aspects, as you suggested. You need to correctly configure AspectJ Maven Plugin in this case, though, which you did not. You need to tell it in the Spring Boot module where to find the aspect library and which dependencies to weave, in addition to the main application. Did you ever read the plugin documentation, e.g. chapters Weaving classes in jars, Using aspect libraries and Multi-module use of AspectJ? I also answered tons of related questions here already.

*But actually, the preferred approach for weaving aspects into Spring applications is to use load-time weaving (LTW), as described in the Spring manual. That should be easier to configure and you would not need any AspectJ Maven Plugin stuff and probably would not have any Lombok issues during compilation either.

Judging from your sample projects and the absence of any aspectLibraries and weaveDependencies sections in your AspectJ Maven configuration, you simply did not bother to read any documentation, which leaves me to wonder what you did during the one month you tried to get this working.
I would appreaciate a comment, explaining why you want to use CTW instead of LTW. The only reason I can think of is that in addition to your native aspect, you also want to use Spring AOP aspects withing your Spring application. But if you activate native AspectJ LTW, you cannot use Spring AOP at the same time anymore. If that is not an issue, I recommend LTW, as it is documented and tested well in Spring. CTW is no problem either, but more difficult to understand and manage in your POMs.

Update: OK, I did not want to wait any longer for your reason to use CTW and simply decided to show you a LTW solution instead. What I did was:

*

*Remove AspectJ Maven Plugin and AspectJ Tools from your Spring project

*Add src/main/resources/org/aspectj/aop.xml, configuring it to use your aspect and target your base package + subpackages

*Fix pointcut to also use your base package + subpackages, because in your base package there are no classes. This is a typical beginner's mistake. You need to use execution(* com.ak..*(..)) with .., not just com.ak.*.

Non-essential cosmetics I applied are:

*

*Call context.getBean(TestController.class).mainRequest() from the Spring Boot application's main method in order to automatically produce some aspect output, in order to avoid having to use curl or a web browser in order to call a local URL.

*Use the Spring application as an auto-closeable via try-with-resources in order to make the application close after creating the desired log output.

*Change the aspect to also log the joinpoint in order to see in the log, which methods it actually intercepts. Otherwise all log lines look the same, which is not quite helpful.

*Use try-finally in order to make sure that the log message after proceeding to the original method is also logged in case of an exception.

The diff looks like this (I hope you can read diffs):
diff --git a/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java b/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java
--- a/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java  (revision Staged)
+++ b/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java  (date 1626233247623)
@@ -7,14 +7,14 @@
 @Aspect
 public class MethodLogAspect {

-   @Around("@annotation( MethodLog) && (execution(* com.ak.*(..)))")
+   @Around("@annotation(MethodLog) && execution(* com.ak..*(..))")
    public Object wrap(final ProceedingJoinPoint joinPoint) throws Throwable {
-       System.out.println("***Aspect invoked before calling method***");
-
-       final Object obj = joinPoint.proceed();
-
-       System.out.println("***Aspect invoked after calling method***");
-
-       return obj;
+       System.out.println("[BEFORE] " + joinPoint);
+       try {
+           return joinPoint.proceed();
+       }
+       finally {
+       System.out.println("[AFTER]  " + joinPoint);
+       }
    }
 }
diff --git a/src/main/java/com/ak/ParentprojectSpringbootApplication.java b/src/main/java/com/ak/ParentprojectSpringbootApplication.java
--- a/src/main/java/com/ak/ParentprojectSpringbootApplication.java  (revision Staged)
+++ b/src/main/java/com/ak/ParentprojectSpringbootApplication.java  (date 1626233555873)
@@ -1,14 +1,17 @@
 package com.ak;

+import com.ak.controller.TestController;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ConfigurableApplicationContext;

 @SpringBootApplication(scanBasePackages = { "com.ak.*" })
-//@SpringBootApplication
 public class ParentprojectSpringbootApplication {

    public static void main(String[] args) {
-       SpringApplication.run(ParentprojectSpringbootApplication.class, args);
+       try (ConfigurableApplicationContext context = SpringApplication.run(ParentprojectSpringbootApplication.class, args)) {
+           context.getBean(TestController.class).mainRequest();
+       }
    }

 }
diff --git a/parentproject-springboot/pom.xml b/parentproject-springboot/pom.xml
--- a/parentproject-springboot/pom.xml  (revision Staged)
+++ b/parentproject-springboot/pom.xml  (date 1626232421474)
@@ -71,13 +71,6 @@
            <version>1.9.6</version>
        </dependency>

-       <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
-       <dependency>
-           <groupId>org.aspectj</groupId>
-           <artifactId>aspectjtools</artifactId>
-           <version>1.9.6</version>
-       </dependency>
-
        <dependency>
            <groupId>com.ak.aspect</groupId>
            <artifactId>aspect-test-project</artifactId>
@@ -100,24 +93,6 @@
                </configuration>
            </plugin>

-           <plugin>
-               <groupId>com.nickwongdev</groupId>
-               <artifactId>aspectj-maven-plugin</artifactId>
-               <version>1.12.6</version>
-               <configuration>
-                   <source>11</source>
-                   <target>11</target>
-                   <complianceLevel>11</complianceLevel>
-               </configuration>
-               <executions>
-                   <execution>
-                       <goals>
-                           <goal>compile</goal>
-                           <goal>test-compile</goal>
-                       </goals>
-                   </execution>
-               </executions>
-           </plugin>
        </plugins>
    </build>

For your convenience, here are the complete changed files:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ak</groupId>
    <artifactId>parentproject-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>parentproject-springboot</name>
    <description>Test project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.ak.dependency</groupId>
            <artifactId>dependencyprojet</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <!-- aspectj runtime dependency -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.6</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.ak.aspect</groupId>
            <artifactId>aspect-test-project</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>

    <weaver options="-verbose -showWeaveInfo">
        <!-- only weave classes in our application-specific packages -->
        <include within="com.ak..*"/>
    </weaver>

    <aspects>
        <aspect name="com.ak.aspect.MethodLogAspect"/>
    </aspects>

</aspectj>

package com.ak.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class MethodLogAspect {

    @Around("@annotation(MethodLog) && execution(* com.ak..*(..))")
    public Object wrap(final ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("[BEFORE] " + joinPoint);
        try {
            return joinPoint.proceed();
        }
        finally {
        System.out.println("[AFTER]  " + joinPoint);
        }
    }
}

package com.ak;

import com.ak.controller.TestController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication(scanBasePackages = { "com.ak.*" })
public class ParentprojectSpringbootApplication {

    public static void main(String[] args) {
        try (ConfigurableApplicationContext context = SpringApplication.run(ParentprojectSpringbootApplication.class, args)) {
            context.getBean(TestController.class).mainRequest();
        }
    }

}

Now you simply make sure to add the JVM argument -javaagent:/path/to/aspectjweaver-1.9.6.jar to your Java command line in order to activate native AspectJ LTW. For more details about how to configure LTW within Spring if more sophisticated ways, please read the Spring manual, section Using AspectJ with Spring Applications.
The console log should look something like this:
[AppClassLoader@3764951d] info AspectJ Weaver Version 1.9.6 built on Tuesday Jul 21, 2020 at 13:30:08 PDT
[AppClassLoader@3764951d] info register classloader jdk.internal.loader.ClassLoaders$AppClassLoader@3764951d
[AppClassLoader@3764951d] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_SpringCTWMultiModule_68040124/parentproject-springboot/target/classes/org/aspectj/aop.xml
[AppClassLoader@3764951d] info register aspect com.ak.aspect.MethodLogAspect
[AppClassLoader@3764951d] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
[RestartClassLoader@1f385e10] info AspectJ Weaver Version 1.9.6 built on Tuesday Jul 21, 2020 at 13:30:08 PDT
[RestartClassLoader@1f385e10] info register classloader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@1f385e10
[RestartClassLoader@1f385e10] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_SpringCTWMultiModule_68040124/parentproject-springboot/target/classes/org/aspectj/aop.xml
[RestartClassLoader@1f385e10] info register aspect com.ak.aspect.MethodLogAspect

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.2)

(...)
[RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.AccountInfo com.ak.service.TestService.incomingRequest())' in Type 'com.ak.service.TestService' (TestService.java:20) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java)
[RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.AccountInfo com.ak.dependency.Route.accountInfo())' in Type 'com.ak.dependency.Route' (Route.java:12) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java)
[RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.BalanceInfo com.ak.dependency.Pipeline.balanceInfo())' in Type 'com.ak.dependency.Pipeline' (Pipeline.java:11) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java)
(...)

Controller
[BEFORE] execution(AccountInfo com.ak.service.TestService.incomingRequest())
[BEFORE] execution(AccountInfo com.ak.dependency.Route.accountInfo())
[BEFORE] execution(BalanceInfo com.ak.dependency.Pipeline.balanceInfo())
[AFTER]  execution(BalanceInfo com.ak.dependency.Pipeline.balanceInfo())
[AFTER]  execution(AccountInfo com.ak.dependency.Route.accountInfo())
[AFTER]  execution(AccountInfo com.ak.service.TestService.incomingRequest())
(...)


Q: group by ratio and seniority list IN SQL I am working on a MYSQL, and I am looking for a solution to show data grouping by ratio.
I have a COURSE table which contain courses id and courses ratio. I have another table, ASK, which contain askers id, and another field course id pointing on COURSE table (ids correspond). With one SQL query, I would like to display all asks grouping by ratio and rejecting other demands. Demands are considered by seniority list.
By example, I have 3 courses: the first one allow only 2 people and 2 other courses allow only one person. In the ASK table, we have 3 askers (JACK, JOE AND JOHN) pointing on first course, (JOHN AND JOE) 2 on second and third (JACK AND JOHN).  JACK is the older, after its JOHN and after its JOE.
I would like to see:
course id   studentName
-------------------------
1           JACK
1           JOHN
2           JOHN
3           JACK

A: SELECT c.courseID
       s.studentName
FROM course AS c
    JOIN asks AS a
        ON a.courseID = c.courseID
    JOIN student AS s
        ON s.studentName = a.studentName
    JOIN asks AS a2
        ON a2.courseID = c.courseID
    JOIN student AS s2
        ON s2.studentName = a2.studentName
        AND s2.seniority <= s.seniority
GROUP BY c.courseID
       , c.ratio
       , s.studentName
HAVING c.ratio >= COUNT(*)
ORDER BY c.courseID
       , s.seniority


Q: Iteration of a for loop based on a text file Question: How can I make a for loop iterate over a text or a csv file instead of an array?
Scenario:
fruits = ["apple", "banana", "cherry"]

For instance regarding the code above, instead of the fruits array I want it to be the text or csv file

A: Try this:
filename=["1.txt","2.txt","3.txt"]
for file in filename:
    with open(file,'r/w') as f: #r for reading w for writing
        #Other code

Or if you want to iterate throught all files from a folder then try this:
import os
filename=os.listdir("/path/to/folder you want the files from")
for file in filename:
    with open(file,'r/w') as f: #r for reading w for writing
        #Other code


Q: Postgres 13 pg_cron error on RDS that's hard to track down pg_cron jobs all fail with "role of....doesn't provide permission to schedule a job"
I'm working on getting pg_partman and pg_cron set up on RDS, but when my pg_cron jobs run, they return this error:
ERROR: The protected role of rds_super doesn't provide permission to schedule a job.

From the error text, it seems like I'm missing a simple permissions issue on something in the directory or resources holding pg_cron, but I can't find the source of the problem. And, it's possibly something else. A lot of Googling, hunting through sources, and trial-and-error hasn't lead me to any answers, and I'm hoping for help.
For background, this is Postgres 13.4 with pg_cron 1.3. These are the latest versions now available on RDS. My goal is to have pg_cron running jobs in various databases in this cluster, but I've reduced the problem example to the cron schema in postgres.
RDS defines a role named rds_superuser that doesn't have a login, which you can then grant to other users. We're using a custom role named rds_super, and have for years.
When you create extension pg_cron up on RDS, the install is into the postgres database by default, and it creates a new schema named cron. That's all fine. As a "hello world" version of the problem, here's a simple table and task to insert the current time every minute into a text field.
DROP TABLE IF EXISTS cron.foo;

CREATE TABLE IF NOT EXISTS cron.foo (
    bar text
);

GRANT INSERT ON TABLE cron.foo TO rds_super;

INSERT INTO cron.foo VALUES (now()::text);

select * from cron.foo;

-- Run every minute
SELECT cron.schedule('postgres.populate.foo','*/1 * * * *',
$$INSERT INTO cron.foo VALUES (now()::text) $$);

The bare statement INSERT INTO cron.foo VALUES (now()::text) works fine, when connected directly as the rds_super user. But when it's executed through the cron.job defined above, the cron.job_run_details output has the right code, the expected user, but a failure result with this error:
ERROR: The protected role of rds_super doesn't provide permission to schedule a job.

Does this ring a bell for anyone? I've deleted, reinstalled, set permissions explicitly. No improvement.
Public
This may be off, but I ran into a couple of things where it looked like I needed to provide access to public. I started in PG 9.4 or 9.5, couldn't get my head around securing public...and stripped all of the rights off it everywhere. Putting some back in may be needed here?
Permissions checks
Here are the permissions checks that I could think of.
select grantor,
       grantee,
       table_schema,
       table_name,
       string_agg (privilege_type, ',' order by privilege_type) as grants

  from information_schema.role_table_grants
where table_catalog = 'postgres'
  and table_schema  = 'cron'
  and grantee       = 'rds_super'

group by 1,2,3,4

order by 1,2,3,4;

I gave the user all privileges on all of the tables, just to see if that cleared things up. No joy.
grantor          grantee     table_schema  table_name             grants
rds_super        rds_super   cron          foo                    DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE
rds_super        rds_super   cron          job_run_details_plus   DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE
rds_superuser    rds_super   cron          job                    DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE
rds_superuser    rds_super   cron          job_run_details        DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE

Nothing is obviously wrong with the schema rights:
select pg_catalog.has_schema_privilege('rds_super', 'cron', 'CREATE') AS create,
       pg_catalog.has_schema_privilege('rds_super', 'cron', 'USAGE')  AS usage;

create  usage
t       t

Likewise, nothing pops out when I check function execution rights:
   select proname, proargnames
     from pg_proc
    where has_function_privilege('rds_super',oid,'execute')
      and pronamespace::regnamespace::text = 'cron'
order by 1,2

proname                  proargnames
job_cache_invalidate
schedule                 {job_name,schedule,command}
schedule                 {schedule,command}
unschedule               {job_id}
unschedule               {job_name}

Answer
I do not know if this is the answer, but it seems to have fixed my problem. Spoiler: Log in as the user the pg_cron scheduler background worker runs as.
I burned everything down and restarted, and then found that my jobs simply would not run. No error, no results. I checked the status of the background workers like this:
 select application_name,
        usename,
        backend_type,
        query,
        state,
        wait_event_type,
        age(now(),backend_start) as backend_start_age,
        age(now(),query_start)  as query_start_age,
        age(now(),state_change) state_change_age

  from pg_stat_activity
 where backend_type != 'client backend';

I noticed that the background worker had been running for over a day (it's loaded as a shared library), and seemed to be stuck. I rebooted the server, and redid everything logged in as dbadmin, instead of my custom user. That's the user name that the pg_cron scheduler process is running as, in this case. I don't remember if dbadmin is part of the package with RDS Postgres, or if it's something I added years back. There's nothing in the RDS pg_cron instructions about this, so maybe it's just me. I needed to set up its search_path and permissions a bit to get everything working the way I needed, but that's normal.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL_pg_cron.html

A: At least in my case, the answer is to run the jobs as the same user as the pg_cron background thread. I've posted more details to the end of the original question.


Q: Why would a motor manufacturer offer multiple coil winding types? I'm currently looking through a part catalog from a motor manufacturer and notice that you can purchase this motor with different motor winding types. Specifically, you can order the motor coil wound either delta or wye configured.
Why would a manufacturer offer multiple winding type? What are the pros and cons for each style?

A: A spec sheet link and actual component IDs would be very useful.
Presumably these are BLDC motors.
Compared to the other configuration:

*

*Wye configuration

*

*Needs higher voltage

*Requires more cells.

*Requires lower current so lower I^2 R losses, lower spec cells, lower current FET needed.

*Delta configuration

*

*Requires lower voltage

*Requires fewer cells

*Draws more current
When optimising a design the above factors may affect design cost.
Real world example:
I'm looking at a design that pushes current LiIon cells to their limit power wise.
Energy wise I could built the packs I need with 18650 cells.
But the top 21700 cells allow higher power per cell.
So, to achieve the same power levels with 1850 cells I need more cells and so higher voltage.
In my case, to minimise costs, current volume pricings mean that fewer 21700 cells at lower prices overall cost less than more 18650 cells. In this case, unusually, the available energy is not important - 18650 or 21700 will both meet the needs once power requirements are met.
SO in my case a Delta wound motor with lower voltage and higher current will make sense.
Given other requirements, the opposite may apply.


Q: Enabling TLS-1.2 on embedded Jetty Currently I am using this code which is enabling TLS 1.2:
ServerConnector httpsConnector = new ServerConnector(server,
       new SslConnectionFactory(sslContextFactory, "http/1.1"),
       new HttpConnectionFactory(https_config));
httpsConnector.setPort(8443);
httpsConnector.setIdleTimeout(50000)

Now I am using TLS 1.1 and want to change it to TLS 1.2.

A: Java 8 is TLS/1.2 by default.

*

*https://blogs.oracle.com/java-platform-group/entry/java_8_will_use_tls
You can diagnose TLS in the JVM using the techniques at:

*

*https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https
If you want to force TLS/1.2, see the prior answer at:
How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections
Know that the ciphers and protocols you expose in Jetty's SslContextFactory will also have an influence on your TLS support level. (For example: you can exclude the ciphers that TLS/1.0 knows about leaving no ciphers to negotiate against)

A: Yeah, I resolved this question just now.
We can customize it by org.eclipse.jetty.util.ssl.SslContextFactory just like this:

*

*exclude TLSv1、TLSv1.1 protocol etc.

sslContextFactory.addExcludeProtocols("TLSv1", "TLSv1.1");

By the way, my jetty version is 9.4.45, default protocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3") have already excluded by Jetty.
// org.eclipse.jetty.util.ssl.SslContextFactory#DEFAULT_EXCLUDED_PROTOCOLS
private static final String[] DEFAULT_EXCLUDED_PROTOCOLS = {"SSL", "SSLv2", "SSLv2Hello", "SSLv3"};

*include only TLSv1.2 protocol (some protocols etc.)

    sslContextFactory.setIncludeProtocols("TLSv1.2");

The final protocols selected you can see in the method org.eclipse.jetty.util.ssl.SslContextFactory#selectProtocols , you can debug yourself.


Q: Meromorphic extension example Meromorphic was defined as follows:
Let $M \subseteq \mathbb{C}$ be a region. $f$ is meromorphic on M if any $a\in M$ is a removable or pole singularity of $f$. This is to say that there are no essential singularities.
From there, the following was given:
Let $S \subseteq M$ be the discrete set of poles of $f$. Then $f$ has a unique holomorphic extension $g$ that is holomorphic on $M - S$ and if we are only concerned with partial functions on $M$ then $g$ is maximal.
My questions are the following:
What is a partial function?
What would be an example of an $f$ and a $g$ in the situation provided above?
Any help is greatly appreciated!

A: *

*A "partial function" on $U$ is a function $f: V \to X$, where $X$ is any codomain and $V \subset U$. (In other words: it's only "partially defined" because in some places it doesn't make sense. A stock example: $f(x) = 1/x$ is a "partial function on the real line".)

*Example: $f:  \mathbb C \to  \mathbb C^{*} : z \mapsto 1/z$, is meremorphic. $g: \mathbb C - \{0\} \to \mathbb C: z \mapsto 1/z$ is holomorphic on its domain, which is a subset of the domain of $f$. In this case, the domain $M$ is all of $\mathbb C$.


Q: Liferay Service Builder - Database Persistence i understand that persistence layer is where you store your data, and that not all data is persisted in the same manner -- some use databases, some use XML, some use a remote service.
What then is (as a verb) Database Persistence? I'm studying Liferay Service Builder and came across a definition that "it automates creation of interfaces and classes for database persistence"
In other words, What is database persistence in the context above in simple plain English!

A: Lifera service builder generates classes that can be used to do CRUD operations for database entity only. So its referred as database persistence.


Q: primefaces datatable selectionMode multiple not working with mojarra Recently I switched to mojarra from myfaces and noticed that primefaces datatable checkbox multiple row selection is not working.
I have tried the exact sample program available at http://www.primefaces.org/showcase/ui/datatableRowSelectionRadioCheckbox.jsf
With myfaces both single and multiple selection are working ,but with mojarra multiple selection is not working(selectedCars.length is 0 in setSelectedCars method)
I have tried with mojarra 2.0.3 and mojarra 2.1.0 with primefaces 2.2.1

A: Adding 'f:view contentType="text/html"' solved the problem.
Read this in http://www.primefaces.org/faq.html

A:

           <p:column sortBy="#{tup.docTypeAndDirection}" >
                                <f:facet name="header">
                                <h:outputText value="Document Type"/>

                                </f:facet>
                                <h:outputText value="#{tup.docTypeAndDirection}"/>
          </p:column>

          <p:column sortBy="#{tup.partnerEDIAddress}" >
                                <f:facet name="header">
                                <h:outputText value="Partner Trading Address"/>
                                </f:facet>
                                <h:outputText value="#{tup.partnerEDIQual}:#{tup.partEDIAddr}"></h:outputText>
          </p:column>
        </p:dataTable>


Q: iOS 11 - Location update not received after adding delegate I have been having trouble with location services in iOS 11 for both "Allow while Use" and "Always Allow". Works without issue in iOS < 11. Followed this thread in trying to fix but still doesn't work. What am I missing? Thank you in advance.

*

*I have UITabViewController in my app and a UINavigationController inside each tab.

*I have a singleton LocationManager class. I'm setting my UINavigationController's RootViewController as delegate the ViewController's viewWillAppear to receive location updates and removing in viewWillDisappear.

*Now, When I launch the app, before the tab bar is created, I can see the location update is being called in the LocationManager Class.

*But when I add my UIViewController as delegate and give startUpdatingLocation I'm not receiving the location update in my UIVIewController.

*Then I press Home button and exit the app. Again immediately launch the app and I get the location update in my delegate method.

I have added all three location authorization description in my Info.plist file.
Info.Plist:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Blah Blah Blah</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Blah Blah Blah</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Blah Blah Blah</string>

LocationController.m:
#import "LocationController.h"

//static int LOCATION_ACCESS_DENIED = 1;
//static int LOCATION_NETWORK_ISSUE = 2;
//static int LOCATION_UNKNOWN_ISSUE = 3;
enum {
    LOCATION_ACCESS_DENIED = 1,
    LOCATION_NETWORK_ISSUE = 2,
    LOCATION_UNKNOWN_ISSUE = 3
};

static LocationController* sharedCLDelegate = nil;

@implementation LocationController
int distanceThreshold = 10.0; // in meters
@synthesize locationManager, currentLocation, locationObservers;

- (id)init
{
    self = [super init];
    if (self != nil) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = distanceThreshold;
        self.locationManager.pausesLocationUpdatesAutomatically = NO;
        [self.locationManager startMonitoringSignificantLocationChanges];
        self.locationManager.delegate = (id)self;
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization]; //I tried both commenting this line and uncommenting this line. Didn't make any difference
        }
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.locationManager requestAlwaysAuthorization];
        }
        [self.locationManager startUpdatingLocation];
        [self.locationManager startUpdatingHeading];
        locationObservers = [[NSMutableArray alloc] init];

    }
    return self;
}

#pragma mark -
#pragma mark CLLocationManagerDelegate Methods

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    NSLog(@"locationManager  didUpdateLocations = %@",locations);
    CLLocation *newLocation = [locations lastObject];
    if (newLocation.horizontalAccuracy < 0) {
        return;
    }
    currentLocation = newLocation;

    for(id<LocationControllerDelegate> observer in self.locationObservers) {
        if (observer) {
//            CLLocation *newLocation = [locations lastObject];
//            if (newLocation.horizontalAccuracy < 0) {
//                return;
//            }
//            currentLocation = newLocation;

            NSTimeInterval interval = [currentLocation.timestamp timeIntervalSinceNow];
            //check against absolute value of the interval
            if (fabs(interval)<30) {
                [observer locationUpdate:currentLocation];
            }

        }
    }
}

- (void)locationManager:(CLLocationManager*)manager
       didFailWithError:(NSError*)error
{
    NSLog(@"locationManager didFailWithError: %@", error);

    for(id<LocationControllerDelegate> observer in self.locationObservers) {
        if (observer) {
            [observer failedToGetLocation:error];
        }
    }
    switch (error.code) {
        case kCLErrorDenied:
        {
            break;
        }
        case kCLErrorNetwork:
        {
            break;
        }
        default:

            break;
    }

}

#pragma mark - Singleton implementation in ARC
+ (LocationController *)sharedLocationInstance
{
    static LocationController *sharedLocationControllerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedLocationControllerInstance = [[self alloc] init];
    });
    return sharedLocationControllerInstance;
}

-(void) locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    NSLog(@"didChangeAuthorizationStatus = %i",status);
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager stopUpdatingLocation];
        [self.locationManager startUpdatingLocation];
    }
}
- (void) addLocationManagerDelegate:(id<LocationControllerDelegate>)delegate {
    if (![self.locationObservers containsObject:delegate]) {
        [self.locationObservers addObject:delegate];
    }
    [self.locationManager startUpdatingLocation];
}

- (void) removeLocationManagerDelegate:(id<LocationControllerDelegate>)delegate {
    if ([self.locationObservers containsObject:delegate]) {
        [self.locationObservers removeObject:delegate];
    }
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedCLDelegate == nil) {
            sharedCLDelegate = [super allocWithZone:zone];
            return sharedCLDelegate;  // assignment and return on first allocation
        }
    }
    return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

#pragma mark UIAlertViewDelegate Methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (alertView.tag) {
        case LOCATION_ACCESS_DENIED:
        {
            if (buttonIndex == 1) {

                //[[UIApplication sharedApplication] openURL: [NSURL URLWithString: UIApplicationOpenSettingsURLString]];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];

            }

        }
        break;
        case LOCATION_NETWORK_ISSUE:
            break;
        case LOCATION_UNKNOWN_ISSUE:
            break;
        default:
            break;
    }
    [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
}
@end

LocationController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <Foundation/Foundation.h>

// protocol for sending location updates to another view controller
@protocol LocationControllerDelegate
@required
- (void)locationUpdate:(CLLocation*)location;
- (void)failedToGetLocation:(NSError*)error;
@end

@interface LocationController : NSObject<CLLocationManagerDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;
@property (nonatomic, strong) CLLocation* currentLocation;
@property (strong, nonatomic) NSMutableArray *locationObservers;

+ (LocationController*)sharedLocationInstance; // Singleton method

- (void) addLocationManagerDelegate:(id<LocationControllerDelegate>) delegate;
- (void) removeLocationManagerDelegate:(id<LocationControllerDelegate>) delegate;

@end

ViewController.m
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"VC viewWillAppear");
    [locationControllerInstance addLocationManagerDelegate:self];
}

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [LocationController sharedLocationInstance];
}

A: I had one of the new devices reported this problem, as you know the the Location Manager usually calls this:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation

The bizarre thing is that the UserLocation object contains two coordinate objects:
1) userLocation.location.coordinate: This used to work fine, but for some reason it's returning NULL on IOS11 on some devices (it's unknown yet why or how this is behaving since IOS11).
2) userLocation.coordinate: This is another (same) object as you can see from the properties, it has the location data and continues to work fine with IOS11, this does not seem to be broken (yet).
So, with the example above, "I guess" that your:

*

*(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

Might be having the same problem (i.e. the array might be returning a NULL somewhere in the location object, but not the coordinate object, the solution I did on my code which gets one location at a time, is now fixed by by replacing userLocation.location.coordinate with userLocation.coordinate, and the problem gone away.
I also paste my function below to assist you further, hopefully it would help you to resolve yours too, notice that I have two conditions for testing one for sourcing the location object and the other for sourcing the coordinate object, one works fine now, and the other seems to be broken in IOS11:
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    Log (4, @"MapView->DidUpdateUL - IN");

    if (_OrderStartTrackingMode == enuUserMapTrackingMode_User)
    {
        if (userLocation)
        {
            if (userLocation.location)
            {
                if ( (userLocation.location.coordinate.latitude) && (userLocation.location.coordinate.longitude))
                {
                    [_mapLocations setCenterCoordinate:userLocation.location.coordinate animated:YES];
                } else {
                    if ( (userLocation.coordinate.latitude) && (userLocation.coordinate.longitude))
                    {
                        [self ShowRoutePointsOnMap:userLocation.coordinate];
                    }
                }
            }
        }

    } else if (_OrderStartTrackingMode == enuUserMapTrackingMode_Route) {

        if (userLocation)
        {
            if ( (userLocation.coordinate.latitude) && (userLocation.coordinate.longitude))
            {
                [self ShowRoutePointsOnMap:userLocation.coordinate];
            }
        }

    }

    Log (4, @"MapView->DidUpdateUL - OUT");
}

Needless to say, have you checked your settings for the Map object, you should have at least "User Location" enabled:

P.S. The Log function on the code above is a wrapper to the NSLog function, as I use mine to write to files as well.
Good luck Uma, let me know how it goes.
Regards, Heider


Q: Meteor: Count data from collection anyone please i need you help. before this I have asking question but I cannit find this solution. I have create code to count variable in collection. I can get the result when count one by one but not by group. Thats my code, I want to count this but the code not given any resut to me. I want the result like this:

PTR 1
  KOM 4

This my code:
<template name="laporankategori">

        Jenis Peralatan
        Kuantiti

      {{#each profil}}

          {{PTR}}
          {{KOM}}

      {{/each}}

</template>

//js
Template.laporankategori.helpers({
  profil: function() {
    return Profil.find({kategori: { $in: ['PTR', 'KOM'] } }).count();
  }
});

A: Whenever you're iterating with {{#each ...}} your helper should return either a cursor or an array. Your helper is returning a scalar: the count. In your {{#each }} block you refer to {{PTR}} and {{KOM}} but those won't exist.
I suspect that you weren't actually looking for the count in this case and your helper should just be:
Template.laporankategori.helpers({
  profil: function() {
    return Profil.find({kategori: { $in: ['PTR', 'KOM'] } });
  }
});

Also you don't often need to count things in a helper since in a template you can refer to {{profil.count}} and get the count of the cursor directly.

A: <template name="laporankategori">

     Jenis Peralatan
     Kuantiti

   {{#each profil}}

       {{count}}

   {{/each}}

</template>

//js
Template.laporankategori.helpers({
 profil: function() {
  var PTR = {
    count: Profil.find({kategori: { $in: ['PTR'] } }).count()
  };
  var KOM = {
    count : Profil.find({kategori: { $in: ['KOM'] } }).count()
  };
  var resultArr = [PTR, KOM];
  return resultArr;
 }
});


Q: How do I get an external USB hard drive recognized in Windows PE environment (WinPE running off disc)? I'm running WinPE on a disc. I believe it's PE 2.0. It's being run on a laptop with USB 3.0 ports, as I'm sure that may matter. I want to connect either a USB thumb drive or USB hard drive but it's not recognizing the USB hard drive. Is it supposed to automatically detect and install drivers or are a set of commands I'm supposed to run to get it to recognize the external hard drive?
I would even be open to connecting it to the network and retrieving data in that fashion.
Any help would be appreciated.

A: I'd strongly suggest you do what Ramhound said, but if that's not an option you can download drivers and inject them to your WinPE image using the servicing utilities:
http://technet.microsoft.com/en-us/library/cc749350%28v=ws.10%29.aspx
http://technet.microsoft.com/en-us/library/dn613857.aspx
This links are for different versions (Vista and Win8).
I don't have access to WinPe 2, but one of them should work (assuming you have WAIK installed).


Q: new ATMEGA1281 and avrdude I'm experiencing sometimes problems when programming my new ATMEGA1281. It is suposed to be the same as my old one, the only difference I guess is the serial number:
ATMEGA1281 16AU 1104 vs ATMEGA1281 16AU 1304
I'm used to program the ATMEGA1281 with avrdude command, but with the new chip, I have sometimes this error:
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
0x0c != 0xff
avrdude: verification error; content mismatch

Do you know why I'm having this problem?
Thanks in advance!

A: What programmer do you use?
The brand new microcontroler might have lower clock than your previous one and it might be to slow for your programmer.
Try decreasing your programmer bitclock (-B option of avrdude). It should be 4 times slower than the  clock. Then you can change microcontroller fuses and use the programmer with the old bitclock.


Q: insert data into html table from flat file I have lots of user records similar to the following inside my main index.html page:

    Angelica Ramos
    Chief Executive Officer (CEO)
    London
    47
    2009/10/09
    $1,200,000
    504

This is of course in a table.  Now, what i want to do is make this dynamic. I cant modify the original index.html page each time a user record is updated.  so my question is, how do i make html read from a file and insert the records in the file in the table in the original index.html file?
my index.html file has a code that allows you to type a user name in a search box and the record for that particular user will pop up.  the preferred solution will work with this already existing code so that, after html reads from the record from the external file, an admin can still search for the user name and have the user name pop up as though it was still embedded in the original index.html file.
I tried to do this on my own, but was not successful:

The record did not show up when searched for through the search box.

A: The following works with a CSV file. You may need to do this before proceding.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>StackOverflow</title>

    <input type="text" id="searchvalue"><button onclick="search()">Search</button>


Q: Error: is a 'field' but is used like a 'type' c# I have a global variable averagel that I am trying to manipulate in a method. The compiler doesn't have a problem with me setting the value averagel = averagel / (xrestriction * yrestriction); but for some reason it doesn't like it when I try to use it to set another variable:
inside = (inside + averagel * (xrestriction * yrestriction)) - 2 * (averagel)(suml);
Only on the line where I try to use averagel's value to set another int does it return the error 'sqlDataReader.ReaderDemo.averagel' is a 'field' but is used like a 'type'. I also tried setting an int in the method to the value of averagel and then trying to use that value to set my inside variable but that returned with an error of "The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?)" and all I did the line before was declare int test=averagel;
Any ideas what could be going on here?

A: You probably need an asterisk:
inside = (inside + averagel * (xrestriction * yrestriction)) - 2 * averagel * suml;

You can't multiply two values in C# like you can in mathematics. E.g. (averagel)(suml) makes sense in a math equation but you have to write averagel * suml in C#.

A: You've got your parentheses wrong and accidentally included a typecast in the expression. The bit at the end
(averagel) (suml)

Tries to cast suml to type averagel, and so the compiler's right to complain. I suspect you're missing an operator between those two terms.


Q: SWT Help button in TrayDialog I have a class that extends TrayDialog and that has a help button. I have set the folowing:
setDialogHelpAvailable(true);
setHelpAvailable(true);

And I can't find how I'm supposed to implement the Help button in the lower left corner. I've tried
@Override
protected void buttonPressed(int buttonId) {
    super.buttonPressed(buttonId);
    if(buttonId == IDialogConstants.HELP_ID) {
        System.out.println("Help requested");
    }
}

But it doesn't work. I've seen Can't put content behind SWT Wizard Help Button but I have no performHelp() method because I'm not in a wizard.
What am I missing here? thanks

A: When the help button is pressed TrayDialog looks for a control with a SWT.Help listener. It starts at the currently focused control and moves up through the control's parents until it finds a control with the listener (or runs out of controls).
You can set up a help listener that is connected to a 'help context' in the Eclipse help system using
PlatformUI.getWorkbench().getHelpSystem().setHelp(control, "context-id");

or you can write your own help listener.

A: I had the same problem and solved it by just adding a HelpListener to one of my controls:
Composite area.addHelpListener(new HelpListener() {

    @Override public void helpRequested(HelpEvent e) {
        System.out.println("This is the help info");
    }
});

and adding the following to my Constructor:
setDialogHelpAvailable(true);


Q: Allowing user to save contents of html list to text file I'm working on an application (ASP.NET, Webforms) that generates a list of outputs based on a user input. I want to allow the user to save the contents of said list as text file, or possibly as other filetypes such as .csv. What is the best way to approach this? Can it be done client-side with Javascript?

A: I think you will need to use ActiveX or Java Applets or Silverlight to do something like that. JavaScript does not have access to local file system.
Another way to go with this is create a file on server (physically or on the fly) and make it available for download to the user. That will get him the save file dialog.
To do this on the fly, create a blank page (without any markup. not even ), set Response.ContentType = 'text/plain' and use Response.Write() to write your content in Page_Load.

A: You can generate a plain text or csv file purely in client-side JavaScript by constructing and opening a data URI.
Example using jQuery:
window.open(
    'data:text/csv;charset=utf-8,' +
    escape(
        $('#yourlist li') // <- selector for source data here
            .map(function(){
                // format row here
                return $(this).text();
            })
            .get()
            .join('\r\n')
    )
);

Unfortunately, this technique will not work in IE due to lack of data URI support until IE8 and security restrictions once IE added support for data URIs.  You'd have to use an alternative technique for IE, either hitting the server again or using ActiveX / Silverlight / Flash / Java Applet to avoid a round trip for data that is presumably already on the client.


Q: Convert InfluxQL to FLUX query in Grafana In Grafana I have a dashboard that uses InfluxDB 1.x as data source, I'm migrating it to use InfluxDB 2.0 data source and Flux querys.
In the Grafana dashboard there is a Variable called "Server" which has the following query defined:
SHOW TAG VALUES ON telegraf WITH KEY = "host"

I'm really struggling creating a similar Variable with Flux query..
Any idea how to accomplish this?
Thanks

A: Try this:
import "influxdata/influxdb/schema"

schema.measurementTagValues(
  bucket: "my_bucket",
  tag: "host",
  measurement: "my_measurement"
)

A: this work for me:
from(bucket: "telegraf")
 |> range(start: -15m)
 |> group(columns: ["host"], mode:"by")
 |> keyValues(keyColumns: ["host"])

Note: if you want more time back (e.g. -30d) the performance will be slow, you can solve it by load this query only once (available in grafana variables) or better add some filters and selectors
for example:
from(bucket: "telegraf")
  |> range(start: -30d)
  |> filter(fn: (r) => r._field == "you field")
  |> filter(fn: (r) => /* more filter*/)
  |> group(columns: ["host"], mode:"by")
  |> first()
  |> keyValues(keyColumns: ["host"])

A: I'm using the following flux-code to extract all host tag-values for the bucket "telegraf" - just as your posted InfluxQL:
import "influxdata/influxdb/schema"

schema.tagValues(bucket: "telegraf", tag: "host")

InfluxDB has a bit about this in their documentation:
https://docs.influxdata.com/influxdb/v2.0/query-data/flux/explore-schema/#list-tag-values


Q: Managing a windows cluster from C# I am trying to start/stop a windows based cluster in C#, below is the code I am working with so far...when I get to TakeOffLine function below I get a "Not Found" exception from, System.Management.ManagementStatus.NotFound. Not sure what is exactly not being found? If there is a (alternate) better way of doing this please let me know.
Thanks!
using System.Management;
class App
{
    public static void Main()
    {
        string clusterName = "clusterHex";    // cluster alias
        string custerGroupResource = "clusterHex.internal.com"; // Cluster group name

        ConnectionOptions options = new ConnectionOptions();
        options.Authentication = System.Management.AuthenticationLevel.PacketPrivacy;

        // Connect with the mscluster WMI namespace on the cluster named "MyCluster"
        ManagementScope s = new ManagementScope("\\\\" + clusterName +
            "\\root\\mscluster", options);

        ManagementPath p = new ManagementPath("Mscluster_Clustergroup.Name='" + custerGroupResource + "'");

        using (ManagementObject clrg = new ManagementObject(s, p, null))
        {
            // Take clustergroup off line and read its status property when done
            TakeOffLine(clrg);
            clrg.Get();
            Console.WriteLine(clrg["Status"]);
            System.Threading.Thread.Sleep(3000);    // Sleep for a while
            // Bring back online  and get status.
            BringOnLine(clrg);
            clrg.Get();
            Console.WriteLine(clrg["Status"]);

        }
    }
    static void TakeOffLine(ManagementObject resourceGroup)
    {
        ManagementBaseObject outParams =
        resourceGroup.InvokeMethod("Takeoffline", null, null);
    }
    static void BringOnLine(ManagementObject resourceGroup)
    {
        ManagementBaseObject outParams =
        resourceGroup.InvokeMethod("Takeoffline", null, null);
    }
}

A: Looks like you're missing case in your method call. You have to use TakeOffline according to msdn
static void TakeOffLine(ManagementObject resourceGroup)
{
    ManagementBaseObject outParams =
    resourceGroup.InvokeMethod("TakeOffline", null, null);
}


Q: Inserting icc color profile into image using Pillow ImageCMS I am trying to insert an ICC color profile into an image. Using code from this post as an example my code looks like this:
from PIL import Image, ImageCms

# Read image
img = Image.open(IMG_PATH)

# Read profile
profile = ImageCms.getOpenProfile(PROFILE_PATH)

# Save image with profile
img.save(OUT_IMG_PATH, icc_profile=profile)

I get the following error
Traceback (most recent call last):
  File "/home/----/Documents/code_projects/hfss-misc/icc_profiles/insert_icc_profile_into_image.py", line 17, in <module>
    img.save(OUT_IMG_PATH, icc_profile=srgb_profile)
  File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/Image.py", line 2102, in save
    save_handler(self, fp, filename)
  File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 706, in _save
    markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
TypeError: 'PIL._imagingcms.CmsProfile' object is not subscriptable

I thought that there might be a problem with my ICC profile so I tried to use one generated by Pillow.
from PIL import Image, ImageCms

# Read image
img = Image.open(IMG_PATH)

# Creating sRGB profile
profile = ImageCms.createProfile("sRGB")

# Save image with profile
img.save(OUT_IMG_PATH, icc_profile=profile)

I still get the same error, however.
Does anyone know what the cause for this error is?
My system environment is as follows:

*

*Ubuntu 18.04

*Python 3.6

*Pillow==7.0.0

A: The answer from github at (https://github.com/python-pillow/Pillow/issues/4464) was to use profile.to_bytes():
img.save(OUT_IMG_PATH, icc_profile=profile.tobytes())


Q: PHP voting system check votes I’m working on a PHP voting system and I want to check logged in user voted on posts and display voted if the user have voted. I would like to do it in one single query without using multiple quires.
Posts table
+---------+--------+--------+
| post_id | title  | c_id   |
+---------+--------+--------+
|       1 | post 1 |   2    |
|       2 | post 2 |   3    |
|       3 | post 3 |   2    |
|       4 | post 4 |   1    |
+---------+--------+--------+

MySQL Loop
SELECT *
  FROM posts
  LEFT
  JOIN categories
    ON categories.cat_id = posts.c_id
 WHERE posts.c_id = categories.cat_id
   AND posts. active = 1
 ORDER
    BY posts.post_id DESC
 LIMIT 0, 10

Votes table
+---------+--------+---------+
| vote_id | p_id   | u_id    |
+---------+--------+---------+
|       1 |   1    |   1     |
|       2 |   2    |   1     |
|       3 |   2    |   2     |
|       4 |   4    |   1     |
+---------+--------+---------+

Logged in user = $uid
So if I run query inside the above MySQL loop it work fine
SELECT * FROM votes WHERE u_id = $uid AND p_id= $post_id

Is there a way to combine these two queries?

A: SELECT *
  FROM posts P
  LEFT
  JOIN categories C
    ON C.cat_id = P.c_id
  LEFT JOIN (SELECT p_id FROM votes WHERE u_id = $uid)  V
    ON V.p_id=P.post_id
   WHERE P. active = 1
 ORDER
    BY P.post_id DESC
 LIMIT 0, 10 ;

A: LEFT JOIN votes table (also no need fo left join categories if you don't want null-joins). If user has voted there will be values in joined columns - nulls will be joined otherwise.
SELECT *
FROM posts AS p
INNER JOIN categories AS c ON c.cat_id = p.c_id
LEFT JOIN votes AS v ON p.post_id = v.p_id AND v.u_id = $uid
WHERE p.active = 1
ORDER BY p.post_id DESC
LIMIT 0, 10

Not voted post will have nulls in vote columns, but since you want only know if user has voted you may limit output data (get only what you need) specifying concrete fields and make voted column that returns 1/0 values only:
SELECT p.*, c.title, ..., IF(v.vote_id; 1; 0) AS voted

A: You could use a join targeting the common Fields in both the Votes Table and the Posts Table like so:
    <?php
        $sql  = "SELECT * FROM votes AS V LEFT JOIN posts AS P ON V.p_id=P.post_id
                 WHERE (V.u_id={$uid} AND V.p_id={$post_id}) GROUP BY V.u_id";

A: You can't select votes as an array in a column but you can actually extract votes and group them. So basically what we'll do is join the two tables partially and maybe sum all the votes
SELECT p.*, c.*, sum(v.Score) FROM posts p LEFT JOIN categories c ON c.cat_id = p.c_id LEFT JOIN votes v ON p.post_id = v.p_id WHERE p.active = 1 AND v.u_id = $uid GROUP BY p.post_id ORDER BY p.post_id DESC LIMIT 0, 10

You can see that I'm summing all the scores in the votes in case there're duplications