text:
Q: Is it possible to extend WebMvcConfigurationSupport and use WebMvcAutoConfiguration? I need to extend the WebMvcConfigurationSupport class too modify two things:
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setRemoveSemicolonContent(false);
        handlerMapping.setOrder(1);
        return handlerMapping;
    }
}

I like the defaults that are registered from the WebMvcAutoConfiguration class but due to the conditional annotation on the class, when I extend the WebMvcConfigurationSupport class it prevents the auto configuration from happening.
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
    WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class WebMvcAutoConfiguration {...}

Is there to have the WebMvcAutoConfiguration class load without having to essentially copy/paste most of the code in that class?
Or is it possible to call RequestMappingHandlerMapping setOrder() and setRemoveSemicolonContent() from somewhere else so I can just use the @EnableWebMvc annotation and have the autoconfiguration class run without any issues?
Thanks in advance!

A: I managed to customize the RequestMappingHandlerMapping while keeping WebMvcAutoConfiguration using a BeanPostProcessor:
@Configuration
public class RequestMappingConfiguration {
    @Bean
    public RequestMappingHandlerMappingPostProcessor requestMappingHandlerMappingPostProcessor() {
        return new RequestMappingHandlerMappingPostProcessor();
    }

    public static class RequestMappingHandlerMappingPostProcessor implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof RequestMappingHandlerMapping) {
                ((RequestMappingHandlerMapping) bean).setUseSuffixPatternMatch(false);
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }
}

I would be happy if Spring Boot provides a better way to handle that... maybe something could be done around PathMatchConfigurer ?

A: Your analysis is correct (@EnableWebMvc or directly extending WebMvcConfigurationSupport will switch off the WebMvcAutoConfiguration). I'm not sure what the alternative is, since a) we need a "get-out" clause for the autoconfig, and b) I don't think Spring likes to have two WebMvcConfigurationSupports in the same context. Happy to discuss on github if you want to try and find a way to change it (there might be some middle ground).

A: Extend from DelegatingWebMvcConfiguration instead of WebMvcConfigurationSupport, it will not prevent the autoconfig to take place:
@Configuration
public class WebConfig extends DelegatingWebMvcConfiguration {
    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setRemoveSemicolonContent(false);
        handlerMapping.setOrder(1);
        return handlerMapping;
    }
}

A: I think the best way to do this in Spring Boot now is to add a WebMvcRegistrations component to your context - this solution didn't exist at the time of your question (it's been available since Spring Boot 1.4.0).


