Q: Rails: Clarifying purpose of precompile:assets I'm trying to understand what exactly precompiling:assets does, because I've realized that for my last project my CSS would never update when I pushed my app to heroku unless I typed bundle exec rake assets:precompile, but this only started happening towards the end, so I believe I probably added something to the config file.
I'm currently trying to understand caching, which made me think about precompile:assets. Is precompile:assets similar to caching by pre-loading the assets to the web server so that those assets aren't loaded directly from the Rails stack? This is for performance purposes right?

A: You can find everything you need to know in the Asset Pipeline Rails Guide.

A: Caching is a related, but separate topic.
The purpose of compiling assets includes the combining and minimizing of assets, e.g. javascript that is all on 1 line with 1 letter variables, as opposed to the originals which are used in development mode and let you debug there using the original source code.


Q: Jonckheere-Terpstra test for DEPENDENT samples with an ordered alternative hypothesis I have a question about the tests that consider an a priori ordering  (the alternative hypothesis is ordered - testing the hypothesis u1 ≤ u2 ≤ ... ≤ un). We want to compare a variable in the same individual in three consecutive intervention points (like repeated measures ANOVA but non-parametric and testing for a specific order of treatments).
I though about the Jonckheere terpstra test, but it is use for independent samples which is not our case...
Could you tell me which test is more appropriate in my case (with the alternative hypothesis is ordered and the samples are DEPENDENT!)
Is Page's L test the answer ?


Q: Workbook.save - "the following features cannot be saved in macro-free workbooks..." My sub opens up a .xlsm file in a new Excel instance, makes changes to the file, and saves the changes.
However, despite the fact that the file being opened is .xlsm, upon workbook.save I get the alert message "the following features cannot be saved in macro-free workbooks..."
This doesn't make sense to me because the file is .xlsm. Any ideas?
Edit: I believe I found the source of the problem. Although the variable "path" contains C:\file.xlsm, wkb.path is empty. (see Debug.print's below). Why is the wkb.path empty?
    Set XL = New Excel.Application
    XL.Visible = False

    For Each Path In XLSMPaths

        Set wkb = XL.Workbooks.Add(Path)

        Debug.Print Path      ' "C:\file.xlsm"
        Debug.Print wkb.path  ' ""
        Debug.print wkb.name  ' "file"

        wkb.Save   '<- alert message "The following features cannot be saved in macro-free workbooks..."

    Next Path

A: By default, the .save method will save the file as .xls or .xlsx (dependant on your version of excel), you need to force this with .saveas
wkb.SaveAs Filename:=MyNewPathFilename, FileFormat:=xlOpenXMLWorkbookMacroEnabled

obviously change the variable 'MyNewPathFilename' to whatever you want to save the file as, probably want to take the Path and check it ends in .xlsm then pass it into this variable


Q: Play Framework Return Partial View I am using Play Framework and, using AJAX, would like to return a partial view to the calling script to render.  I come from the world of ASP.NET MVC so this is a very simple concept there, but I don't see a place for it in Play.
An example of what I would like to do:
Main.html

<title>Test</title>

Here's my list

<input type="text" id="new-entry" /><button id="add-new-entry">Add</button>

  #{list items, as:'item'}

#{anitemtemplate item}

  #{/list}

anitemtemplate.html
${item.title} by ${item.author}

Me.java
public static void add(String title) {
  //add the item
  return render("anitemtemplate", newitem); //how to do this??
}

A: It should be :
public static void add(String title) {
  //add the item
  return render("anitemtemplate.html", item);
}

or
public static void add(String title) {
  //add the item
  renderArgs.put("item", newitem);
  return render("anitemtemplate.html");
}

And if the anitemtemplate.html is in /app/views/tags/ , like the tag usage suppose to in your main.html, you should use render("tags/anitemtemplate.html") - the first argument of render is the relative path of the template from the /app/views/ directory.
And BTW,
this
  #{list items, as:'item'}

#{anitemtemplate item}

  #{/list}

should be
  #{list items, as:'item'}

#{anitemtemplate item /}

  #{/list}


Q: Expected value of picking one rope end of $2n-1$ rope ends There are $n$ ropes in a bucket. From $n-1$ ropes you can reach both rope ends. Only one rope is knotted to the bottom of the bucket. Therefore you can reach $2n-1$ rope ends. You pick randomly one rope end and pull the rope out until you pick the rope that is knotted to the bottom. Let $X$ be the number of ropes you pull out before picking the one rope. What is the expected value of $X$?
I tried to calculate the probabilty that the one rope is picked as the i-th rope. $P[X_i] = \prod_{k=1}^{i-1}\left( \frac{2n-2k}{2n-(2k-1)}\right) * \frac{1}{2n-(2i-1)}.$
Then for the expectetd value $E[X] = \sum_{i=1}^{n}((i-1)*P[X_i]),$
which gets a little bit complicated. Is there a more comfortable way of doing this?

A: $$E(X_n)=\frac 23n+\frac13$$
We have $E(X_n)=\frac 1{2n-1}+\frac {2n-2}{2n-1}(1+E(X_{n-1}))=1+\frac {2n-2}{2n-1}E(X_{n-1})$ because when you pull the first end you have $\frac 1{2n-1}$ chance of getting the tied rope and otherwise you used a move and have the case with one less rope. $E(X_1)=1$ as you only have the tied rope end available.  This is the base case of our induction.  Now let it be true up to $k$.  We have $$\begin {align}E(X_{k+1})&=1+\frac {2k}{2k+1}E(X_k)\\&=1+\frac {2k}{2k+1}\left(\frac 23k+\frac 13\right)\\&=\frac {6k+3+4k^2+2k}{3(2k+1)}\\&=\frac {2k+3}3\\&=\frac 23(k+1)+\frac 13 \end {align}$$


Q: How many timers can I create in C on Windows? I am working with a table (struct) that stores entries of received messages. I need to monitor a specific operation for each entry periodically, which is why I thought of creating a timer for each created entry to monitor how long this entry has been in the table, and based on the duration, I need to execute some commands and restart the timer.
I am new to timers and callbacks in C, but I know that each timer leads to a new thread. My questions is, how many timers can I create on a standard board?
I know a different method would be to add a new member for the timer operation and iterate over the table for this to work in non-critical events with one timer, but I am trying to avoid this as the table entries can affect the whole program. If it is not possible to create many timers (+1000), what would be the other ideal way of doing this?

A: If the entries in the table should be "expired" (and removed) at certain times, then here is a possible solution, using only a single timer:
First of all use a priority queue where the "priority" is the expiration time. You can of course use any other table-like structure, but keep it sorted on the expiration time (it simplify things later).
Then have your single recurring timer, which is triggered ten, twenty or maybe more times per second.
When the timer is triggered, you get the current time, and simply remove all elements in the table whose expiration time have passed (comparing its expiration time with the current time). If the table is sorted on expiration date, it's a very simple loop where you compare the time from the "top" element, and if expired then "pop" the top element.
You can use the same or similar techniques for just about any timing-related issue.


Q: Android mixed language text - BidiFormatter on String with RTL and LTR text I have a ListView with custom View where I have a TextView :
 <TextView
     android:id="@+id/textViewItemTitle"
     android:layout_width="0dp"
     android:layout_weight="1"
     android:layout_height="wrap_content"
     android:gravity="right|center_horizontal"
     android:text="title" />

This TextView contains Hebrew text.
 if(!bidi.isRtl(event)){
     event = bidi.unicodeWrap(event);
 }

 holder.title.setText(String.format("%s  %s  %s", bidi.unicodeWrap(item.getStartTimeNoDate().trim()), event,
 bidi.unicodeWrap(item.getDuration().trim())));

Where the first argument is time hh:mm:ss, second (event) is a Hebrew String and third like the first.
The problem:  some time the event String contains mixed text in Hebrew and English like abc-אבג then all the text behave like the the gravity is left (and not right like I defined in the text view), I mean indented to left.
How to solve that?

A: The accepted answer will do the job when the text is in a TextView. This is a more general answer, applicable both to the basic/happy scenario and to other, more complicated use cases.
There are situations when mixed-language text is to be used someplace other than inside a TextView. For instance, the text may be passed in a share Intent to Gmail or WhatsApp and so on. In such cases, you must use a combination of the following classes:

*

*BidiFormatter

*TextDirectionHeuristics
As quoted in the documentation, these are ...

Utility class[es] for formatting text for display in a potentially opposite-directionality context without garbling. The directionality of the context is set at formatter creation and the directionality of the text can be either estimated or passed in when known.

So for example, say you have a String that has a combination of English & Arabic, and you need the text to be

*

*right-to-left (RTL).

*always right-aligned, even if the sentence begins with English.

*English & Arabic words in the correct sequence and without garbling.

then you could achieve this using the unicodeWrap() method as follows:
String mixedLanguageText = ... // mixed-language text

if(BidiFormatter.getInstance().isRtlContext()){
    Locale rtlLocale = ... // RTL locale
    mixedLanguageText = BidiFormatter.getInstance(rtlLocale).unicodeWrap(mixedLanguageText, TextDirectionHeuristics.ANYRTL_LTR);
}

This would convert the string into RTL and align it to the left, if even one RTL-language character was in the string, and fallback to LTR otherwise. If you want the string to be RTL even if it is completely in, say English (an LTR language), then you could use TextDirectionHeuristics.RTL instead of TextDirectionHeuristics.ANYRTL_LTR.
This is the proper way of handling mixed-direction text in the absence of a TextView. Interestingly, as the documentation states,

Also notice that these direction heuristics correspond to the same types of constants provided in the View class for setTextDirection(), such as TEXT_DIRECTION_RTL.

Update:
I just found the Bidi class in Java which seems to do something similar. Look it up!
Further references:
1. Write text file mix between arabic and english.
2. Unicode Bidirectional Algorithm.

A: Try adding to your TextView:
android:textDirection="anyRtl"

For more reading:
http://developer.android.com/reference/android/view/View.html#attr_android:textDirection

A: I had the same issue and I am targeting API 16
My solution was very simple, I added to the beginning of the String "\u200F"
String mixedLanguageText = ... // mixed-language text
newText = "\u200F" + mixedLanguageText;

"\u200F" = Unicode Character 'RIGHT-TO-LEFT MARK' (U+200F)

A: The following code snippet demonstrates how to use unicodeWrap():
String mySuggestion = "15 Bay Street, Laurel, CA";
BidiFormatter myBidiFormatter = BidiFormatter.getInstance();

// The "did_you_mean" localized string resource includes
// a "%s" placeholder for the suggestion.
String.format(R.string.did_you_mean,
        myBidiFormatter.unicodeWrap(mySuggestion));


Q: bootstrap 3 navbar active li background I have a bootstrap navbar in this fiddle and its dropdown is visible on hover the mouse as
 $('.navbar .dropdown').hover(function () {
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
    }, function () {
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(180)
    });

But how to make the parent li background still active as when mouseover down to dropdown menu similar to one without sliding.

A: You can simply add class open on-hover and remove it on mouse leave.
See below example,

  $(document).ready(function() {
    $('.navbar .dropdown').hover(function() {
        $(this).addClass('open');
      },
      function() {
        $(this).removeClass('open');
      });
  });

<link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link


Q: What Http verb should the route to log out of your web app be? Browser support issues aside, if you're being an Http/hateoas stickler what verbs should the request to log into/out of a site be?
DELETE would seem like the obvious choice but I'm not sure what the resource you're deleting would be.

A: Just want to clarify the accepted answer on how to logout, I use POST to a session resource (http://example.com/sessions/) for Login and the response includes a Location of the newly created session (http://example.com/sessions/a8edjn239sd8h2er).
For Logout, DELETE the session resource pointed by the Location from POST response.
You can Login/Logout multiple of times. Only first DELETE would return no content (204), after that it should return not found response (404). Logging in multiple times will create multiple sessions.

A: The common choice is POST, and it makes sense. The 'safe' verbs (GET, HEAD, OPTIONS, TRACE) are out, because they cannot have semantic side effects that change the observable state of the application (and logging in and out is such a state).
PUT and DELETE are theoretical possibilities; the resource you are creating (PUT) and removing (DELETE) would be the user's session. However, there are a few oddities about this: first of all, PUT and DELETE, while not safe like HEAD, are still supposed to be idempotent, that is, logging out several times in a row without logging back in would have to be valid, and so would logging in again while still logged in. Furthermore, such a double login cannot alter the state of the application beyond what the first login does, which, considering things like session IDs and such, is problematic. Also, strictly speaking, the URL you are PUTting to is supposed to uniquely identify the resource you are pushing, so in order to be semantically correct, you'd have to PUT to http://example.com/sessions/a8edjn239sd8h2er instead of http://example.com/login, that is, a unique identifier for the session would have to be encoded in the URL - but then, the session ID is generated along with the session, so the ID does not exist yet until after successful login.
The semantics of POST are a much better fit: your login URL (say, http://example.com/login) identifies a resource (the application's 'login functionality') that you are about to "annotate", that is, it changes an aspect of that resource. Unlike PUT and DELETE, POST requests do not have to be idempotent, which means multiple identical POST requests can continue to change the application state - this is exactly what you want.
Wikipedia's description of the various verbs is actually quite revealing in this regard:
https://en.wikipedia.org/wiki/HTTP_Verbs#Request_methods

A: HTTP is stateless, so you're never logging in/out of a website, those are just clever names we use for the cookie implementation.
What you actually do is GET an authentication token (cookie), after you POST authentication details. That your browser stores that cookie for you is just a convenience. Finally, after you're done with your authentication token, you POST that token to the server to let it know that it can be destroyed. Again, this all happens with cookies in the browser as a convenience.
If you want to be an HTTP stickler, your HTTP needs to be stateless (and maybe RESTful).


Q: Export selected columns (to excel or dbf) in ArcGIS Desktop 10.1 I have lots of column in shapefile and I need few columns.
Therefore, I am trying to select using control and trying to export but it exports all the columns (I did not get “selected records “option while exporting)
Image 1 :
I tried using ArcToolbox (Data management tools and few more) but not getting suitable option.
Researching on Google and going through following posts:
Post 1 ,Post 2 (I do not think its proper way)
So any help will be great!!

A: Use can use the ArcToolbox > Data Management Tools > Fields > Delete Field geoprocessing tool. Your shapefile can be specified in the Input Table parameter. Then just choose what fields will be deleted. Remember to create a copy of the shapefile first, so you have original data!

A: There have been updates since this question was last posted. But just in case, here is a possible way to resolve and/or split your full database table into smaller feature classes or tables.
right click on the shapefile/table/feature class that has your entire data, select the fields tab, deselect/Deselect fields for the sub class or table you need, click OK, then export your data into the format you need. It should only have the columns you have chosen
Layer > Fields > "choose which fields will be visible" > OK
then Layer>Export Data

A: Please try in ModellBuilder:
Use tool Make Table View (Data Management) to create a subset of fields. Then use Copy Rows (Data Management) to export these fields to new table.

A: You can turn Fields off  by right-clicking on them in the table view and selecting "Turn Field off".
Or you can do it in the dataset properties -> "Fields" tab by unchecking the checkboxes next to the field name.
Fields that are turned off won´t be exported.


Q: Handling STX-ETX frame with Netty Have to implement the following TCP/IP protocol implementation with Netty:
Message structure:
The messages are embedded in an STX-ETX frame:

STX    MESSAGE      ETX
0x02   7b20224d...  0x03

An `escaping` of STX and ETX within the message is not necessary since it is in JSON format

Escape sequence are following:

JSON.stringify ({"a": "\ x02 \ x03 \ x10"}) → "{" a \ ": " \ u0002 \ u0003 \ u0010 \ "}".

Here is more info about STX, ETX control codes.
Length of the message could be different and it will have JSON format, something like:

\0x02{"messageID": "Heartbeat"}\0x03

My idea was made a combination of custom Frame delimiter with StringEncoder/StringDecoder.
For custom Frame delimiter -> use 0x03 as a delimiter and skip the first byte (0x02).
So created the following FrameDelimiterDecoder:
@Slf4j
public class FrameDelimiterDecoder extends DelimiterBasedFrameDecoder {

    public FrameDelimiterDecoder(int maxFrameLength, ByteBuf delimiter) {
        super(maxFrameLength, delimiter);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
        ByteBuf buffFrame = null;

        Object frame = super.decode(ctx, buffer);
        if (frame instanceof ByteBuf) {
            buffFrame = (ByteBuf) frame;
        } else {
            log.info("frame: {}", frame);
        }

        if (buffFrame != null) {
            buffFrame.writeBytes(buffer.skipBytes(1));
        } else {
            log.warn("buffer is <null>");
        }

        return buffFrame;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage(), cause);
    }
}

And use it for initialisation:
@Slf4j
@Component
@RequiredArgsConstructor
public class QrReaderChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final StringEncoder stringEncoder = new StringEncoder();
    private final StringDecoder stringDecoder = new StringDecoder();

    private final QrReaderProcessingHandler readerServerHandler;
    private final NettyProperties nettyProperties;

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast(new FrameDelimiterDecoder(1024 * 1024, Unpooled.wrappedBuffer(FrameConstant.ETX)));

        if (nettyProperties.isEnableTimeout()) {
            pipeline.addLast(new ReadTimeoutHandler(nettyProperties.getClientTimeout()));
        }
        pipeline.addLast(stringDecoder);
        pipeline.addLast(stringEncoder);
        pipeline.addLast(readerServerHandler);
    }
}

