text:
Q: Calling Remote Action Method only When User completes entering Data i have been working on MVC4 Application where i am using Remote Data-Annotation to check whether UserName is already present in DB or not. But my problem is as soon as i enter first character in TextBox, it calls JSON method and for each character insert it is going to call JSON method but what i'm looking is, it should execute JSON only when User Completes Entering UserName into TextBox.
Here is my class where i have created object with Remote DataAnnotation
public class Student
{
        [Display(Name = "User Name")]
        [Required(ErrorMessage = "Please enter {0}")]
        [StringLength(100)] //If i give minLength here as 3 then after entering 3 characters it is going to call JSON Method which i don't want so i removed minLength Attribute
        [Remote("IsAvailable", "Home", ErrorMessage = "{0} already in use!")]
        public string UserName { get; set; }
}

Here is my JSON Method in my Home Controller where i am checking Username
public JsonResult IsAvailable(string UserName)
{
        bool blnResult = false;
        if (UserName != null)
        {
            blnResult = !objDBContext.Student.Any(X => X.UserName == UserName);
        }
        return Json(blnResult, JsonRequestBehavior.AllowGet);
}

My View is simple for entering Username

                    @Html.LabelFor(model => model.UserName, new { @class = "control-label" })

                        @Html.TextBoxFor(model => model.UserName, new { @class = "form-control", maxlength = "100" })
                        @Html.ValidationMessageFor(model => model.UserName, "*")

Advance thanks to everyone for there valuable feedback!!


text:
Q: Textarea doesn't get updated Trying to use a custom build example to generate and load code pages only when the user clicks on check boxes and submits. However the textarea does not seem to update at all.
I am attempting to get my code working like this example
http://gregfranko.com/jquery.selectBoxIt.js/customDownload.html
jsfiddle
http://jsfiddle.net/lollipopwizardkid/ujp0b1uw/
Here is the code.

    Toggle all

      1. Choose and Download CSS components
      Get just the CSS you need

      <input checked="checked" type="checkbox" value="selectboxit/jquery.selectBoxIt.css"> SelectBoxIt CSS

  Generate CSS
  Download CSS

  <textarea class="source-area default sourceView" id="generated-css-source">// Minified source</textarea>

    Toggle all

      2. Choose and Download JavaScript components
      Get just the JavaScript you need

      <input checked="checked" type="checkbox" value="selectboxit/jquery.selectBoxIt.core.min.js" disabled> SelectBoxIt Core
      <input checked="checked" type="checkbox" value="selectboxit/jquery.selectBoxIt.ariaAccessibility.min.js"> Aria Accessibility
      <input checked="checked" type="checkbox" value="selectboxit/jquery.selectBoxIt.destroy.min.js"> Destroy method
      <input checked="checked" type="checkbox" value="selectboxit/jquery.selectBoxIt.disable.min.js"> Disable method

  Generate JavaScript
  Download JavaScript

  <textarea class="source-area default sourceView" id="generated-javascript-source">// Minified source</textarea>

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

Downloads

            Download CSS
            Download JavaScript

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Cisco ACS to authenticate users on multiple domains We are a sort of service provider network for schools, and use a Cisco ACS and its internal user database to authenticate users onto the remote access VPN which we provide.  Every school we support has a separate Windows domain.
We would like to be able to use the ACS to connect to the different school ADs to be able to allow them to authenticate using their local network credentials.
Can this be done, and if so is there a specific software version of the Cisco ACS that is required?  We are currently running 3.3 and I don't seem to be able to find a way of making this work.
Thanks,
Tom

A: The install guide for ACS 3.3 (see http://www.cisco.com/en/US/docs/net_mgmt/cisco_secure_access_control_server_for_windows/3.3/installation/guide/windows/install.html#wp981552) briefly mentions trusted domains, as does the end-user documentation (http://www.cisco.com/en/US/docs/net_mgmt/cisco_secure_access_control_server_for_windows/3.3/user/guide/d.html#wp353805). I suppose you could create one-way trust relationships with each of the schools Active Directory infrastructures to facilitate doing this via AD.
The negative thing about doing this with an AD trust relationship is that you're going to need name resolution for the schools' domain controller computers. You might be able to use the "Generic LDAP" user database functionality and get by with using IP addresses of their Active Directory domain controllers in lieu of using the underlying plumbing in Windows to handle doing the authentication against their AD databases.
Finally, it looks like an ACS 3.3 install can use another RADIUS server for token-based authentication. I'd try that with a standard RADIUS server (w/o actually using tokens) and see if you can get ACS to authenticate to another RADIUS server. If you can, you could ask the schools to run a RADIUS server (like Microsoft IAS) and expose only that to you. That would make both of you as de-coupled as possible while still accomplishing what you want. It's a long shot, but it might work.
I'd probably pursue the generic LDAP route first (http://www.cisco.com/en/US/docs/net_mgmt/cisco_secure_access_control_server_for_windows/3.3/user/guide/d.html#wp354503).


text:
Q: Quake 3 portal and frustum culling I am trying to understand the Quake3's source code.
Does anyone know what the function R_MarkLeaves() in ( tr_world.c) file is doing?
I think this has to do something with portal culling ?
I need to know how this works so i can also implement this in my code to speed up the rendering.

A: R_MarkLeaves() marks the precomputed PVS (potentially visible set) of leaf nodes (convex hulls) given the location of the camera / eye. The BSP tree traversal solves the drawing order problem (depth sorting) for software rendering, but at the time, it still resulted in too much overdraw. The PVS is used to prune leaf nodes that are demonstrably not visible from the current node / position.


text:
Q: List with items returns empty I have created a simple List function but if I Loop through the List it's empty. It should not be!
// List function
    public class process_hook
    {
        public static List<String> pro_hook = new List<String>
                                              (new String[] { list_all_pocesses() });
        protected static string list_all_pocesses()
        {
            StringBuilder _list = new StringBuilder();
            foreach (Process i in Process.GetProcesses("."))
            {
                try
                {
                    foreach (ProcessModule pm in i.Modules)
                    {
                        pro_hook.Add(pm.FileName.ToString());
                    }
                }
                catch { }
            }
            return _list.ToString();
        }
    }

        // call
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (String _list in process_hook.pro_hook)
            {
                Console.WriteLine(_list);
            }
        }

A: Well this is a problem to start with:
catch { }

If anything goes wrong, you'll just silently abort.
Maybe that's what's happening? (EDIT: It is. See later.)
The next problem is that your "list" will only ever contain a single string... is that really what you intended? I doubt that the list you're seeing is actually empty - but it will contain a single empty string.
(As a side note, I would strongly suggest that you start following .NET naming conventions and avoid global variables like this.)
EDIT: Aargh - I've just realized what you've done. You're probably actually getting a NullReferenceException in list_all_pocesses, which you've caught and ignored.
Your call to pro_hook.Add is made before you've assigned a value to pro_hook. Basically you've got a variable initializer which uses a method which in turn uses the variable. Don't do that. If you step through your code in the debugger, you may get more of an idea of what's going on, but basically you've created a big ball of spaghetti for yourself.
Why doesn't list_all_pocesses just return a List<string>? Why are you using a StringBuilder at all?

A: Well... you're returning an empty string builder. That's your problem. Your code is doing what you're telling it to do. :)
 return _list.ToString();

A: public class process_hook
{
    public static List<string> pro_hook = list_all_pocesses();
    protected static List<string> list_all_pocesses()
    {
        List<string> list = new List<string>();

        foreach (Process i in Process.GetProcesses("."))
        {
            foreach (ProcessModule pm in i.Modules)
            {
                list.Add(pm.FileName.ToString());
            }
        }
        return list;
    }
}

A: _list.ToString() is not going to return any meaningful value.  Try something like this instead:
public static List<string> pro_hook = list_all_processes();

protected static List<string> list_all_processes()
{
    var list = new List<string>();

    foreach (Process i in Process.GetProcesses(".")) {
        try {
            foreach (ProcessModule pm in i.Modules) {
                list.Add(pm.FileName);
            }
        } catch { }
    }

    return list;
}


text:
Q: Linear regression implementation from scratch I'm trying to understand the gradient descent algorithm.
Can someone please explain why I'm getting high MSE values using the following code, or if I missed some concept can you please clarify?
import numpy as np
import pandas as pd

my_data = pd.DataFrame({'x': np.arange(0,100),
                       'y': np.arange(0,100)})
X = my_data.iloc[:,0:1].values
y = my_data.iloc[:,1].values

def gradientDescent(X, y, lr = 0.001, n = 1000):

    n_samples, n_features = X.shape
    cost = []
    weight = np.zeros([n_features])
    b = 0

    for _ in range(n):
        # predict
        y_hat = np.dot(X, weight) + b # y = ax + b

        residual =  y - y_hat
        db = -(2/n_samples) * np.sum(residual)
        dw = -(2/n_samples) * np.sum(X.T * residual, axis = 1)

        # update weights

        weight -= (lr * dw)
        b -= (lr * db)

        cost.append(((y-y_hat) **2).mean())

    return weight, b, cost

gradientDescent(X,y)

A: Not an expert, but I think you are currently experiencing the exploding gradient problem. If you step through your code you will notice that your weight value is swinging from positive to negative in increasing steps. I believe you cannot find the minimum because using mse for this dataset is causing you to jump back and forth never converging. Your x and y ranges to 100, so when you look at the cost it is just blowing up.
If you want to use mse with your current x and y values you should normalize your data. You can do this by subtracting the mean and dividing by the standard deviation, or just normalize both x and y to 1.
For example:
my_data.x = my_data.x.transform(lambda x: x / x.max())
my_data.y = my_data.y.transform(lambda x: x / x.max())

If you do this you should see your cost converge to ~0 with enough iterations.


text:
Q: Screenshot em Python Olá! Meu problema é o seguinte:
Eu quero fazer uma screenshot da tela do meu pc usando python, eu até consigo bater a screenshot, porém, a captura de tela só é salva após a execução do programa, digo, a print só é salva após meu código terminar de rodar... Tem alguma forma da screenshot salvar enquanto executo o programa?
Segue o código:
import pyautogui
import time

capturar = pyautogui.screenshot()
capturar.save('foto.jpg')

for a in range(1,10):
    print(a)
    time.sleep(1)

Como eu disse, a captura de tela só é salva após o for, ou seja quando o código para de executar. Tem como ela ser salva antes da finalização da execução do programa?

A: MODIFICADO EM 5/Jan/2021
Acredito que seja isso que vc está querendo fazer:
import os
import pyautogui
import time

foto = 'foto.jpg'

pyautogui.screenshot(foto)  # Desta forma o pyautogui salva a imagem

if os.path.isfile(foto):
   print("Foto salva")

for a in range(1,10):
    print(a)
    time.sleep(1)

A saída será
% python salva_screenshot.py
Foto salva
1
2
3
4
5
6
7
8
9

Espero que ajude