text:
Q: How to improve quality of this Plot3D I tried driving up PlotPoints and MaxRecursion but the intersections look weird, is there some other trick I can do?
plot = Plot3D @@ {Abs[Sqrt[x] + Sqrt[y]] /. {x -> Sin[2 x],
     y -> Cos[2 y]}, {x, -2, 2}, {y, -2, 2},
   PlotPoints -> 200, MeshFunctions -> {#3 &}, Mesh -> 15,
   MaxRecursion -> 6, Ticks -> None}

A: The funny color the OP points out is the lighting effect that arises from a sharp-corner-like singularities in the surface. The discretization causes some polygons to bridge a sharp corner and reflect the light in a different way than its neighbor polygons. Added: In particular, the recursive subdivision algorithm of Plot3D causes adjacent polygons to have different angles.  Nasser's ListPlot approach has the same problem with bridging the corner, but it has a regular and very fine mesh aligned with the singularities: the mesh gives the singularities a regular appearance along their paths. The ListPlot approach also uses almost 50 times the memory than the method below on the OP's example.
It's too bad the *Plot* functions do not have a way of specifying and treating singular points as NIntegrate does.  For a plot with a tensor-product-like structure in the OP's post, all it would take is to specify the singular x values and singular y values to have the plot restart at these boundary points.
Here's a way to accomplish something like that by dividing the plot region into subrectangles.  Plot3D has a lot of automatic processing, and coordinating the subplots will require some tweaking.  For instance, the Mesh is computed based on the PlotRange of each subplot.  Therefore you have to manually specify Mesh. (One could make this automatic by computing the plot twice, once to determine the mesh range and specs, and again with the proper mesh specification.)
ClearAll[plot3D];
SetAttributes[plot3D, HoldAll];
plot3D[f_, {x_, x0__}, {y_, y0__}, opts : OptionsPattern[Plot3D]] :=
 Show[
  Plot3D[f, {x, #[[1, 1]], #[[1, 2]]}, {y, #[[2, 1]], #[[2, 2]]}, opts] & /@
   Flatten[  (* Partition into rectangles *)
    Outer[List,
     Partition[SortBy[{x0}, N], 2, 1],
     Partition[SortBy[{y0}, N], 2, 1],
     1],
    1],
  PlotRange -> (OptionValue[PlotRange] /. Automatic -> All)
  ]

(* compute the singular values of x and y *)
sing = With[{s =
    Simplify`FunctionSingularities[
     Abs[Sqrt[x] + Sqrt[y]] /. {x -> Sin[2 x], y -> Cos[2 y]},
     {x, y}, {"ALL"}]},
  Merge[
   Cases[Flatten[
     Quiet@Simplify[
       Solve[# && -2 < x < 2 && -2 < y < 2, {x, y}, Reals] & /@
        Or @@@ Apply[And, s, {2}], -2 < x < 2 && -2 < y < 2]],
    sol : Verbatim[Rule][x | y, _] :> <|sol|>],
   Join]
  ]
(*  <|x -> {0, -(π/2), π/2}, y -> {-(π/4), π/4}|>  *)

(* plot the OP's graph *)
plot3D @@ {Abs[Sqrt[x] + Sqrt[y]] /. {x -> Sin[2 x], y -> Cos[2 y]},
  Flatten@{x, -2, sing[x], 2}, Flatten@{y, -2, sing[y], 2},
  MeshFunctions -> {#3 &}, Mesh -> {Subdivide[0., 2., 15 + 1]},
  Ticks -> Automatic, PlotRange -> All}

A: Increase the MaxRecursion and use the WorkingPrecision option
plot = Plot3D @@ {Abs[Sqrt[x] + Sqrt[y]] /. {x -> Sin[2 x],
     y -> Cos[2 y]}, {x, -2, 2}, {y, -2, 2}, PlotPoints -> 200,
   MeshFunctions -> {#3 &}, Mesh -> 15, MaxRecursion -> 8,
   Ticks -> None, WorkingPrecision -> 15, ImageSize -> Large}

A: You can do it using ListPlot3D, and those effect go away
data=Table[ Abs[Sqrt[Sin[2 x]]+Sqrt[Cos[2 y]]],{x,-2,2,.005},{y,-2,2,.005}];
ListPlot3D[data,ImageSize->700,MeshFunctions->{#3&}]

Compare to your plot

It seems to be due to different sampling used by Plot3D vs. the manual method used in ListPlot3D. At least this can be a workaround until a better solution is found.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error changing the ports in Mamp 3 when i try to change the port , the error is show up "There is a problem with the server ports. Each server must be assigned a unique port. Please check your configuration."

A: I was able to set port 3306 for SQL in the MAMP interface, and able to set port 80 for apache by editing the httpd.conf and changing 8888 to 80 on lines 48 and 182


text:
Q: What is the difference between "scold" and "criticize"? The word "scold" as defined at http://www.learnersdictionary.com/definition/scold

to speak in an angry or critical way to (someone who has done something wrong)
  - He scolded [=reprimanded] the children for making a mess.
  - The article scolds [=(more formally) berates, upbraids] the United Nations for not doing enough about the situation.
  - "You should never have done that," she scolded.

Also, from the same website "criticize" is defined as

to express disapproval of (someone or something) : to talk about the problems or faults of (someone or something)
  [+ object]
  - His boss criticized him for his sloppy work habits.
  - The judge was widely/roundly criticized for his verdict.
  - The editor criticized the author's work as trite.

I think "scold" is used when you someone senior tells shouts angrily at you for something that is considered considered incorrect, indicating that the recipient is at fault. On the other hand "criticize" could be when anyone "finds fault" without what you have done or the way you do things. I tend to use these words in different situations.However, looking at meanings their synonyms berate, rebuke, censure, lambaste, there does not seem to be much of a difference,could those two words be considered same?
On the same note, could rebuke and censure be considered the same?

A: Connotations for some of those words differ. Connotation is everything when considering which words are most synonymous.
You're right that to scold is to criticize or rebuke with more annoyance or even anger. -

To reprimand or criticize harshly and usually angrily; to find fault with or reprimand (a person) harshly; chide - AHDEL, Collins/TFD

Criticize itself doesn't carry a particular connotation of motive or emotion, just that of finding fault. Criticize can even mean merely to evaluate without necessarily finding fault.

To find fault with - AHDEL/TFD.

Censure connotes formality, as in a formal, public pronouncement of strong criticism, or one that may carry a penalty.

An official rebuke, as by a legislature of one of its members. - AHDEL

Rebuke carries no connotation of formality, and is more like scold, but focuses a bit more on the harsh/sharp nature of the criticism.

To criticize (someone) sharply; reprimand

If you want to learn about connotations, you need to look for them; just looking at a list of synonyms doesn't help much.
Look for a headword (usually bolded) in the synonyms, or preceded by "see usage notes at" (or something similar). This often involves, then, looking at several different entries for words that are listed as synonyms.


text:
Q: Code duplication in AngularJS Application I recently started working the AngularJS MVC framework. I was previously working with GWT. No here is the problem that I noticed working with AngularJS. When I start implementing a new Controller Acceptance test suite is created at the beginning, I practice TDD as much as I can, then after write you first acceptance test you start write unit tests and step by step implement your controller.The problem, as I see it, is the your objects fields should be the same in at lease 4 places in unit tests, in E2E tests, in Controller and View. This is a nightmare to chase. I will give a simple example of what I mean. I wish I am wrong and my approach of work is wrong and if so I hope some one to correct me.
// in controller

     $scope.newUsers = new Array(); // <-- $scope.newUsers should be the same array In unit tests.

        $scope.addUserTobeCreated = function (user) {// <-- functions should be added in the view too
            $scope.newUsers.push(user);
        };

        $scope.createUsers = function () {
            $http.post("some url", $scope.newUsers).success(function () {
              // do something
            });
        };

// in view
  name:
  <input type="text" size="15" maxlength="15" class="form-input-field  ipInput"  ng-model="user.name">
age:
<input type="text" size="15" maxlength="15" class="form-input-field  ipInput"  ng-model="user.age">
position:
<input type="text" size="15" maxlength="15" class="form-input-field  ipInput"  ng-model="user.position">

            Name:{{user.name}}, Age:{{user.age}}

// in unit test

  it("should add user to new users array to be added", function () {
        var user = {name:"ivan"};
        scope.addUserToBeCreated(user);
        expect(scope.newUsers.length).toBe(1); // <-- we have "newUsers" in 4 palces until now. Controller, unit tests, and view 2 times ! .
        // do some assertions ...
    });

If I want to change the newUsers array name I have to do it in 4 places !.
Also, consider passing an object to a server that accepts a JSON objects. On the server I have to map the JSON to my server objects. with frameworks like sitebircks it is very easy to do so. But, again a have to keep classes names consistent in order to be able to deserialize objects coming from the client.
Am I the only one who sees this problem ?.Correct me If I am mistaken. Or its just me who really have this problem. If that is the case please guide me to the correct way to work with JS frameworks.
Thanks for replies.

A: If you use a good Javascript IDE the refactoring support will let you do it in one go.
For example, in IDEA I can put my cursor on newUsers and press Shift-F6. Then check "Search in comments and strings" to also pick up the string in the html.
This problem exists also with GWT, but then you probably didn't notice because you were comfortable with refactoring support in your Java IDE.


text:
Q: Compare two columns of a collection in laravel? I want to compare two columns of a collection.I don't want to do this in db level, only in collection level.
I have a collection like this (I returned it in array model for readability)
   array:3 [
  0 => array:5 [
    "total_amount" => 200000.0

    "admin_max_amount" => "200000000"

  ]
  1 => array:5 [
    "total_amount" => 100000.0

    "admin_max_amount" => "200000000"

  ]
  2 => array:5 [
    "total_amount" => 100000.0

    "admin_max_amount" => "0"

  ]
]

I want to get first of them where total_amount > admin_max_amount.

A: Here is a more 'Laravel' way to do it:
$items = collect([
    [
        "total_amount" => 200000.0,

        "admin_max_amount" => "200000000",
    ],
    [
        "total_amount"     => 100000.0,
        "admin_max_amount" => "200000000",
    ],
    [
        "total_amount"     => 100000.0,
        "admin_max_amount" => "0",
    ],
]);
$result = $items->first(function ($item)
{
    return (float)$item['total_amount'] > (float)$item['admin_max_amount'];
});
dump($result);


text:
Q: Python : Running loop while waiting for server socket connection I have a LCD that I use to display timecode of the movie I am watching on my XBMC, and I would like to display current date and hour when nothing is played. The machine hosting the LCD is running a python TCPSocketServer server receiving text to be displayed from my XBMC installation. The problem is that I have to keep an active network connection so XBMC can send the hour and date through the socket and the LCD can display it.
In my opinion, the best thing to do would be to display the date of the machine hosting the LCD and then switch to a "timecode view" when the socket is active.
Is there any "pythonic" way set up a TCPSocketServer that compute a loop for displaying the date while waiting for a connection, and then change its behaviour to compute data received through the socket ?
Many thanks in advance

A: Here's some code that does what you want.  It starts up a TCP server listening to text sent to port 9876. When it gets some text it sends it to the Display object.  The code also sets up a timer which runs once a second, sending "idle text" (ie: the current timestamp) to the display object.
The display gets normal update text (from the server), and "idle text" from the 2nd thread.  The object knows how long it's been since it got some real text, and displays one or the other messages.
If the display object was attached to hardware, it could use a multiprocessing.RLock or other mechanism to protect itself.
Have fun!
lcdcontrol.py source
import signal, SocketServer, threading, time

class Display(object):
    IDLE_TIME = 5               # seconds

    def __init__(self):
        self.updated = None
        self.write('Hello')

    def _write(self, arg):
        print 'DISPLAY:', arg

    def write(self, arg):
        """
        update display and 'last updated' timestamp
        """
        self._write(arg)
        self.updated = time.time()

    def idle(self, arg):
        """
        update display only if it's been a few seconds
        """
        if time.time() - self.updated >= self.IDLE_TIME:
            self._write(arg)

class DisplayHandler(SocketServer.BaseRequestHandler):

    DisplayObj = None          # class var

    def handle(self):
        text = self.request.recv(1024).strip()
        print "{} wrote: {}".format(
            self.client_address[0], text,
            )
        # send text to LCD immediately
        self.DisplayObj.write(text)

def check_idle(display_obj):
    """
    update display with current time if it's idle
    """
    while True:
        display_obj.idle(
            time.strftime('time: %H:%M:%S'),
        )
        time.sleep(1)

def start_server(host, port):
    """
    start (single threaded) server
    """
    SocketServer.TCPServer(
        (host, port),
        DisplayHandler,
    ).serve_forever()

def main(host, port):
    display = Display()

    # store global display obj so Handler can get to it
    DisplayHandler.DisplayObj = display

    print 'serving on {}:{}'.format(host, port)
    print 'Example: echo beer | nc localhost {}'.format(port)
    print

    server_t = threading.Thread(
        target=start_server, args=(host, port)
    )
    server_t.daemon = True
    server_t.start()

    idle_t = threading.Thread(
        target=check_idle, args=[display],
        )
    idle_t.daemon = True
    idle_t.start()

    # wait for control-C to interrupt
    try:
        signal.pause()
    except KeyboardInterrupt:
        pass

if __name__ == "__main__":
    main("localhost", 9876)

sample run
Here I started the server, waited a few seconds, then typed fortune -s | nc localhost 9876
 to send a short fortune cookie to my LCD server.
Notice the "idle timer" stopped at :07, output the fortune cookie, waited five seconds, then continued with :13, :14. The message displayed for five seconds before switching back to the idle timestamp.
python ./lcdcontrol.py
DISPLAY: Hello
serving on localhost:9876
Example: echo beer | nc localhost 9876

DISPLAY: time: 13:08:06
DISPLAY: time: 13:08:07
127.0.0.1 wrote: Some people need a good imaginary cure for their painful imaginary ailment.
DISPLAY: Some people need a good imaginary cure for their painful imaginary ailment.
DISPLAY: time: 13:08:13
DISPLAY: time: 13:08:14
DISPLAY: time: 13:08:15
DISPLAY: time: 13:08:16


text:
Q: 32 bit hook doesn't ignore 64 bit processes I use a global CBT hook to recognize windows setfocus messages.
When keyboard focus changes, I want my application to notice that.
Therefore, I store the handle of my application using memory mapped files so that every process can use it for sending a message to the application after the focus changed.
I used 32-bit windows as target platform in both the hook.dll and the application.
Now, as far as I know, 32 bit processes should be hooked and 64 bit processes should be ignored. On a 32 bit system, the application works great.
When it is used it on a 64 bit windows, it also works in 32 bit processes (e.g. the delphi IDE),
but sometimes the application freezes.
for example when I start the internet explorer.
I noticed that there is a 32 bit and a 64 bit iexplore.exe in the task manager when Internet Explorer is running.
Could this be the problem? I don't understand why 64 bit processes are not simply ignored... Please help!
Below is the code of the hook.dll which is called by the main application:
library Project1;

uses
  {System.SysUtils,
    System.Classes,
    sharemem,
    windows,
    messages,}
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants;

const
  WM_MYFOCUSCHANGED = WM_USER + 1;

type
  PHookRec = ^THookRec;
  THookRec = packed Record
    HookHandle: hhook;
    WindowHandle: hwnd;
  End;

var
  MapHandle: THandle;     // File Mapping Objekt
  IpHookRec: PHookRec;    // Zeiger auf Hook Record

{$R *.res}

 procedure MapFileMemory(dwAllocSize: DWORD);
begin
  {Create a process wide memory mapped variable}
  MapHandle := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0,     dwAllocSize, 'HookRecMemBlock');
  if (MapHandle = 0) then
  begin
    MessageBox(0, 'Hook DLL', 'Could not create file map object', MB_OK);
    exit;
  end;

  {Get a pointer to our process wide memory mapped variable}
  ipHookRec := MapViewOfFile(MapHandle, FILE_MAP_WRITE, 0, 0, dwAllocSize);
  if (ipHookRec = nil) then
  begin
    CloseHandle(MapHandle);
    MessageBox(0, 'Hook DLL', 'Could not map file', MB_OK);
    exit;
  end;
end;

procedure UnMapFileMemory;
begin
  {Delete our process wide memory mapped variable}
  if (ipHookRec <> nil) then
  begin
    UnMapViewOfFile(ipHookRec);
    ipHookRec := nil;
  end;
  if (MapHandle > 0) then
  begin
    CloseHandle(MapHandle);
    MapHandle := 0;
  end;
end;

function GetHookRecPointer: pointer stdcall;
begin
  {Return a pointer to our process wide memory mapped variable}
  result := ipHookRec;
end;

function FocusHookProc(code: integer; wParam: wParam; lParam: lParam):     LResult; stdcall;
begin
 if (code < 0) then
  begin
    result := CallNextHookEx(ipHookRec^.HookHandle, code, wParam, lParam);
    exit;
  end;

  result := 0;

  if (code = HCBT_SETFOCUS) then
  begin
    if (ipHookRec^.WindowHandle <> INVALID_HANDLE_VALUE) then
      PostMessage(ipHookRec^.WindowHandle, WM_MYFOCUSCHANGED, wParam,     lParam);
    // wParam: Handle to the window gaining the keyboard focus

  end;
end;

procedure InstallHook(Hwnd: Cardinal); stdcall;
begin

  if ((ipHookRec <> nil) and (ipHookRec^.HookHandle = 0) and     (ipHookRec^.WindowHandle = 0)) then
  begin
    ipHookRec^.WindowHandle := Hwnd;   // handle to the application window
    ipHookRec^.HookHandle := SetWindowsHookEx(WH_CBT, @FocusHookProc,     Hinstance, 0);
  end;
end;

procedure UninstallHook; stdcall;
begin
   if ((ipHookRec <> nil) and (ipHookRec^.HookHandle <> 0)) then
  begin
    {Remove our hook and clear our hook handle}
    if (UnHookWindowsHookEx(ipHookRec^.HookHandle) <> FALSE) then
    begin
      ipHookRec^.HookHandle := 0;
      ipHookRec^.WindowHandle := 0;
    end;
  end;
end;

procedure DllEntryPoint(dwReason: DWORD);
var
currHwnd: Hwnd;
is64: Boolean;
begin
  case dwReason of
    Dll_Process_Attach:
      begin
        {If we are getting mapped into a process, then get a pointer to our
                                process wide memory mapped variable}
        MapHandle := 0;
        ipHookRec := nil;
        MapFileMemory(sizeof(ipHookRec^));
      end;
    Dll_Process_Detach:
      begin
        {If we are getting unmapped from a process then, remove the pointer     to
                                our process wide memory mapped variable}
        UnMapFileMemory;
      end;
  end;
end;

exports
  InstallHook name 'INSTALLHOOK',
  UninstallHook name 'UNINSTALLHOOK',
  GetHookRecPointer name 'GETHOOKRECPOINTER';

begin
  DLLProc := @DllEntryPoint;         // set DLL main entry point
  DllEntryPoint(Dll_Process_Attach); // call DLL main entry point
end.

A: Your 32 bit hook will not be loaded into a 64 bit process. This means that your problem is likely elsewhere.


text:
Q: pandas filter rows based on atmost matching criteria I have a dataframe like as shown below
df=pd.DataFrame({'subjects':['A','A','D','B','B','C'],
                'B':['12','12','13','14','14','16'],
                'C':[21,23,24,25,26,27]
                })
df['r_no'] = df.groupby(['subjects','B']).cumcount()+1

Now, I would like to only select rows that had only r_no = 1 (and not r_no > 1).
I tried the below
df[df['subjects'].value_counts() == 1]
df.iloc[df['subjects'].value_counts() == 1:,]
df.ix[df['subjects'].value_counts() == 1:,]
df[(df['r_no'] == 1) & (df['r_no'] < 2)]

None of them worked.
I expect my output to be like as shown below.
You can see that subjects = A and subjects = B is excluded because they also had rows where r_no > 1.  Basically, I want to select subjects that had only one record for them (r_no) in dataframe

A: IIUC, what you want to do it just to keep the groups of size 1:
df[df.groupby(['subjects','B'])['C'].transform(len).le(1)]

Or maybe even just keeping the subjects with unique rows:
df[~df['subjects'].duplicated(keep=False)]

output:
  subjects   B   C
2        D  13  24
5        C  16  27

A: df[df.groupby('subjects')['r_no'].transform(lambda x: ~(x.ne(1).any()))]

   subjects   B   C  r_no
2        D  13  24     1
5        C  16  27     1


text:
Q: Not able to print correct List (java.util) size I have tried this sample program and everytime I run it, it is giving "zero items in the list". I have tried sleep also, just to avoid the doubt that page ran so fast that it couldn't find the element.
What wrong I am doing?
driver.get("https://www.google.co.in/");

        driver.findElement(By.id("gbqfq")).clear();
        driver.findElement(By.id("gbqfq")).sendKeys("test");
        List<WebElement> allElements = driver
                .findElements(By
                        .xpath("html/body/div[2]/div[2]/div[1]/div/ul/li"));
        Thread.sleep(3000);
        System.out.println("there are "+allElements.size()+" items in this list");

PS:I am new in JAVA programming.

A: In the above code xpath is absolutely right, there is no problem in it. It's just page went to fast that webdriver couldn't get proper time to get how many items are there as "li" i.e. size of the list.
 To correct that one way is to put a sleep which is not the most optimum way and
 another way is to use WebDriverWait
new WebDriverWait(driver, 60).until(ExpectedConditions
                .elementToBeClickable(By
                        .xpath("html/body/div[2]/div[2]/div[1]/div/ul/li")));

It should be before yuu want to store items in the list.


text:
Q: Form inside a menu-dropdown does not stay when clicked in the input field - Bootstrap3 I have bootstrap site I am working on and it has very typical, straight from bootstrap navbar. One of the links in the navbar menu drops down to a login form. However, as soon as I click inside the form, it collapses back as if it was a hyperlink. I tested it alone in a FIDDLE so I know that is not something else conflicting in my code and as you can tell it is still not working as it should.
Does anyone know what is going on here? and how to fix it.
Do I need to add a JS hook passing a show function? SOmething like this didn't work
<script>
    $(document).ready(function () {
        $('.dropdown-toggle').show('click') //I also tried 'focus'
    });
</script>

The fiddle works for me, but apparently not for others. So I created a video showing you the fiddle and the bootstrap implementation as they have it in their own website (which of course it works for them )
SEE VIDEO HERE

A: AH! I found it! Well, anyway, here it is for anyone who may have this problem in the future, which I can see that there are many already asking this question and many using Bootstrap.
Add the following at the bottom:
<script>
    $(document).on('click', '.dropdown-menu', function (e) {
        e.stopPropagation()
    })
</script>

Make sure the classes match and you are on your way!


text:
Q: Delphi looking for writeable folder in localhost SetCurrentDir(s); // S='//localhost/'
FindFirst(s+'*.*', faDirectory, searchResult);
x:=searchResult.Name;  // Result (name finded folder)

*

*I'm trying to find folder's in //127.0.0.1/ directory. This code dosent work in localhost directory, the result is empty.

*How to detect that detected folder is writeable or only read?

A: \\127.0.0.1\ is not a directory. It is the basic UNC for any folders shared on the local machine. How to list shared folders, see this question or search the web for examples:
Enumerate list of network computers and shared folders in a tree view?


text:
Q: Using Docker Secrets in Container I am using Docker CE 17.09-1. I am leveraging Docker Swarm and have deployed a Stack with multiple services.
I've decided to use Docker Secrets for various credentials. One of the services I am running requires that I enter the database username and password in a configuration file. I have created two secrets for each required credential and I see the read-only files under /run/secrets/ in the container. How do I insert the contents of those files into my configuration file? My config file is a .ini file, and contains a number of values.
Thank you in advance for any suggestions.

A: What I considered before is to modify my ENTRYPOINT or CMD script in order for that script to modify or generate my local config file (a template), valued with the secrets read at runtime in /run/secrets.
Then the same script would launch the service in foreground, once the configuration files are properly generated/valued.

A: Depending on the service, you may be able to set the path to the secrets file (within /run/secrets) in an environment variable, or else either point to the secrets file in the .ini file or mount the secrets file where the image is expecting the secret
For an example of the former, look at the mysql image on Docker Hub -
as indicated https://hub.docker.com/_/mysql/ :

As an alternative to
  passing sensitive information via environment variables, _FILE may be
  appended to the previously listed environment variables, causing the
  initialization script to load the values for those variables from
  files present in the container. In particular, this can be used to
  load passwords from Docker secrets stored in
  /run/secrets/ files.

For an example of the latter, see the rabbitmq image on Docker Hub.  As noted https://hub.docker.com/_/rabbitmq/ :

If you wish to provide the cookie via a file (such as with Docker
  Secrets), it needs to be mounted at /var/lib/rabbitmq/.erlang.cookie:


text:
Q: Как защититься от подмены значения параметра в URL? Банальный пример, имеется страница с формой заявки по адресу order.php?id=2
где 2 - есть номер заявки.
Как защититься от подмены параметра id другим числом? Т-е если человек впишет 3 - то заказ отправится в слот для оптовиков.
A: Можно создать дополнительный параметр запроса, который равен хэшу всех остальных. При обработке запроса заново рассчитывать хэш и сравнивать с полученным. Если значения совпадают значит все ок!
Преимущества: простота реализации.
Недостатки: возможность подмены хэша; необходимость пересылать дополнительный набор данных в запросах.
Но, по-хорошему, Вам нужно постоянно синхронизировать данные с сервером при помощи AJAX. Тут и параметров запросов не нужно. Про100 привязка по SESSIONID или любом другом уникальном ID.
A: Используйте маршрутизацию.
Например, введите параметр recipient, значением которого будет имя модуля, в который отсылаете данные, а уже в самом модуле проверяйте, правильный ли набор данных вам пришел.
Если вам необходимо одним пользователям позволять только одни действия, а другим пользователям - другие - используйте ACL (Списки контроля доступа).


text:
Q: Current line text font size gets increased while typing in Xcode While I am typing on a specific line in workspace, the text present in the particular line's font is getting increased ! And it gets to regular size as soon as I stop typing.
I also upgraded to XCode 8.2 still the same issue occurs.
FYI:
I have also tried the following code to reset the XCode default settings, but still no use.

defaults delete com.apple.dt.Xcode

A: I had a similar problem but I am not sure is exactly the same.
Did you try to change this settings?

Xcode preferences > Fonts & Colors Your chosen theme will have a
  "current line" option just under the font. Can't remember exactly but
  I think you can find something there.

A: Solution:

This happens when you change font size for one particular element but the other editor's elements are using the previous/default font size.
If you want to change the font size either press cmd + or in preferences -> Fonts and Colors choose your theme and in the right pane select all the elements (press cmd a) and then change the font size.
See this SO answer


text:
Q: Downloading files over ssh based on a list of filenames So here is what I have done already:
I have a file called abc.txt which contains list of files. I am using abc.txt to
move those files to a folder, tar that folder and finally I download the tar to my local PC from my server, which is running GNU/Linux.
Here are the steps in list form:

*

*abc.txt

*abc.txt (listed files) -> folder

*Folder -> folder.tar

*folder.tar -> local PC.

If abc.txt contains 2 files, for example:
example1.css
example2.css

I need to download those files from abc.txt separately and directly to the local PC.
Since ftp or sftp need the file name to download it, how can I read that from abc.txt?

A: If the file abc.txt contains the list of filenames relative from /path/to/base:
ssh user@server tar c -T /path/to/abc.txt -C /path/to/base | (cd /tmp; tar xv)

This creates a tarball on-the-fly, without actually saving it anywhere, pipe it to the local shell, extract, effectively copying the listed files.
EXTRA TIPS
If the file abc.txt contains the list of absolute paths:
ssh user@server tar c -T /path/to/abc.txt | (cd /tmp; tar xv)

If the file abc.txt is on your local system, not the remote:
ssh user@server tar c -T- < /path/to/abc.txt | (cd /tmp; tar xv)

To use gzip compression (using default level 6):
ssh -C user@server tar c -T /path/to/abc.txt | (cd /tmp; tar xv)

To use gzip compression level 9:
ssh user@server 'tar c -T /path/to/abc.txt | gzip -9' | (cd /tmp; tar zxv)

A: Here is a simple script witch works with files containing spaces in the filename :
SAVEIFS=$IFS; IFS=$(echo -en "\n\b") ; for elt in `cat abc.txt` ; do scp $elt <YOUR_SFTP_CONNECTION> ; done ; IFS=$SAVEIFS

A: I think the hub of your problem is how to extract the correct files from your list for your subsequent two logic paths.
egrep 'example1.css|example2.css' abc.txt

will give you all lines that match the exceptions, and
egrep -v 'example1.css|example2.css' abc.txt

will give you all lines that don't match the exceptions


text:
Q: Unpermitted parameters for nested form many-to-many relationship Rails 4 I have a simple blog app, where I want to be able to create a Post and also create a new Tag for it in the same form, using a nested form.
Post and Tag have a many-to-many relationship, via a join table:
class PostTag < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag
end

Here's the tag model:
class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, :through => :post_tags

  validates_presence_of :name
  validates_uniqueness_of :name
end

Post model accepts nested attributes for tags:
class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => :post_tags
  accepts_nested_attributes_for :tags
  validates_presence_of :name, :content
end

On the posts controller, I permit tags_attributes:
    def post_params
      params.require(:post).permit(:name, :content, :tag_ids => [], :tags_attributes => [:id, :name])
    end

In my form for a new post, where I want to be able to either associate already existing tags (via checkboxes) or create a new one via a nested form using fields_for:
....

   <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %>

    <%= f.fields_for [@post, Tag.new] do |tag_form| %>

Add a new tag:

     <%= tag_form.label :name %>
     <%= tag_form.text_field :name %>
    <% end %>

  <%= f.submit %>

 <% end %>

My error is "Unpermitted parameters: tag":
Parameters: {"utf8"=>"✓",  "authenticity_token"=>"dZnCgFxrvuoY4bIUMMxI7kTLEr/R32pUX55wwHZsS4Q=", "post"=>{"name"=>"post title", "content"=>"post content", "tag_ids"=>[""], "tag"=>{"name"=>"new tag"}}, "commit"=>"Create Post"}
Unpermitted parameters: tag

A: Change:
<%= f.fields_for [@post, Tag.new] do |tag_form| %>

to
<%= f.fields_for(:tags, Tag.new) do |tag_form| %>


text:
Q: Storing "readonly" object as serialized data in relational DB I was wondering if storing objects as serialized data (example json) in a relational db is ever a good practice. I know it is generally a bad thing, and I'm not planning on using it extensively, but I stumbled on a case which got me thinking.
So, here is my situation. I'm basically building an mobile ordering system for delivering items from point A to point B. A is starting address, B is destination... both are current GPS coordinates of users (alongside with readable data like street name, street number etc).
These are the requirements:

*

*each order has a starting address

*destination address is optional

*once the order is created and addresses along with it, addresses will never be updated

*each order stores a new set of addresses, meaning if there are more orders from the same address, previously saved address will not be reused

*I don't need any queries on address data, like filtering, sorting ...

*structure of address data if fixed. I know this is where serialization has its advantages, but I will certainly not need it.

So, the dilemma is whether to use a separate table for address data (columns: id, street, street number, lat, lng...), or to simply store addresses as JSON strings?
The only down side with JSON, that I see, is that the data has to be serialized/deserialized. Since it has just a few fields it can't make much of a difference.
On the other hand there are a few things I don't like with separate table:

*

*it could have millions of rows which are needed only for display purposes

*it is easier to monitor data if everything is in one table

*the data is needed wherever information about the order is displayed, so I would need to join those 2 tables all the time

*highly unlikely, but theoretically, I could run out of autoincremented ids

I guess I can't go much wrong with a standard relational approach and store addresses in a separate table, but I just can't see any real advantage in it.

A: i'd go for the relational option, for the following reasons:

*

*I'm religious about data normalization

*If your json address pattern changes, you don't have to reprocess all your strings. You just add or remove one field from the table, and adapt your crud.

A: Are you SURE that you will never need to do any queries/analyses on the address data?
If this is for a little personal project, this seems fine.
However, if you ever need to change any properties, especially if this project is not completely dictated by you, it will be a gigantic hassle. I wouldn't worry too much about having "millions of rows used only for display purposes" -- modern database systems are optimized for storing a lot of rows, but not necessarily unstructured data.
So, I would strongly suggest you go with the tried-and-true relational approach.

*

*it could have millions of rows which are needed only for display purposes: If you're concerned about running out of auto incremented IDs, I bet you want to make this some massive delivery service. You really wouldn't want to group by GPS coordinates?

*it is easier to monitor data if everything is in one table: I don't think this is true. Obviously, if all of the data is stored in a consistent format, this will be the case. But monitoring data that has JSON that you'll have to process every time seems like another story.

*the data is needed wherever information about the order is displayed, so I would need to join those 2 tables all the time: If this is actually slower, fair point. However, if you only join the sub-tables with which you're concerned, I imagine that the joins will run faster than json parsing.

*highly unlikely, but theoretically, I could run out of auto-incremented ids : see this question. Not gonna happen.


text:
Q: Is it possible to combine these two queries wtih a join in SQLite? Is it possible to create a JOIN in SQLite between these two queries from different tables...
SELECT EventId as event,
SUM(CASE WHEN name = 'computer' THEN 1 ELSE 0 END) as computer,
SUM(CASE WHEN name = 'desk' THEN 1 ELSE 0 END) as desk,
SUM(CASE WHEN name = 'chair' THEN 1 ELSE 0 END) as chair
FROM TagsMSCV
WHERE name IN ('computer','desk','chair')
GROUP BY EventId

...and something like...
SELECT COUNT(MicrosoftId) as total FROM Images WHERE Images.EventId = TagsMSCV.EventId

...So that the top query goes from producing...
event   computer   desk   chair
####    ########   ####   #####
etc...

to
event   computer   desk   chair   total
####    ########   ####   #####   #####
etc...

EDIT: The second query I wrote was pseudo code attempting to create the join. The actual query as a normal select looks like this...
SELECT Count(MicrosoftId) FROM Images WHERE EventId IN ("10003", "10004", etc.) GROUP BY EventId

A: I would do the aggregation first and then left join:
SELECT t.EventId as event,
       SUM(CASE WHEN t.name = 'computer' THEN 1 ELSE 0 END) as computer,
       SUM(CASE WHEN t.name = 'desk' THEN 1 ELSE 0 END) as desk,
       SUM(CASE WHEN t.name = 'chair' THEN 1 ELSE 0 END) as chair,
       i.total
FROM TagsMSCV t LEFT JOIN
     (SELECT i.eventId, COUNT(MicrosoftId) as total
      FROM Images i
      GROUP BY i.eventId
     ) i
     ON i.EventId = t.EventId
WHERE t.name IN ('computer', 'desk', 'chair')
GROUP BY t.EventId, i.total;

By doing the aggregation first, you prevent double counting.


text:
Q: calculating new gps coordinates given initial coordinate and *Small* range I'm trying to figure out how to calculate a min/max lat/long bound on the specific given range of a gps coordinate.
for example: gps coord 37.42935699924869,-122.16962099075317  range .2 miles
I'm looking at the point + range + bearing in the http://www.movable-type.co.uk/scripts/latlong.html site but im not sure if this is exactly what i want.
This gives 4 unique lat/long pairs and I want/need a max/min lat and a max/min long.

A: *

*Calculate the distance between the (constant) central point and the point you want to test. (This page should give you the distance (in meters)).

*If (distance < 0.2) then ...

Well, given a point and a distance, you will get a circle.
You're looking for two points, which will essentially describe a square (two opposite corners). The two points you're looking for won't even be on the circle. I'm not exactly sure why you want this, but I don't think there is an answer to your question.
Perhaps you could tell us what you're trying to accomplish.
EDIT: Added image to illustrate. The orange line is the distance from the centre (e.g. 0.2 miles)
alt text http://img155.imageshack.us/img155/1315/diagramp.png

A: After your clarification, here is a less elegant answer that might give you what you want. Well, you want the inverse of a really complicated function. I'm afraid my math skills aren't up to the task, but it should be doable.
A less elegant solution is to find it by trial and error. Essentially, keep longitude the same and vary latitude. Using the right algorithm, you should be able to find one that is very close to the distance you want. This will give you a point on the circle (one of four that is also on the square).
Then keep latitude the same and vary longitude. This will give you a second point on the square (on the middle of one of the sides), from there you can find the 4 corners of the square.
This will slow, depending on how often you have to do it, that might or might not matter.


text:
Q: ERROR ON HANDEL AsyncFileUpload1 OnClientUploadComplete EVENT and OnClientUploadError event ON PAGE LOAD AsyncFileUpload1.OnClientUploadComplete  = New EventHandler(Of AsyncFileUploadEventArgs)(**AsyncFileUpload1_UploadedComplete**)

AsyncFileUpload1.OnClientUploadError  = New EventHandler(Of AsyncFileUploadEventArgs)(**AsyncFileUpload1_UploadedFileError**)

getting error like as below quota:

" Delegate 'System.EventHandler(Of
  AjaxControlToolkit.AsyncFileUploadEventArgs)' requires an 'AddressOf'
  expression or lambda expression as the only argument to its
  constructor. "


text:
Q: Relation between infimum of function in segment and subsegment Let $f:[a,b]\to \mathbb{R}$.
How to prove that $\inf\limits_{[a,b]} f=\min\{\inf\limits_{[a,c]} f,\inf\limits_{[c,b]} f\}$?

A: Since $\inf_{[x,y]} f \ge \inf_{[a,b]} f$ for any $a \le x \le y \le b$ we have
$\inf_{[a,b]} f \le \min(\inf_{[a,c]} f,\inf_{[c,b]} f)$.
Now suppose $\epsilon>0$, then there is some $x \in [a,b]$ such that
$f(x) < \inf_{[a,b]} f + \epsilon$. Since either $x \in [a,c]$ or $x \in [c,b]$ (or both) we have
$\min(\inf_{[a,c]} f,\inf_{[c,b]} f) \le f(x) <  \inf_{[a,b]} f + \epsilon$.
Since $\epsilon>0$ is arbitrary, we have the desired result.


text:
Q: Clearance code while working with Promises I am new to Nodejs and as well as async programming so I am trying to make shopping project I just want to clarify that even though my program works just fine but is my approach correct or not
controllers file
exports.posteditproduct = (req, res, next) => {
  const upprodid = req.body.productid;
  const upprodtitle = req.body.title;
  const upprodprice = req.body.price;
  const upprodimg = req.body.imageurl;
  const upproddesc = req.body.description;
  Product(
    upprodid,
    upprodtitle,
    upprodimg,
    upprodprice,
    upproddesc
  );

  Product.updateproduct(
    upprodid,
    upprodtitle,
    upprodprice,
    upprodimg,
    upproddesc
  ).then(function(value){
    console.log(value)
    fs.writeFile(p,JSON.stringify(value),err=>{
      console.log(err)
    })
  })
  res.redirect('/')
}

models
static updateproduct(
  upprodid,
  upprodtitle,
  upprodprice,
  upprodimg,
  upproddesc
) {
  const p = path.join(
    path.dirname(process.mainModule.filename),
    'data',
    'products.json'
  )

  return new Promise((resolve, reject) => {
    fs.readFile(p, (err, data) => {
      const allproducts = JSON.parse(data)
      const existproductid = allproducts.findIndex(prod => prod.id === upprodid)
      const upproduct = [...allproducts]
      const spreadall = upproduct[existproductid]

      spreadall.id = upprodid
      spreadall.title = upprodtitle
      spreadall.imageurl = upprodimg
      spreadall.price = upprodprice
      spreadall.description = upproddesc
      upproduct[existproductid] = spreadall

      return resolve(upproduct)
    })
  })
}

So is it okay if in my models file I do all the stuff and then return the final variable within the resolve ( ) and then in my controllers file I just use
.then(function(value) {
  //and then write in file here
})

Would this approach be okay if I have a very large file with n no. of entries ?
Or should I write the writeFile method too inside the Promise in the updateproduct method?


text:
Q: Uncaught Error in $A.getCallback() [Cannot read property 'apply' of undefined] Here is My cmp
<aura:component controller="BlacklistController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >

   <aura:attribute name="recordId" type="Id" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

    <ui:outputText aura:id="Blacklist" value="This record is currently locked" class="Invisible" />

</aura:component>

Here is my .js
({
    doInit : function(component, event, helper) {
        var action = component.get("c.CheckBlackListStatus");
        action.setParams({
            leadId: component.get("v.recordId")
        });

        action.setCallback(this, function(a) {
            var Blacklisted

            If (Blacklisted == True){
                var MakeBlacklist = component.find("Blacklist");
                $A.util.removeClass(MakeBlacklist, 'Invisible');
                $A.util.addClass(MakeBlacklist, 'blue');
            }

        });
        $A.enqueueAction(action);
    }
})

Here is my Apex Controller
public with sharing class BlacklistController {
   String caseId {get; set;}

    @AuraEnabled
    public static Boolean CheckBlackListStatus(Id leadId)
    {
        Lead lead = [SELECT Name, Status FROM Lead WHERE Id = :leadId];
        return lead.Status == 'Blacklisted';
            }
}

And my css
.THIS.blue {
    background-color: #16325C;
   display: block;
    margin-left: auto;
    margin-right: auto
}

.THIS .logo
{
    display: block;
    margin-left: auto;
    margin-right: auto
}
.THIS.Invisible {
    display: none;
}

A: You have a number of problems with your code, mostly related to the fact that, unlike Apex Code, JavaScript and Lightning are particularly case sensitive. Let's go over a few issues.
force:hasRecordId
When you use this interface, do not include a recordId attribute. Your component should look like this:
<aura:component controller="BlacklistController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <ui:outputText aura:id="Blacklist" value="This record is currently locked" class="Invisible" />
</aura:component>

JavaScript
It is case sensitive, so values like If and True are undefined. Also, you're not actually checking the return value from your callback. Here's how your client controller should be fixed:
({
    doInit : function(component, event, helper) {
        var action = component.get("c.CheckBlackListStatus");
        action.setParams({
            leadId: component.get("v.recordId")
        });

        action.setCallback(this, function(a) {
            var Blacklisted = a.getReturnValue();
            if(Blacklisted) {
                var MakeBlacklist = component.find("Blacklist");
                $A.util.removeClass(MakeBlacklist, 'Invisible');
                $A.util.addClass(MakeBlacklist, 'blue');
            }
        });
        $A.enqueueAction(action);
    }
})

Note: I'm not sure if just fixing those problems will fix your code's behavior, but it should get you closer to your goal.


text:
Q: C Program exits before taking input from user Why does my program close before taking the input for k and then displaying it.
I am writing a code for a menu based program so I need to take input from user after he has entered the information so I can have 1.Print names 2.Exit
while doing this I realized my program didn't take the input and just skipped the part where it is supposed to take value of l from user. So trying to debug it I deleted stuff and came down to this simple program and realized it still wont work any idea why?
#include <stdio.h>

struct student
{
    char name[50];
    char lname[50];
    float marks;
} s[15];

int main ()
{
    int i, j,k;

    printf("Please enter the number of students:\n");
    scanf ("%d", &j);

    printf ("Please enter the information for students as asked.\n");

    for (i = 0; i < j; i++)
    {
        scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
    }

    printf("Please enter a number\n");
    scanf ("%d", &k);

    printf("your number was %d", k);

    return 0;
}

A: scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
should be
scanf ("%s %s %f", s[i].name, s[i].lname, &s[i].marks);
The \n in scanf just consumes newline char. It will continue consuming newline until a non-newline char is found, which is put back into stdin for the next IO operation

A: Try this Code
#include<stdio.h>
typedef struct student
{
char name[50];
char lname[50];
int mark;
}S;

int main ()
{
int i, j,k;

printf("Please enter the number of students:\n");
scanf ("%d", &j);

S record[j];

for (i = 0; i < j; i++)    {
   printf ("Please enter the information for %d student as asked.\n",i+1);

  scanf ("%s %s %f",record[i].name, record[i].lname, &record[i].mark);
}

printf("Please enter a number\n");
scanf ("%d", &k);

printf("your number was %d \n", k);

return 0;
}

You were declaring structure student array in the structure declaration itself.you have to declare the array in main function.


text:
Q: Getting Reorder to ignore stock levels in magento i've been tasked to create a system where a customer can edit an order before it reaches the processing stage, i figure that the easiest way is to use the cart but with some edits to it to detect that your editing the order rather than making a new one
i have been testing out theories so far and everything seem to pan out, on theory i have been trying to get to work is utilizing the same process for re-ordering to populate the cart with the previous order, however i've ran into a problem, if an item is out of stock, it wont be added and until the customer confirms the changed to their order, i can go and release what they ordered, i can store how much the customer ordered but only if the item is added to the cart
so is there a way to get magento to add items to the cart with the re-order while ignoring what stock levels are
EDIT:
i've tried removing the Try Catch in Mage_Sales_Controller_Abstract in the function reorderAction() and it's adding the items however this means also i can't catch the exception of it's if it's just a notice or if there is any other reason why it can't add the item to the cart besides not having the stock

A: Got it working now, the trick was to enable Backorders and also modify parts of magento to prevent sellers from exceeding stock levels when they normally order (since if an item only has 6 in stock, with backorders enabled a customer can buy 10), after that it was simply setting up a system in the cart to detect when your editing an order and only allow backordering there since all orders are checked in the warehouse


text:
Q: Can this be achieved more elegantly with databinding? In one application I have developed I am storing data in custom objects (I call these files). These objects have quite a few properties.
The files are sorted into groups. I display certain properties of the files in a ListView control with Groups enabled.
I am storing the files in a Dictionary(Of String, List(Of MyFile)), where String is the group name.
The user is able to move files form one group to another, sort groups, move files in a group up and down, add and delete files and so on.
Currently I am doing this all by hand. I manually add the files to the group and synchronize the listview and the stored files whenever the user changes anything.
This gets very messy, very quickly and I don't like my approach. It works currently but it is a nightmare to change and maintain.
I know only little about data binding. I have tried it a some times but I found it equally clumsy.
So I am currently looking for pointers for a data structure that allows me to maintain this kind of database with groups of object-lists and always let the user interact with the list in some way.
Leads that are helpful, for example:

*

*Is a Dictionary(Of Group, List(of Objects)) a good way to store this kind of data or are there better alternatives? There can be hundreds of files in multiple groups.

*Is a ListView a good tool or are there better alternatives?

*What is the best way to synchronize a data structure with a user interface?

I am developing a WinForms application.
If the question is too broad in its current form please leave a comment so I can add to the specific problem.


text:
Q: Confusion regarding the 'new' keyword in C#, Unity Maybe a silly question, but having difficulty understanding it.
public class A
{
  public void Message()
    {
      Debug.Log("Some Message")
    }
}

public class B: MonoBehaviour
{
  A obj1 = new A(); //instance of object is made and constructor is called
  A obj2;           // object is made

  obj1.Message();
  obj2.Message();

 void Start(){}
 void Update(){}
}

What's the purpose of 'new' keyword if in both cases, the object is able to use methods of the class

A: A obj2;           // object is made

The object is not instantiated at this time, you only told here that you have a variable with the name obj2, and it is hold reference to nothing, in case of class it is null. You have a class named A and in it, you have a method called Message() and compiler in compile-time have a signal you have Message method defined, and that it is. In this case, this code should throw an exception NullReferenceException

A: There are a few quirks to Unity which may be tripping you up here. Actually, obj2 is not null, because it is of type "A" (not a Monobehavior). Since Class B is derived from Monobehavior, all of its "class variables" (the ones defined in immediate scope) will be instanced by the Inspector automatically. You can read about that here.
In other words, obj2 will still be usable. This is a property of custom classes in regards to how they are loaded from MonoBehaviors. If class A was also a MonoBehavior, then it would be nullable here, and you would see it as an empty variable in your inspector when Class B is put onto a GameObject. This is the case where Message() would not work, since obj2 would actually be null. Note there are other complications though--if Class A is a MonoBehavior, then you shouldn't be using Constructors on it, you should be using AddComponent(). Also, you can't define two MonoBehaviors in the same script file.
Finally, I'm not sure of the specifics here since I haven't tested it, but obj1.Message() may not be able to be called from where you're currently doing it. Typically code is run using the Callback functions provided by the MonoBehavior inheritance, i.e. Start(), Update(), etc. In order to call obj1.Message() at the start of the game, you need to run it from the Start() method. Let me know if you have any questions and I can clear up anything you find confusing!
EDIT: This is only true if obj2 appears in the inspector--if it is public and the class A is tagged as Serializable.


text:
Q: Retrive Query for Different Pages with the same class I'm having 2 visualforce pages with the same class
<apex:pageBlockButtons location="bottom" >
   <apex:CommandButton value="Search" action="{!Search}" rerender="theblock,themsg" />
   <apex:commandButton value="Cancel" action="{!Cancel}" rerender="thepg" onclick="this.form.reset()"/>
</apex:pageBlockButtons>

Search function in controller
public void search(){
   // for 1st page query should be
   case c = [select id,name from case where status="new"];
   // for 2nd page query should be without any condition
   case c = [select id,name from case ];
}

Can I get this by putting some condition in the class?

A: Pass some value with <apex:param through <apex:commandButton from VF page to Controller. The attribute assignTo is A setter method that assigns the value of this param to a variable in the associated Visualforce controller.
In controller check the value and apply logic for that page.
VF Page
.......
.......
    <apex:commandButton value="Search" action="{!Search}" rerender="theblock,themsg" />
         <apex:param name="eventId" value="fromPage1" assignTo="{!paramValue}"/>
    </apex:commandButton>
.......
.......

Controller
............
............
public String paramValue {get;set;}

............
............
public void search(){
    if(paramValue.equals('fromPage1')){
       // for 1st page query should be
       case c = [select id,name from case where status="new"];
    }else if(paramValue.equals('fromPage2')){
       // for 2nd page query should be without any condition
       case c = [select id,name from case ];
    }else{
        //To-Do
    }
}
................
................

Working Example
VF Page1
<apex:page controller="SearchController" >
    <apex:form>
        <apex:outputPanel id="theblock">{!callFrom}</apex:outputPanel>
        <apex:commandButton action="{!Search}" value="Search" reRender="theblock"  >
        <apex:param value="fromPage1" assignTo="{!paramValue}" />
        </apex:commandButton>
    </apex:form>
</apex:page>

VF Page 2
<apex:page controller="SearchController" >
    <apex:form>
        <apex:outputPanel id="theblock">{!callFrom}</apex:outputPanel>
        <apex:commandButton action="{!Search}" value="Search" reRender="theblock"  >
        <apex:param value="fromPage2" assignTo="{!paramValue}" />
        </apex:commandButton>
    </apex:form>
</apex:page>

Controller
public class SearchController {
    public String paramValue {get;set;}
    public String callFrom {get;set;}
    public void search(){
        if(paramValue.equals('fromPage1')){
            callFrom = 'Page One';
        }else if(paramValue.equals('fromPage2')){
            callFrom = 'Page Two';
        }else{
            //To-Do
        }
    }
}

A: Of course, just use
ApexPages.currentPage();

Source
And test its value (thanks to the getUrl()) in the controller method search() to make sure to run the query for the relevant page.
Be careful though not to use the same controller on multiple places if it occurs often. It can have some side effects. The controller will have a lot of complexity just because of being used in multiple places instead of one.
Divide to conquer


text:
Q: Can [[UILocalNotification alloc] init] be nil? The Local and Push Notification Programming Guide uses this code:
//...etc..
 UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
//...etc..

I am wondering what could be the scenarios in which localNotif is nil?
Otherwise, I don't see the point of having that if-statement.

A: It looks like it's a generic protection against a failed alloc/init, just like standard -init code includes the nil check (if (self == nil) { ... }), even though on modern systems it's extremely unlikely that the alloc fails.

A: Try disabling all notifications for your app (including sound/badge).


text:
Q: Is safe to switch battery while laptop is on and plugged? I want to know if is safe to switch my laptop battery while I'm using the laptop, with the AC charger connected.
Will the laptop shut down? Will the battery be damaged?
Thank you

A: As long as the charger is plugged in, the laptop won't shut down.  It also won't hurt the cells inside the battery pack.
The only potential risk could be a little momentary arcing when you separate the battery from its socket, which could pit the connector contacts.  I don't know if the voltage and current are high enough for that on your computer.
You can tell whether that is happening by putting your nose close to the battery connector, remove the battery, and see if you smell any ozone.  If you do, you're better off shutting down before removing the battery.  If you don't smell ozone, there isn't enough action to worry about if you need to do it occasionally.  I still wouldn't make a habit of doing it all the time, though, because even a trivial amount of arcing would crap up the connector over time.
The exception would be if the system is specifically designed for live swapping (it would probably be discussed in the user manual or you could find out from the manufacturer's customer service or tech support).  In that case, you can swap batteries to your heart's content.
People with laptops do it all the time and I haven't come across complaints on forums that they damaged their battery doing it.  This is probably more of a theoretical risk, but if you can easily avoid it, why not?


text:
Q: Cursor NotSerializableException in Android I need to pass a Cursor object from one android emulator to another. But when I try to serialize it, I am getting a "NotSerialiableException: android.database.sqlite.SQLiteCursor" error.
I know that one way to handle this is to tear down to serializable classes & serialize (on one emulator), de-serialize & rebuild the Cursor object (on another emulator).
Is there no other way to do this? I was looking at Parcelable and I am not so sure if this is what I want. Any pointers will be greatly appreciated!

A: There's not a chance in hell that that'll work. A cursor is basically a view of the contents of your database.
What are you trying to do exactly? How are you trying to pass the data between emulators? You're probably going to want to put the data from the cursor into something that IS serializable, like a map.


text:
Q: Persisting a hierarchical ordered list (flatfile/sql/nosql) I want to store hierarchical ordered lists. One example would be nested todo lists. Another example would be XML. It would just be a tree where the children are in a order. For simplicity, entries are just strings of text.
The thing is that the list will be edited by the user, so it is important that the common operations are fast:

*

*Edit an element

*Delete an element

*Insert an entry before another

I can imagine how to do this in a data structure: entries are linked lists, if they contain children, they also point to the head of another linked list. There is a hash table linking entry id to the actual data.

*

*Editing is looking up the hash and then replacing the data part of the linked list

*Deletion is looking up the hash and doing linked list deletion

*Insertion is looking up the hash and doing linked list insertion

However, I need to store the data, and I have no idea how to achieve this. I don't want to save the entire tree if only one element changes. What is the best way? Flat files/SQLs/NoSqls/voodoos?

A: You store lists (or rather trees) and don't want to rewrite the entire tree once a small piece of it changes. From this I conclude the stuctures are huge and small changes happen relatively often.
Linked lists are all about pointer chasing, and pointers and what they reference are much like keys and values. You need to efficiently store key-value pairs. Order of items is preserved by the linked list structure.
Suppose that you use a typical key-value store, from xDBM or Berkeley DB to any of modern NoSQL offerings. Also you could take a compact SQL engine, e.g. sqlite. They typically use trees to index keys, so it takes O(logN) to access a key, or hash tables that take about as much or a bit less.
You haven't specified when you persist your data incrementally. If you only do it once in a while (not for every update), you'll need to effectively compare the database to your primary data structure. This will be relatively time-consuming because you'll need to traverse the entire tree and look each node ID in the database. This is logarithmic but with a huge constant because of necessary I/O. And then you'll want to clean you persistent store from items that are no longer referenced. It may happen that just dumping the tree as JSON is far more efficient. In fact, that's what many in-memory databases do.
If you update your persistent structure with every update to the main structure, there's no point to have that main structure anyway. It's better to replace it with an in-memory key-value store such as Redis which already has persistence mechanisms (and some other nice things).

A: Using a relational database is viable solution. For your needs - fast insert, update, delete - I'd use an Adjacency List with an additional customizations as such:
id
parent_id
cardinality -- sort order for all nodes with the same parent_id
depth -- distance from the root node

Calculating cardinality and depth is either done with code or - preferably - a database trigger for any insert, delete or update. In addition, for retrieving an entire hierarchy with one SELECT statement, a hierarchy bridge table is called for:
id
descendent_id

This table would also be populated via the same trigger mentioned above and serves as a means for retrieving all nodes above or beneath a given id.
See this question for additional detail around Adjacency List, Hierarchy Bridge and other approaches for storing hierarchical data in a relational database.
Finally to provide some additional clarification on the options you listed:

*

*Flat Files: a combination of linked lists and memory mapped files would probably serve, but you're really just rolling your own at that point, where a SQL or NoSQL solution would probably do better.

*SQL: this would be my approach - tooling is the best here for data manipulation, backup and recovery.

*

*XML: this is also a possibility with a database, very vendor specific, you'll need to study the syntax for node insert, update and delete. Can be very fast if the database offers an XML data type.

*NoSQL: if you're talking key-value storage, the typical approach for hierarchical data appears to be materialized path, but this would require recalculating the entire path for all affected nodes on change, which is likely slow. Instead consider the Java Content Repository (JCR) - Apache Jackrabbit is an implementation - entire API centered around representing hierarchical structured data and persisting it - perhaps too heavyweight for the problem you're trying to solve.

*voodoo: um...

Update
If you implement all pieces from this answer, add is cheap, re-sort is small cost, move is expensive. Trade-off is fast hierarchy traversal reads - for instance find a node's complete ancestry in one operation. Specifically, adding a leaf is an O(1) operation. Re-sort means updating cardinality all peer nodes coming after the moved node. Move means update of (1) cardinality for source and destination peer nodes coming after, (2) moved - and descendant - node depth, and (3) removal and addition of ancestry to hierarchy bridge table.
However, go with an Adjancency List alone (i.e. id, parent_id) and write becomes cheap, reads for one level are cheap, but reads that traverse the hierarchy are expensive. The latter would then require using recursive SQL such Oracle's CONNECT BY or Common Table Expressions as found in SQL Server and other RDBMSs.


text:
Q: Remove Chart Hyperlink How do I remove a chart hyperlink?
I have tried the following code, but it does not seem to have removed the link.
ActiveSheet.ChartObjects(1).Activate
ActiveChart.Hyperlinks.Delete

A: Something like this should work:
Dim i As Long
Dim c As Chart
'Set c = ActiveChart ' or...
Set c = ActiveSheet.ChartObjects(1).Chart

'add hyperlink
c.Hyperlinks.Add Anchor:=Selection.ShapeRange.Item(1), Address:="", _
    SubAddress:= "'Product'!A1"

'now remove hyperlink
With c.Hyperlinks
    For i = .Count To 1 Step -1
        .Item(i).Delete
    Next i
End With

As you see, I'm deleting the hyperlinks one by one, counting backwards from the last to the first.


text:
Q: Transpose in Postgresql I am trying to design a database of customer details. Where customers can have up to two different phone numbers.
When I run the Select * command to bring out the customers that match criteria, I get this:
Name  |  Number
James |   12344532
James  |  23232422

I would like it to display all customers with two numbers this way:
Name  |   Number  | Number
James     12344532   23232422
John      32443322
Jude      12121212   23232422

I am using Postgresql server on Azure Data studio.
Please assist.
I tried using this command:
Select * FROM name.name,
min(details.number) AS number1,
max(details.number) AS number2
FROM name
JOIN details
ON name.id=details.id
GROUP BY name.name

I got this:
Name  |   Number  | Number

James     12344532   23232422

John      32443322   32443322

Jude      12121212   23232422

Customers with just 1 phone number gets duplicated in the table. How do I go about this?

A: I would aggregate the numbers into an array, then extract the array elements:
select n.name,
       d.numbers[1] as number_1,
       d.numbers[2] as number_2
from name n
  join (
    select id, array_agg(number) as numbers
    from details
    group by id
  ) d on d.id = n.id
order by name;

This is also easy to extend if you have more than two numbers.

A: Try using the following query:
SELECT
    Name,
    MIN(CASE WHEN rn = 1 THEN Number END) AS Number1,
    MIN(CASE WHEN rn = 2 THEN Number END) AS Number2
FROM
    (SELECT
        Name, Number,
        ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Number) AS rn
    FROM name) t
GROUP BY  Name

This query will use the ROW_NUMBER() function to assign a unique row number to each phone number for each customer. The ROW_NUMBER() function is ordered by the Number column, so the lowest number will have a row number of 1, and the second lowest number will have a row number of 2, etc.
Then we use the outer query to group customer by name and use MIN() function to get the first and second number based on the row number.
This query will return the desired output, with two columns, one showing the customer's first phone number and the other showing their second phone number.
Note: The query above assumes that the phone number is unique for each customer. If a customer has duplicate phone numbers, the query will return the first one it encounters.


text:
Q: ASP.NET MVC URL routing doesn't give me pretty URLs I have set up an ASP.NET MVC project, and everything is working great, but I do have one problem with the routing. My Global.asax looks like this:
public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
    }

So, nothing out of the ordinary. My problem is that when I link to a controller/action/params with an HTML.ActionLink like so:
<%= Html.ActionLink("My link", "SomeAction", "SomeController", new {param="someParam"})%>

it should generate (at least what makes sense in my head) a link such as: http://www.localhost/SomeController/SomeAction/someParam.
But instead it generates a link like this: http://localhost/SomeController/SomeAction?param=someParam
If i manually make a link that links to the expected result (SomeController/SomeAction/someParam) then the right controller and action are called, but the parameter defined in the action method is always null.
Any ideas?

A: try adding:
routes.MapRoute(
                    "Default",                                                                                // Route name
                    "{controller}/{action}/{param}",                                                   // URL with parameters
                    new { controller = "Home", action = "Index", param = "" }  // Parameter defaults
            );

A: I think that link will only use the default route like you expect if the parameter name is id instead of param.  You'll have to create a different route if you want to provide some other parameter there.


text:
Q: How can i ignore react warnings? (Not Native app) I get this warring in my react app.

It says componentWillReceiveProps has been renamed...
But I don't have "componentWillReceiveProps" in my code only effects ...
Maybe it is inside in node modules.
So i trying to ignore them
But i don't know how...
I used create-react-app
And i am using ts-lint.

A: Largely inspired from this answer
const error = console.error;
function logError(...parameters) {
    let filter = parameters.find(parameter => {
        return (
        // Filter error because XXX
        parameter.includes("Warning: %s is deprecated in StrictMode")
        // Another error to filter because of YYYY
        || parameter.includes("Warning:")
        );
    });
    if(!filter) error(...parameters);
}
console.error  = logError;

Note that this code only works for errors, but you can duplicate it for console.warn or info
You can manage this in a particular .js file, and import it in the App.js

A: By using below code you can hide the desirable warnings
import React from 'react';
import { YellowBox } from 'react-native';
import AppNavigator from './app/main';

YellowBox.ignoreWarnings([
  'Warning: isMounted(...) is deprecated',
  'Module RCTImageLoader',
  'Class RCTCxxModule',
  'Task orphaned for request ',
  'Warning',
  'Require',
  'Missing field __typename in',
  'Node',
]);

const App = () => <AppNavigator />;
export default App;


text:
Q: Clickable Python CLI Instantiation I'm trying to make my .py script clickable!
What I Have
The CLI program I created using Python works. I open Command Prompt and enter python my_script.py and everything works as expected. I want to make it clickable so a user doesn't have to run any commands!
What I've Tried
I created a .bat file in vim that runs the python my_script.py command. When I click it, the desired behavior is not achieved. Command Prompt opens for about a millisecond then closes.
My Question
How can I create a better .bat file so that my CLI program works with the click of a button?

A: Python, for better or worse does not allow you to specify the path to the script, and will not search the path for the script.
The official word, and I hate to say this, is that you must associate the Python.exe executable you want to run python scripts with the extension .py and then you can double click your script.py or type \path\to\script.py into the CMD prompt, and it will run the script.
I hate this from a standpoint of not wanting to accidentally execute a script by clicking it, and from the perspective of wanting to have multiple versions of python installed and choosing which one would do the execution.
There is an (IMHO) annoying (Kludgy) work-around.
You can create a File type for each instance of Python, you might have, and then associate it with the .py
so you could create the FTypes you need and associate them in a script at the time of to launch the script from the batch file:
FTYPE Py23=C:\Path\To\Pthon-23\python.exe %*
FTYPE Py38=C:\Path\To\Pthon-38\python.exe %*

Then your script could do this:
@Echo off
ASSOC .py=Py38
"C:\Path\To\Script.py"
ASSOC .py=

A: Python supports being called in a mode where it can ignore the first line of the script with -x.  This coupled with a wrapper batch file means you can actually put the entire Python script in a batch file.
This little script shows how this can be done.  It's a self-contained
@echo off
rem = """ # This is run in the batch file to launch Python
python -x "%~f0" %*
goto endofPython
rem = """

# Your python code goes here ..

def main():
    print("Hello from Python")

if __name__ == "__main__":
    main()

rem = """ # This section is run after Python is done, here just
          # just run pause to keep the console window open
:endofPython
pause
rem = """


text:
Q: Java - How to define a variable with variable type I have to declare a variable, the type of this variable depends on a parameter, so I have an if clause and define this variable there:
if(this.httpMethod == "POST"){
    HttpPost request = new HttpPost(url);
}
if(this.httpMethod == "GET"){
    HttpGet request = new HttpGet(url);
}

The problem is that in Java, the scope of that variable lies inside the if, so I can't use it later !. If I try:
request.addHeader("Accept", "application/json");

That gives me:  request cannot be resolved
So, the question would be: how can I define a variable, that it's type depends on a parameter.
What I have tried:

*

*Setting the variable to final.

My current solution is to duplicate the code, inside every if clause, I set the same
Headers, Connection, grab the response,  .... So, of course, I don't like this.
Design. I have this HTTP request class like this, so I can use it to handle the request, so, I just have to send it some parameters (URL, method, authentication, ...) , and it will give me back the result. This class is my bottom layer of my Android app, that looks like this:

*

*Activities.java (all the activities)

*Core.java (handle resources)

*HttpRequest.java (handle internet resources)

A: Both HttpPost and HttpGet inherit HttpRequestBase. So you can declare the request variable outside the if statement like so:
HttpRequestBase request = null;

if (this.httpMethod.equals("POST")) {
   request = new HttpPost(url);
}
else if (this.httpMethod.equals("GET")) {
   request = new HttpGet(url);
}

request.addHeader(...); etc

A: You need to declare the variable to be of the supertype outside of the if blocks and then use it inside them:
        HttpRequestBase request = null;

        if("POST".equals(this.httpMethod)){
            request = new HttpPost(url);
        }
        else if("GET".equals(this.httpMethod)){
            request = new HttpGet(url);
        }

And then later in your code when you're ready to use it, be sure to check whether the request is null or not.
Edited based on changes to the original question

A: You should declare a variable of both variable types' superclass outside the if statements.  Example:
Superclass object;

if (condition){
    object = new Subclass1();
}
else {
    object = new Subclass2();
}


text:
Q: App crashes every time a button is clicked to go to another activity My app has two buttons and the button with "more info" on it directs to another activity.But if i click on the button it crashes. I have included the activity and the intent on the manifest file.
This is my MainActivity
public class MainActivity extends Activity {
    Integer[] pics = {
            R.drawable.rah,
            R.drawable.rah18a,

    };
    ImageView imageView;
    Button Button1;
    Button Button2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Gallery ga = (Gallery)findViewById(R.id.Gallery01);
        ga.setAdapter(new ImageAdapter(this));

        imageView = (ImageView)findViewById(R.id.ImageView01);
        Button1 = (Button)findViewById(R.id.button1);
        Button2 = (Button) findViewById(R.id.button2);

        Button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("Description.Main.Activity2");
                startActivity(intent);
            }
        });

        ga.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, final int pos,
                    long arg3) {

                imageView.setImageResource(pics[pos]);
                Button1.setOnClickListener(new OnClickListener() {
                  public void onClick(View v) {
                    WallpaperManager wm = WallpaperManager.getInstance(v.getContext());
                    try {
                        wm.setResource(pics[pos]);
                        Toast.makeText(getBaseContext(),
                                "Wallpaper has been set",
                                Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                  }
                });
            }
        });

            }

    public class ImageAdapter extends BaseAdapter {

        private Context ctx;
        int imageBackground;

        public ImageAdapter(Context c) {
            ctx = c;
            TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
            imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
            ta.recycle();
        }

        @Override
        public int getCount() {

            return pics.length;
        }

        @Override
        public Object getItem(int arg0) {

            return arg0;
        }

        @Override
        public long getItemId(int arg0) {

            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            ImageView iv = new ImageView(ctx);
            iv.setImageResource(pics[arg0]);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(new Gallery.LayoutParams(300,400));
            iv.setBackgroundResource(imageBackground);
            return iv;
        }

    }
}

My second activity is called MainActivity2.java and is blank.Help Please.
EDIT: Adding Manifest entry for MainActivity2
<activity android:label="@string/app_name" android:name=".MainActivity2" >
   <intent-filter>
     <action android:name="AnotherActivity" />
     <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</activity>

Here is my logcat:
07-22 06:40:37.639: E/AndroidRuntime(770): FATAL EXCEPTION: main
07-22 06:40:37.639: E/AndroidRuntime(770): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rahuldravid/com.example.rahuldravid.MainActivity2}: java.lang.RuntimeException: Binary XML file line #2: You must supply a layout_width attribute.
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.os.Looper.loop(Looper.java:137)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-22 06:40:37.639: E/AndroidRuntime(770):  at java.lang.reflect.Method.invokeNative(Native Method)
07-22 06:40:37.639: E/AndroidRuntime(770):  at java.lang.reflect.Method.invoke(Method.java:511)
07-22 06:40:37.639: E/AndroidRuntime(770):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-22 06:40:37.639: E/AndroidRuntime(770):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-22 06:40:37.639: E/AndroidRuntime(770):  at dalvik.system.NativeStart.main(Native Method)
07-22 06:40:37.639: E/AndroidRuntime(770): Caused by: java.lang.RuntimeException: Binary XML file line #2: You must supply a layout_width attribute.
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:491)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:5614)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:5756)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.widget.FrameLayout$LayoutParams.<init>(FrameLayout.java:610)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.widget.FrameLayout.generateLayoutParams(FrameLayout.java:554)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.widget.FrameLayout.generateLayoutParams(FrameLayout.java:56)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.view.LayoutInflater.inflate(LayoutInflater.java:477)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
07-22 06:40:37.639: E/AndroidRuntime(770):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.Activity.setContentView(Activity.java:1881)
07-22 06:40:37.639: E/AndroidRuntime(770):  at com.example.rahuldravid.MainActivity2.onCreate(MainActivity2.java:13)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.Activity.performCreate(Activity.java:5104)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-22 06:40:37.639: E/AndroidRuntime(770):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-22 06:40:37.639: E/AndroidRuntime(770):  ... 11 more

LAYOUT1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerHorizontal="true" >

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="match_parent"
        android:layout_height="110dp" />
        <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="368dp"
        android:layout_height="279dp"
        android:layout_above="@+id/linearLayout1"
        android:layout_alignParentLeft="true" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="68dp"
        android:background="@android:drawable/bottom_bar"
        android:orientation="horizontal"
        android:paddingBottom="1.0dip"
        android:paddingLeft="4.0dip"
        android:paddingRight="4.0dip"
        android:paddingTop="5.0dip" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Set Wallpaper" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="47dp"
            android:layout_weight="1"
            android:text="More Info" />

    </LinearLayout>

</RelativeLayout>

LAYOUT2:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerHorizontal="true">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

A: This line is incorrect
Intent intent = new Intent("Description.Main.Activity2");

It should be more like
Intent intent = new Intent(MainActivity.this, Activity2.class); //define the name of your java class
                                                  //this intent is pointing to

EDIT: The line isn't incorrect per se, as an Intent can also take a String action parameter, but it seems that's not what you're going for

A: please try it this way :
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
startActivity(myIntent);


text:
Q: How to simplify this combinatorial expression? Find
\begin{eqnarray}
\sum_{j\in\mathbb{N}}(n-2j)^k\binom{n}{2j-m}
\end{eqnarray}
Note that this question is a generalization of this one. I tried to imitate the steps in the answer given in that post but without success. Any idea?

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{j\ \in\ \mathbb{N}}\pars{n - 2j}^{\,k}\ {n \choose 2j - m} & =
\sum_{j = 0}^{\infty}\pars{n - j}^{\,k}\ {n \choose j - m}{1 + \pars{-1}^{\,j} \over 2} =
{\mrm{f}\pars{1} + \mrm{f}\pars{-1} \over 2}\label{1}\tag{1}
\\[2mm] &\ \mbox{where}\ \,\mrm{f}\pars{x} \equiv
\sum_{j = m}^{\infty}\pars{n - j}^{k}\ {n \choose j - m}x^{\,j}
\end{align}

\begin{align}
\mrm{f}\pars{x} & =
x^{m}\sum_{j = 0}^{\infty}{n \choose j}x^{\,j}\,\pars{n - m - j}^{\,k} =
x^{m}\sum_{j = 0}^{\infty}{n \choose j}x^{\,j}\ \overbrace{%
\bracks{k!\oint_{\verts{z} = 1}{\expo{\pars{n - m - j}z} \over z^{k + 1}}}
\,{\dd z \over 2\pi\ic}}^{\ds{\pars{n - m - j}^{\,k}}}
\\[5mm] & =
k!\,x^{m}\oint_{\verts{z} = 1}{\expo{\pars{n - m}z} \over z^{k + 1}}
\sum_{j = 0}^{\infty}{n \choose j}\pars{x\expo{-z}}^{\,j}\,{\dd z \over 2\pi\ic} =
k!\,x^{m}\oint_{\verts{z} = 1}{\expo{\pars{n - m}z} \over z^{k + 1}}
\pars{1 + x\expo{-z}}^{n}\,{\dd z \over 2\pi\ic}
\\[5mm] & =
k!\,x^{m}\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}
\pars{\expo{z} + x}^{n}\,{\dd z \over 2\pi\ic}
\end{align}

$\ds{\Large\mrm{f}\pars{-1}:\ ?.}$
\begin{align}
\mrm{f}\pars{-1} & =
k!\,\pars{-1}^{m}\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}
\pars{\expo{z} - 1}^{n}\,{\dd z \over 2\pi\ic}
\end{align}
The integral over $\ds{z}$ can be evaluated by using an identity which involves the
Stirling Number of the Second Kind
$\ds{a \brace b}$. Namely,
\begin{equation}
\pars{\expo{z} - 1}^{s} = s!\sum_{j = 0}^{\infty}{j \brace s}{z^{\,j} \over j!}
\label{2}\tag{2}
\end{equation}
Then,
\begin{align}
\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}
\pars{\expo{z} - 1}^{s}\,{\dd z \over 2\pi\ic} & =
s!\sum_{j = 0}^{\infty}{j \brace s}{1 \over j!}
\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1 - j}}\,{\dd z \over 2\pi\ic}
\\[5mm] & =
s!\sum_{j = 0}^{\infty}{j \brace s}{1 \over j!}\,
{\pars{-m}^{k - j} \over \pars{k - j}!}
\\[5mm] & =
\bracks{k \geq s}{s! \over k!}\,\pars{-1}^{k}\,m^{k}
\sum_{j = s}^{k}{j \brace s}{k \choose j}\,{\pars{-1}^{\,j} \over m^{\,j}}
\label{3}\tag{3}
\end{align}
\begin{align}
&\mbox{With this result,}\ \,\mrm{f}\pars{-1}\ \mbox{is given by}
\\
&\bbx{\mrm{f}\pars{-1} = \bracks{k \geq n}\pars{-1}^{m + k}\,m^{k}\,n!
\sum_{j = n}^{k}{j \brace n}{k \choose j}{\pars{-1}^{\,j} \over m^{\,j}}}
\label{4}\tag{4}
\end{align}

$\ds{\Large\mrm{f}\pars{1}:\ ?.}$
\begin{align}
\mrm{f}\pars{1} & =
k!\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}
\pars{\expo{z} + 1}^{n}\,{\dd z \over 2\pi\ic} =
k!\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}
2^{n}\pars{1 + {\expo{z} - 1 \over 2}}^{n}\,{\dd z \over 2\pi\ic}
\\[5mm] & =
k!\sum_{\ell = 0}^{n}{n \choose \ell}
\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}
2^{n}\pars{\expo{z} - 1 \over 2}^{n\ell}\,{\dd z \over 2\pi\ic}
\\[5mm] & =
k!\sum_{\ell = 0}^{n}{n \choose \ell}2^{\pars{1 - \ell}n}
\oint_{\verts{z} = 1}{\expo{-mz} \over z^{k + 1}}\pars{\expo{z} - 1}^{n\ell}
\,{\dd z \over 2\pi\ic}
\end{align}
With result \eqref{3}:
\begin{align}
&\mrm{f}\pars{1} =
k!\sum_{\ell = 0}^{n}{n \choose \ell}2^{\pars{1 - \ell}n}\braces{%
\bracks{k \geq n\ell}{\pars{n\ell}! \over k!}\,\pars{-1}^{k}\,m^{k}
\sum_{j = n\ell}^{k}{j \brace n\ell}{k \choose j}
\,{\pars{-1}^{\,j} \over m^{\,j}}}
\\[5mm] &
\bbx{\mrm{f}\pars{1} = \pars{-1}^{k}\,2^{n}\,m^{k}\sum_{\ell = 0}^{M}\sum_{j = n\ell}^{k}
{n \choose \ell}{j \brace n\ell}{k \choose j}\pars{-1}^{\,j}\,
{\pars{n\ell}! \over 2^{n\ell}m^{\,j}}}\label{5}\tag{5}
\\
&\mbox{where}\quad M \equiv
\min\braces{\left\lfloor\,{k \over n}\,\right\rfloor,n}
\end{align}

The final result is given by \eqref{1}, \eqref{4} and \eqref{5}.


text:
Q: What is the probability that a random walk on this graphs ends at point A? Consider the symmetric RW on a graph constructed from two cycles $C_{m}$ and $C_{n}$ in such a way that the two cycles have exactly two consecutive common vertices, like in Figure 2.

Let S denote one of the two common vertices, let S' denote the other common vertex, let A be a vertex of $C_{m}$ not in $C_{n}$, and let B be a vertex of $C_{n}$ not in $C_{m}$. Suppose now that $m=2*10^{6}+1$, where the SS' A-arc is a path of $10^{6}+1$, edges and the other SA-arc(="lower arc") is a path of $10^{6}$ edges; and $n = 4*10^{6} +1$, where the SS'B-arc is a path of $2*10^{6} +1$ edges, and the other SB-arc(="lower arc") is a path of $2 * 10^{6}$ edges.
I am interested in the probability that the symmetric random walk, starting from S, ends at endpoint A. B is also an end point, however we are interested in solving the probability it ends at A. If the random walk reaches A at any time it immediately ends.

A: I'm going to assume the random walk also stops when reaching $B$, which the question currently doesn't say; otherwise, the probability is just $1$.

Divide the diagram into a top half (consisting of the $A,B$-path passing through $S'$) and a bottom half (consisting of the $A,B$-path passing through $S$).
By symmetry, the probability of reaching $A$ before $B$ is the same for a vertex in the top half and the corresponding vertex in the bottom half. So we can just solve the same problem for a random walk on a single $A,B$-path of length $3 \cdot 10^6$.
For this random walk, the probability of reaching $A$ before $B$, starting from $S$, is well-known to be $\frac{d(S,A)}{d(S,A) + d(S,B)}$ which gives $\frac13$ in this case.


text:
Q: How to suppress output in imported module I have a module with one method:
def find_inverse_matrix(C, log=False):

    n = C.shape[0]

    Cs = C.copy()
    i = 0
    C = np.matrix(np.eye(n))
    B = np.matrix(np.eye(n))
    J = set(range(n))
    S = [0] * n

    if log: print Cs

    while i <= n-1:
        if log: print '\nIteration', i
        f = False
        j = 0
        ei = get_ek(i, n)

        for j in J:
            cj = get_ck(Cs, j)
            alpha = (ei * B * cj)[0, 0]
            if log: print 'alpha%s = %s' % (j, alpha)
            if not(is_zero(alpha)):
                f = True
                break

        if not(f):
            exit('Inverse matrix is not exist')

        J.remove(j)
        S[j] = i
        C[:, i] = Cs[:, j]
        if log: print 'C%s:\n%s' % (i, C)
        D = get_Dkz(i, B * C[:, i])
        if log: print 'D%s:\n%s' % (i, D)
        B = D * B
        if log: print 'B%s:\n%s' % (i, B)

        i += 1
    if log: print '\n S = ', S

    if log: print 'Result'
    R = construct_matrix(B, S)
    if log: print R

    if log: print '\nCheck result:'
    if log: print Cs * R
    return R

If I call this method from this file it shows all print, but if I call if from another all print should be suppressed. Now I use check before every print, but how it do simple and pretty in 'pythonic' style?

A: Normally, print is a statement in the language. But if you add the line from __future__ import print_function to your imports then it is used as a function. This means two things:
a) You need to use this as a function - meaning print(Cs) instead of print Cs.
b) You can override it, since in python functions are objects you can play with.
You can define your own "my_print" functions which you can later change instead of the builtin print.
Example:
>>> from __future__ import print_function
>>> _print_ = print
>>> def myprint(*arg, **kwarg):
...     _print_("yeah.")
...     _print_(*arg,** kwarg)
...
>>> myprint("ok")
yeah.
ok
>>> print = myprint
>>> print('3')
yeah.
3
>>>

So just write your myprint function so that it'd check for "log" before, and your prints should be the same. Or just override print only when you don't want to suppress printing.

A: if __name__ == '__main__': will execute a block of code only if a file is executed directly, not loaded as a module. You can set a flag there to turn on logging.
A more pythonic way might be to pass a log function into the module instead of a flag. That way you could pass in an empty function to suppress logging.