However, it always fails with:
c.s.netty.init.FrameDelimiterDecoder     : java.lang.IndexOutOfBoundsException: readerIndex(28) + length(1) exceeds writerIndex(28): PooledUnsafeDirectByteBuf(ridx: 28, widx: 28, cap: 1024)

io.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException: readerIndex(28) + length(1) exceeds writerIndex(28): PooledUnsafeDirectByteBuf(ridx: 28, widx: 28, cap: 1024)
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:471)

Could not understand what is missing there.
How to process STX-ETX frame for request/response with Netty?

A: After try and fails finally, solved this issue.
Rethink the code for FrameDelimiterDecoder and found the way how to do it with an array of bytes and at the end convert to ByteBuf. I believe it could be done with the buffer directly or to use ByteBuffer from NIO package and then convert.
The simplest for me was:
@Slf4j
public class FrameDelimiterDecoder extends DelimiterBasedFrameDecoder {
    public FrameDelimiterDecoder(int maxFrameLength, ByteBuf delimiter) {
        super(maxFrameLength, delimiter);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) {
        boolean inMessage = false;

        int size = buffer.readableBytes();

        ByteBuffer byteBuffer = ByteBuffer.allocate(size);
        buffer.readBytes(byteBuffer);

        byte[] byteArray = new byte[size - 2];
        byte[] data = byteBuffer.array();

        int index = 0;
        for (byte b : data) {
            if (b == FrameConstant.START_OF_TEXT) {
                if (!inMessage) {
                    inMessage = true;
                } else {
                    log.warn("Unexpected STX received!");
                }
            } else if (b == FrameConstant.END_OF_TEXT) {
                if (inMessage) {
                    inMessage = false;
                } else {
                    log.warn("Unexpected ETX received!");
                }
            } else {
                if (inMessage) {
                    byteArray[index] = b;
                    index += 1;
                }
            }
        }

        return Unpooled.wrappedBuffer(byteArray);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof InterruptedException) {
            log.warn("interrupted exception occurred");
            Thread.currentThread().interrupt();
        } else {
            log.error("FrameDelimiterEncoder exception occurred:", cause);
        }
    }
}

Where FrameConstant look like:
@UtilityClass
public class FrameConstant {
    public final int START_OF_TEXT = 0x02;
    public final int END_OF_TEXT = 0x03;

    public final int MAX_FRAME_LENGTH = 1024 * 1024;
}

Then initialize it:
@Slf4j
@Component
@RequiredArgsConstructor
public class QrReaderChannelInitializer extends ChannelInitializer<SocketChannel> {
    private final StringEncoder stringEncoder = new StringEncoder();
    private final StringDecoder stringDecoder = new StringDecoder();