A: Coloca o código dentro de While True e captura a função com um evento do teclado
import pyautogui
import keyboard
while True:

    if keyboard.is_pressed('q'):
        myScreenshot = pyautogui.screenshot()
        print ('impresso')


text:
Q: LLDB Type Summary with properties (NSManagedObject) After viewing the WWDC2013 LLDB Debug session, I want to add a custom type formatter for one my NSManagedObject subclasses. You can do this by typing in the debugger
type summary -add MyClass --summary-string "${var._name}"

This works but only on variables, not on methods, hence properties. I've also tried using a python script via valobj.GetChildMemberWithName without success.
How can I display a property on an NSManagedObject subclass on LLDB ?
More Info:
http://lldb.llvm.org/varformats.html

A: Long story short, as you realized the ${var.foo} syntax only works for ivars. Not for methods. Not for properties (which are methods, give or take syntactic sugar).
I have been thinking about a syntax to run expressions in the string summary format. It would look something like ${expr:[$var selector]} or ${expr:3+$var}
Lacking that, for now your workaround is to go to Python, and use the SBFrame.EvaluateExpression command. There are examples of Python formatters in the LLDB source code, and on the website that you can use as a starting point.


text:
Q: How can I make sure a method is only called once by multiple threads? I have the following structure:
public void someMethod(){
   //DO SOME STUFF
   try{
    doSomeProcessing();
   }
   catch (Exception e){
        loadSomeHeavyData();
        doSomeProcessing();
   }
}

The method someMethod may be called concurrently by many threads. The doSomeProcessing may throw an exception (it is using some data in the backend that could become obsolete).
If an exception is thrown then loadSomeHeavyData(); does some timeconsuming task that let's say "updates" all the current data and I am able to call doSomeProcessing();.
Problem: How can I make sure that loadSomeHeavyData(); is called only once? If I put some atomic flag in the entry of loadSomeHeavyData(); then I can not be sure when this should be cleared.
How can I solve this? Just a note: I can not modify doSomeProcessing(); as it is an external API and I am using decorator pattern to use it.

A: Using the synchronized keyword:
public synchronized void someMethod(){
    //doStuff
}

You assure that only one thread enters at a time.
To assure that the method is called only once, there is no special language feature; you could create a static variable of type boolean which is set to true by the first thread entering the method. When calling the method always check that flag:
public class MyClass {
    private static boolean calledMyMethod;

    public synchronized void someMethod() {
        if(calledMyMethod) {
            return;
        } else {
            calledMyMethod = true;
            //method logic
        }
    }
}

A: Your loadSomeHeavyData method could use a blocking mechanism to make all threads wait until it has finished its update, but only let one of them actually do the update:
private final AtomicBoolean updateStarted = new AtomicBoolean();
private final CountDownLatch updateFinished = new CountDownLatch(1);

public void loadSomeHeavyData() {
    if (updateStarted.compareAndSet(false, true)) {
        //do the loading
        updateFinished.countDown();
    } else {
        //update already running, wait
        updateFinished.await();
    }
}

Note my assumptions:

*

*you want all the threads to wait until the loading completes so they can call doSomeProcessing a second time with updated data

*you only call loadSomeHeavyData once, ever - if not you will need to reset the flag and the CountdownLatch (which would then probably not be the most appropriate mechanism).

EDIT
Your latest comment indicates that you actually want to call loadSomeHeavyData more than once, just not more than once at a time.
private final Semaphore updatePermit = new Semaphore(1);

public void loadSomeHeavyData() {
    if (updatePermit.tryAcquire()) {
        //do the loading and release updatePermit when done
        updatePermit.release();
    } else {
        //update already running, wait
        updatePermit.acquire();
        //release the permit immediately
        updatePermit.release();
    }
}

A: public void someMethod()
{
    //DO SOME STUFF
    try
    {
        doSomeProcessing();
    }
    catch (Exception e)
    {
        loadSomeHeavyData();  // Don't call here but add a request to call in a queue.
                              // OR update a counter
        doSomeProcessing();
    }
}

One of the solutions could be to create a queue in which each thread puts its request to call loadSomeHeavyData. when no. of requests reach a threashold, block the execution of someMethod and call loadSomeHeavyData and clear the queue.
Pseudocode may look like this:
int noOfrequests = 0;
public void someMethod()
{
    // block incoming threads here.
    while(isRefreshHappening);

    //DO SOME STUFF
    try
    {
        doSomeProcessing();
    }
    catch (Exception e)
    {
        // Log the exception
        noOfrequests++;
    }
}

// Will be run by only one thread
public void RefreshData()
{
    if(noOfrequests >= THRESHOLD)
    {
        isRefreshHappening = true;
        // WAIT if any thread is present in try block of somemethod
        // ...
        loadSomeHeavyData();
        noOfrequests = 0;
        isRefreshHappening = false;
    }
}

A: As I understand your question you need to load data in an unpredictable but limited time interval. There are three possible ways to do so:
1) You could surround your call to loadSomeHeavyData with an if statement which controls the access to the method.
2) You could change your method to handle the control flow (decision to update or not)
3) Write an update thread and let it do the work for you
The first two alternatives could use an external boolean value or generate a boolean decision by using the timedelta between the last call und the current calling time.
Third alternative would be a timed thread which runs every n seconds/minutes and load the heavy data.

A: We wrote a library that includes a utility lazily load/call a method. It guarantees single usage semantics and preserves any thrown exceptions as you'd expect.
Usage is simple:
LazyReference<Thing> heavyThing = new LazyReference<Thing>() {
  protected Thing create() {
    return loadSomeHeavyData();
  }
};

public void someMethod(){
  //DO SOME STUFF
  try{
    doSomeProcessing();
  }
  catch (Exception e){
    heavyThing.get();
    doSomeProcessing();
  }
}

All threads block on the get() and wait for the producer thread (the first caller) to complete.


text:
Q: Apportable GCM implementation Looking for further information how to implement registration and unregistration methods for Android Google Cloud Messaging.
Any piece of code or even how to use the BridgeKit wrapper of Apportable to do this will be appreciated.
I don't have too much skill in Java.

A: See this Apportable docs page for a tutorial and this github project for an example.


text:
Q: $100$ can be divided into the sum of several numbers. How many different possibilities are there?
$100$ can be divided into the sum of several numbers as $1+99$ or $1+1+98$, and we set all the numbers have to be positive. Besides, $1+99$ is different from $99+1$. How many different possibilities are there?

I start to divide $100$ into the sum of two numbers. There are 99 possibilities.
Then divide $100$ into the sum of three numbers. There are $98+97+\dots+1$ possibilities.
Then divide $100$ into the sum of four numbers. For example $1+a+b+c=100$. Then there are $97+96+\dots+1$ ways to write $a,b,c$. For $2+a'+b'+c'=100$, there are $96+95+\dots+1$ ways to write $a',b',c'$.
However I don't think this approach is promising. Is there any feasible way to solve this problem?