    private final QrReaderProcessingHandler readerServerHandler;
    private final NettyProperties nettyProperties;

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();

        // Add the delimiter first
        pipeline.addLast(getDelimiterDecoder());

        if (nettyProperties.isEnableTimeout()) {
            pipeline.addLast(new ReadTimeoutHandler(nettyProperties.getClientTimeout()));
        }
        pipeline.addLast(stringDecoder);
        pipeline.addLast(stringEncoder);
        pipeline.addLast(readerServerHandler);
    }

    private FrameDelimiterDecoder getDelimiterDecoder() {
        ByteBuf delimiter = Unpooled.wrappedBuffer(new byte[]{FrameConstant.END_OF_TEXT});
        return new FrameDelimiterDecoder(FrameConstant.MAX_FRAME_LENGTH, delimiter);
    }
}

And some modification for handler:
@Slf4j
@Component
@RequiredArgsConstructor
@ChannelHandler.Sharable
public class QrReaderProcessingHandler extends ChannelInboundHandlerAdapter {
    private final PermissionService permissionService;
    private final EntranceService entranceService;
    private final Gson gson;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String remoteAddress = ctx.channel().remoteAddress().toString();
        String stringMsg = (String) msg;

        if (log.isDebugEnabled()) {
            log.debug("CLIENT_IP: {}", remoteAddress);
            log.debug("CLIENT_REQUEST: {}", stringMsg);
        }

        if (HEARTBEAT.containsName(stringMsg)) {
            HeartbeatResponse heartbeatResponse = buildHeartbeatResponse();
            sendResponse(ctx, heartbeatResponse);

        }
    }

    private <T> void sendResponse(ChannelHandlerContext ctx, T response) {
        ctx.writeAndFlush(formatResponse(response));
    }

    private <T> String formatResponse(T response) {
        String realResponse = String.format("%s%s%s",
                (char) FrameConstant.START_OF_TEXT,
                gson.toJson(response),
                (char) FrameConstant.END_OF_TEXT);

        log.debug("response: {}", realResponse);
        return realResponse;
    }

And finally, it sends correctly formed response back:


Q: Deploy small change to google app engine I want to deploy a change in my app.yaml file to google app engine. Is there a simple way to do this without redeploying the whole app? Is there a way of changing the app.yaml file on the google cloud directly? Or just deploying one file from my Windows directory?
My app is working fine in the virtual environment but I'm having some issues on the google cloud platform. The whole deploying process takes quite a while so I'm looking for a faster way to make a change and test it.

A: You can use appcfg.py update app.yaml from AppEngine Python SDK:
https://cloud.google.com/appengine/docs/standard/python/tools/appcfg-arguments#update

Use the files argument to upload one or more YAML files that define
  modules. No other types of YAML files can appear in the command line.
  Only the specified modules will be updated.

A: You can try using gcloud app deploy inside the directory where your application is located in order to upload the file you need.

Specifying no files with the command deploys only the app.yaml file of a given service.

This command will only upload to the cloud the files where there are changes, so if you have only modified the app.yaml file, it should not take too much time for the upload. However, as that is the configuration file of your application, it might need to be re-deployed completely, as the changes made in that file might affect the behaviour of the whole app. That is the reason why it might be taking longer than expected.
On the other side, you may want to know that if you are using App Engine Flexible environment, the deployment will always be slower than in a Standard environment, as resources have to be deployed before launching the application itself.


Q: How can a SQLAlchemy query use MySQL's REGEXP operator? How can this SQL query:
SELECT * from table where field REGEXP 'apple|banna|pear';

be written using SQLAlchemy?
My base query looks like this:
query = session.query(TableFruitsDTO)

A: The SQLAlchemy docs describe how to use the MySQL REGEXP operator.  Since there is no built-in function, use .op() to create the function:
query = session.query(TableFruitsDTO).filter(
     TableFruitsDTO.field.op('regexp')(r'apple|banana|pear')
)


Q: Ball released from accelerating car, and observed by observer in two different frames Consider an accelerating car in which u r sitting and holding a ball and a guy stand outside.
Now if u release the ball, what will be the motion of the ball seen by u and the guy? Now switch of earth's gravity, now what is the motion of ball seen by you and guy. Another case is considering elevator which is accelerating upward and the bwll is dropped inside and one is outside the elevator, now what will be the motion of ball seen by observer in and out of elevator?

A: For you the ball will fall down with an acceleration g and move left with an acceleration equal to car ( if the car is going right for an inertial observer who is out of the car (obviously)). The path would be complicated. For the ground observer the ball would be going right with a final velocity and also going down with an acceleration g. The path will be a parabola.
If you switch off gravity , then for you the ball would go left with an acceleration equal to that of the car. For the ground person it shall be going with a constant velocity after you release it without any vertical fall.

A: Suppose that the car, a ball and Mohapatra are moving to the left and accelerating to the left relative to a stationary observer, Guy, on the ground with magnitude $a$.
Mohapatra is in the car, holding a ball and not moving relative to the car.
At some instant when the car and Mohapatra are moving to the left at a velocity $\vec v_{\rm drop}$, Mohapatra lets go of the ball.
At the instant of release the ball is not moving relative to Mohapatra but Guy  sees the ball moving to the left with velocity $\vec v_{\rm drop}$.
Guy on the ground now sees the ball undergo motion consisting of a constant velocity to the left (no horizontal forces) and an acceleration $\vec g$ downwards due to the attraction of the ball by the Earth.
This is the parabolic motion of a projectile shown in green on the diagram.

Mohapatra sees the sum of two accelerated motions.
Acceleration of free fall $\vec g$ downwards and an acceleration $\vec a$ to the right equal in magnitude to the acceleration of the car relative to the ground.
Mohapatra will see the ball drop and move to the right along a straight line path (red on the diagram) with acceleration of magnitude $\sqrt{a^2+g^2}$ at an angle to the vertical of $\tan^{-1} \left ( \dfrac {a}{g}\right)$.
Switching off gravity will result in the motions shown by the dots at the top of the diagram.
Guy on the ground will see the ball move to the left along a horizontal path with a constant velocity $\vec v_{\rm drop}$.
Mohapatra in the car will see the ball accelerate horizontally to the right with an acceleration $\vec a$.
I both cases Mohapatra is in a non-inertial frame of reference and could reason that there is a horizontal (pseudo)force acting on the ball to the right, $m \vec a$ , where $m$ is the mass of the ball.

Hopefully you can now answer your own last few questions?


Q: Is there an analog to the Church-Turing thesis in model theory? Before the applications in theoretical computer science, Turing machines were developed as a model of what the idealized mathematician could possibly compute in order to give a precise definition of "effectiveness", and thus giving a universal model of computation. The affirmation that Turing machines actually are such a universal model, at least roughly speaking, is the Church-Turing thesis.
It thus seems like a natural question to ask: "Is there a universal theory for all possible mathematical theories?" In other words, does there exist some theory in which we could interpret any theory that an idealized human mathematician could possibly devise? Such a theory would be an honest to goodness "foundation of mathematics", in the sense that, unlike ZFC, in which we can express any most theories that mathematicians tend to think about, we can express anything possibly devisable.
Call this theory $X$, then for example, $X$ admits an interpretation of ZFC, ZFC + any large cardinal you could think of, MLTT, MLTT with arbitrary type universes, etc...
I would imagine that like the Chruch-Turing thesis, we could not possibly rigorously prove such a proposition, but that we should be able to find some reasonable candidate for this "$X$" theory. Has this, or similar notions, been thought about in model theory?

A: Since you mention universal Turing machines, perhaps this satisfies what you are looking for:
Any reasonable, in practice usable axiomatisation of mathematics has the property that proofs in that system can be expressed as finite strings of characters from a finite alphabet; and if $T$ is a string of characters, then there is an algorithm (a computable function) which determines whether or not that is a valid proof in the system. E.g., for ZFC, the alphabet consists of (say) alphanumeric characters, parentheses, logical symbols, the symbol $\in$ and maybe some separators. The computable function checks whether the proof consists of well formed formulas, and whether each one either follows from a previous one (depending on the proof system chosen) or is an axiom (of ZFC or in the proof system).
Now such an algorithm can be formalized within a "weak" theory like Peano arithmetic. Thus, if we have $\mathrm{ZFC} \vdash \phi$, then we can also prove $\mathrm{PA} \vdash ``\mathrm{ZFC} \vdash \phi"$. For instance, we have that $\mathrm{PA} \vdash ``\mathrm{ZFC} +\mathrm{IC} \vdash \mathrm{Con}(\mathrm{ZFC})"$. Hence, every system of mathematics that I referred to above as reasonable/usable can be internalized in Peano arithmetic (or another sufficiently strong) theory.


Q: toggle menu with javascript One of the theme I am using on wordpress use toggle menu if the parent menu have child menu under.
This is the current js code
    var navItemDropdown = $('#nav li .dropdown');
navItemDropdown.each(function(){
    thisDropdown = $(this);
    $(this).parent().prepend('');
});

$('body').on('click','.sub-nav-toggle',function(event){

    $(this).parents('li').toggleClass('active');
    thisDropdown = $(this).parents('li').find('.dropdown');
    thisDropdown.slideToggle('fast');
    return false;

});

It's added  if there's a child menu.
The code of menu which have child menu becomes like this

About Us

Who we are

Our Vision

What I would like to achieve is instead of injecting the , I would like to insert class="sub-nav-toggle" inside the a href tag. Which means  tag will become like this
About Us

There's a way I can add the class for the menu through Wordpress Menu, but it's only added the class inside
 tag instead of  tag, so it's not working and cannot do that way.
Please help me out. Thank you.

A: I think you need  to change this:
$(this).parent().prepend('');

to this:
$(this).prev().addClass('sub-nav-toggle');


Q: how can we make ListHeaderComponent as sticky header in SectionList? Description
i am using horizontal tab bar inside ListHeaderComponent and I want make ListHeaderComponent as a sticky header in SectionList. we can make stickyheader in flatlist by stickyHeaderIndices={[0]} but it does not work in SectionList
React Native version:
React Native Environment Info:
    System:
      OS: macOS 10.14.6
      CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
      Memory: 38.35 MB / 16.00 GB
      Shell: 5.3 - /bin/zsh
    Binaries:
      Node: 12.15.0 - /usr/local/bin/node
      Yarn: 1.21.1 - /usr/local/bin/yarn
      npm: 6.13.4 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.4, macOS 10.14, tvOS 12.4, watchOS 5.3
      Android SDK:
        API Levels: 28, 29
        Build Tools: 28.0.3, 29.0.1, 29.0.2
        System Images: android-26 | Google Play Intel x86 Atom, android-27 | Google APIs Intel x86 Atom
    IDEs:
      Android Studio: 3.5 AI-191.8026.42.35.5791312
      Xcode: 10.3/10G8 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.6 => 16.8.6
      react-native: 0.59.8 => 0.59.8
    npmGlobalPackages:
      rename-horizon: 1.1.0
      react-native-cli: 2.0.1

Steps To Reproduce
Provide a detailed list of steps that reproduce the issue.

*

*make section list  and add ListHeaderComponent props

*add stickyHeaderIndices={[0]} in section list
it will not make ListHeaderComponent as sticky header

Expected Results
it should be making ListHeaderComponent as a sticky header. or alternative way to make it sticky header

A: Use something like this.
<View style={{ flex: 1 }}>
  {renderStickyListHeaderComponent()}
  <SectionList
    {...sectionListprops}
    ref={sectionListRef}
    sections={sectionData}
    stickySectionHeadersEnabled={false}
  />
</View>

A: To make the top or any other header sticky for section list, provide a custom scroll component:
const CustomScrollComponent = (props) => <ScrollView {...props} stickyHeaderHiddenOnScroll={true} stickyHeaderIndices={[0]} />

then in your section list:
<SectionList
  // other props
  renderScrollComponent={CustomScrollComponent}
/>

A: you can use renderSectionHeader & stickySectionHeadersEnabled = true
render() {
  return (
    <SectionList
      data={sections}
      renderSectionHeader = {({section:{title}}) => (<YourHeader>)}
      stickySectionHeadersEnabled/>
 )
}


Q: (HTML5) Can't load my image For some reason, despite using the right syntax(to my knowledge) and having the image file in the same folder as my HTML document, when I load the document, the image I programmed to load does not appear on the page. What could be the issue here?
Here, my HTML file is clearly in the same folder as my image..
https://gyazo.com/ac35ed711716d9e8c5b34123f80d71d1
And here is my code (this is for q3.html)
<!DOCTYPE html>

        <title>Question Three</title>

Dominos Pizza order form

I am running this on a Macbook Pro, using TextEdit as my editing tool. Here is what my page looks like after I open the document:
https://gyazo.com/0a527e90897d082b1f722c3293ad34d0

A: Notice “ in your . It is not the actual quotes. Thus replace “ with ".
Thus the new HTML would be as follows
<!DOCTYPE html>

        <title>Question Three</title>

Dominos Pizza order form


Q: Benefits of using WITH TABLOCK on an INSERT Under some circumstances, doing an INSERT INTO <tablename> (WITH TABLOCK) will be faster due to minimal logging. Those circumstances include having the database in the BULK_LOGGED recovery model.
Is there any other potential performance benefit to using WITH TABLOCK on an INSERT on an empty table when the database (tempdb) is using the SIMPLE recovery model?
I'm working with SQL Server 2012 Standard Edition.
My use case is for creating and then immediately populating a temp table within a stored procedure using an INSERT...SELECT, which could contain as many as a few million rows. I try to avoid that kind of tempdb abuse, but it is sometimes needed.
I'm trying to build a case to require TABLOCK. It doesn't seem like it would hurt anything, and might have a benefit. I'm trying to figure out if there is enough potential benefit to add it wherever throughout our code base, where I'm sure there is no other process that wants to write to the table.
I'm usually inserting into a newly created local temp table with a clustered PK, but do sometimes use a heap.

A: I know of a few benefits but they're mostly situational.

*

*Using TABLOCK will reduce concurrency but will immediately take a table lock on the target table. As long as you can guarantee that just one session will insert into the table this will avoid unnecessary row or page locks and will prevent lock escalation. After all, if you are inserting so much data that you'll get lock escalation anyway why not do it upfront?

*If you are inserting into an empty page-compressed heap without TABLOCK all of the pages will have row compression instead of page compression:

The newly inserted row is page-compressed:

*

*if new row goes to an existing page with page compression

*if the new row is inserted through BULK INSERT with TABLOCK

*if the new row is inserted through INSERT INTO ... (TABLOCK) SELECT FROM
Otherwise, the row is row-compressed.

*In SQL Server 2016 the TABLOCK hint is required to get parallel insert into heaps, CCIs (Clustered Columnstore Indices), and local temp tables. There are lots of restrictions, some of which aren't documented. There can't be an IDENTITY column, the insert can't be done through an OUTPUT, etc.

See also The Data Loading Performance Guide


Q: First selected item value from checkbox collection My html code is as below.

                <%
                    var rooms = Model.AvailableRooms.ToList();
                %>

                    <%
                        foreach (var r in rooms)
                        {
                    %>
                        <input type="checkbox"
                            value="<%: r.Id %>-<%: r.Name %>-<%: Model.Provider.Key %>" />

                        <%: r.Name %>

                    <%
                        }
                    %>

From that I need to get the first selected item's value.How could I do that ?

A: Use jQuery selectors to get it:
$("input[type='checkbox']:checked").first().val()

or
$("input[type='checkbox']:checked:first").val()

JSFIDDLE

A: $('input[type=checkbox]:checked').first()

A: $('#rooms input:checked:first').val()


Q: Put json data from jquery into Thymeleaf I am using google book api for ISBN and I am able to get data. Now I want to attach that data into a form. I am not able to that.
This is my Jquery Code
$(document).ready(function(){
    $('#submitCode').click(function(){
    var x;
     var isbn = $('#isbn').val();
     var xmlhttp = new XMLHttpRequest();
     var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;

        xmlhttp.onreadystatechange = function() {
        /*<![CDATA[*/
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        x = JSON.parse(xmlhttp.responseText);
        callback(x);
       }/*]]>*/
       };
       xmlhttp.open("GET", url, true);
       xmlhttp.send();

function callback(x) {
alert(JSON.stringify(x));
console.log(x);
};
});
});

My HTML code

 <input id="author" name="author" th:field="*{author}" type="text" class="validate" />
  Author

  <input id="title" name="title" th:field="*{title}" type="text" class="validate" />
   Title

How should I attach author data and title into the form in Thymeleaf?

A: If you've been able to retrieve the data already, you should only need to update the DOM using $('#id').val(value). I did a bit of digging, and it looks like your API returns the title and authors like this, hence the use of json.items[0].volumeInfo in the new callback code.
{
  "items": [{
    "volumeInfo": {
      "title": "Example Title",
      "subtitle": "Example Subtitle",
      "authors": [ "Example Author" ]
    }
  }]
}

$(document).ready(function() {
  $('#submitCode').click(function() {
    var x;
    var isbn = $('#isbn').val();
    var xmlhttp = new XMLHttpRequest();
    var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;

    xmlhttp.onreadystatechange = function() {
      /*<![CDATA[*/
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        x = JSON.parse(xmlhttp.responseText);
        callback(x);
      } /*]]>*/
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    function callback (json) {
      var book = json.items[0].volumeInfo
      $('#author').val(book.authors.join('; '))
      $('#title').val(book.title)
    };
  });
});

<input id="isbn" type="text" value="1904764827"/>ISBN

  <input id="author" name="author" th:field="*{author}" type="text" class="validate" />
  Author

  <input id="title" name="title" th:field="*{title}" type="text" class="validate" />
  Title

<button id="submitCode">Submit</button>


Q: Uneven Results Doing A Sort / Orderby on Amazon SimpleDB I've been getting really uneven results trying to request a numerically sorted list of records from Amazon SimpleDB.
I am zero padding my numbers to get them selected lexigraphically, but still no luck. These two queries are giving the same result, for example:

select * from cbcallers where calls_completed is not null order by calls_completed desc

select * from cbcallers where calls_completed is not null order by calls_completed asc

However, I am getting the correct results using Amazon's query language:

['calls_completed'starts-with ''] sort 'calls_completed' desc

And last week, I was getting different (unordered) results from this query on the same dataset. Anyone have any idea what's up? Is my query jacked?
The dataset looks like this:

Sdb-Item-Name, calls_completed, name, icon
8uda23sd7, 0000002, john smith, /myimgicon.jpg
8uda5asd3, 0000015, john smarts, /myimgicon2.jpg
8udassad8, 0000550, john smoogie, /myimgicon3.jpg

A: Your query looks completely correct. I loaded your data and used your queries verbatim and got just what you would expect.
Ascending:
select * from cbcallers where calls_completed is not null order by calls_completed asc
[
Item  8uda23sd7
  icon: myimgicon.jpg
  name: john smith
  calls_completed: 0000002,
Item  8uda5asd3
  icon: myimgicon2.jpg
  name: john smarts
  calls_completed: 0000015,
Item  8udassad8
  icon: myimgicon3.jpg
  name: john smoogie
  calls_completed: 0000550]

Descending:
select * from cbcallers where calls_completed is not null order by calls_completed desc
[
Item  8udassad8
  icon: myimgicon3.jpg
  name: john smoogie
  calls_completed: 0000550,
Item  8uda5asd3
  icon: myimgicon2.jpg
  name: john smarts
  calls_completed: 0000015,
Item  8uda23sd7
  icon: myimgicon.jpg
  name: john smith
  calls_completed: 0000002]

Maybe it is an issue with your SimpleDB client, which one are you using, do you know if it is using the latest SimpleDB API version ("2009-04-15")?