A: There are $\binom{n-1}{r-1}$ integer solutions $(x_1 ,\ldots, x_r)$, all $\ge 1$ to $x_1 + x_2 + \ldots x_r  =n$ , see here, e.g.
You want this for all $r=1,\dots 100$, just sum these:
$$\sum_{r=1}^{100} \binom{99}{r-1} = 2^{99}$$
I think the following combinatorial argument works: write $100 = 1 + \ldots + 1$,
now we can either leave or delete one of the 99 $+$-signs ((and when deleting combine the numbers on both sides): e.g. for $n=3 = 1 + 1 + 1$, deleting none leaves 3 =1 + 1 +1 , deleting the first + leaves 3 = 2 + 1, deleting the second 1+2, deleting all leaves 3 = 3, etc., so $2^2$ solutions in all, if you don't want the last trivial one, subtract 1 from my answer. )


text:
Q: Add backslash to String in Objective-c I have a problem identical to this problem here.
I even want to encode the same infromation as him (it's a date/time for asp.net)...
When ever I try to add a backslash i get two backslashes since I used \.
Everyone in the thread above has claimed that this is a problem with NSLog and that NSString does treat \\ as a \. I have checked this further by using a packet sniffer to examine the packets I'm sending to the webserver and I can confirm that it is transmitting a double backslash instead of a single backslash.
Does anyone know how to add a backslash to a NSString?

A: The strings and NSLog are working fine for me:
NSLog(@"\\"); // output is one backslash
NSLog(@"\\\\"); // output is two backslashes
NSLog(@"\\/Date(100034234)\\/"); // output is \/Date(100034234)\/

What am I missing?

A: Try this:
yourStr =  [yourStr stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
NSLog(@"%@", yourStr);

I had the same problem, turned out that my JSON Parser replaced all occurrances of "\\" with "\\\\", so when I NSLogged my original code like this:
NSString *jsonString = [myJSONStuff JSONRepresentation];
NSLog(@"%@", jsonString);

This is what I got:

{TimeStamp : "\\/Date(12345678)\\/"}

However, the string itself contained FOUR backslashes (but only 2 of them are printed by NSLog).
This is what helped me:
NSString *jsonString = [myJSONStuff JSONRepresentation];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
NSLog(@"%@", jsonString);

The result:

{TimeStamp : "\/Date(12345678)\/"}


text:
Q: Count Should show zero value if it null I am using MYSQL DB
I have table joborder when I select with case getting no date I need to show zero like
select * from joborder;
10

select * from joborder where jobid='ID';
null

it should show 0 ?

A: you can use IFNULL on your mysql query
LIKE select IFNULL((select ID from joborder where jobid='ID'),0);

A: I am assuming that you need value where ever it exists and 0 where it is null.
Use your query as per below:
SELECT IFNULL(order_value,0) AS 'order_value' FROM joborder WHERE jobid='ID';

check below:
SELECT IFNULL(t21.n1,0) n1 ,t22.n2 FROM t1 AS t21 RIGHT JOIN (SELECT n2 FROM t2) t22 ON t22.n2=t21.n1;


text:
Q: Set default (auto) slug prefix for Tags Is it possible to add default prefix to the slug of each newly added Tag. So that full slug, would be stored in database (no rewrites).
For example:

*

*Name: Tag1 -> Slug: prefix-tag1

*Name: Tag2 -> Slug: prefix-tag2

*...

A: You can use the created_term or the created_{taxonomy} hooks which are fired just after a taxonomy term is created (the second only if it matches the taxonomy).
The following will only alter terms in the taxonomy 'my-taxonomy'. (I believe for the default tags, taxonomy should be 'post_tag').
add_action('created_term', 'my_add_prefix_to_term', 10, 3);
function my_add_prefix_to_term( $term_id,$tt_id,$taxonomy ) {
    if( $taxonomy == 'my-taxonomy'){
        $term = get_term( $term_id, $taxonomy );
        $args = array('slug'=>'my-prefix-'.$term->slug);
        wp_update_term( $term_id,$taxonomy, $args );
    }
}

Note: From the Codex:

It should also be noted that if you set 'slug' and it isn't unique then a WP_Error will be passed back

This shouldn't be a problem if you use this function before any terms are created, because prefixing the same string to unique slugs preserves uniquness.


text:
Q: Charting with Dygraphs: Data sampling depending on zoom Although Dygraphs performs very well compared to other solution, when viewing more and more data points, the performance inevitably slows.
I already have all my data loaded locally. Is there a way for Dygraphs to intelligently display a lower resolution (in terms of number of data points) and then show more on zoom?

A: There's no built-in facility, but it is possible. See this thread for an example of one user who pulled it off: https://groups.google.com/forum/#!topic/dygraphs-users/kgdNdt1A0dk


text:
Q: Dependent selectbox issue I am trying to make two dependent select-boxes. There are two same select-boxes and the first selection hides the other one when it is selected, like this:
1st select-box
   Option one
   Option two (selected)
   Option three
2nd select-box
   Option one
   Option two (disappears)
   Option three

A: You can write something like this
<select id="s1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
<select id="s2">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

and
$('#s1').change(function() {
    $('#s2').empty().append($('#s1 :not(:selected)').clone());
});

try it here http://fiddle.jshell.net/zDLMZ/
not optimal, but should work good on not big set of options


text:
Q: Connect Internet through two different LAN Interfaces I am trying to connect an IoT device to internet. It is running on Ubuntu.
It has two Ethernet interfaces. One is connected to a LTE modem + antenna (fast and cheap connection), and the other is connected to a Satellite modem + antenna (can connect everywhere, expensive and unreliable).
I have two types of message to send to my server:

*

*An alarm, if any problem occurs on the device, that I want to send
through Satellite, at anytime.

*All the data when an LTE connection is available.
Most of the time no LTE connection is available.
Is there anyway I could program this networking strategy?
I thought about alternating between the interfaces with ifup and ifdown, but I don't want the data message to be interrupted by the alarm message and vice-versa.
I appreciate any solution or idea. Since the project is mostly written in python it would be awesome if there is a library solution that exists, but I am open to anything.
Thank you,

A: You could do this with static routes, where you send over certain interface. You just have to make sure that the destination has a valid backroute so that all trafic that goes out over one interface will also get its answer on the same interface.


text:
Q: localStorage quota exceeded even though localStorage is empty I have an app in which I'm setting the localStorage, and suddenly the localStorage isn't setting anymore, and I get the error in the console:
Failed to execute 'setItem' on 'Storage': Setting the value of 'myapp' exceeded the quota.

However, when I go to Chrome localStorage under Application tab, and go into where my app is hosted, i.e., localhost:5000, there are no values in it, which means that localStorage for localhost:5000 is empty. Why does Chrome say that the quota is exceeded?


text:
Q: capture optional substring I'm trying to match these lines:
X=1 a b c Y=5 a bb aa
X=2 aa ccc d
X=3 ccc Y=9 d ee ff

The 'Y=x' substring is optional. It may be present in a line or not.
I want to capture the X=x in group 1, and Y=x in optional group 2.
I'm using this regular expression:
^(X=[0-9]+?).+?(Y=[0-9]+?)?.+?$

The whole line is matched, but I'm capturing only the first group. The second group is never captured even if the optional substring exists. The problem is that between X= and Y= could be a lot of different words (with '=' character too).
Any ideas how to capture optional group 2?
Actual example: http://regex101.com/r/rD4sO4/1

A: Updated
Here's a more efficient and cleaner option (that doesn't require alternation):
^(X=[0-9]+)(?:.+?(Y=[0-9]+))?.+?$

Demo
Note that I removed the lazy repetition from [0-9] since you shouldn't have any issues with it matching too many characters anyways.

Explanation
The original expression wasn't working because regular expression match from left to right (and since you were using lazy repetition, I assume you understand the concept that regex is "greedy"). So even though your middle .+? was lazy, the Y=[0-9]+ was optional so it could continue to match all the way to the trailing/required .+?$. This may not be exactly what one would expect, since there was a lazy repetition..but why stop for an optional segment when you can always backtrack and try to match it again.
Mine worked because I made the middle .+? only exist if Y=[0-9]+ existed. So Y=[0-9]+ always is checked for, but if it is not found that is okay since the whole group is still optional. Then we still can end with a trailing .+?$.

Original
I'm racking my brain for a more concise answer, but I used alternation to make the regex engine always check for a Y=[0-9]+? before just matching everything:
^(X=[0-9]+)(?:.+?(Y=[0-9]+).+?|.+?)$

Demo

A: or this pattern
(X=\d+)(?>[^Y\r\n]+|Y(?!=\d+))*(Y=\d+)?

Demo

A: (X=\d+)|(Y=\d+)

Try this.See demo.
http://regex101.com/r/lS5tT3/21


text:
Q: Multiple edit text field Im trying to modify the following code so it can save for multiple edited text while at the moment this code only saving one (first) edited text ... could anybody please modify this code for me say for example: you modify it to save 3 or 4 edited text, and based on that I can add any number of text field I need.
and onother thing to menstion when if you write in text fild, saved it and then refresh the page your written contents will still there same as if you try with the following code with one text field, I want this featear also applied when adding multiple text fields.

<title>Allowing Users to Edit Multiple Text field and save the contents</title>

Here is the element's original content

<input type="button" value="save my edits" onclick="saveEdits()"/>

 Edit the text and click to save for next time

Thanks in Advance.
this is what i've tried.

<title>Allowing Users to Edit Multiple Text field and save the contents</title>

Here is the element's original content

This is another text field.

<input type="button" value="save my edits" onclick="saveEdits()"/>

 Edit the text and click to save for next time

A: Dirty copy paste job. At least it demonstrates how to add more editable divs.
To make it dynamic, you may cnosider to construct the function a bit differently, or start adding jQuery in it to make the element selection easier..

<title>Allowing Users to Edit Multiple Text field and save the contents</title>

Here is the element's original content

Here is the element's original content

Here is the element's original content

Here is the element's original content

<input type="button" value="save my edits" onclick="saveEdits()"/>

 Edit the text and click to save for next time


text:
Q: conversion of multiplication of int32 to int64 I have following structure
struct {
    int myData;
    int myAnotherData;
}Value;

struct AnotherStructure {
    unsigned int uiLowData;
    unsigned int uiHighData;
};

AnotherStructure m_AnotherStructure;
Value val;
val.myData = 10;
#define MULTIPLY 36000000000

unsigned __int64 &internalStructure = *(unsigned __int64*)&m_AnotherStructure;
internalStructure  = 0;
internalStructure += ((unsigned __int64)val.myData * MULTIPLY );

My questions is there any overflow of data in above case as we are multiplying unsigned int with big value, is result stored in temp value of type unsigned int and then stored in int 64? If now how there won't be any overflow?
Thanks

A: val.myData is casted to unsigned __int64 before the multiplication, because you explicitly cast.
still overflows can occur, depending on the value stored in val.myData - the maximum int multiplied by 36000000000 wont fit into 64 bits.
and you loose your algebraic sign with the cast.
you should try this:
struct AnotherStructure {
    int64_t uiLowData;
    int64_t uiHighData;
};
// signed_128bit_integer: look into your compiler documentation
signed_128bit_integer &internalStructure = *(signed_128bit_integer*)&m_AnotherStructure;
internalStructure  = 0;
internalStructure += ((signed_128bit_integer)val.myData * MULTIPLY );


text:
Q: Selecting BLOB column from Oracle database to SQL Server database over linked server How do I select a blob column from an Oracle database using OPENQUERY on a SQL Server that is using Linked Server to connect to the Oracle database?
When I try using this syntax, I receive an error:
SELECT * FROM OPENQUERY(LINKED_SERVER_NAME ,
'Select blobColumn from TABLE') AS derivedtbl_1

Errors:

OLE DB provider "MSDAORA" for linked
  server "LINKED_SERVER_NAME" returned
  message "Oracle error occurred, but
  error message could not be retrieved
  from Oracle.". OLE DB provider
  "MSDAORA" for linked server
  "LINKED_SERVER_NAME" returned message
  "Data type is not supported.".

A: Can you change the OLE DB provider you're using to connect to Oracle?  The Microsoft OLE DB Provider for Oracle does not support BLOB data types.  The Oracle OLE DB Provider does.  If you change the connection to Oracle to use the Oracle provider, it should work.

A: This works:
SELECT * FROM OPENQUERY(LINKED_SERVER_NAME ,
'Select DBMS_LOB.SUBSTR(blobColumn,4000,1) from TABLE') AS derivedtbl_1

This returns only the first 4000 characters of the blob columns, and only works for columns that have text (not binary) data.  But it works for me.


text:
Q: I can't overwrite the OnCreateOptionMenu() I want to create an application that shows me the optionMenu, but when i wanted to overwrite the onCreateOptionMenu, there's no trace of that. I mean I can't see it in the collection of activity class methods!!
Can you help me???
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.optionsmenu"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="16" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.derakhshani.optionsmenu.Main"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

A: Inside your class that extends Activity, you should be able to override it like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Do other stuff here
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}


text:
Q: Checkbox in the beginning of jTable I am new to Swing and seeking some help here. I need to show the data from an .xls file in a jTable. Below is my code which I followed from here :-
jbClick.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent arg0) {
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if(!file.getName().endsWith("xls")){
            JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",JOptionPane.ERROR_MESSAGE);
            }
        else {
                fillData(file);
                model = new DefaultTableModel(data, headers);
                tableWidth = model.getColumnCount() * 150;
                tableHeight = model.getRowCount() * 25;
                table.setPreferredSize(new Dimension( tableWidth, tableHeight));
                table.setModel(model);
                jbClick.setVisible(false);
                jbText.setVisible(true);
                }
        }
    });

    JPanel chooserPanel = new JPanel();
    JPanel filterPanlel = new JPanel();
    //filterPanlel.add(jbText,"OLa");

    final Color alternate = new Color(186,246,244);
    table = new JTable();
    table.setAutoCreateRowSorter(true);
    model = new DefaultTableModel(data, headers);
    table.setModel(model);
    table.setBackground(alternate);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setEnabled(false);
    table.setRowHeight(25);
    table.setRowMargin(4);
    tableWidth = model.getColumnCount() * 200;
    tableHeight = model.getRowCount() * 25;
    table.setPreferredSize(new Dimension( tableWidth, tableHeight));
    scroll = new JScrollPane(table);
    scroll.setBackground(alternate);
    scroll.setPreferredSize(new Dimension(500, 500));
    scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    getContentPane().add(buttonPanel, BorderLayout.NORTH);
    getContentPane().add(scroll, BorderLayout.CENTER);
    //setSize(600, 600);
    setResizable(true);
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    //setUndecorated(true);
    setVisible(true);
    }

    /** * Fill JTable with Excel file data. * * @param file * file :contains xls file to display in jTable */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    void fillData(File file) {
        Workbook workbook = null;
        try {
            try {
                workbook = Workbook.getWorkbook(file);
                }
            catch (IOException ex) {
                Logger.getLogger( excelTojTable.class. getName()).log(Level.SEVERE, null, ex);
                }
            Sheet sheet = workbook.getSheet(0);
            headers.clear();
            for (int i = 0; i < sheet.getColumns(); i++)
            {
                Cell cell1 = sheet.getCell(i, 0);
                headers.add(cell1.getContents());
            }
            data.clear();
            for (int j = 1; j < sheet.getRows(); j++)
            {
                Vector d = new Vector();
                for (int i = 0; i < sheet.getColumns(); i++)
                {
                    Cell cell = sheet.getCell(i, j);
                    d.add(cell.getContents());
                }
                d.add("\n");
                data.add(d);
                }
            }
        catch (BiffException e) {
            e.printStackTrace();
            }
        }