Q: Handling user registrations Using only Django without the need to be redirected to other template This is my view
class UserRegistrationView(FormView):
    template_name = "register/register_form.html"
    form_class = None
    extra_fields_form_page_slug = ""
    email_template = "register/account_activation_email.html"

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        add_extra_fields(
            form.fields, form.helper.layout.fields, self.extra_fields_form_page_slug
        )
        return form

    def get_extra_form(self):
        return FormPage.objects.filter(slug=self.extra_fields_form_page_slug).first()

    def form_valid(self, form):
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        email = form.cleaned_data.get("email")
        email_template = "register/account_activation_email.html"

        send_confirmation_email(
            self, "Activate Your  Account", user, email, email_template
        )
        return render(self.request, "register/after_submission.html")

This is working fine (registration wise) but it's not from many other sides, because I have the registration form as a pop up window in the header, so it's available throughout the whole website, my problems are:

*

*if the user had a successful registration they will be redirected to the specified template "after_submission" what I want is to stay on the same page and display a pop up with some message

*if the user had an unsuccessful registration they will be redirected to the main template "register_form.html" with the errors displayed their, what I want is to stay on the same page and to display the error messages on the pop up form if the user opened it again

is this achievable using only Django?? or I must throw some JS in there, and if JS is the answer, can you give me a quick insight into how to do it?

A: You can redirect to the same page in your CBV :
from django.http import HttpResponseRedirect

return HttpResponseRedirect(self.request.path_info)

As stated in the comment your solution require Ajax and JS, you can however redirect to the same page but that will make a new request and refresh the whole page which might no be ideal for you.
There is a tutorial to work with Django and Ajax Ajax / Django Tutorial


Q: Data return is undefined vue.js? i have a problem i don't understand why i can't recover my recette.
My route at node is ok i have my good res ut at vue my code don't work my res is undefined.
What I am trying to do is to filter my recipes by retrieving only the recipes which have as category recipe 1. I made a route on node which works and which returns me exactly what I want but at the level of view i have a problem.
NODE.JS
router.get("/recette_light", (req, res) => {
    db.cat_recette
        .findOne({
            where: { id: req.body.id },
            include: { all: true },
        })
        .then((cat_recette) => {
            if (cat_recette) {
                res.status(200).json({
                    cat_recette: cat_recette,
                });
            } else {
                res.json("il n'y a pas de cat_recettes");

            }
        })
        .catch(err => {
            res.json(err);
        });
});

VUE.JS
<div>
    <navbar_user />
    <mylight :recette="recette" :user="user" />
    <myfooter />
  </div>
</template>

<script>
import navbar_user from "../components/navbar_user";
import mylight from "../components/light";
import myfooter from "../components/myfooter";

export default {
  name: "",
  data() {
    return {
      recette: "",
      user: "",
    };
  },
  components: {
    navbar_user,
    mylight,
    myfooter,
  },
  created: function() {
    this.axios
      .get("http://localhost:3000/recette/rec_recette/:1")
      .then((res) => {
        (this.cat_recette.recette = res.data.recette),
          this.axios
            .get(
              "http://localhost:3000/user/rec_user/" +
                localStorage.getItem("email")
            )
            .then((res) => {
              this.user = res.data.user;
            });
      });
  },
};

Thank you for your help i'm novice

A: On the frontend, you are making an HTTP request with the GET method, which has no body. On the backend, req.body.id will be undefined because there is no request body in the first place.
So you have several options:

First: use a POST request on the front end

axios({
  method: 'POST',
  url:"http://localhost:3000/recette/rec_recette",
  headers: {},
  data: {
    id: 'votre_id_ici', // This is the body part
  }
});

The backend code to handle the post request:
(Use async/await to make the code cleaner)
router.post('/recette_light', async (req, res) => {

    try {
        // Assuming you are searching for your recette using MongoDB doc.id
        const cat_recette = await db.cat_recette.findById(req.body.id);
        // If there are no matching docs.
        if (!cat_recette) {
            return res.json("il n'y a pas de cat_recettes");
        }
        // Otherwise send the data to the frontend
        res.status(200).json({ cat_recette: cat_recette, });

    } catch (err) {
        console.log(err);
        res.status(500).json({ msg: 'Server Error', });
    }

});

Second: use the GET method still but with URL parameters

axios.get("http://localhost:3000/recette/rec_recette/votre_id_ici")

The backend code to handle it:
// Note the /:id at the end
router.get('/recette_light/:id', async (req, res) => {

    try {
        // Assuming you are searching for your recette using MongoDB doc. id
        // Note the req.params.id here not req.body.id
        const cat_recette = await db.cat_recette.findById(req.params.id);
        // If there are no matching docs.
        if (!cat_recette) {
            return res.json("il n'y a pas de cat_recettes");
        }
        res.status(200).json({ cat_recette: cat_recette, });

    } catch (err) {
        console.log(err);
        res.status(500).json({ msg: 'Server Error', });
    }

});


Q: iOS project can't run when AIR SDK upgraded to 3.6 That is very simple flash iOS project with FB 4.7, AIR SDK 3.6, and running on iPad2(5.1.1).
When I debug with the default AIR SDK 3.4 of FB 4.7, the project is running ok. But, when I upgrade the AIR SDK to 3.6 according the help of Adobe. The FB 4.7 debuger can't connect to running process, and the "hello world" doesn't show as well.
Any suggestions?

A: I know what's wrong with the problem.
The key is the step 4. in Adobe AIR SDK Upgrade Help.
Copy the contents from the aot folder (AIRSDK_back_up\lib\aot) of the AIR SDK backup to the aot folder of the newly created AIR SDK (AIRSDK\lib\aot).
Don't copy all contents from the aot folder, just copy strip from lib\aot\bin to the aot bin folder of the newly created AIR SDK 3.6 (AIRSDK\lib\aot\bin).
Then, I restart the FB 4.7, the "hello world!" show as well.


Q: Orthogonal system in Sobolev Space $H^1(-\pi,\pi)$ I am having trouble with this exercise:
Prove that $\{e^{int}\}_{n\in\mathbb{Z}}\bigcup \{sinh(t)\}$ constitute a complete orthogonal system in Sobolev space $H^1(-\pi,\pi)$, defined as:
$$H^1(-\pi,\pi):=\{f \in L^2(-\pi,\pi): f'\in L^2(-\pi,\pi) \}$$
which forms a Hilbert space, provided the inner product:
$$\langle f(t),g(t) \rangle_1 = \int_{-\pi}^{\pi}{f(t)\overline{g(t)}dt}+\int_{-\pi}^{\pi}{f'(t)\overline{g'(t)}dt}$$
I have so far established that it would be sufficient to prove that $\{e^{int}\}_{n\in\mathbb{Z}}^\bot$ has dimension 1 and $sinh(t)\in\{e^{int}\}_{n\in\mathbb{Z}}^\bot$
But I don't know how to prove that $\{e^{int}\}_{n\in\mathbb{Z}}^\bot$ has dimension 1.
There is also a hint: the standard Fourier coefficients of a function orthogonal to $\{e^{int}\}_{n\in\mathbb{Z}}$ are like:
$$g_n = \frac{c (-1)^n n}{n^2 + 1}$$ with $n \in \mathbb{Z}$ and $c \in \mathbb{C}$.
Any help would be very appreciated.

A: The main tricky thing here is that you cannot really differentiate a given function in $H^1$ term-by-term since the resulting sum may diverge. Instead you want to integrate term-by-term, which is more likely to be safe. So if you consider arbitrary $g' \in L^2,g'=\sum_n g_n e^{int}$, then you can write $g=f_0 + g_0 t + \sum_{n \neq 0} \frac{g_n}{in} e^{int}$.
Then $\langle g,e^{int} \rangle_{H^1}=\langle g,e^{int} \rangle_{L^2} + \langle g',ine^{int} \rangle_{L^2}$. But now these two inner products can both be evaluated by interchanging integration and summation. In particular $\langle g',ine^{int} \rangle_{L^2}=g_n \langle e^{int},ine^{int} \rangle$ and $\langle g,e^{int} \rangle_{L^2}=f_0 \langle 1,e^{int} \rangle_{L^2} + g_0 \langle t,e^{int} \rangle_{L^2} + \frac{g_n}{in} \| e^{int} \|_{L^2}^2$. Sum those up and set them all equal to zero.

A: OK, I think I just overthought this. Once I get that
$$g_n = c\frac{(-1)^n n}{n^2+1}$$
It's clear that any such $g(t)\in \{e^{int}\}_{n \in \mathbb{Z}}^{\bot}$ could written as:
$$g(t)= \sum_{n\in \mathbb{Z} } g_n e^{int} = c \sum_{n\in \mathbb{Z}} \frac{(-1)^n n}{n^2 +1} e^{int}$$
which obviously lives in a one-dimensional space.
Now, if I prove that $sinh(t)\in \{e^{int}\}_{n \in \mathbb{Z}}^{\bot}$ the proof is done.
Please tell me if I am right or not. I am new on this topic.


Q: convergence of the series $\sum u_n, u_n = \frac{n^n x^n}{n!}$ for $x>0$ While checking the convergence of the series $\sum u_n, u_n = \frac{n^n x^n}{n!}$ for $x>0$, we used ratio test to say that for $0< x < \frac1e$ $\sum u_n$ is convergent and for $\frac1e < x<\infty$ $\sum u_n$ is divergent.
We use Logarithimic Test for the case $x = \frac1e$, where we came across computing the limit $$\lim_{n \to \infty} n+n^2 \log \frac{n}{n+1}$$ but I am stuck in finding the limit.

A: $$
n+n^2\log\frac{n}{n+1} = n-n^2\log\frac{n+1}{n} = n-n^2\log\left(1+\frac{1}{n}\right)
$$
So do some asymptotics.  As $n \to +\infty$, we have
\begin{align}
\log\left(1+\frac{1}{n}\right) &= \frac{1}{n}-\frac{1}{2n^2}+o\left(\frac{1}{n^2}\right)
\\
n^2\log\left(1+\frac{1}{n}\right) &= n-\frac{1}{2}+o(1)
\\
n-n^2\log\left(1+\frac{1}{n}\right) &= \frac{1}{2}+o(1)
\end{align}

A: It follows from Stirling's approximation that$$\frac{n^n\left(\frac1e\right)^n}{n!}=\frac{n^n}{e^nn!}\geqslant\sqrt{2\pi n}.$$Therefore, the series diverges.


Q: How to add some known objects to ace editors syntax checker? we're using the ACE editor to write javascript code that's interpreted on the server side. So the server has a JavaScript interface and can execute submitted code to accomplish some task from the outside.
The server implements some new objects that are not known by ACE. So ACE shows a warning, if one of this unknown objects is used in code.
What is the correct way to tell ACE, that there are some new objects, variables und functions? I already took a look into worker-javascript.js, but I DON'T want to reimplement this whole stuff (updating ACE would get harder than). Is there any interface I can use?

A: Ace uses jshint, which have an option to set a list of global variables.
Ace supports changeOptions call on worker to modify default options it passes to jshint, but doesn't have a way to pass list of gloabals
You can add it by changing line at https://github.com/ajaxorg/ace/blob/v1.1.8/lib/ace/mode/javascript_worker.js#L130
to lint(value, this.options, this.options.globals);
and from your code calling
editor.session.$worker.call("changeOptions", [{
   globals: {foo: false, bar: false...},
   undef: true, // enable warnings on undefined variables
   // other jshint options go here check jshint site for more info
}]);

the change to worker.js#L130 is simple enough and should be accepted if you make a pull request to ace


Q: Avoid trigger trigger execution several times - Best Practices I've been looking for a while for best practices when trying to avoid recursive trigger execution, but I haven't really found anything that I like.
At the moment, the most straight forward solution I know is to implement a small flag variable,
public static Boolean hasAlreadyExecuted = false;

and afterward simply check the flag before allowing any logic to be executed,
public void beforeUpdate(SObject oldSo, SObject so)
{
    if(!hasAlreadyExecuted)
    {
        // Do some magic with the record
    }
}

Nonetheless, I was wondering if any of you know any other methods worth commenting. At the moment, most of the times, I use a trigger-handler-helper framework to control execution, but it doesn't have any tools to help me control this, so I basically implement stuff like I commented above to solve it.

A: If you are not going to go with a full-blown trigger framework (these frameworks often handle recursion), then you can go with something like my TriggerControl object.
It uses the static variable concept, but is able to keep track of this per sObject which is good if you are dealing with a complex set of triggers interacting with each other.
Try this:
public class TriggerControl {

  @testVisible
  private static Map<System.Type, Boolean> hasRunMap = new Map<System.Type, Boolean>{
    Event.class => false,
    Opportunity.class => false
  };
  public static Boolean hasRun(System.Type entityType) {
    if (hasRunMap.containsKey(entityType)) {
      return hasRunMap.get(entityType);
    }
    return false;
  }
  public static void setHasRun(System.Type entityType) {
    hasRunMap.put(entityType, true);
  }
  public static void clearHasRun(System.Type entityType) {
    hasRunMap.put(entityType, false);
  }
}

Use it like this:
if (TriggerControl.hasRun(Event.class)){
  return;
}
else {
  TriggerControl.setHasRun(Event.class);
}

There are some improvements you can make (calling set has run in the hasRun() check) but it works quite well for me when I'm doing small projects.
This approach has some drawbacks, as Eric mentioned.
If you wanted to get a bit fancier, you could try using a per Object per Id, per major functionality method.
First you'd define your major functions in a metadata type - say

*

*Event - change status - 1 recurse

*Event - update whoId - 2 recursions

*Account - copy opportunity data - 1 recursion
Then, you could create a multilevel map (or use a multipart key like Event_ChangeStatus_a00230000rhtrgh
You could use this map or key to generate lists of records to pass to each of these helper functions.
This way you could achieve more granularity by restricting recursion at the functional level rather than the object level.

A: If you use what you've written in your question, it MUST be placed in an external class. Otherwise, a new instantiation of the same class running at the same time will see the boolean variable as being in the same context as another class that's running concurrently. This will cause your 2nd trigger handler class to fail if the recursion prevention boolean has already been set.
As others have noted, you'd also want to set this variable by trigger class. This is one of the many reasons that trigger frameworks are superior to base triggers that call handler classes.

A: This is a tricky problem. The ideal solution is to write triggers that only do something when the data matches a specific pattern - e.g. a field value changes - so that the recursion stops naturally. So avoiding recursion isn't something that can always be done in a framework independently of the specific logic.
The boolean flag approach (or keeping a set of Id values) while simple are both potentially broken. For the boolean flag, what if the set of records involved in the second execution is different than the first execution? While a set of Id values can avoid that problem, the field values might be different in the second execution so requiring different trigger output. These amount to quick fixes when you find a problem: you are typically relying on good luck (or more ideally careful analysis of the situation) that no data inconsistencies are introduced.


Q: junit and ant issue. Cannot start test When I am running a junit test from ant I always get:
D:\metrike>ant test
Buildfile: build.xml

init:

compile:

test:
    [junit] Running jmt.test.TestCodeBase
    [junit] Testsuite: jmt.test.TestCodeBase
    [junit] Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 0,046 sec
    [junit] Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 0,046 sec
    [junit]
    [junit] Testcase: warning(junit.framework.TestSuite$1):     FAILED
    [junit] No tests found in jmt.test.TestCodeBase
    [junit] junit.framework.AssertionFailedError: No tests found in jmt.test.TestCodeBase
    [junit]
    [junit]
    [junit] Test jmt.test.TestCodeBase FAILED

This is the ant file:
<target name="test" depends="compile">
    <mkdir dir="target/test-results"/>
    <junit haltonfailure="no" printsummary="on">
        <classpath >
            <pathelement location="target/classes"/>
            <pathelement location="Libraries/junit3.8.1/junit.jar"/>
        </classpath>
        <formatter type="brief" usefile="false"/>
        <formatter type="xml" />
        <batchtest todir="target/test-results" >
            <fileset dir="target/classes" includes="**/TestCodeBase.class"/>
        </batchtest>
    </junit>
</target>

But when I manually run the test, junit test works:
D:\metrike>cd target

D:\metrike\target>cd classes

D:\metrike\target\classes>java jmt.test.TestCodeBase
fatsource.jar eclapsed : 2297 ms
over all : 2297 ms
contains 3073 classes and 3700 referred classes, 35968 referred methods, 22351 referred fields
Memory usage: 21326 KB
Post gc-memory usage: 19506 KB
contains 3073 classes and 3700 referred classes, 35968 referred methods, 22351 referred fields

Can someone please tell me what I am doing wrong? I have been trying to fix this for a whole day but I cannot find the solution.

A: 1)  Does jmt.test.TestCodeBase extend TestCase (junit.framework.TestCase)?
If not, it will need to to be picked up by the junit ant task.
2)  Is the class written as a junit TestCase, or is it just called from the main method?  See this link for an example of writing simple tests in Junit3 style.  For Junit4, just add @Test above the methods.
3)  Are the test methods in Junit3 style (every method starts with test) or Junit4 style (every method has a @Test above it)?
If Junit3, you should be good to go.  If Junit4, you need to include the Junit4 test library in your ant classpath, rather than using junit3.8.1.

A: It seems your test class is not actually a JUnit test class. When you run it manually, you are not running it as a test, but as a regular Java application. The class has a main method, right? To run as a JUnit 3 (which you seem to be using) test, the class needs to extend TestCase and have one or more public void methods whose names start with 'test'. For testing, I would try running the class as a JUnit test in the IDE.

A: Please post sample code of jmt.test.TestCodeBase, esp. class definition and one of the test methods.
I looks like you use public static int main() instead of JUnit convention public void testFoo() methods. If you're using JUnit4, your test methods should have the @Test annotation.
JUnit tests usually cannot be run just with java <Testclass>


Q: Prevent new WordPress users from logging in until manually "activated"? I'm developing a plugin for WordPress which has 3 groups of users.  I need to disable some users and prevent them from login.  what I mean isn't preventing them to access the backend.  I want to prevent them from is log in.  For example, when they want to login they should see a message like this account isn't active yet.
thank you guys.

A: after some search and see similar problems I solved this problam like this :
first add a user meta for user status so we can checking if user is active or not then we can disable or enable users.
add_filter( 'authenticate', 'chk_active_user',100,2);
function chk_active_user ($user,$username)
   {
     $user_data = $user->data;
     $user_id = $user_data->ID;
     $user_sts = get_user_meta($user_id,"user_active_status",true);
     if ($user_sts==="no")
     {
        return new WP_Error( 'disabled_account','this account is disabled');

      }
      else
      {
       return $user;
      }
        return $user;
     }


Q: Using Carbon Copy Cloner 4 to create encrypted bootable HFS+ clones from APFS source Background
According to the Carbon Copy Cloner documentation CCC4 cannot clone the Recovery HD from an APFS source to an HFS+ target:

Note: CCC v4 requires an HFS+ formatted source for creating Recovery HD volumes on HFS+ formatted destination volumes. If your source volume is formatted APFS, CCC v4 will not be able to create (or update) a recovery volume on the destination. CCC v5 adds support for APFS recovery volumes.

According to other CCC documentation, spinning platter target disks should be formatted as HFS+:

Starting in macOS High Sierra, both APFS and Mac OS Extended (Journaled) are acceptable formats for a backup of macOS 10.13. Mirroring Apple's recommendations, we recommend that you choose APFS if your destination device is a Flash storage-based device (e.g. an SSD) and will be used to back up 10.13 or higher. Choose Mac OS Extended (Journaled) if your destination device is a spinning-platter-based device (i.e. a hard disk drive, or HDD), or if you are backing up an operating system older than 10.13.

Anyone who's upgraded to High Sierra with an SSD internal disk knows that your startup disk was automatically updated from HFS+ to AFPS as part of that upgrade.
A Recovery HD on an external clone might not seem like that big of a deal: you could use a bootable USB thumb drive, or maybe Internet Recovery, if needed. However, FileVault requires a Recovery HD in order to encrypt the volume, according to Apple's support documentation:

Without a Recovery System, FileVault won't encrypt your startup drive.
  https://support.apple.com/en-us/HT204837
You don't need a recovery system to install and use macOS, but without it you can't use FileVault, set up a firmware password, or use Disk Utility to repair the disk.
  https://support.apple.com/en-us/HT201316