Problem :- Now I need to add a editable checkbox in-front of each row in the table.
Please help.

A:
I need to add a editable checkbox in-front of each row in the table.

Before your loops that create the "header" and "d" Vectors, you need to add your Boolean information.
So for the header you might do:
headers.clear();
header.add("Select");

and for each row:
Vector d = new Vector();
d.add( Boolean.FALSE );.

i got a new column in my table but its not a checkbox

Then you would need to set the default renderer for the first column of the table by updating the TableColumn of the TableColumnModel using the default renderer for the Boolean class:
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellRenderer( table.getDefaultRenderer( Boolean.class ) );

i am new to swing

Start with the Swing tutorial on [How to Use Table]
(http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) for the basics of renderers.
Edit:
A simple SSCCE that demonstrate the solution:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        Vector<String> header = new Vector<String>();
        header.add("Select");
        header.add("Column1");
        header.add("Column2");
        header.add("Column3");

        Vector<Vector<Object>> data = new Vector<Vector<Object>>();

        for (int row = 0; row < 5; row++)
        {
            Vector<Object> d = new Vector<Object>();
            d.add( Boolean.FALSE );

            for (int column = 0; column < 3; column++)
            {
                d.add(row + " : " + column);
            }

            data.add(d);
        }

        DefaultTableModel model = new DefaultTableModel(data, header);
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        TableColumn tc = table.getColumnModel().getColumn(0);
        tc.setCellRenderer( table.getDefaultRenderer( Boolean.class ) );
        tc.setCellEditor( table.getDefaultEditor( Boolean.class ) );

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new SSCCE() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}


text:
Q: Shell script - deal with floats math operations in an array, without drop the value in a var first? I am writing a small script that will get the output of one of my tools, and will read values in files.
I am using an array as storage, so once the array has the values from the files, I process them, calculating various metrics.
Now I realized that is impossible to do something like this:
thearray=(1.1 2.2 3.3 4.4 5.5)

tempval=${thearray[0]} + ${thearray[1]}

I want to get the first element of the array (position 0), and the second (position 1) and make the sum of them, and save the result in tempval.
The whole array contains floats, so I assume that shell knows the type of data in the array, and should allow me to make the sum.
Instead the output is the value of field 0, a "+" and the value of field 1
echo $tempval
1.1+2.2

I assume that the problem is generic to variables that contains numbers, and the shell consider them as string, doing the concatenation instead than the sum.
If I take the output of ${the array[0]} amd ${the array[1]}, and put them in variables first, then I can sum them using the $(( )) syntax
var1=${the array[0]}
var2=${the array[1]}

tempvar=$((var1+var2))

Altho this seems to work with integers, not floats.
Is there a way to avoid this, and get directly the arithmetic sum, without have to go trough the creation of variables to store the array values, before doing the sum? I need to make the sum of more than 14 elements, and seems a big waste to have to create 14 different variables to hold the values, when I calculate the average for example.
I have tried to do this
tempval=$((${thearray[0]} + ${thearray[1]}))

But it return me a syntax error: invalid arithmetic operator. In other languages I would cast as float, but here I am quite lost.
Any suggestion is more than welcome. Thanks

A: $ thearray=(1.1 2.2 3.3 4.4 5.5)
$ sum=$( IFS="+"; bc <<< "${thearray[*]}" )
$ echo $sum
16.5

The form "${array[*]}" returns a string with each array element joined by the first character of $IFS. So we're passing the string 1.1+2.2+3.3+4.4+5.5 to bc

A:
But it return me a syntax error: invalid arithmetic operator.

Seems like your array contains floats.  bash would natively support only arithmetic operations, so you can make use of bc.  Use a loop to sum:
sum=0
for i in "${thearray[@]}"; do
  sum=$(echo $sum + $i | bc -l);
done
echo "Sum = ${sum}"

You can calculate the average by saying:
average=$(echo $sum / ${#thearray[@]} | bc -l)
echo "Average = ${average}"


text:
Q: How to initialize a constant array in heap memory using C++? In C++, we can allocate heap memory for a dynamic array, but how can we initialize it if it's a read only array? Here is an example:
const char* str = new char[3];

After operating this statement, the system seems to initialize variable str with garbage value implicitly which means i cannot change its value since it has a constant qualifier. So how can i creat a constant string in heap memory and intialize it explicitly?
If i want to creat a object in heap memory, i need a pointer to the object. But if it's constant, i cannot even change it with the pointer after its creation in heap memory. So it became a vicious circle for me.

A: You can start with char * modify the array, then convert it to const char *:
char *str = new char[3];
// str[i] = ...
const char *cstr = str;

But unless you're trying to practice dynamic memory management, none of this should be necessary. Just use std::string or std::vector<char>.

A: Your operator new call doesn't allocate const memory. It gets converted to const when you assign it to the variable. The solution is to make a temporary variable that's not const, write the data to it and then finally convert it to a const pointer:
#include <cstring>
#include <memory>

std::unique_ptr<const char[]> PutBytesOntoHeap(const char* data, size_t size)
{
    std::unique_ptr<char[]> result(new char[size]);
    memcpy(result.get(), data, size);
    return result;
}

A: In current c++ avoid calling new/delete explicitly, only use it internally in datastructures (and even then std::make_unique is prefered). So use std::vector (or alternatively std::string/std::string_view)
@273K Also note most C++ books (teachers, online material) are out of date.
#include <vector>

int main()
{
    std::vector<char> str{ 'a', 'b', 'c' }; // this will do the memory allocation for you

    // for local use (when a legacy api needs a pointer, otherwise don't use)
    const char* ptr = str.data();

    return 0;

    // std::vector goes out of scope
    // will free the allocated memory (so you can't forget to call delete[])
}

A:
if it's constant, i cannot even change it with the pointer after its creation in heap memory

In
const char* str = new char[3];

you actually create a non-const char array and assign it to a const char*. You could just assign it to a char* instead, make the changes you want and then return a const char*. Example:
auto str = []() -> const char* {
    char* rv = new char[3];
    rv[0] = '1';
    rv[1] = '2';
    rv[2] = '\0';
    return rv;
}();

how can i creat a constant string in heap memory and intialize it explicitly?

You use new const char[] with an initializer:
auto str = new const char[3]{'1', '2', '\0'};

A helper function could look like this:
#include <cstddef>
#include <iostream>
#include <utility>

template <std::size_t N>
auto make_const_cstring(const char (&s)[N]) {
    return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
        return new const char[N]{s[Is]...};
    }(std::make_index_sequence<N>());
}

int main() {
    auto str = make_const_cstring("Hello world");
    std::cout << str << '\n';
    delete[] str;
}

A: If you want to use an array after the function that created it returns, allocate that array in the heap, not in the run-time stack. Expression new T[size] allocates a new array with size variables in it, each of type T. Remember that an array is treated just like a pointer to the first thing in the array. So expression new int[25] has type int*. Statement
int* A = new int[25];
allocates a new array of 25 ints and stores a pointer to the first one into variable A.
The size can be given by any expression that yields an integer. For example, if you already have an integer variable called n that currently holds 50, then
double* B = new double[n];
allocates an array of 50 doubles.


text:
Q: Choosing an intermediate language I am currently playing around with programming languages. I have spent some time writing parsers and interpreters in high level languages (most notably Haxe).
I have had some results, that I think are actually quite nice, but now I'd like to make them fast.
My idea was to translate the input language into C.
My C knowledge is limitted to what you learn at university. Beyond some exercises, I have never written actual C programs. But I feel confident I can make it work.
Of course I could try to write a frontend for the LLVM or to generate MSIL or JVM bytecode. But I feel that's too much to learn right now, and I don't see much of a gain actually.
Also C is perfectly human readable, so if I screw up, it's much easier to understand why. And C is, after all, high level. I can really translate concepts from the input language without too much mind-bending. I should be having something working up and running in a reasonable amount of time and then optimize it as I see fit.
So: Are there any downsides to using C? Can you recommend an alternative?
Thank you for your insight :)

Edit: Some Clarification

*

*The reason why I want to go all the way down is, that I am writing a language with OOP support and I want to actually implement my method dispatching by hand, because I have something very specific in mind.

*A primary area of use would be writing HTTP services, but I could image adding bindings to a GUI library (wxWidgets maybe) or whatever.

A: C is a good and quite popular choice for what you're trying to do.
Still, take a look at LLVM's intermediate language (IR). It's pretty readable and I think it's cleaner and easier to generate and parse than C. LLVM comes with quite a big collection of tools to work with it. You can generate native code for variety of platforms (as with C but with slightly more control over output) or for virtual machines. Possibility of JIT compilation is also a plus.
See The Architecture of Open Source Applications, Chapter 11 for introduction to LLVM approach and some snippets of IR.

What is your target environment? This might help us give you better answer.

A: C is actually a pretty good choice for a target language for a little or experimental compiler -- its widely available on many platforms, so your compiler becomes immediately useful in many environments.  The main drawback is dealing with things that are not well supported in C, or are not well defined in the C spec.  For example, if you want to do dynamic code generation (JIT compilation), C is problematic.  Things like stack unwinding and reflection are tricky to do in C (though setjmp/longjmp and careful use of structs for which you generate layout descriptions can do a lot).  Things like word sizes, big or little-endian layout, and arithmetic precision vary between C compilers, so you have to be aware of that, but those are things you need to deal with if you want to support multiple target machines anyways.
Other languages can be used as well -- the main advantage of C is its ubiquity.

A: You might consider C--, a C-like language intended to be a better target for code generation than C.

A: C is a good choice, IMHO.  Unlike many languages, C is generally considered "elegant" in that you have only 32 keywords, and very basic constructs (sequence, selection, iteration), with a very simple-and-consistent collection of tokens and operators.
Because syntax is very consistent within C (brackets and braces, blocks and statements, use of expressions), you're not marching into an unbounded world of language expansion.  C is a mature language, has weathered time nicely, and now-a-days is a "known quantity" (which is really hard to say about many other languages, even "mature" ones).


text:
Q: Is It Possible To Sign Messi on Career mode With Man. City I have tried buying Messi and giving him a wage of 1.1 million a week but he still won't join. I am currently Man. City.

A: I'm pretty sure it is basically impossible to sign Messi. Just play as Barca, and you get to play with him. Other than that, maybe try to sign him in a few seasons time?

A: Me being man City I offered Barca 45 mil plus ageuro and signed messi on a 500,000 a week in wages expensive but affordable if you have won many trophies


text:
Q: Illegal access: this web application instance has been stopped already. Tomcat Stop Run Apache Tomcat Server 9.0.19 Not Start.
I created new project and include the tomcat but not start and giving this error
08-May-2019 23:18:03.205 INFO [mysql-cj-abandoned-connection-cleanup] org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
 java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1383)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1036)
    at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.checkThreadContextClassLoader(AbandonedConnectionCleanupThread.java:117)
    at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:84)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

Some solutions at below, which prev questions on stackoverflow

*

*restart tomcat

*delete caches

*enter to vm option this : "-XX:MaxPermSize=1024m"

but still doesn't work.
can anyone help me

A: You should try deleting existing deployed war from webapps of tomcat and try redeploying a fresh war. It seems your any of the existing application has same packaging details which are conflicting with your new project.
Clear those wars ( and there directories ) from webapps which are not required.

A: had the same problem with me. I just deleted(not un-installed) the old tomcat and installed new tomcat with same version on the same directory as before. Worked perfectly for me.


text:
Q: SSIS - Cannot connect to SP List with OData Source I have a SSIS Package with an OData Source Connection to a SharePoint List. To connect to the list, I have a Service Account, which I add as Basic Authentification in the OData Source Task. With this Credentials I can connect to SP and can choose the collection (also preview of the list).
When I now execute the Package (in VS or from Management Studio) the package always fails with the error Message "Cannot acquire a managed connection from the run-time connection manager".
In Management Studio I run the Package with the Service Account User.
Does everybody know whats my problem here ?
I am using SQL Server 2016.


text:
Q: Minimum Between 3 Attributes I have to prepare a flow that calculates in how many installments we can divide a purchase.
There are 3 conflicting business rules that give different answers. Our rule is to return the lesser value.
However how can I instruct a UpdateAttribute processor to return the minimum between the 3 attributes that contain the number returned by the business rules?

A: You could use two UpdateAttribute processors in a row, lets say you have three attributes a, b, and c.
The first UpdateAttribute has something like:
result = ${a:lt(b):ifElse(a, b)}
Now result is the lesser of a and b.
Second UpdateAttribute:
result = ${result:lt(c):ifElse(result, c)}
Now result is the lesser of the previous result and c.

A: you can use ExecuteGroovyScript processor with code like:
def ff=session.get()
if( !ff )return
ff.result = [ ff.a, ff.b, ff.c ].collect{ it as BigDecimal }.max()
REL_SUCCESS << ff


text:
Q: Когда нужно использовать CoInitialize? Добрый день! Подскажите пожалуйста, когда нужно использовать связку CoInitialize(nil); - CoUninitialize;?
A: Полагаю, вот эта статья вам поможет - Понимание потоковых моделей в COM при программировании на Delphi, в частности на стр. 5
A: В любом Thread, в котором планируется использовать COM объекты все места использования следует обложить CoInitialize(nil); - CoUninitialize.


text:
Q: Why this code Force Quits? I have starting learning Java and android application development side-by-side. Currently, I a String-array colorsArray which I am trying to print using Log.v
    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, defaultActivity!</string>
    <string name="app_name">Challenge</string>
    <string name="red">Red</string>
    <string name="orange">Orange</string>
    <string name="yellow">Yellow</string>
    <string name="green">Green</string>
    <string name="blue">Blue</string>
    <string name="indigo">Indigo</string>
    <string name="violet">Violet</string>
    <string-array name="colorsArray">
        <item>@string/red</item>
        <item>@string/orange</item>
        <item>@string/yellow</item>
        <item>@string/green</item>
        <item>@string/blue</item>
        <item>@string/indigo</item>
        <item>@string/violet</item>
    </string-array>
</resources>

Now I am trying to print that array in different ways, just for practice.
package com.gaurish.challenge;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class defaultActivity extends Activity {
    /** Called when the activity is first created. */
    public static final String DEBUG_TAG = "PracticeApp";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String aColors[] = getResources().getStringArray(R.array.colorsArray);
    printUsingForEach(aColors);
    printUsingWhile(aColors);
    printReverse(aColors);
}

private void printUsingForEach(String[] aColors) {
    for(String i : aColors) {
        Log.v(DEBUG_TAG, "String array printed using for each loop: " + i);
    }
}

private void printUsingWhile(String[] aColors) {
    byte i=0;
    while(i<=aColors.length) {
        Log.v(DEBUG_TAG, "String array printed using While loop: " + aColors[i++]);
    }
}

private void printReverse(String[] aColors) {
    int i=aColors.length -1;
    while(i> (-1) ) {
        Log.v(DEBUG_TAG, "String array printed in reverse order -> " + aColors[i--]);
    }
}
}

printUsingForEach() & printUsingWhile() run just fine but printReverse method just not run, the application force quits before reaching. here is the log I am building against android 1.6
Please guide this n00b, why this is happening

A: You have a bug in your code:
while(i<=aColors.length) { ... }

This will cause a loop iteration with i = aColors.length, which is out of bounds.
You can see this in your log:
02-13 15:24:24.226: ERROR/AndroidRuntime(396): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gaurish.challenge/com.gaurish.challenge.defaultActivity}: java.lang.ArrayIndexOutOfBoundsException
02-13 15:24:24.226: ERROR/AndroidRuntime(396): Caused by: java.lang.ArrayIndexOutOfBoundsException
02-13 15:24:24.226: ERROR/AndroidRuntime(396):     at com.gaurish.challenge.defaultActivity.printUsingWhile(defaultActivity.java:31)


text:
Q: I've created a code to convert binary to decimal, but doesn't work with more than 10 bits I've created a small code to convert binary number to decimal number.
When I enter a binary number until 10 bits, the result be correct, but when I increase than 10 bits, the result would be wrong.
The algorithm that I used is the following
1   1   0  0  1  0
32  16  8  4  2  1 x
------------------
32+ 16+ 0+ 0+ 2+ 0

The Code:
unsigned long binary, i=0, j=0, result=0, base=1;
unsigned char *binaryStandalone = (unsigned char *)malloc(16);
memset(binaryStandalone, 0, 16);

printf("Enter a binary number: ");
scanf("%u", &binary);

while(binary > 0){
   binaryStandalone[i] = binary % 10;
   binary = binary / 10;
   i++;
}

for(j=0;j<i;j++){
   result +=  (binaryStandalone[j] * 1 << j);
   printf("%u = %u\n", j, base << j);
}
printf("The decimal number is: %u\n", result);

free(binaryStandalone);

Now I want to know, what is the reason that the code doesn't give me the correct result when increase the binary number more than 10 bits ?

A: It seems that your platform uses 32 bit for a long int, therefore your binary
variable can hold at most the value 2^32 - 1 = 4294967295, which is sufficient
for 10 digits, but not for eleven.
You could use unsigned long long instead (64 bit would be sufficient for 20 digits), or read the input as a string.

A: you store in an unsigned long which has range 0 to 4,294,967,295 -> only 10 numbers

A: Because the long value you're using to store the "binary" value has not more decimal digits. You might want to use a string type for input instead.


text:
Q: how hidden TextInput IOS Keyboard top area (ok button) Screenshot
i want to hidden this area
What shall I do?
thanks

A:         <TextInput
          returnKeyType={'default'}
          autoFocus
          style={{ paddingBottom: 97,height: 238,padding: 0}}
          // blurOnSubmit={true}
          multiline={true}
          // onSubmitEditing={onConfirm}
          // maxLength={30}
          // autoCorrect={false}
          clearButtonMode={'always'}
          textContentType={'none'}
          placeholder={'Please enter note'}
          placeholderTextColor={'#454545'}
          value={note}
          enablesReturnKeyAutomatically
          caretHidden
          keyboardType="default"
          blurOnSubmit={false}
          contextMenuHidden={false}
          inputAccessoryViewID={inputAccessoryViewID}
          // disableFullscreenUI={false}
          onChangeText={noteChanged}
        ></TextInput>

A: Remove these props from TextInput

*

*enablesReturnKeyAutomatically

*returnKeyType={'default'}