The Question
Given all of this, how can I create a bootable, encrypted clone of my APFS High Sierra source drive using Carbon Copy Cloner 4 (CCC4) and using external HFS+ disks?

A: Here's what worked

*

*Download the High Sierra installer from the App Store.

*Run the installer, choosing the external clone disk as the target. This will automatically create a new Recovery HD partition associated with the target disk.

*Reboot from the external disk. Hold down option key during startup to select the boot disk.

*Enable FileVault encryption as usual from the Security & Privacy panel in System Preferences.

Additional Notes

*

*You can reboot from your internal drive for better performance, after enabling FileVault on the external. The encryption task will continue as long as you're plugged into power and the external disk is connected.

*It may take several hours, or even days, before encryption is done, depending on the volume of data to be encrypted.

*You can view encryption task progress using the Terminal command diskutil cs list
What didn't work
There are some articles posted about how to clone the internal disk Recovery HD volume to any other drive, but I didn't have success with them:
$ diskutil list
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *500.3 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                 Apple_APFS Container disk1         499.4 GB   disk0s2

/dev/disk1 (synthesized):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      APFS Container Scheme -                      +499.4 GB   disk1
                                 Physical Store disk0s2
   1:                APFS Volume Mac-HD                  431.9 GB   disk1s1
   2:                APFS Volume Preboot                 22.9 MB    disk1s2
   3:                APFS Volume Recovery                518.8 MB   disk1s3
   4:                APFS Volume VM                      2.1 GB     disk1s4

$ sudo hdiutil create ~/Desktop/Recovery_HD.dmg -srcdevice /dev/disk1s3
hdiutil: create failed - No such file or directory

I didn't find any articles that specifically addressed the case where the source disk is APFS format.

A: Note that the solution offered mostly only works with macOS 10.13 High Sierra. Though it may be possible to clone an APFS macOS 10.14 Mojave boot drive to HFS+, it is trickier and does not work in all cases. Also though CCC v4 may work, it is not certified to work with Mojave, so you would need CCC v5.
Also be aware of these general caveats: https://bombich.com/kb/ccc5/help-my-clone-wont-boot


Q: How can I have a test unit in the same source file? This question is Ruby related.
Suppose I want to have the test unit for my class in the same file as it's definition. Is it possible to do so? For example, if I'd pass a "--test" argument when I run the file, I'd want it to run the test unit. Otherwise, execute normally.
Imagine a file like this:
require "test/unit"

class MyClass

end

class MyTestUnit < Test::Unit::TestCase
# test MyClass here
end

if $0 == __FILE__
   if ARGV.include?("--test")
      # run unit test
   else
      # run normally
   end
end

What code should I have in the #run unit test section?

A: This can be achieved with a module:
#! /usr/bin/env ruby

module Modulino
    def modulino_function
        return 0
    end
end

if ARGV[0] == "-test"
    require 'test/unit'

    class ModulinoTest < Test::Unit::TestCase
        include Modulino
        def test_modulino_function
            assert_equal(0, modulino_function)
        end
    end
else
    puts "running"
end

or without module, actually:
#! /usr/bin/env ruby

def my_function
    return 0
end

if ARGV[0] == "-test"
    require 'test/unit'

    class MyTest < Test::Unit::TestCase
        def test_my_function
            assert_equal(0, my_function)
        end
    end
else
    puts "running rc=".my_function()
end


Q: SettingWithCopyWarning while assigning value_counts() I am trying to assign certain values to a column in a dataframe within a Python function.
    df = df[(df['date'] <= max_date) & (df['date'] > min_date) | (df['x_date'] <= max_date) & (df['x_date'] > min_date)]
    numbers = len(df)
    df["patients"] = value_counts.patients
    df["numbers"] = numbers

However, I get this error:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df["patients"] = value_counts.patients
file.py:52: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

How can I get rid of this warning?


Q: How to access htdocs folder when xampp can't open in mac Big Sur? I just found that I couldn't open Xampp after upgrading to Big Sur.
My question is: How do I access htdocs folder?
I'm afraid that it will override the htdocs folder if I install the latest version of Xampp.

A: did you check the hide folder named ".bitname" in your profile root folder? If not, try to find the "xampp" folder inside ".bitname/machines" and copy it to another folder to backup current xampp data.
After isntall/reinstall xampp just put the folder back to the same place ".bitname/machines".
Steps:

*

*Open Finder and make hidden files visible (cmd + shift + .)

*Go to folder /Users/USERNAME/.bitnami/stackman/machines and backup/copy complete xampp folder to a safe place

*Delete everything in folder /Users/USERNAME/.bitnami/stackman

*Download from https://sourceforge.net/projects/xamp...

*Install newest version of XAMPP

*Run XAMPP once for all folders to be created

*Quit XAMPP

*Rename new folder /Users/USERNAME/.bitnami/stackman/machines/xampp to /Users/USERNAME/.bitnami/stackman/machines/xampp_original

*Copy saved folder xampp  to /Users/USERNAME/.bitnami/stackman/machines

*Run XAMPP

PS: If you have another MAC maybe is a good idea to test it before using a simulated xampp instalation!


Q: Why don't I need to specify "typename" before a dependent type in C++20? This bit of code compiled in C++20 (using gcc 10.1) without using the typename keyword before the dependent type std::vector<T>::iterator. Why does it compile?
#include <vector>

template<typename T>
std::vector<T>::iterator // Why does this not require "typename" before it?
f() { return {}; }

int main() {
    auto fptr = &f<int>;
}

code playground

A: One of the new features in C++20 is Down with typename.
In C++17, you had to provide the typename keyword in nearly all† dependent contexts to disambiguate a type from a value. But in C++20, this rule is relaxed a lot. In all contexts where you need to have a type, the typename keyword is no longer mandatory.
One such context is the return type of a function in class scope, as in your example. Others include the type in a member declaration, the type on the right-hand side of a using declaration, the parameter declaration of a lambda, the type you're passing to static_cast, etc. See the paper for the full list.

† Nearly all because base-specifiers and mem-initializer-ids were always excluded, as in:
template <typename T> struct X : T::type  { }; // always ok

This is okay because, well, that needs to be a type. The paper simply extends this logic (well, it has to be a type, so let's just assume it's a type) to a lot more places that have to be types.

A: From the reference, from c++20, in contexts where the dependent name is unambiguously a typename, the typename keyword is no longer needed. In particular:

A qualified name that is used as a declaration specifier in the (top-level) decl-specifier-seq of:

a simple declaration or function definition at namespace scope


Q: Plugin data shared in Multisite I am trying to build a site that very closely resembles another and so far so good with WordPress Multisite Networks. I am also using the plugin WP-FileBase - this plugin creates a database table per site (http://wordpress.org/support/topic/plugin-wp-filebase-download-manager-does-it-work-on-multisite) - is there any way for me to set it up so that the sites share the same database?

A: You are asking a question that is specific to a plugin and not WordPress.  How the plugin  functions depends entirely on the plugin author's design.  Reading the article above, sure the plugin works in WP multsite, but as the author mentions extra works needs to be done to share that content among other mulisite sites.  You should follow up on the plugin support forum for answers.


Q: Log sqlite selected values I have select query like this
 String innerSelectQuery = "SELECT * FROM " + TABLE_NAME_EVENT_TYPE_MASTER + " WHERE EventTypeKey = '" + cursor.getInt(2) + "'";

            Cursor innerCursor = db.rawQuery(innerSelectQuery, null);
            if (innerCursor.moveToFirst()) {

                userEvent.setEventTypeKey(innerCursor.getString(1));
                Log.e("tag", "EventTypeKey " + innerCursor.getString(1));
                innerCursor.close();

            }

I was able to log the values using innerCursor.getString(1).Is there a way to log and see the returned values in a table format like sql.

A: to show full output of your cursor use following.
Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor))

A: Log.d("TAG", "Your Message : " + innerCursor.getString(1));

i hope it's helpful to you ..!


Q: Algorithm for finding end of a list (SAP GUI) I'm writing a script that adds elements to a list in a SAP GUI screen.  Now, it seems that when using SAP GUI, nothing "exists" unless it is actually on screen, so the first step involves finding the end of the list.
I accomplished this by scrolling though each element, and checking if it was blank.
Do While Not blank
If session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010/ctxtMAPL-MATNR[2,0]").Text = "" Then blank = True
session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position = i
i = i + 1
Loop

However, for very large existing lists, this takes a long time.  I'm trying to figure out a way to find the end more quickly. Some truths/limitations I know:

*

*I'm assuming I have no knowledge of the list length.

*I cannot command the verticalScrollbar.position too far beyond the end of
the list. For ex. if the list contains 62 elements, .verticalScrollbar.Position = 100 will not work.

*In the case of  the above example, SAP does NOT throw an error. Nothing happens at  all, and then next line of code executes.

*All references to elements are with respect to their position on the screen. Ex, if I scroll down 5 positions, the 6th element of the overall list would actually indexed as 1.

*On the other hand, verticalScrollbar.Position is absolute

I'm thinking of doing the following (in very psuedocode):
i = 0
do while scrolled = true
    scrolled = false
    a = GUIlist[0]
    verticalScrollbar.Position = i + 1000
    b = GUIlist[0]
    'check to see the first element shown has changed
    if a <> b then
        scrolled = true
        i = i + 1000
    end if
loop

do while scrolled = true
    scrolled = false
    a = GUIlist[0]
    verticalScrollbar.Position = i + 500
    b = GUIlist[0]
    if a <> b then
        scrolled = true
        i = i + 500
    end if
loop

...and so on until I'm iterating i by one.
Is there a generally accepted better way of doing this kind of 'search'?
Any input is appreciated.
Thanks

A: My suggestion:
session.findById("wnd[0]").sendVKey 83
myPosition = session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position
do
if session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010/ctxtMAPL-MATNR[2,0]").Text = ""  then exit do
myPosition = myPosition + 1
session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position = myPosition
loop
msgbox myPosition

Regards,
ScriptMan

A: Just to go to the end
max_scrollbar = session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Maximum ' Get the maximum scrollbar value
session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position = max_scrollbar  ' Go to the end