text:
Q: OTRS Installation on AWS Linux AMI results in 500 Internal Server Error page I am creating a new instance of OTRS on Amazon Linux AMI 2017.03.0 (HVM) and cannot get the installer.pl to run. My installation steps are as follows (and I've done this about four times so far):

*

*Set the HOSTNAME

*Add the private IP address to the hosts file with the FQDN of the server (172.10.10.10 otrs.example.com)

*sudo yum -y update

*sudo yum -y install bash-completion --enablerepo=epel

*wget http://ftp.otrs.org/pub/otrs/RPMS/rhel/ ... noarch.rpm

*sudo yum -y install --nogpgcheck otrs-5.0.18-01.noarch.rpm

*sudo yum install -y mod24_perl "perl(JSON::XS)" "perl(GD::Text)" "perl(Encode::HanExtra)" "perl(GD::Graph)" "perl(Mail::IMAPClient)" "perl(PDF::API2)" "perl(Text::CSV_XS)" "perl(YAML::XS)" "perl(DBD::mysql)"

*sudo /sbin/chkconfig httpd on

*sudo reboot
SELinux is disabled. Following a reboot, I can get to the Amazon Linux AMI Test Page but not otrs.example.com/otrs/installer.pl (results in a 500 Internal Server Error).
My httpd_error logs shows:
[Thu Apr 20 22:21:31.894716 2017] [core:notice] [pid 2721] AH00094: Command line: '/usr/sbin//opt/'
[Thu Apr 20 22:21:41.067143 2017] [:error] [pid 2725] Cannot find current script '/opt/' at /usr/share/perl5/FindBin.pm line 166.\nBEGIN failed--compilation aborted at /usr/share/perl5/FindBin.pm line 166.\nCompilation failed in require at /opt/otrs/bin/cgi-bin/installer.pl line 25.\nBEGIN failed--compilation aborted at /opt/otrs/bin/cgi-bin/installer.pl line 25.\n
[Thu Apr 20 22:21:48.280174 2017] [:error] [pid 2726] Cannot find current script '/opt/' at /usr/share/perl5/FindBin.pm line 166.\nBEGIN failed--compilation aborted at /usr/share/perl5/FindBin.pm line 166.\nCompilation failed in require at /opt/otrs/bin/cgi-bin/installer.pl line 25.\nBEGIN failed--compilation aborted at /opt/otrs/bin/cgi-bin/installer.pl line 25.\n
[Thu Apr 20 22:58:25.283392 2017] [autoindex:error] [pid 2724] [client 64.62.178.49:52639] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive

A: I didn't figure out what was wrong exactly but it concerned specifying mod24_perl. This install works on Amazon Linux:

*

*sudo yum -y install --nogpgcheck otrs-5.0.18-01.noarch.rpm

*sudo yum install -y "perl(Crypt::Eksblowfish::Bcrypt)" "perl(JSON::XS)" "perl(GD::Text)" "perl(Encode::HanExtra)" "perl(GD::Graph)" "perl(Mail::IMAPClient)" "perl(PDF::API2)" "perl(Text::CSV_XS)" "perl(YAML::XS)" "perl(DBD::mysql)"
I thought I had attempted an install like this in the beginning but must have misconfigured something then.


text:
Q: how the set glyph names in virtual fonts I have created a virtual font which contains some non-standard characters (made up of superimposed characters from other fonts).  I would like to use the pdftex command \pdfglyphtounicode to make pasting from generated pdf files work.  This command needs a "glyph name" as the first argument.
How can I set the glyphname for my new characters?
For example, one of my character is at index 65, so TeX thinks it is an "A".  But I cannot use \pdfglyphtounicode{a}{0102}, say, because this would damage all the regular "a" in my text.

A: In the PDF it makes no difference whether the input is via a virtual file or via explicit characters and kerns in the source. You can not use \pdfglyphtounicode as that works at the font level and in the PDF there are two characters, however you can use the ActualText feature and tag the range with a suitable replacement,
\documentclass{article}

\begin{document}

a Ț b

\end{document}

looks like

but if you cut and paste the inputenc faking if the T-comma becomes apparent, and you get
a T, b

However you can mark the region using accsupp:
\documentclass{article}

\usepackage{accsupp}

\begin{document}

a \BeginAccSupp{method=hex,unicode,ActualText={021A}}Ț\EndAccSupp{} b

\end{document}

The visual output looks the same, but now cut and paste produces
a Ț b

with a U+021A character.
Rather than putting \BeginAccSupp in the document you could modify the definition
\DeclareUnicodeCharacter{021A}{\textcommabelow T}

and add the accsupp markup to the last argument.
You could also place the equivalent construct in the vf definition for the character when using a virtual font.


text:
Q: ImportError: DLL load failed while importing module I'm trying to run the code I downloaded from this site: http://deeplearning.net/tutorial/lstm.html
and when I try to run it, it says
model options {'dim_proj': 128, 'patience': 10, 'max_epochs': 100, 'dispFreq': 10, 'decay_c': 0.0, 'lrate': 0.0001, 'n_words': 10000, 'optimizer': <function adadelta at 0x2043DC40>, 'encoder': 'lstm', 'saveto': 'lstm_model.npz', 'validFreq': 370, 'saveFreq': 1110, 'maxlen': 100, 'batch_size': 16, 'valid_batch_size': 64, 'dataset': 'imdb', 'noise_std': 0.0, 'use_dropout': True, 'reload_model': None, 'test_size': 500}
Loading data
Building model
Traceback (most recent call last):
  File "C:\Users\KaguyaHour\Desktop\PythonBin\lstm.py", line 661, in <module>
    train_lstm(
  File "C:\Users\KaguyaHour\Desktop\PythonBin\lstm.py", line 517, in train_lstm
    y, f_pred_prob, f_pred, cost) = build_model(tparams, model_options)
  File "C:\Users\KaguyaHour\Desktop\PythonBin\lstm.py", line 395, in build_model
    proj = dropout_layer(proj, use_noise, trng)
  File "C:\Users\KaguyaHour\Desktop\PythonBin\lstm.py", line 84, in dropout_layer
    trng.binomial(state_before.shape,
  File "C:\Python3\lib\site-packages\theano\sandbox\rng_mrg.py", line 901, in binomial
    x = self.uniform(size=size, nstreams=nstreams, **kwargs)
  File "C:\Python3\lib\site-packages\theano\sandbox\rng_mrg.py", line 872, in uniform
    rstates = self.get_substream_rstates(nstreams, dtype)
  File "C:\Python3\lib\site-packages\theano\configparser.py", line 117, in res
    return f(*args, **kwargs)
  File "C:\Python3\lib\site-packages\theano\sandbox\rng_mrg.py", line 779, in get_substream_rstates
    multMatVect(rval[0], A1p72, M1, A2p72, M2)
  File "C:\Python3\lib\site-packages\theano\sandbox\rng_mrg.py", line 61, in multMatVect
    multMatVect.dot_modulo = function(
  File "C:\Python3\lib\site-packages\theano\compile\function.py", line 306, in function
    fn = pfunc(params=inputs,
  File "C:\Python3\lib\site-packages\theano\compile\pfunc.py", line 483, in pfunc
    return orig_function(inputs, cloned_outputs, mode,
  File "C:\Python3\lib\site-packages\theano\compile\function_module.py", line 1841, in orig_function
    fn = m.create(defaults)
  File "C:\Python3\lib\site-packages\theano\compile\function_module.py", line 1714, in create
    _fn, _i, _o = self.linker.make_thunk(
  File "C:\Python3\lib\site-packages\theano\gof\link.py", line 697, in make_thunk
    return self.make_all(input_storage=input_storage,
  File "C:\Python3\lib\site-packages\theano\gof\vm.py", line 1087, in make_all
    thunks.append(node.op.make_thunk(node,
  File "C:\Python3\lib\site-packages\theano\gof\op.py", line 954, in make_thunk
    return self.make_c_thunk(node, storage_map, compute_map,
  File "C:\Python3\lib\site-packages\theano\gof\op.py", line 857, in make_c_thunk
    outputs = cl.make_thunk(input_storage=node_input_storage,
  File "C:\Python3\lib\site-packages\theano\gof\cc.py", line 1215, in make_thunk
    cthunk, module, in_storage, out_storage, error_storage = self.__compile__(
  File "C:\Python3\lib\site-packages\theano\gof\cc.py", line 1153, in __compile__
    thunk, module = self.cthunk_factory(error_storage,
  File "C:\Python3\lib\site-packages\theano\gof\cc.py", line 1623, in cthunk_factory
    module = get_module_cache().module_from_key(
  File "C:\Python3\lib\site-packages\theano\gof\cmodule.py", line 1189, in module_from_key
    module = lnk.compile_cmodule(location)
  File "C:\Python3\lib\site-packages\theano\gof\cc.py", line 1520, in compile_cmodule
    module = c_compiler.compile_str(
  File "C:\Python3\lib\site-packages\theano\gof\cmodule.py", line 2420, in compile_str
    return dlimport(lib_filename)
  File "C:\Python3\lib\site-packages\theano\gof\cmodule.py", line 317, in dlimport
    rval = __import__(module_name, {}, {}, [module_name])
ImportError: DLL load failed while importing m75022cac696dc858984a7c4467166cc6915405b19d04c2580f5acf71c834d9de: The specified module could not be found.[Finished in 9.9s]

So this "m75022cac696dc858984a7c4467166cc6915405b19d04c2580f5acf71c834d9de" makes me wonder what type of dll is that... Any help would be appreciated.

A: Since it is unanswered until now, I was having a similar problem running training with Theano on Jupyter Notebook on Win10, as I was installing packages with pip.
The solution for me was installing Theano with conda install theano, that installed all kinds of additional packages which made Theano work in the end. I used the same Jupyter Notebook on Ubuntu Google Cloud VM, and I didnt have to solve this problem.


text:
Q: How to open the application its settings with nativescript on both Android and IOS? I would like to know how you can open the app settings page on both ios and android.

A: Change org.nativescript.app with your app's package id.
import { Application, isAndroid } from '@nativescript/core';

const openAppSetting = async () => {
  if(isAndroid) {
    var activity = Application.android.foregroundActivity || Application.android.startActivity

    activity.startActivity(new android.content.Intent(
      android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
      android.net.Uri.fromParts("package", "org.nativescript.app", '')
    ))
  } else {
    UIApplication.sharedApplication.openURL(NSURL.URLWithString(UIApplicationOpenSettingsURLString));
  }
}

export {
  openAppSetting
}


text:
Q: move nodes on a treeview control I am using the standard asp.net treeview control to display a menu structure that is getting bound from a database. The data structure has a parentID column to represent the node relationship if one exists.
Anyway, that's not an issue, I am looking for a treeview control that would allow a user to rearrange the node by dragging them to a new position within the tree. Can anyone point me in the right direction as to any controls out there that can do this? The windows form control has the move node events. IS there something like this for web forms? Any pointers greatly appreciated.

A: Why not try the JQuery TreeView plug-in?
http://plugins.jquery.com/project/treeview
Not sure if meets all of your non-functional requirements, but if you click on the "Try out a demonstration" link, you should be able to see if it meets your needs.

A: You can have look at ExtJS TreePanel.
Drag and Drop ordering in a TreePanel


text:
Q: iron-router choose different subscriptions in waitOn function - Meteor I want to decide based on a boolean attribute in a document (mode), which subscriptions the user gets, but I have problems with the design approach. If I use this.data() and a if clause in the waitOn function, I will get the 404 page rendered, because I need first the subscription.
Here is my code:
this.route('gamePage', {
        path: '/game/:slug/viewGame/:produceDate?/:releaseDate?',
        onBeforeAction: [memberFilter],
        waitOn: function() {
            var game = this.data();
            if (game.mode) {
                if (this.params.produceDate && this.params.releaseDate) {
                    return [Meteor.subscribe('singleGame', this.params.slug),
                        Meteor.subscribe('authorsMode', this.params.slug, this.params.produceDate, this.params.releaseDate)];
                } else {
                    return [Meteor.subscribe('singleGame', this.params.slug), Meteor.subscribe('console', this.params.slug)];
                }
            } else {
                return [Meteor.subscribe('singleGame', this.params.slug),
                    Meteor.subscribe('authors', this.params.slug)];

            }
        },
        data: function() {
            return Games.findOne({slug: this.params.slug});
        }

Any help would be greatly appreciated.

A: To achieve that directly you would need Iron Router to let you have 2 levels of subscriptions, the first one making data available to the next level of subscription. This feature doesn't exist right now. I've just submitted an issue to IR repo asking for this feature.
The workaround for this is having different URL for each case, making intermediate redirections:
this.route('gamePage', {
  path: '/game/:slug/viewGame/:produceDate?/:releaseDate?',
  onBeforeAction: function() {
    var game = this.data();
    var params = {
      slug: this.params.slug,
      produceDate: this.params.produceDate,
      releaseDate: this.params.releaseDate
    }
    if (game.mode) {
      if (this.params.produceDate && this.params.releaseDate) {
        this.redirect('gamePageOption1', params);
      } else {
        this.redirect('gamePageOption2', params);
      }
    } else {
      this.redirect('gamePageOption3', params);
    }
  },
  waitOn: function() {
      return [Meteor.subscribe('games')];
  },
  data: function() {
      return Games.findOne({slug: this.params.slug});
  }
}

If you are using IR v < 0.9.3 be aware of an issue about intermediate redirections: ref1, ref2. If this is the case, you have to the redirection inside a Meteor.defer:
Meteor.defer(function() {
    this.redirect(...)
})


text:
Q: how a django reusable apps can initialize itself? I'm creating a django app as a python package , almost similar to django-tinymce
interesting point about django-tinymce is that every time I restart my web server , for example I run :
python manage.py runserver

somehow automatically  a settings.py file inside django-tinymce start running.
how is this possible ?
I just add tinymce in the INSTALLED_APPS and nothing else but the code inside python2.7/site-packages/tinymce/settings.py starts running and do a few initialization operations every time I restart my web server or run any manage.py command.

A: Such initialisation code is often put in the models.py which is run by Django at start or restart.
In this example app it is just a matter of imports run - models.py imports widgets and widgets import settings.

A: As django 1.7 each app can contain an app.py file to do any initialization it needs to do.
Imagine we have a app called profile.In your app directory create an apps.py like this :
#apps.py
from django.apps import AppConfig
class ProfileConfig(AppConfig):
     name = "profiles"
     verbose_name = 'User Profiles'
     def ready(self):
         #do what ever you want

One more step to complete this behavior is to specify default_app_config
Which should happened in init.py of your app :
# profile/__init__.py
default_app_config = 'profile.apps.ProfileConfig'

This behavior can be used in many usecases including : changing project settings,registering signal handlers
More details can be found in Django 1.7 release notes and Django docs:Applications


text:
Q: population structure by memory address in C i am having a problem while populating the structure members with address reference but when it is done using the member it self then its fine.
with structure memmber
memcpy(&(AVPFieldStructureObj->resource_value),data_start,actual_data_length);

With Memory Address
memcpy((&AVPFieldStructureObj+fieldOffset),data_start,actual_data_length);

where actual_data_length is the size of varibale and data_start is pointer pointing to the data buffer.
with memory its giving garbage value when i print the field and after executing the whole i am getting a segmentation fault but when debug with GDB the program exited normally.there was no segmentation fault
please suggest
Thanks in advance
Regards,
Soheb

A: I believe fieldOffset is the offset in bytes?
If you're doing something like:
Type* pointer = somewhere;
pointer += 3;

then pointer gets moved forward by 3*sizeof(Type) bytes - so 3 Type objects forward.
So in your code, in the latter variant, you're not offsetting the address by fieldOffset bytes, but by fieldOffset*sizeof(AVPFieldStructureObj) bytes.
You can work around that by casting to the pointer to char* temporarily.


text:
Q: Ionic InAppBrowser not working how to open external link from a ng-repeat.
I already tried different combinations but not external window opens.
when I put just one link it works but when I use expressions {{event.lermais}} to open links does not work.
this is my code:

 <ion-item class="item-text-wrap item-icon-right" ng-repeat="event in events.data.results">

 </ion-item>

I'm using Android

A: HTML
ng-click ="openLink(event.lermais)"

Controller
$scope.openLink= function(url){
     window.open(url, "_blank", "location=yes");
}

Its a cakewalk.

A: you can do that bu using following eg-

    {{menu.title}}

this might work for you.


text: Q: Where is Html property defined in asp.net core razor pages or mvc We can use @Html to generate html directly in razor markup files. But I can't where this Html property is defined. Could anyone help me? Appreciate help in advance.


text:
Q: Conjugate upto isomorphism Let $V= \{1,2,3,\cdots, n\}$ is a vertex set and Sym$(V)$ is a symmetric group. Let $G \le $ Sym$(V)$, i.e. subgroup of Sym$(V)$. Now
$$H= Sym(V_0^{\sigma}) \times Sym(V_1^{\sigma}) \cdots \times Sym(V_n^{\sigma}) $$
where $\sigma \in$ Sym$(V)$ and $V_i$ means set of vertices of degree $i.$
My question : What is a relationship between $G$ and $\sigma^{-1}H\sigma$ ? To me it appears that they are conjugate to each other upto isomorphism.
Second question : Is it true that $x^g = x^{\sigma^{-1}g_1 \sigma}$, where $g \in G$ and $g_1 \in H$ ?

A: In chat you explain that $V_i^{\sigma}$ is supposed to be the image of $V_i$ under the function $\sigma_i$. This is contrary to standard notation in the context of group actions: the standard notation is $gX$ for the image of $X$ under $g$, and $X^g$ for the set of fixed points of $g$ in $X$.
The question is nonsense without saying what $G$ is. Indeed, the obvious interpretation is to say $G$ is the automorphism group of the graph. ($V$ is the vertex set of some graph.)
In this case, since graph automorphisms preserve vertex degree, we must have
$$ G\subseteq \mathrm{Sym}(V_0)\times\mathrm{Sym}(V_1)\times\cdots\times\mathrm{Sym}(V_n)\subseteq\mathrm{Sym}(V) $$
where the product is internal (so $\mathrm{Sym}(V_i)$ is the subgroup of $\mathrm{Sym}(V)$ of permutations whose support is contained in the complement $V\setminus V_i$).
Then
$$ \begin{array}{lcccccccc} H & = &  \mathrm{Sym}(\sigma V_0)~ & \times &  \mathrm{Sym}(\sigma V_1)~ & \times & \cdots & \times & \mathrm{Sym}(\sigma V_n)~ \\ & = & \sigma \mathrm{Sym}(V_0)\sigma^{-1} & \times & \sigma\mathrm{Sym}(V_1)\sigma^{-1} & \times & \cdots & \times & \sigma\mathrm{Sym}(V_n)\sigma^{-1} \end{array} $$
$$ =\sigma\big(\,\mathrm{Sym}(V_0)\times\mathrm{Sym}(V_1)\times\cdots\times\mathrm{Sym}(V_n)\, \big)\sigma^{-1} $$
contains $\sigma G\sigma^{-1}$. This containment follows from conjugating $G\subseteq\prod_i \mathrm{Sym}(V_i)$ by $\sigma$.
Note the containment is proper unless $G=\prod_i\mathrm{Sym}(V_i)$, which pretty much never happens.


text:
Q: how to allocate a block of memory in ANSI C and then ON their all bits i just want to allocate a block of memory for int type and set all bits to  ON(1) after that how can i read that block of memory back.

A: int *type = malloc(sizeof(int);
memset(type,~0,sizeof(int));

Reading back is nothing but,
int value = *type;

And value has all bits set to 1.


text:
Q: initWithNibName .... method not firing In my navigation based application, initWithNibName method does not called/fire
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

I'm defining rootViewController (calViewController) in appdelegate like this
calViewController *objCalViewController = (calViewController *) [navController topViewController];

objCalViewController.context = [self managedObjectContext];

[window addSubview:navController.view];
[window makeKeyAndVisible];

Is this is the issue? Please give me a help

A: When your UIViewController is defined in a nib file or Storyboard (usually as an IBOutlet), initWithNibName:bundle: is not called, rather initWithCoder: is. This is the case when you use Interface Builder to set your UIViewController as part of UITabBarController or  UINavigationController, and almost always when using Storyboards.

A: in your appdelegate.m do like this
calViewController *objCalViewController = [[calViewController alloc] initWithNibName:@"WebViewController_iPhone" bundle:nil];
objCalViewController.managedObjectContext = self.managedObjectContext;
navController = [[UINavigationController alloc] initWithRootViewController:objCalViewController];
[self.window setRootViewController:navController];
[window makeKeyAndVisible];

A: Ok lets say i have a viewController named TCViewController with
TCViewController.h, TCViewController.m and TCViewController.xib

and in TCViewController.m
i am overriding the below method.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
       // Custom initialization
   }
   return self;
}

In my RootViewController i want to initialize TCViewController like this
RootViewController.m
-(void)viewDidLoad //not necessarily this one, can be any method
{
 // This initialization calls the initWithNibname method implemented in TCViewController.m
TCViewController *viewController  = [[TCViewController alloc] initWithNibName:@"TCViewController" bundle:nil];

[self.navigationController pushViewController:viewController animated:YES];

}

If you initialize a viewController like this, control will pass to the initWithNibName method in your subclass if you have implemented it.


text:
Q: Problems with CSS multicolumn with tiled background image I'd like to make a carousel-type scrolling horizontal card view using CSS multicol with column-width, and use a repeating background (such as a white background with a black border) on the element, but I'm having problems.
The first problem is the background does not tile horizontally past the page width. If I set a width on the multicol element the background repeats to that extent, but that interferes with the natural width.
The second problem is the column widths change when I horizontally resize the window. I can tell it's trying to tile the columns in a pretty way but I need the widths not to do that or my background gets out of sync.

.holder {
  overflow-x: scroll;
  position: relative;
}

.columns {
  column-width: 100px;
  height: 200px;
  column-rule: 10px solid rgba(0, 0, 250, 0.2);
  background-repeat: repeat-x;
  background-size: 120px 200px;
  background-image:
    linear-gradient(90deg, red 95px, transparent 50%),
    linear-gradient(white 5px, transparent 100%);
}

    Tons Of Text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid igitur dubitamus in tota eius natura quaerere quid sit effectum? Ne in odium veniam, si amicum destitero tueri. Disserendi artem nullam habuit. Nam his libris eum malo quam reliquo
    ornatu villae delectari. Illud quaero, quid ei, qui in voluptate summum bonum ponat, consentaneum sit dicere. Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis? Quaero igitur, quo modo hae tantae commendationes
    a natura profectae subito a sapientia relictae sint. Beatus autem esse in maximarum rerum timore nemo potest. Utram tandem linguam nescio? Eam si varietatem diceres, intellegerem, ut etiam non dicente te intellego; Recte, inquit, intellegis. Consequentia
    exquirere, quoad sit id, quod volumus, effectum. Dat enim intervalla et relaxat. Tum Torquatus: Prorsus, inquit, assentior; Qui enim existimabit posse se miserum essudicio aut, si coronam times, dic in senatu. Etenim semper illud extra est, quod arte
    comprehenditur. Quid ei reliquisti, nisi te, quoquo modo loqueretur, intellegere, quid diceret? Itaque a sapientia praecipitur se ipsam, si usus sit, sapiens ut relinquat. Quos quidem tibi studiose et diligenter tractandos magnopere censeo. Quo plebiscito
    decreta a senatu est consuli quaestio Cn. Quid ergo attinet dicere: Nihil haberem, quod reprehenderem, si finitas cupiditates haberent? Aliena dixit in physicis nec ea ipsa, quae tibi probarentur; Refert tamen, quo modo. Quis negat? Quamquam tu hanc
    copiosiorem etiam soles dicere. Sed haec quidem liberius ab eo dicuntur et saepius. Respondeat totidem verbis. Re mihi non aeque satisfacit, et quidem locis pluribus. Expressa vero in iis aetatibus, quae iam confirmatae sunt. Aliter homines, aliter
    philosophos loqui putas oportere? An hoc usque quaque, aliter in vita? Sin dicit obscurari quaedam nec apparere, quia valde parva sint, nos quoque concedimus; Ego quoque, inquit, didicerim libentius si quid attuleris, quam te reprehenderim. Quantum
    Aristoxeni ingenium consumptum videmus in musicis? Illud non continuo, ut aeque incontentae. Tanta vis admonitionis inest in locis; Sed ad haec, nisi molestum est, habeo quae velim. Te ipsum, dignissimum maioribus tuis, voluptasne induxit, ut adolescentulus
    eriperes P. Facit enim ille duo seiuncta ultima bonorum, quae ut essent vera, coniungi debuerunt; Nummus in Croesi divitiis obscuratur, pars est tamen divitiarum. Quae cum praeponunt, ut sit aliqua rerum selectio, naturam videntur sequi; Duo Reges:
    constructio interrete. Audeo dicere, inquit. Semper enim ita adsumit aliquid, ut ea, quae prima dederit, non deserat. Huius, Lyco, oratione locuples, rebus ipsis ielunior. Sin te auctoritas commovebat, nobisne omnibus et Platoni ipsi nescio quem illum
    anteponebas? Sed tu istuc dixti bene Latine, parum plane. Respondent extrema primis, media utrisque, omnia omnibus. Quid ei reliquisti, nisi te, quoquo modo loqueretur, intellegere, quid diceret? Paulum, cum regem Persem captum adduceret, eodem flumine
    invectio? Nec vero alia sunt quaerenda contra Carneadeam illam sententiam. Tu autem, si tibi illa probabantur, cur non propriis verbis ea tenebas?

A: Although there are still bugs I'm tracking down in Safari involving the CSS --variables, I feel I have been able to find an answer to the question! Try it for yourself.

  :root {
   --colwidth: 120px;
   --colcount: 30;
   }

  .holder {
   overflow: scroll;
   position: relative;
   width: 360px; width: calc(var(--colwidth) * 3);
   xbackground: gray;
   word-wrap: break-word;
   border: thin solid gray;
   }
  .columns {
   position: relative;
   display: inline-block;
   column-width: 110px; column-width: calc(var(--colwidth) - 10px); /* this is really minimum width, it rounds up to the next 1/3, 1/2, etc of the holder */
   height: 200px;
   column-rule: 10px solid rgba(0,0,250,0.2); /* does not affect gap size, is centered on it instead */
   column-fill: auto;
   column-gap: 0px; /* seems to change the column width too, what the hell is the formula? soemthing to do with the holder*/
   }
  .columns:before {
   content: ""; position: absolute; left: 0px; top: 0px; bottom: 0px;;

   width: calc(var(--colcount) * var(--colwidth));
   z-index: -1;

   background: orange;
   background-position: 0 0;
   background-repeat: repeat-x;
   background-size: var(--colwidth) 100%;
   background-image: linear-gradient(90deg, red 33%, transparent 66%), linear-gradient(white 0%, transparent 100%);
  }
  .end { }
  .text {
   padding-left: 10px;
   padding-right: 10px;
  }
<button onclick="document.documentElement.style.setProperty('--colwidth', prompt('new width (120px, 10em, 30vw, etc)'));">Change column width</button>

<button onclick="document.documentElement.style.setProperty('--colcount', Math.ceil((document.querySelector('.end').getBoundingClientRect().right - document.querySelector('.columns').getBoundingClientRect().x)/120))">Make .end the last backgrounded column</button>

      Tons Of Text: .....................................Periods Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid igitur dubitamus in tota eius natura quaerere quid sit effectum? Ne in odium veniam, si amicum destitero tueri. Disserendi artem nullam
      habuit. Nam his libris eum malo quam reliquo ornatu villae delectari. Illud quaero, quid ei, qui in voluptate summum bonum ponat, consentaneum sit dicere. Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?
      Quaero igitur, quo modo hae tantae commendationes a natura profectae subito a sapientia relictae sint. Beatus autem esse in maximarum rerum timore nemo potest. Utram tandem linguam nescio? Eam si varietatem diceres, intellegerem, ut etiam non dicente
      te intellego; Recte, inquit, intellegis. Consequentia exquirere, quoad sit id, quod volumus, effectum. Dat enim intervalla et relaxat. Tum Torquatus: Prorsus, inquit, assentior; Qui enim existimabit posse se miserum esse beatus non erit. Eorum enim
      omnium multa praetermittentium, dum eligant aliquid, quod sequantur, quasi curta sententia; Quis istud possit, inquit, negare? Scio enim esse quosdam, qui quavis lingua philosophari possint; Neutrum vero, inquit ille. Idem iste, inquam, de voluptate
      quid sentit? Quid ait Aristoteles reliquique Platonis alumni? Uterque enim summo bono fruitur, id est voluptate. Omnia contraria, quos etiam insanos esse vultis. Inde igitur, inquit, ordiendum est. At tu eadem ista dic in iudicio aut, si coronam
      times, dic in senatu. Etenim semper illud extra est, quod arte comprehenditur. Quid ei reliquisti, nisi te, quoquo modo loqueretur, intellegere, quid diceret? Itaque a sapientia praecipitur se ipsam, si usus sit, sapiens ut relinquat. Quos quidem
      tibi studiose et diligenter tractandos magnopere censeo. Quo plebiscito decreta a senatu est consuli quaestio Cn. Quid ergo attinet dicere: Nihil haberem, quod reprehenderem, si finitas cupiditates haberent? Aliena dixit in physicis nec ea ipsa,
      quae tibi probarentur; Refert tamen, quo modo. Quis negat? Quamquam tu hanc copiosiorem etiam soles dicere. Sed haec quidem liberius ab eo dicuntur et saepius. Respondeat totidem verbis. Re mihi non aeque satisfacit, et quidem locis pluribus. Expressa
      vero in iis aetatibus, quae iam confirmatae sunt. Aliter homines, aliter philosophos loqui putas oportere? An hoc usque quaque, aliter in vita? Sin dicit obscurari quaedam nec apparere, quia valde parva sint, nos quoque concedimus; Ego quoque, inquit,
      didicerim libentius si quid attuleris, quam te reprehenderim. Quantum Aristoxeni ingenium consumptum videmus in musicis? Illud non continuo, ut aeque incontentae. Tanta vis admonitionis inest in locis; Sed ad haec, nisi molestum est, habeo quae
      velim. Te ipsum, dignissimum maioribus tuis, voluptasne induxit, ut adolescentulus eriperes P. Facit enim ille duo seiuncta ultima bonorum, quae ut essent vera, coniungi debuerunt; Nummus in Croesi divitiis obscuratur, pars est tamen divitiarum.
      Quae cum praeponunt, ut sit aliqua rerum selectio, naturam videntur sequi; Duo Reges: constructio interrete. Audeo dicere, inquit. Semper enim ita adsumit aliquid, ut ea, quae prima dederit, non deserat. Huius, Lyco, oratione locuples, rebus ipsis
      ielunior. Sin te auctoritas commovebat, nobisne omnibus et Platoni ipsi nescio quem illum anteponebas? Sed tu istuc dixti bene Latine, parum plane. Respondent extrema primis, media utrisque, omnia omnibus. Quid ei reliquisti, nisi te, quoquo modo
      loqueretur, intellegere, quid diceret? Paulum, cum regem Persem captum adduceret, eodem flumine invectio? Nec vero alia sunt quaerenda contra Carneadeam illam sententiam. Tu autem, si tibi illa probabantur, cur non propriis verbis ea tenebas?

    <button class=end onclick="alert('I am in column ' + Math.ceil((document.querySelector('.end').getBoundingClientRect().right - document.querySelector('.columns').getBoundingClientRect().x)/120));">end</button>


text:
Q: ListView doesn't display data in xamarin I am new to xamarin and trying to display a listview. My attempt is as follows.
<ContentPage.Content>
    <StackLayout>
        <ListView x:Name="ComListView" RowHeight="80">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <Grid Margin="8">
                                <Label Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="2" Text="hello world" FontAttributes="Bold"  />
                            </Grid>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

But when I ran the app, even I navigate to correct page; nothing display. For any other views, it will display the right output. So where could I get wrong on the listview?

A: You have to put items to the ListView. Currently, you only specify the ItemTemplate, which determines how an item will look (in your case, they will all look the same (i.e. Labels with 'hello world' text)). But the ListView is empty and so there are no items to show.
You can set items using the ItemsSource property of the ListView.
Usually, you use Binding inside an ItemTemplate to show item content.
Let's say we have a class Person:
class Person
{
    public string Name { get; set; }
}

Then you create a List of Person objects and add it to your ListView in code:
var personnel = new List<Person>
{
    new Person { Name = "Booker" },
    new Person { Name = "Elizabeth" }
};

ComListView.ItemsSource = personnel;

And in your XAML, you have to set the ItemTemplate so that it shows the Name of each Person:
<Label Text="{Binding Name, Mode=OneWay}" />

Note: You can also bind to ItemsSource from XAML if you have a ViewModel.

A: You are not binding the data to the listview.
use the ItemSource property to bind data, either from xaml, code behind or use a binding to populate from your ViewModel


text:
Q: Can we use "consumptions" in this case?
It is clear that the consumptions of beef, lamb and fish declined over
  a 5-year period.

I would like to ask that is it grammatically correct to use "consumption" as plural noun (consumptions) in order to mean: the consumption of beef, the consumption of lamb and the consumption of fish?
I know that consumption is an uncountable noun which is not supposed to be used as a plural form, but I still feel somewhat wrong to use just "consumption" to describe 3 objects.
Which one do you think is correct in the case above: "consumption" or "consumptions"?

A: The singular form is more idiomatic. If you want to avoid the issue, you can reword it, such as saying "The amount of beef, lamb and fish consumed declined over a 5-year period" or "Consumption levels of beef, lamb and fish declined over a 5-year period".
Another issue to consider is whether you're claiming that the total amount declined, or that each amount declined individually. If the former, then you definitely should use the singular. If the latter, you would need to reword it if you wanted to make it clear. You can do that by using a plural term such as my "consumption levels" example, or by using "each", e.g. "It is clear beef, lamb and fish each declined in amount consumed over a 5-year period.

A: Consumption usually appears as a singular collective to mean generally to use a resource and especially to ingest food. The plural consumptions is found but is quite rare, its uses far less than 1% of the singular form consumption, even taking into account that the latter is an old-fashioned name for tuberculosis. The plural occurs in two settings, the first when the things consumed are disparate.
From Energy Pricing in India by H Sarkar and G K Kadekodi (1988):

Second, while primary energy consumptions (consisting of solid fuels, oil, gas, nuclear and hydropowers) have increased both on per capita and GNP basis, the non-commercial energy consumptions (consisting of firewood, agricultural waste, animal dung etc.) declined between the same period.

The second, when the consumers are distinct:
From Wild Otters: Predation and Populations by H Kruuk (1995):

Wayre (1979) weighed the food for two captives [otters] over 1 week, and found daily consumptions of 12.2 and 12.8 per cent of body weight.

The plural is also employed to distinguish between what is being consumed and who is doing consuming. From Opinions and Decisions of the Railroad Commission of Wisconsin (1980):

The application of the proposed lighting schedules to the 1924 consumptions of lighting customers indicates that these schedules will produce about 10 per cent more total revenues than the schedules now in effect.

The singular could lead to the interpretation that it was lighting customers who were being used every day to produce the lighting.
You'll have to decide for yourself whether beef, lamb, and fish are sufficiently different as foodstuffs to warrant the plural or whether they are sufficiently alike as comestibles to stick with the singular.