Q: Memory leak in background process on Heroku I was wondering if anyone can advise me on how to track down a memory leak / issue on a background process on Heroku.
I have one dyno worker running with a delayed_job queue, processing all sorts of different processes. From time to time, I'm getting a sudden jump in the memory consumed. Subsequent jobs then exceed the memory limit and fail, and all Hell breaks loose.
The weird thing is I can't see that the jump in memory is connected to any particular job. Here's the sort of log I see:
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=load_avg_1m val=0.00
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=load_avg_5m val=0.01
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=load_avg_15m val=0.01
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_total val=133.12 units=MB
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_rss val=132.23 units=MB
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_cache val=0.88 units=MB
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_swap val=0.01 units=MB
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_pgpgin val=0 units=pages
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_pgpgout val=45325 units=pages
Aug 15 07:13:25 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=diskmbytes val=0 units=MB
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=load_avg_1m val=0.15
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=load_avg_5m val=0.07
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=load_avg_15m val=0.17
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=memory_total val=110.88 units=MB
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=memory_rss val=108.92 units=MB
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=memory_cache val=1.94 units=MB
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=memory_swap val=0.01 units=MB
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=memory_pgpgin val=2908160 units=pages
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=memory_pgpgout val=42227 units=pages
Aug 15 07:13:31 vemmleads heroku/web.1:  source=heroku.10054113.web.1.bf5d3fae-2b1b-4e1d-a974-01d9fa4644db measure=diskmbytes val=0 units=MB
Aug 15 07:13:35 vemmleads app/heroku-postgres:  source=HEROKU_POSTGRESQL_CHARCOAL measure.current_transaction=1008211 measure.db_size=482260088bytes measure.tables=39 measure.active-connections=6 measure.waiting-connections=0 measure.index-cache-hit-rate=0.99996 measure.table-cache-hit-rate=1
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=load_avg_1m val=0.00
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=load_avg_5m val=0.00
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=load_avg_15m val=0.14
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=memory_total val=108.00 units=MB
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=memory_rss val=107.85 units=MB
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=memory_cache val=0.15 units=MB
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=memory_swap val=0.01 units=MB
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=memory_pgpgin val=0 units=pages
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=memory_pgpgout val=33609 units=pages
Aug 15 07:13:45 vemmleads heroku/run.2472:  source=heroku.10054113.run.2472.e811164e-4413-4dcf-8560-1f998f2c2b4e measure=diskmbytes val=0 units=MB
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=load_avg_1m val=0.30
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=load_avg_5m val=0.07
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=load_avg_15m val=0.04
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_total val=511.80 units=MB
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_rss val=511.78 units=MB
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_cache val=0.00 units=MB
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_swap val=0.02 units=MB
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_pgpgin val=27303936 units=pages
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=memory_pgpgout val=154826 units=pages
Aug 15 07:13:46 vemmleads heroku/worker.1:  source=heroku.10054113.worker.1.4589e3f4-8208-483a-a927-67c4c1cbee46 measure=diskmbytes val=0 units=MB

The memory usage of worker.1 jumps from 108.00 to 551.80 for no apparent reason. It doesn't look like any jobs were processed during that time, so it's hard to understand where that giant chomp of memory comes from. Some way later in the log, worker1 hits the memory limit and fails.
I have NewRelic Pro running. It doesn't help at all - in fact it doesn't even create alerts for the repeated memory errors. The above Heroku logs give me no more information.
Any ideas or pointers about what to investigate next would be appreciated.
Thanks
Simon

A: There isn't enough information here to pinpoint what's going on.
The most common cause of memory leaks in Rails applications (especially in asynchronous background jobs) is a failure to iterate through large database collections incrementally.  For example, loading all User records with a statement like User.all
For example, if you have a background job that is going through every User record in the database, You should use User.find_each() or User.find_in_batches() to process these records in chunks (default is 1000 for ActiveRecord).
This limits the working set of objects loaded into memory while still processing all of the records.
You should look for un-bounded database lookups that could be loading huge numbers of objects.


Q: SQL Dynamic ASC and DESC I have the following SQL statement where order by clause is passed dynamically .
How can I pass 'order by asc and desc' dynamically to SQL?
SELECT table1.prod_id,table2.prod_name from table1 left outer join table2
              ON table1.prod1 = table2.prod_id
              ORDER BY CASE WHEN :odb = 1 THEN prod_id END

I would like pass order by asc or desc to above SQL dynamically,
how can I do this?

A: You can do solutions like @TonyAndrews by manipulating numeric or data values. For VARCHAR2 an alternative to dynamic SQL could be to have two expressions:
order by
   case when :sorting='ASC' then col1 end ASC,
   case when :sorting='DESC' then col1 end DESC

When :sorting has the value 'ASC' the result of that ORDER BY becomes like if it had been:
order by
   col1 ASC,
   NULL DESC

When :sorting has the value 'DESC' the result of that ORDER BY becomes like if it had been:
order by
   NULL ASC,
   col1 DESC

One downside to this method is that those cases where the optimizer can skip a SORT operation because there is an index involved that makes the data already sorted like desired, that will not happen when using the CASE method like this. This will mandate a sorting operation no matter what.

A: If the column you are sorting by is numeric then you could do this:
order by case when :dir='ASC' then numcol ELSE -numcol END

For a date column you could do:
order by case when :dir='ASC' then (datecol - date '1901-01-01')
              else (date '4000-12-31' - datecol) end

I can't think of a sensible way for a VARCHAR2 column, other than using dynamic SQL to construct the query (which would work for any data type of course).

A: This will work for all data types:
SELECT *
FROM   (SELECT table.*
              ,ROW_NUMBER() OVER (ORDER BY prod_id) sort_asc
              ,ROW_NUMBER() OVER (ORDER BY prod_id DESC) sort_desc
        FROM   table)
ORDER BY CASE WHEN :odb = 1 THEN sort_asc ELSE sort_desc END

A: Unfortunatelly, you can not do it dynamically, because Oracle builds the execution plan based on these ASC and DESC keywords.
What you can do is changing the ORDER BY clause to this:
SELECT * table
 ORDER BY :order_param

And pass :odb value to :order_param if you want to order it by ASC (bigger :odb values would be least in order) or 1/:odb if you want to order by DESC (bigger :odb values would produce smaller 1/:odb values and would appear on top of the result).
And, as always, you can generate the query dynamically in a stored procedure:
IF ... THEN
  EXECUTE IMMEDIATE 'SELECT * table ORDER BY CASE WHEN :odb = 1 THEN 1 END ASC';
ELSE
  EXECUTE IMMEDIATE 'SELECT * table ORDER BY CASE WHEN :odb = 1 THEN 1 END DESC';
END IF;


Q: paypal chained payment ipn not returning notification I am using the following code for PayPal chained payment
require_once ("paypalplatform.php");
$amount=100;
$amt1=($amount * 10 )/100;
$amt2=$amount-$amt1;

$actionType         = "PAY";
$cancelUrl          = "http://test.com/test";

$returnUrl          = "http://test.com/test";
$currencyCode               = "USD";

$receiverEmailArray = array(
        'a***********_per@gmail.com',
        'a***********_biz@gmail.com'
        );

$receiverAmountArray = array(
        $amt1,
        $amt2
        );

$receiverPrimaryArray = array();

$receiverInvoiceIdArray = array(
        '1',
        '2'
        );

$senderEmail                    = "a************_per@gmail.com";
$feesPayer                  = "";
$ipnNotificationUrl             = "http://test.com/paypal/buynow.php";
$memo                       = "";
$pin                        = "agalameex";
$preapprovalKey                 = "";
$reverseAllParallelPaymentsOnError          = "";
$trackingId                 = generateTrackingID();
$resArray = CallPay ($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray,
                        $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray,
                        $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey,
                        $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId
);

$ack = strtoupper($resArray["responseEnvelope.ack"]);
if($ack=="SUCCESS")
{
    if ("" == $preapprovalKey)
    {
        // redirect for web approval flow
        $cmd = "cmd=_ap-payment&paykey=" . urldecode($resArray["payKey"]);
        RedirectToPayPal ( $cmd );
    }
    else
    {
        // payKey is the key that you can use to identify the result from this Pay call
        $payKey = urldecode($resArray["payKey"]);
        // paymentExecStatus is the status of the payment
        $paymentExecStatus = urldecode($resArray["paymentExecStatus"]);
    }
}
else
{
    //Display a user friendly Error on the page using any of the following error information returned by PayPal
    //TODO - There can be more than 1 error, so check for "error(1).errorId", then "error(2).errorId", and so on until you find no more errors.
    $ErrorCode = urldecode($resArray["error(0).errorId"]);
    $ErrorMsg = urldecode($resArray["error(0).message"]);
    $ErrorDomain = urldecode($resArray["error(0).domain"]);
    $ErrorSeverity = urldecode($resArray["error(0).severity"]);
    $ErrorCategory = urldecode($resArray["error(0).category"]);

echo "Preapproval API call failed. ";
echo "Detailed Error Message: " . $ErrorMsg;
echo "Error Code: " . $ErrorCode;
echo "Error Severity: " . $ErrorSeverity;
echo "Error Domain: " . $ErrorDomain;
echo "Error Category: " . $ErrorCategory;

}
In the above code every thing is working fine except return notification ( $ipnNotificationUrl). I am not getting any notification from the $ipnNotificationUrl when a payment is done. Can any body help me in this?

A: Check your IPN history in PayPal.  If it shows anything other than 200 response code you know something is wrong with your IPN listener.
You can check your web server logs to see exactly what error is happening when the script is hit.
Alternatively, you could setup a simple HTML form with hidden fields that match what you'd expect to get from PayPal.  Then you can submit this in a browser so you can see the result on screen.
Keep in mind that testing this way will result in an INVALID response back from PayPal because the IPN data did not come from their server, but you can adjust for that accordingly for testing purposes, get your issues fixed, and then you'll be good to go.

A: Debugging tips: check your IPN configuration at the PayPal backend. Replace your script by a simple script that just shows you when it's called and with what input.