C - calling a function via func_ptr, why doesnt it work?

Question: i have the following code:
void print(const char* str){
      system_call(4,1,str,strlen(str)); }

void foo2(void){ print("goo \n");}

void buz(void){ ...}

int main(){
char buf[256];
    void (*func_ptr)(void)=(void(*)(void))buf;
    memcpy(buf,foo2, ((void*)buz)-((void*)foo2));
    func_ptr();
    return 0;
}

the question is, why will this code fall?
the answer was, something about calling a function not via pointer is to a relative address, but i havent been able to figure out whats wrong here? which line is the problematic one?
thank you for your help
Comment: You seem to have left out a `}` on `print`.
Comment: Because it's undefined behavior and is legally allowed to do anything? Among other things, you'll probably need to make the data in `buf` executable. Operating systems have protections to prevent people from doing things like this.
Comment: Hmya, explore viral code by the looks of it.  You fell victim to a basic one, relative addressing.  The absolute addressing loophole has been plugged too, it is called 'address space layout randomization'.  And the NX bit added to cores as of late.
Answer: Well to begin with, there is nothing which says that foo2() and buz() must be next to each other in memory. And for another, as you guess, the code must be relative for stunts like that to work. But most of all, it is not allowed by the standard.
As Chris Luts referred to, stack (auto) variables are not executable on many operating systems, to protect from attacks.
Comment: And you can't really just move executable bytes, without properly relocating any necessary symbols.
Comment: I didn't even think about that. Interesting.
Answer: The first two lines in your main() function are problematic.
Line 1.  (void(*)(void))buf
converting buf to a function pointer is undefined
Line 2.  ((void*)buz)-((void*)foo2)
subtraction of pointers is undefined unless the pointers point within the same array.
Also, Section 5.8 Functions of H&S says "Although a pointer to a function is often assumed to be the address of the function's code in memory, on some computers a function pointer actually points to a block of information needed to invoke the function."
Comment: Also in line 2, casting function pointers to non-function pointer types is illegal.
Comment: @Chris Lutz: I believe casting function pointers to (void*) is allowed.  The only defined operation on the resulting void pointer would be to cast it back to the original function pointer type.
Comment: @sigjuice - You'd be wrong. You can cast them to a generic function pointer type (I use `typedef void (*func)(void);` myself) and back freely, but the C standard does not allow casting them to `void *`. (I believe POSIX _does_ allow casting them to `void` however.)
Comment: @Chris Lutz: "5.3.3 Some Caution With Pointers" of H&S says "In Standard C, void * can be used as a generic object pointer, but there is no generic function pointer."
Comment: Check the standard itself. I would cite it but I'm on an iPhone.
Comment: @Chris Lutz: I stand corrected.  22.214.171.124§8 A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
Answer: First and foremost, C function pointers mechanism is for equal-signature function calling abstraction. This is powerful and error-prone enough without these stunts.
I can't see an advantage/sense in trying to copying code from one place to another. As some have commented, it's not easy to tell the amount of relativeness/rellocatable code within a C function.
You tried copying the code of a function onto a data memory region. Some microcontrollers would just told you "Buzz off!". On machine architectures that have data/program separated memories, given a very understanding compiler (or one that recognizes data/code modifiers/attributes), it would compile to the specific Code-Data Move instructions. It seams it would work... However, even in data/code separated memory archs, data-memory instruction execution is not possible.
On the other hand, in "normal" data/code shared memory PCs, likely it would also not work because data/code segments are declared (by the loader) on the MMU of the processor. Depending on the processor and OS, attempts to run code on data segments, is a segmentation fault.
Comment: first of all, thank you all for your replies. from what i understand, the idea itself is not possible, and moreover, the copy of compiled code into data segment and the running of code from that segment will cause segmentation fault. the relative call idea is minor, but still of importance for such "stunts" to work. and again, your info was priceless.
Comment: R.A. not impossible, but you would have to be very lucky to find the combination of compiler and OS which results in that code working. If you want to copy code around, it's easier to go for assembler directly.


Signal click on QSpinBox Qt

Question: I would like to open a window when I click on a QSpinBox. The problem is that there is no such signal "clicked" for this widget.
Does someone has an idea how to do that?
Comment: Why do you want to open a window instead of letting the user change the value of the spinbox ? QSpinBox has no *clicked* signal because they're suppose to handle it themselves. It sounds like you need a custom Widget.
Comment: It's a tactile application, so when the user clicked on the spinBow, I want open a numpad app to let him type the number
Comment: So if you don't use the `QSpinBox` buttons, why not use a simple `QLineEdit` ?
Answer: A QSpinBox is just a QLineEdit with two buttons, input validation and event handling. It doesn't have clicked signal because it's supposed to handle the mouse even itself.
The problem is that even making a custom widget derived from QSpinBox won't be enough since it doesn't receive the mouse events itself, they are handled by its children widgets. You could install an event filter on the QSpinBox children in order to catch the click event, but that's not the neatest way.
If you just want to display a numpad when the user select the box, you can use directly a QLineEdit. You will lose the QSpinBox buttons (but you can add your own ones if you need them) and the validation (but you can add you own using QValidator).
Then you just have to derive it in order to catch the focus event, trigger a custom signal which would show your keyboard :
class MySpinBox: public QLineEdit
{
  Q_OBJECT

public:
  MySpinBox(QWidget *parent = 0);
  ~MySpinBox();

signals:
  needNumpad(bool hasFocus);

protected:
  virtual void focusInEvent(QFocusEvent *e) {
      QLineEdit::focusInEvent(e);
      emit(needNumpad(true));
  }
  virtual void focusOutEvent(QFocusEvent *e) {
      QLineEdit::focusInEvent(e);
      emit(needNumpad(false));
  }
}

Answer: You can use an event filter and do something like this:
ui->spinBox->installEventFilter(this);
QObjectList o_list = ui->spinBox->children();
for(int i = 0; i < o_list.length(); i++)
{
    QLineEdit *cast = qobject_cast<QLineEdit*>(o_list[i]);
    if(cast)
        cast->installEventFilter(this);
}

And in the event filter you check for a mouse click (in this example its triggered by all mouse buttons, left click, right click, scroll wheel click etc.).
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        showNumpadDialog();
    }
    return false;
}

Answer: You do not need to create your own QSpinBox with QLineEdit and two buttons.
Since QLineEdit is the child of QSpinBox. You can create an event filter for QLineEdit and check whether its parent is a spinbox. Then so, you would get a click event for spin box.
   if(event->type() == QEvent::MouseButtonPress && dynamic_cast<QSpinBox *>(dynamic_cast<QLineEdit *>(obj)->parent()) )

Signal click on QSpinBox Qt


How to enable gzip?

Question: I would like to enable GZIP throughout my whole website. What would be the best way to do it? Would it be through .htaccess?
Any pointers on how to do this would be greatly appreciated.
Comment: Possible duplicate: http://serverfault.com/questions/21447/apache-gzip-configuration/21483#21483
Answer: See the documentation for mod_deflate.
http://httpd.apache.org/docs/2.0/mod/mod_deflate.html

How to enable gzip?


Ant build file on windows where on earth do I put {sdk.dir} definition?

Question: I have an ant build file:

when I run ant build I get com.android.setupTask cannot be found?
What am I missing?  How exactly do I specify {sdk.dir} in windows. Its no where in any file? Is this the cause of the error message?  How can I see what {sdk.dir} is currently set to? How can I show this on windows. There is no echo.
Answer: You can pass it at the command line as follows
<code>ant -Dsdk.dir=path/to/android/sdk/root/dir -Dtarget=targeted-android-sdk-version
</code>
Comment: You should also ensure that the "path/to/android/sdk/root/dir" is in your path.
Answer: I just googled this one for you.
http://blog.klacansky.com/matter-code/ant-taskdef-class-com-android-ant-setuptask-cannot-be-
found
Does this helps?


Feeding Tempo to DAW

Question: Basically, I have a drummer and I am a Keyboard player from whom I wanted to feed the tempo to the system and thereby play arpeggios and other things which are required, which is very important for me. Is there any best way to do it. DO you want me to have a man keep feeding the tempo, in frequent intervals(right before my arpeggios have to play)? or is there any better way to achieve it?
My drumset is acoustic!
Answer: As MajBoredom said, the simplest way is to sync everyone to the tempo of the DAW. But both Ableton and Logic Pro both have "tap-tempo" which lets you tap in the tempo in manually. You just need to give it a couple taps of the BPM you want and it will detect the speed. You can map a keyboard key to do this, or even a pedal or anything that can send MIDI data. So you can tap out the tempo in the beginning of the track, then adjust it as the band plays.
Answer: You can give the drummer headphones with a click track to play to so that the drummer stays in sync with your DAW - that might be easier than trying to get the computer to adapt to the band as they change tempo slightly over the course of the song.

Feeding Tempo to DAW


Eclipse IDE debugging with code change

Question: I am using Eclipse IDE for Java Developers
Version: Helios Service Release 1
Build id: 20100917-0705
In remote debugging Web app with tomcat 7.0.37, when I make some changes, even a line, the changes can not be made into the runtime, so I need to recompile and re-deploy the war application. Wast a lot of time. The message:
<code>Hot code replace failed - Delete method not implemented
</code>
I do not understand the message.
Anyone know the secret on how to auto reflect the code change in debug mode? Thanks.
Answer: I've found that for hot code replacement to work the code being modified/replaced must be in the execution stack.  So you can hot replace changes made to a method you've stopped in, but you can't hot replace changes to that method once you step out of that method... unless you first stop back in the method on a successive call to the method.
Answer: With the standard JVM (Oracle's), you can only modify existing methods. Both adding and deleting methods, and changing structure of class (moving methods, fields) are NOT supported. For that, go to JRebel!
One thing to notice is that changes to seemingly "normal code" inside some method will actually need for the java compiler to add or delete methods - and hence it will fail. This happens e.g. if you in an inner class accesses private fields in the outer class - the java compiler will need to add synthetic accessor-methods to the outer class to let the inner class access those fields - which hence will fail to Hot Code Replace. Also, if you remove some code accessing such fields, the java compiler wants to remove the corresponding synthetic accessor-method, which also will fail.
Answer: I think there is no way to reflect the code change in debug mode

Debug mode is to trace program flow and find if any issues or errors at particular piece of code....
it just points to line of code in eclipse, which is running in your tomcat, ie. code in eclipse is not used to run application the code u have installed or put in tomcat runs

hence your changes made in eclipse cant reflect in tomcat code
Comment: sometimes it works, like 5%, it is called Hot Code Replacement.
Comment: Oh please.. Get a clue about what you are answering before doing just that.

Eclipse IDE debugging with code change


Check if data follows uniform continuous distribution?

Question: So we have a dataset with birdspecies (factor, 4 levels) and activity time (in minutes after sunrise). We want to know if the birds have a heterogeneous use of time. So do they come into our garden at all times of the morning (after sunrise-12pm), or do they have certain peaks. Our histogram shows for some birds that they are active around 1-2 hours after sunrise, but others do not. Is there an actual easy test to check this? The Kolmogorov-Smirnov was suggested, but in a one-sample test, it checks our distribution against a normal distribution. But is there a uniform continuous distribution to check against?
Thanks in advance!
Comment: Perhaps you mean a uniform distribution? The normal distribution is also continuous (i.e. opposite of discrete). Unrelatedly, could you show those histograms? Your question is clear without it, but it sounds interesting :)
Comment: You could check against a uniform (instead of normal) distribution!?
Comment: yes, sorry, I meant a uniform distribution
Comment: I'm not sure I understand what you're trying to achieve. A normal distribution is a type of continuous distribution. Can you specify what the goal of your research question is? Are you trying to compare the 4 different bird species or are you wanting to make statements about each species seperately?
Comment: we want to know per species of bird if they have an equal distribution and come at all times during the morning or if they have activity peaks where they appear more often at certain times
Comment: You don't need a formal test at this stage: you are trying to learn about the bird behavior. Visualizing the data is always the first step. Have you plotted the visits against time?
Comment: Can you correct the text of your question in accordance with the discussion in comments?
Answer: I would use a quantile quantile plot to get a sense of how far the two distributions are from each other.
If you need a statistical test, the Kolmogorov-Smirnov can be used for continuous normal distributions (as well as normal distributions) but, like all statistical tests, the p value will be partly due to sample size. Given that you are talking about birds visiting your own garden, I would guess that N is going to be pretty small and it will be hard to find significance for any pattern that doesn't pass the IOTT (Interocular Trauma Test - it hits you between the eyes).
Comment: This solution does not seem to address the fundamental problem that the endpoints of the distribution are not well-defined.  Indeed, a better model might be that the visiting times are a point process whose intensity is the convolution of a uniform with a Normal-like density to model the gradual awakening of the birds in the morning and their gradual going to sleep in the evening.  The very nature of the question is much more exploratory than formal: the OP is looking for "activity peaks." A formal test of uniformity isn't going to address that.


Pygame Tuples Surface Error

Question: This is a function I made to draw pipes in an angry birds knockoff I made:
def drawPipes():
#Pipes 1
    if pipes1 == 1:
        topPipe1Y =300
        botPipe1Y =400
        screen.blit( topL, ( col1X, 0))
        screen.blit( botS, ( col1X, 400)) <-----This part keeps getting the error.

    elif pipes1 == 2:
        topPipe1Y = 200
        botPipe1Y = 300
        screen.blit( topM, ( col1X, 0))
        screen.blit( botM, ( col1X, 300)) <-----This part keeps getting the error.

    elif pipes1 == 3:
        topPipe1Y = 100
        botPipe1Y = 200
        screen.blit( topS, ( col1X, 0))
        screen.blit( botL, ( col1X, 200)) <-----This part keeps getting the error.

#Pipes 2
    if pipes2 == 1:
        topPipe2Y =300
        botPipe2Y =400
        screen.blit( topL, ( col2X, 0))
        screen.blit( botS, ( col2X, 400)) <-----This part keeps getting the error.

    elif pipes2 == 2:
        topPipe2Y =200
        botPipe2Y =300
        screen.blit( topM, ( col2X, 0))
        screen.blit( botM, ( col2X, 300)) <-----This part keeps getting the error.

    elif pipes2 == 3:
        topPipe2Y =100
        botPipe2Y =200
        screen.blit( topS, ( col2X, 0))
        screen.blit( botL, ( col2X, 200)) <-----This part keeps getting the error.

#Pipes 3
    if pipes3 == 1:
        topPipe2Y =300
        botPipe2Y =400
        screen.blit( topL, ( col3X, 0))
        screen.blit( botS, ( col3X, 400)) <-----This part keeps getting the error.

    elif pipes3 == 2:
        topPipe2Y =200
        botPipe2Y =300
        screen.blit( topM, ( col3X, 0))
        screen.blit( botM, ( col3X, 300)) <-----This part keeps getting the error.

    elif pipes3 == 3:
        topPipe2Y =100
        botPipe2Y =200
        screen.blit( topS, ( col3X, 0))
        screen.blit( botL, ( col3X, 200)) <-----This part keeps getting the error.

My issue is that when I try to run my program I get an error saying

TypeError: argument 1 must be pygame.Surface, not tuple.

I have no idea what to do, sometimes I am able to run it and sometimes I am not. My surface is called screen and I have used the same syntax in multiple other programs where I have used pygame but I have never had this issue. If anybody can help me I would really appreciate it. If you need to see my entire program it is here:
"""-------------------------------------------------------------------------------
Name:        module1
Purpose:

Author:      Nano
Created:     18/05/2014
Copyright:   (c) Nano 2014
Licence:     Open Source
----------------------------------------------------------------------------------
Notes/ Checklist:
   Turn off option to turn on and off printing.
----------------------------------------------------------------------------------"""
import pygame, sys, math, random, time, datetime
from pygame.locals import *
from datetime import timedelta

pygame.init()
fpsClock = pygame.time.Clock()
fps = 60
screenWid = 750
screenLen = 500
resolution = ( screenWid, screenLen)
pygame.display.set_caption('Flappy Bird')
pygame.display.init()
screen = pygame.display.set_mode((resolution))

printing = True

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
yellow = (255,255,0)
cyan = (0,255,255)
purple = (255,0,255)
lightTurquoise = (153,217,234)
bgColor = (lightTurquoise)

#--------------------------------------Pipes--------------------------------------
topL = pygame.image.load('TopPipe2.png')
topM = pygame.image.load('TopPipe1.png')
topS = pygame.image.load('TopPipe3.png')
botL = pygame.image.load('BottomPipe2.png')
botM = pygame.image.load('BottomPipe1.png')
botS = pygame.image.load('BottomPipe3.png')

sTopX = 100
mTopX = 200
lTopX = 300

sBotX = screenLen-100
mBotX = screenLen-200
lBotX = screenLen-300

col1Start = screenWid
col2Start = col1Start+277
col3Start = col2Start + 277

col1X = col1Start
col2X = col2Start
col3X = col3Start

pipes1=0
pipes2=0
pipes3=0

pipes1 = random.randint(1,3)
pipes2 = random.randint(1,3)
pipes3 = random.randint(1,3)

topPipe1Y = 0
botPipe1Y = 0

topPipe2Y = 0
botPipe2Y = 0

topPipe3Y = 0
botPipe3Y = 0

"""def drawPipes():
#Pipes 1
   if pipes1 == 1:
       topPipe1Y =300
       botPipe1Y =400
       screen.blit( topL, ( col1X, 0))
       screen.blit( botS, ( col1X, 400))

   elif pipes1 == 2:
       topPipe1Y = 200
       botPipe1Y = 300
       screen.blit( topM, ( col1X, 0))
       screen.blit( botM, ( col1X, 300))

   elif pipes1 == 3:
       topPipe1Y = 100
       botPipe1Y = 200
       screen.blit( topS, ( col1X, 0))
       screen.blit( botL, ( col1X, 200))

#Pipes 2
   if pipes2 == 1:
       topPipe2Y =300
       botPipe2Y =400
       screen.blit( topL, ( col2X, 0))
       screen.blit( botS, ( col2X, 400))

   elif pipes2 == 2:
       topPipe2Y =200
       botPipe2Y =300
       screen.blit( topM, ( col2X, 0))
       screen.blit( botM, ( col2X, 300))

   elif pipes2 == 3:
       topPipe2Y =100
       botPipe2Y =200
       screen.blit( topS, ( col2X, 0))
       screen.blit( botL, ( col2X, 200))

#Pipes 3
   if pipes3 == 1:
       topPipe2Y =300
       botPipe2Y =400
       screen.blit( topL, ( col3X, 0))
       screen.blit( botS, ( col3X, 400))

   elif pipes3 == 2:
       topPipe2Y =200
       botPipe2Y =300
       screen.blit( topM, ( col3X, 0))
       screen.blit( botM, ( col3X, 300))

   elif pipes3 == 3:
       topPipe2Y =100
       botPipe2Y =200
       screen.blit( topS, ( col3X, 0))
       screen.blit( botL, ( col3X, 200))"""

def colisions(x,y,columnx,topPipeY,botPipeY):
    if x>=columnx and x + 51 <= columnx:
        if y >=topPipeY or y<= botPipeY:
            print("top pipe 1")
            movement = 'none'
            birdy = int(screenLen/2)
            if score > highScore:
                highScore = score
            score = 0
            speed = 0
            col1X = col1Start
            col2X = col2Start
            col3X = col3Start
            print("Oops")

score = 0
bird = pygame.image.load('FlappyBird.png')
bgImage = pygame.image.load('BackDrop.png')
birdx = 250
birdy = screenLen / 2
birdWid = 51
birdLen = 36
font = pygame.font.SysFont( "Times New Roman, Arial", 20)
scoreBoard = font.render("Score:", True, black)
scoreBoardPos = (5,5)
highScoreText = font.render("High Score:", True, black)
scorePos = (65,5)
movement = 'none'
goingUp = 0
highScore = 0
orgSpeed = 2
speed = 0
two = 200
three = 300
four = 400

"""================================Main Game Loop================================="""
while True:
    topR = birdx+birdWid,birdy
    botL = birdx, birdy+birdLen
    botR = birdx+birdWid ,birdy+birdLen
    if col1X <= -82:
        col1X = screenWid
        pipes1 = random.randint(1,3)
    if col2X <= -82:
        col2X = screenWid
        pipes2 = random.randint(1,3)
    if col3X <= -82:
        col3X = screenWid
        pipes3 = random.randint(1,3)
    col1X-=speed
    col2X-=speed
    col3X-=speed
    scoreAmount = font.render(str(score),True, black)
    highScoreNum = font.render(str(highScore),True, black)
    screen.fill(bgColor)
    screen.blit(bgImage,(0,0))
#-----------------------------------Draws Pipes------------------------------------
##Pipes 1
    if pipes1 == 1:
        topPipe1Y =300
        botPipe1Y =400
        screen.blit( topL, ( col1X, 0))
        screen.blit( botS, ( col1X, four))

    elif pipes1 == 2:
        topPipe1Y = 200
        botPipe1Y = 300
        screen.blit( topM, ( col1X, 0))
        screen.blit( botM, ( col1X, three))

    elif pipes1 == 3:
        topPipe1Y = 100
        botPipe1Y = 200
        screen.blit( topS, ( col1X, 0))
        screen.blit( botL, ( col1X, two))

##Pipes 2
    if pipes2 == 1:
        topPipe2Y =300
        botPipe2Y =400
        screen.blit( topL, ( col2X, 0))
        screen.blit( botS, ( col2X, four))

    elif pipes2 == 2:
        topPipe2Y =200
        botPipe2Y =300
        screen.blit( topM, ( col2X, 0))
        screen.blit( botM, ( col2X, three))

    elif pipes2 == 3:
        topPipe2Y =100
        botPipe2Y =200
        screen.blit( topS, ( col2X, 0))
        screen.blit( botL, ( col2X, three))

##Pipes 3
    if pipes3 == 1:
        topPipe2Y =300
        botPipe2Y =400
        screen.blit( topL, ( col3X, 0))
        screen.blit( botS, ( col3X, four))

    elif pipes3 == 2:
        topPipe2Y =200
        botPipe2Y =300
        screen.blit( topM, ( col3X, 0))
        screen.blit( botM, ( col3X, three))

    elif pipes3 == 3:
        topPipe2Y =100
        botPipe2Y =200
        screen.blit( topS, ( col3X, 0))
        screen.blit( botL, ( col3X, two))

    screen.blit( bird, (birdx,birdy))
    screen.blit( scoreBoard, scoreBoardPos)
    screen.blit(scoreAmount, scorePos)
    screen.blit(highScoreText,(5,45))
    screen.blit(highScoreNum, (105,45))
    if birdx == col1X:
        score +=1
    if birdx == col2X:
        score +=1
    if birdx == col3X:
        score +=1
    for event in pygame.event.get():

        if event.type == MOUSEBUTTONDOWN:
            speed = orgSpeed
            goingUp+=10
            if goingUp > 30:
                goingUp = 30
            movement = 'up'

##Required for closing game
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    if movement == 'up':
        if birdy <= 0:
            birdy = 2
            goingUp = 0
            movement = 'down'
        birdy-=4
        goingUp-=1
        if goingUp == 0:
            movement = 'down'
            goingUp = 0
    if movement == 'down':
        birdy+=4
        if birdy >= screenLen or birdy+36 >= screenLen:
            movement = 'none'
            birdy = int(screenLen/2)
            if score > highScore:
                highScore = score
            score = 0
            speed = 0
            col1X = col1Start
            col2X = col2Start
            col3X = col3Start

#------------------------------Colission Conditions-------------------------------
    colisions(birdx,birdy,col1X,topPipe1Y,botPipe1Y)
    colisions(birdx,birdy,col2X,topPipe2Y,botPipe2Y)
    colisions(birdx,birdy,col3X,topPipe3Y,botPipe3Y)

    if birdx>=col1X and birdx + 51 <= col1X:
        if birdy >=topPipe1Y or birdy<= botPipe1Y:
            print("top pipe 1")
            movement = 'none'
            birdy = int(screenLen/2)
            if score > highScore:
                highScore = score
            score = 0
            speed = 0
            col1X = col1Start
            col2X = col2Start
            col3X = col3Start
            print("Oops")

    pygame.display.update()
    fpsClock.tick(fps)

Answer: I believe a lot has to do with these lines in your code (still don't know what is exactly wrong with botM but think about where you are reassigning it):
topR = birdx+birdWid,birdy # note these now become tuples with two integers
botL = birdx, birdy+birdLen
botR = birdx+birdWid ,birdy+birdLen

I don't know how mutable the Pygame objects are, but some global variables can be written without the global keyword. You currently are changing them to tuples.
Comment: I feel like an idiot. I totally forgot to change tose variables to not be tuples. Thanks.

Pygame Tuples Surface Error


Android: calling Java class from C++ Native Activity

Question: Java code:
    package local.ttt;

    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Typeface;

    public class Text2Bitmap {
        static Bitmap getBitmap(String text,int fontsize) {
            Paint paint=new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            paint.setTextSize(fontsize);
            paint.setAntiAlias(true);
            paint.setTypeface(Typeface.DEFAULT);

            int outwidth=(int)Math.round(paint.measureText(text));
            Bitmap bitmap=Bitmap.createBitmap(outwidth,fontsize,Bitmap.Config.ALPHA_8);

            Canvas canvas=new Canvas(bitmap);
            canvas.drawText(text,0,fontsize-1,paint);

            return bitmap;
        }
    }

C source:

            ...
            MY_ASSERT(vm_cached!=NULL);
            JNIEnv* env;
            jint res=vm_cached->AttachCurrentThread(&env,NULL);
            MY_ASSERT(res==0);
            jclass activityClass=env->FindClass("android/app/NativeActivity");
            MY_ASSERT(activityClass!=NULL);
            jmethodID getClassLoader=env->GetMethodID(activityClass,"getClassLoader","()Ljava/lang/ClassLoader;");
            MY_ASSERT(getClassLoader!=NULL);
            MY_ASSERT(nativeActivityObjHnd!=NULL);
            jobject cls=env->CallObjectMethod(nativeActivityObjHnd,getClassLoader);
            jclass classLoader=env->FindClass("java/lang/ClassLoader");
            MY_ASSERT(classLoader!=NULL);
            jmethodID findClass=env->GetMethodID(classLoader,"loadClass","(Ljava/lang/String;)Ljava/lang/Class;");
            MY_ASSERT(findClass!=NULL);
            jstring strClassName=env->NewStringUTF("Llocal/ttt/Text2Bitmap;");
            jclass text2bitmapClass=(jclass)env->CallObjectMethod(cls,findClass,strClassName); //fails here
            MY_ASSERT(text2bitmapClass!=NULL);
            res=vm_cached->DetachCurrentThread();
            MY_ASSERT(res==0);
            ...

it fails with:

W/dalvikvm(5614): dvmFindClassByName rejecting 'Llocal/ttt/Text2Bitmap;'
W/dalvikvm(5614): threadid=9: thread exiting with uncaught exception (group=0x4002d560)
E/AndroidRuntime(5614): FATAL EXCEPTION: Thread-10
E/AndroidRuntime(5614): java.lang.ClassNotFoundException: Llocal/ttt/Text2Bitmap; in loader dalvik.system.PathClassLoader[.]
E/AndroidRuntime(5614):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
E/AndroidRuntime(5614):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
E/AndroidRuntime(5614):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
E/AndroidRuntime(5614):     at dalvik.system.NativeStart.run(Native Method)

Any hint what I'm doing wrong, please?
Comment: Have you tried debugging? Code dumps aren't really kosher here
Comment: This question is a nightmare, but i took a stab at it anyway.  You need to identify which line of native code is causing the error (since we don't have line numbers).
Comment: i cannot use debugging in my anvironment. I testing on device I cant root. so debugging doesnt work here. the question is about c part, not java.
Comment: it causing error on "fails here" in c code.
Comment: See my answer then, try some of my suggestions.
Comment: My bad. it worked without changes, except i set android:hasCode to true in manifest. lol
Answer: Not sure what is causing your error (you do not indicate where the lines are, or the particular line where you are having difficulty debugging), but I will go ahead and point out a few quick mistakes I see.
One first mistake is you need to use CallStaticObjectMethod since you are calling a static method.  Your jmethodid findClass has a methodID, not a class, which is misleading and wrong.  You also have two parameters, but you seem to be only passing one parameter.
Basically, you need:
(env)->GetStaticMethodID(jclass,"method name", "Parameter list")
--jclass is the class reference
--"method name" is the name of the method IN quotes
--"Parameter list" is the list of parameters, which you need to look up syntax.
Skipping a few things...To call your stuff you need:
(env)->CallStaticObjectMethod(jclass,jmid,parameter1,parameter2)
--jclass is once again the class that has the static method.
--jmid is the java method id which you get from the function above.
--parameter1 and parameter2 are the parameters required for the java method.
Lastly, I think this may just be preference, but I would not attach the thread to the JVM until you have all the necessary information to make the jump into the JVM.
Comment: thank you for answers! trying to use code from http://blog.tewdew.com/ "using jni from native activity"
Comment: the goal is just add simple java class to native activity eclipse project for making bitmap from text string. i want to use java class from c++.
Comment: Let me ease your pain some, Start at the beginning.  Read up on JNI, it took me quite some time to get JNI working in my implementation and making a C call into Java is not one of easiest parts to understand:
http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/index.html
Answer: Don't mess with java class loader. Use this code:
MY_ASSERT(vm_cached!=NULL);

JNIEnv* env;
jint res = vm_cached->AttachCurrentThread(&env,NULL);
MY_ASSERT(res==0);

jclass t2bClass = env->FindClass("local/ttt/Text2Bitmap");
MY_ASSERT(t2bClass!=NULL);

jmethodID getBitmap = env->GetStaticMethodID(t2bClass, "getBitmap","(Ljava/lang/String;I)Landroid/graphics/Bitmap;");
MY_ASSERT(getBitmap!=NULL);

jstring text = ...;
int fontsize = ...;
jobject bitmap = env->CallStaticObjectMethod(t2bClass, getBitmap, text, fontsize);
MY_ASSERT(bitmap!=NULL);

// process bitmap here
// ...

res=vm_cached->DetachCurrentThread();
MY_ASSERT(res==0);

Comment: Well if you don't have code, then of course JNI won't find your classes because they are not there :) Change hasCode to true. The JNI should work fine from NativeActivity and it can find and use your classes - there is really no need to mess with class loader. Here's another example how to use Java code from NativeActivity - comment #1 is mine, and it works fine in authors code: https://github.com/fabiensanglard/Shmup/tree/master/engine/android
Comment: thank you! the reason i "mess with class loader" is, according to i read in blog above and some other sources, when u using native activity, u must use class loader or "FindClass off of the JNIEnv will not give satisfaction. It won't find your classes. The reasons are because the context of the JNIEnv FindClass has no awareness that your classes exist.". that's she said :). i tried your code, and it fails on MY_ASSERT(t2bClass!=NULL);
Comment: maybe i should add something to androidmanifest.xml? hmm. now its set for native activity and has android:hasCode="false".
Comment: just findclass without classloader should work, but doesnt work for me even with hascode=true.
Comment: also According to
https://github.com/fabiensanglard/Shmup/blob/master/engine/android/jni/android/android_main.c :  "* JNI ISSUE :
* New error now when trying to call Java method from my native code: NDK JNI ERROR: non-VM thread making JNI calls
* It seems the JNIEnv is not really valid when we receive it in the game thread. We need to attach the thread to the VM (AttachCurrentThread) and create a new JNIEnv
* http://android.wooyd.org/JNIExample/files/JNIExample.pdf
*
* SNAAAAP !! Even after attaching and getting a valid JNIEnv it seems we still don't have the right classLoader !!!!!!"
Comment: also found this(unconfirmed) : http://webcache.googleusercontent.com/search?q=cache:CYjGWY9ThUMJ:vkswtips.blogspot.com/2012/01/android-how-to-call-java-activity-using.html+&cd=1&hl=ja&ct=clnk≷=jp
Comment: I guarantee you, there is no need to use class loader. I am myself calling Java functions form my NativeActivity without help of java class loader. Just get the jclass/jmethodid of needed method directly and call it.
Comment: For any one else who may run into this issue with the class loader not being able to locate any of your or third party classes, firstly make sure that hasCode=true in your manifest, and you need to make sure to set the classloader, if you dont set the class loader and simply just try using FindClass from your JNIEnv provided by the NativeActivity it wont work, simply put activity->env->FindClass uses the system classLoader and as such can not load anything but system classes, i hope this helps anyone else who has had issues with this.


Windows 10 DNS caching oddity, can someone explain how this can happen?

Question: I was at a friend's house who has Consolidated DSL service (soo slow). She started having problems where Chrome (on her Windows 10 desktop) started reporting that it could not find the IP address for any well-known hosts. I connected my Windows 10 laptop directly to her Zyxel vmg4825-b10a dsl modem/router and tried "ping google.com". It said it couldn't find the IP address. A few minutes later, I tried again, and it worked, getting 4 replies with times in the tens of milliseconds range. A few minutes after that, I tried again, and it was back to reporting it was unable to find the IP address for google.com. This makes no sense to me, as I thought that Windows would cache the working IP address result for a whole lot longer than the time I was away.
Eventually, the problem went away on its own, so I could only conclude that Consolidated fixed a problem with its DNS servers. So I can't reproduce the problem.
I hadn't thought to try "ipconfig /displaydns" at the time. But subsequent experiments with the same laptop on my own FIOS network suggest that a ping of google.com causes the IP address to show up in the output of "ipconfig /displaydns | grep google.com" for  quite a while. Can anyone explain this behavior? Is there a fixed time that DNS lookups get cached? Can the remote DNS server cause Windows to flush its cache? I see that the output of ipconfig/displaydns does not include the IP address that was found for google.com, so maybe it's not really a cache, though I don't understand why it would remember the name without the address...
On a completely different note: I wanted to record the exact error message produced by the ping command when it failed to find the address for a name, so that I could include it here. So I tried ping with a non-existent domain. But I can't make it happen on my network at home, instead I get this:
$ ping blurfo.blurfo

Pinging blurfo.blurfo [126.96.36.199] with 32 bytes of data:

Any nonexistent name I can come up with gets mapped to 126.96.36.199. What's up with that??
Answer: It looks like your Internet provider is intercepting non-existent domains and using them for advertising.
whois on the 126.96.36.199 IP address yields netname: BAREFRUIT-ERRORHANDLING and quick google search for it results in: https://www.barefruit.com/. Go there and you'll get the idea.
Comment: Thanks for this part. I have Verizon FIOS, certainly willing to take an extra buck wherever they can. So I gave you a point, but can't accept it as the answer, since it only answers a footnote to the question :-)
Comment: Well, DNS generally speaking is cached. And the record itself holds the information for how long it can and should be cached. But I am not using Windows and I've heard that it could behave oddly when it comes to name resolution so I'll refrain myself from answering. And BTW I've seen google resolvers (18.104.22.168) to purposefully lower the time to live setting.
Comment: Yeah, Windows behaviors can be puzzling at best. Like what's the point of having the displaydns option to ipconfig display names without addresses? But I guess you're suggesting that the Consolidated DNS server, when it successfully resolved google.com, could have given it a TTL that caused ipconfig to flush it sooner than what I'm seeing at home with Verizon.
Comment: Possible but this would likely require more thorough investigation.
Comment: Lord, how embarrassing. Here I am accusing the Windows ipconfig/displaydns command of not displaying the IP address to which each name resolves, when the problem was that I was grepping for a name, and the address is displayed on a separate line. Duh.


When hovered over the Foundation Jquery menu (without dropdowns) a white patch appears

Question: I used the Foundation top bar to create the menu. None of the elements have drop downs. But if I hover over an item it will leave behind a white patch like this :

This only happens in Google Chrome. When tried in Firefox it works fine! How to get rid of this patch?
Here's a link to the live website : http://secret-temple-3539.herokuapp.com/
The css file :
    @import "compass";
    $top-bar-color: rgba(17, 17, 17, 0.2);

    body{
        font-family: 'Comfortaa', cursive !important;
    }

    .top-bar-section{
        a{
            font-family: 'Comfortaa', cursive !important;
            background: transparent !important;
            @include transition-property(all);
        @include transition-duration(0.3s);
        @include transition-timing-function(ease-in);

            &:hover{
                background: none repeat scroll 0 0 rgba(17, 17, 17, 0.2) !important;
                @include border-radius(50px);
                color: #ffffff !important;
            }
        }
    }

    .top-bar{
        z-index: 10 !important;
        -moz-animation-duration: 1.8s;
        -webkit-animation-duration: 1.8s;
        -o-animation-duration: 1.8s;
        -ms-animation-duration: 1.8s;
        animation-duration: 1.8s;

        li{
            background: transparent !important;
        }
    }

    #title{
        float: left;
        margin-left: -1000000000000000px;
    }

    #homeTop{
        height: 65%;
        background-image: image-url("leafyhomebg.jpg");
        background-repeat: no-repeat;
        background-size: 100% auto;
        overflow: hidden;
        z-index: -1 !important;
    }

    #home{
        overflow: hidden;
        height: 100%;
        background-image: image-url("homebg.jpg");
    }

    .fixed-custom{
        position:fixed;
        z-index: 99;
        width:100%;
    }

    #leafLogo{
            display: block;
        height: 24%;
        margin-left: auto;
        margin-right: auto;
        margin-top: 8%;
    }

    .hiMsg{
        color: #e9e9e9;
        font-size: 242%;
        font-size: 2vw;
        font-weight: 100;
        margin-top: 2%;
        text-align: center;

        &.lineTwo{
            margin-top: -28px;
            margin-top: 2.8%;
        }

        .emTxt{
            color: #b3b3b3;
        }
    }

    .sImgCont{
        width: 20%;
        float: left;

        .sImg{
                border: 3px solid #ffffff;
        border-radius: 50%;
        box-shadow: 0 0 2px #828282;
        display: block;
        margin-left: auto;
        margin-right: auto;
        opacity: 0.7 !important;
        width: 43%;
        }
    }

    .sImgWrap{
        margin-top: 1%;
    }

PS : I think its something to do with links... Go to the link again and refresh... see. I have added some links at the bottom and when we hover them, again a big patch appears!
Comment: @EApubs Could it be one of your SASS variables in Foundation? Although saying that I can't see anything in the CSS referencing the background-color change :-/
Comment: @EApubs Seems to be the transition-duration adding it? Try taking out the transition effect?
Comment: It does not occur with my version chrome (linux mint)
Comment: Can't see the white patch (Chrome 35 on OSX) but the 's turn completely grey on hover (I'm assuming this isn't intended?)
Comment: @arthur.sw Whats the distro? Im also in Chrome in Ubuntu 14.04
Comment: @AdamskiFTW Can you please send me a screenshot?
Comment: @AdamskiFTW I think I saw the issue you are talking about.. I tried in Windows! And no its not intended! What might be the problem?
Comment: Cinnamon v1.8.8, LinuxMint 15: olivia (x86-64)
Comment: @EApubs I can't seem to figure it out from the element inspector alone - there doesn't seem to be :hover states. Are you targeting the 's with Javascript or anything? (Foundation top-bar is a nightmare to style).
Comment: @AdamskiFTW Yep, I also couldn't find anything from the inspector. No I didn't write any javascript my self. :-(
Comment: @AdamskiFTW The only scss variable is $top-bar-color (I added my css in the question above). I even removed it and tried... still not working :-(
Comment: @EApubs Are you setting the background-color to transparent anywhere? You're better off setting it to none. I'm stumped with this one - almost certain it's to do with that transparency though.
Comment: @AdamskiFTW Set all to none. But still didn't work. I think its something to do with links... Go to the link again and refresh... see. I have added some links at the bottom and when we hover them, again a big patch appears!
Answer: I finally found the problem. Its in this piece of code :
#title{
    float: left;
    margin-left: -1000000000000000px;
}

When I remove that float, everything came back to normal. So I replaced the float with this position: fixed; and now everything works fine!
Thank for everyone who tried to help!


How to run my express app on digital ocean droplet

Question: I have a droplet on Digital Ocean and I spent quite some time setting it up by following their tutorials and all that. Then I SFTP'd my app to my server and it got transferred and everything then I ran sudo npm start and the console says that it's running but when I visit http://share3na.com as you can see nothing shows up. I installed all of the modules by running sudo npm install --save [module] then after manually doing all of them just to be sure, I ran sudo npm install.
I also changed the name servers in my domain.
Comment: Are you using a proxy on your server to redirect traffic to your node app?
Comment: have your node server is running ? make sure your node server is configure and running
Answer: In Digital Ocean,
Initially we buy a droplet. Later we have to choose the operating system to be installed, in your case you have chosen Linux maybe Ubuntu.
First, set your ssh access and configure ssh if needed
Later we have to update the package manager by using sudo apt-get update
Copy the NodeJs app into your droplet.
Set up the NodeJs by installing its dependencies and configuring the database etc.
Configure Nginx for the your NodeJs app and also add SSL certificate if any to the nginx.
Restart Nginx after configuring it.
Run your NodeJs app.
You should be able to access your NodeJs app if the Nginx is configured correctly.
Hope this helps.


Divide non normal distribution into classes

Question:
How can I statistically divide such skewed data into classes (Low, medium and high) as shown in the figure.
Any rule like "68–95–99.7 rule" for non-normal data?
Comment: Without knowing why you want to divide the variable, it's impossible to give good advice. However, for most purposes, dividing the data is a mistake and you should not do it at all.
Comment: Welcome to CV. Doesn't this simply involve the *binning* of your counts into a histogram? Binning is dealt with in nearly every introductory text on statistics.
Answer: If you want to divide it just to describe your data, there are a number of ways you can do it. It all comes down to choosing "cuts". Some stuff to help you think about it:

Sort and plot your data.
Aggregate you data (count) by the frequency of the event, compute percentages and accumulate.

** A note of caution: if you want to divide your data just to better describe it, that is fine. Go ahead. But it is generally not a good idea to bin data for analytics purposes. See this.


Cant search for custom CBUUID

Question: I have an app that works (so far so good) in connecting my iOS device to a bluetooth arduino, as of now this has been mostly for practice, but now I received the real thing that I'm supposed to connect to.
The problem is that I can't find it! (when I search for it).
If I do scanwithservices: nil, I can see the device and connect to it. However if i scanwithservices: [device'sCBUUID] then I don't get anything.
I double/triple/quatrupled checked the CBUUID using other apps, using my own app and looking at the device documentation, however no matter what I can't find it.
It has a custom CBUUID, from what I've read that's not standard, the CBUUID is:
BLETPodService = CBUUID(string: "4D494B45-414c-5741-5953-524F434B5321")

Searching for this yields nothing, however if I scan for nil I find it and if i check it's characteristics using the Bluefruit app (from Adafruit) I can see it's services and characteristics ID and they match that string I posted in here!
I told a friend and he said it's a BLE bug thats been there for ages (regarding custom CBUUIDs), is this true? is there really no fix for this?
EDIT adding the full scanning code just FYI:
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        var statusMessage = ""

        switch (central.state)
        {
        case .unsupported:
            statusMessage = "Bluetooth Low Energy is not supported!"
            displayStatusAlert(localmsg: statusMessage)
            print(statusMessage)
        case .unauthorized:
            statusMessage = "Bluetooth Low Energy is not authorized!"
            displayStatusAlert(localmsg: statusMessage)
            print(statusMessage)
        case .unknown:
            statusMessage = "Bluetooth Low Energy is unknown!"
            displayStatusAlert(localmsg: statusMessage)
            print(statusMessage)
        case .poweredOff:
            statusMessage = "Bluetooth Low Energy is powered off!"
            displayStatusAlert(localmsg: statusMessage)
            print(statusMessage)
        case .resetting:
            statusMessage = "Bluetooth Low Energy is resetting!"
            displayStatusAlert(localmsg: statusMessage)
            print(statusMessage)
        case .poweredOn:
            statusMessage = "BLE is ready!" //If BLE is ready then start scanning right away!
            peripheralsFoundNames.removeAll()
            peripheralsFoundCB.removeAll()
            peripheralsFoundRSSIs.removeAll()
            peripheralsFoundData.removeAll() //Remove previous data from previous scans
            central.scanForPeripherals(withServices: nil, options: nil)
        }
    }

//What happens when you discover a peripheral
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        //What to do when it discovers a peripheral, add it to the array list
        print("Peripheral found: " + (peripheral.name ?? "Unknown Name"))
        peripheralsFoundNames.append((peripheral.name ?? "Unknown Name"))
        peripheralsFoundData.append((advertisementData.description ))
        peripheralsFoundCB.append(peripheral)
        peripheralsFoundRSSIs.append(RSSI)
    }

Comment: That's not true.You can scan for specific custom UUIDs. You might want to have "repeating Scan Responses" from an object, maybe yours only appeared once? Try the code below:

let bleQueue = DispatchQueue(label: "BLEQueue",attributes: [],target: nil)

let options = [CBCentralManagerScanOptionAllowDuplicatesKey: true]
let cbManager = CBCentralManager(delegate: self, queue: bleQueue)

let serviceUUIDs = [CBUUID(string: "4D494B45-414c-5741-5953-524F434B5321")]
cbManager.scanForPeripherals(withServices: serviceUUIDs, options: options)
Comment: Additionally, please provide more code to get a better understanding of how your Core Bluetooth layer is supposed to being set up.
Comment: First thing: if you scan with nil services, and you print advertisement data of the didFindPeripheral method, does your services appears? If not, you won't find it, because `scanWithServices:[someService]` will work only if it advertised. If it appears on it the advertisement data, could you show the log. I'm not sure if the CBUUID on iOS is case sensitive (there is an lower "c" on yours, while the other letters are upper case).
Comment: Added more code as requested. Thing is the code already works with another bluetooth module (nRF8001), however this is a custom device that our EE is developing and it has its own custom CBUUID. I thought I could just replace the CBUUID I was scanning for and that would be the end of it but it seems that doesn't work. Scanning nil discovers the device, however searching for it specifically does not
Comment: Lepidopteron, can you elaborate on that code you suggested? where do I implement that?
Answer: I happen to be working on both BLE firmware and iOS App at the same time.
I had the same issue that the filter not working.
The reason that iOS couldn't find the device with the UUID is that the device doesn't include the UUID when it is advertising.
I had to change the device firmware to add service UUID in the advertising data packet. With device advertising the UUID, UUID filter worked as expected.
Answer: I also had this problem, but I've found some tricky way.
You can try to match UUIDs (string value) directly in didDiscoverPeripheral func:
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
  if let services = peripheral.services {
        for service in services {
            if service.uuid.uuidString.lowercased() == "4D494B45-414c-5741-5953-524F434B5321".lowercased() {
              if !peripheralsFoundCB.contains(peripheral) {
                   peripheralsFoundCB.append(peripheral)
              }
            }
        }
    }
}

If this way doesn't work for you I have one more:
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
    peripheral.discoverServices(nil)
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
     if let services = peripheral.services {
        for service in services {
            if service.uuid.uuidString.lowercased() == "4D494B45-414c-5741-5953-524F434B5321".lowercased() {
              if !peripheralsFoundCB.contains(peripheral) {
                   peripheralsFoundCB.append(periphera
              }
            }
        }
    }
}

Of course you should use

scanwithservices: nil
Comment: Thank you, I think that first suggestion will work. Although this just shows that there is a bug with the software? or hardware? so you can't scan directly for the devices? you have to filter them out afterwards?
Comment: I don't think that this is a bug. I think that something should be set on the peripheral side. I don't have practice on hardware side so I can't answer you exactly.
Answer: Swift 3:
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

    self.selectPeripheral.discoverServices(nil)
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

   let services = peripheral.services as [CBService]!{

        for service in services{

            if service.uuid.uuidString == "4D494B45-414c-5741-5953-524F434B5321"{
               print("service found")
            }
        }
   }
 }

Answer: I am having exactly the same issue. Currently I might do the same solution suggested by the folks here! But I think its a problem from the hardware side.
I believe what is happening that your EE is not broadcasting the service UUID! What I mean by that if you printed the advertisedInfo you will not see the the following key-value pair in the info:
"kCBAdvDataServiceUUIDs": <__NSArrayM 0x14e6f3b0>("Your CBUUID")

You might see the name key-value and other stuff but definitely not the one I specified.
For that reason if he can do his part by broadcasting the service UUID's then you will be able to scan for that using the following method.
scanForPeripherals(withServices: ["Your CBUUID"], options: nil)

And you will see it :)

Cant search for custom CBUUID


Finding an English translation to Kazimierz Kuratowski's finiteness paper.

Question: Dear Maths Stackexchange.
I am currently doing some reading into the different notions of how finiteness is modelled in set theory. One formulation that took my eye was Kazimierz Kuratowski's formulation which seems to me rather elegant. Whist I have no problem with understanding the mathematics of this formulation, I am nonetheless interested in viewing the original  source paper for this construction.
The earliest text I can find is given in this short three page paper here in French. Unfortunately I cannot read French, so this is of little use to me in the given state. I have done some poking around on google and google scholar and come up blank when looking for translations of said paper into English. Thus I open the following question up with the hopes that someone knows the location of an appropriate reference:

Is there an English source to this paper?
Comment: Yes, you will have to type the text. Your mathematical knowledge should help you sort out any ambiguities. I think your point about the devil in the details is misguided. If you try, you might even learn some French on the way.
Comment: Good for you. Best of luck!
Comment: Have you tried Google Translate?
Comment: No, for two reasons. Firstly, the given pdf seems to be a scan, so would involve one having to first re-type up the document before google translating. Secondly, despite google translate getting continually much more context aware with its translation, there still aren't any hard guarantees for the precise meaning of the text being conserved by it: which is very important, especially for a subject such as set theory where the devil lies in the details.
Comment: Well, I'll certainly have a go! I guess I can always ask on SE if something feels too ambiguous / wrong. Looking into it seems now that there are  free and actually not too bad web services for instant digitation, so the task may not be too arduous.
Answer: Taking the advice of @Rob Arthan, I digitised the text, corrected any errors in the digitisation before passing this text through to google translate. I then attempted to correct a couple of errors made by the machine in translation. The finished English text seems accurate to my sensibilities, however I am not in a position to give strong guarantees on the accuracy of my translation. I have been as conservative as possible in any edits I have made. Below I present the text, formatted with the usual Math-Stackechange formatting tools:

On The Notion of a Finite Set.
by Casimir Kuratowski (Warsaw).
Mr. W. Sierpiński gave in his work The axiom of M. Zermelo and its role in Set Theory and Analysis${}^1$ a new definition of the finite set. This definition is mainly distinguished by the fact that it depends neither on the notion of natural number nor on the general notion of function, which usually falls within the definitions making use of the notion of correspondence. The definition in question is as follows:

Consider class $K$ of sets each of which satisfies the following
conditions:

Any set containing a single element is part of the class K.
If$A$ and $B$ are two sets belonging to the class $K$, their sum-set $A + B$ also belongs to $K$.

Let us call finite any set which belongs to each of
the classes K satisfying the conditions 1 and 2.

As we know, the set of all. objects (if it exists) has paradoxical properties: contrary to a theorem known by G. Cantor, the power of this set would not be lower than that of the class of all its subsets. It is the same for the class composed of all the sets containing a single element; therefore, the classes K do not satisfy Cantor's theorem. Taking this fact into account, one could question the very existence of $K$-classes.
By modifying Mr. Sierpiński's definition so as to eliminate this drawback, I obtain the following definition:

The set $M$ is finite, when the class of all its (non-empty) subsets is
the unique class satisfying the conditions:

Its elements are (nonempty) subsets of $M$.

Any set containing a single element of $M$ belongs to this class.

If $A$ and $B$ are two sets belonging to this class, their sum-set $A + B$ also belongs to it.

We are going to demonstrate that a finite set according to this definition is also in the ordinary sense and vice versa. In other words: for a set to be finite according to the proposed definition, it is necessary and sufficient that the number of its elements can be expressed by a natural number (the notion of a natural number being assumed to be known).
Indeed, let $M$ be a set whose number of elements can be expressed by a natural number; let Z be any class satisfying conditions 1—3. We will show that every subset of $M$ belongs to $Z$. This is the case - by virtue of condition 2 - with subsets composed of a single element; at the same time, if this is the case with subsets containing $n$ elements, it is the same - according to 3 - with those which contain $n + 1$. As the number of elements of each subset of $M$ can be expressed by a natural number, it follows by induction that $Z$ contains all the subsets of $M$. Therefore, the class $Z$ being necessarily identical to that of all the subsets of $W$, it is the only class satisfying conditions 1—3. Thus, any set whose number of elements can be expressed by a natural number is a finite set in our sense.
Suppose, on the other hand, that the number of elements of a given set $M$ cannot be expressed by a natural number. Let us denote by $Z$ the class of all the subsets of $M$ whose number of elements can be expressed by a natural number. This class obviously satisfies conditions 1—3; at the same time, according to the hypothesis, $M $ does not belong to $Z$ and, therefore, $Z$ is not identical to the class of all the subsets of M; therefore, the class of all the subsets of $M$ is not the only class satisfying conditions 1 - 3 and is not finite in our sense, Q.E.D.
${}^1$ Bull. of Acad. des Sciences de Cracow, 1918, p. 106.

I have made the answer community so that if anyone confident in both English and French wants to either increase the accuracy of this translation, co-sign the accuracy of translation, or otherwise condemn it, they are free to do so.


How do I create an iid Rademacher sequence?

Question: The lecture notes say:
Let $(\Omega,\mathcal{A},P) = ((0,1],\mathcal{B}((0,1]),\lambda)$ where $\lambda$ is the Lebesgue measure on the unit interval.
Define $X(\omega) = 1$ for $\omega > 1/2$ and $X(\omega) = - 1$ for $\omega \le 1/2$. Then $T(\omega) = 2\omega - [2\omega]$.
It can be shown that $X_{k} = \pm 1$ with prob. $1/2$ is an iid Rademacher sequence.
Can someone please outline how this is possible?
Comment: Your description is sufficient enough to generate them. Start with generating a random variable $\omega$ from $\mathcal{U}((0, 1])$.
Comment: @Zhanxiong that begs the question. Has $\omega$ been defined?
Answer: This is just a change of variable calculation. Use the CDF method. The CDF of a Rademacher RV is just $0$ if $x < -1$, $0.5$ if $-1 < x < 1$ and $1$ if $x > 1$. You can show $2\omega - [2\omega]$ satisfies this when $\omega \sim \text{Uniform}(0,1)$.


What if an opposing player uses part of the Batsman's clothing to put down the wicket?

Question: Following on from,
Lets suppose that a batsman is facing an over of spin, he/she has removed thier helmet and placed it behind the stumps for safe keeping.
What if, while the ball is in flight, an opposing player uses the helmet to put down the wicket? Would the batsman be out? Assuming not, which laws preclude this?
Answer: Batting Team is not allowed to keep their helmets behind the wicket or any part of the ground. If the don't want the helmet they should send it back to the dressing room


How to estimate which distribution a new observation belongs to, when the distributions are given by a set of obervations

Question: The question is that I have several probability distributions. For each distribution $P_i$, I don't know what it is. Instead, I have a set of observations $\{x_i^j\}_{j=1}^{n_i}$ drawn from each of the $P_i$. Now for a new observation $x_t$, is there a way to estimate the likelihood of each $P_i$ the new observation belongs to? Or which $P_i$ it most likely belongs to? Here $x_i^j, x_t \in R^m$.
I do hope for a method that can directly calculate the likelihoods without making assumptions on the distributions and calculating their parameters first. But honestly I don't know if such methods even exist.
Thanks!
Comment: Have you looked at classification algorithms. For example k nearest neighbors.
Comment: @shane Thanks! I didn't even realize that it was a classification problem! In fact the observations $\{x_i^j\}_{j=1}^{n_i}$ are labeled by $i$, so it is a supervised learning problem.
Answer: If I understand your problem correctly, I doubt that it is solvable in the general sense.
In fact (if I do understand your problem), you can easily construct a trivial example which has an infinite number of non-unique sets of $P_i$ from which the $x_i$ could have come from.
For example: suppose you have two hidden discrete RVs such that $P_1 = 1$ with probability 1 and $P_2 = 2$ with probabilty 1. Assume also, that the probability you draw an $x_i$ from either of the two distributions is $\frac{1}{2}$ and that these drawings are indept.
You could never distinguish this scenario from one where the distributions where defined such that: $P_1(X=1)=0.25$ and $P_1(X=2)=0.75$, whilst $P_2(X=1)=0.75$ and $P_2(X=2)=0.25$ and the $x_i$ were independently drawn from $P_1$ and $P_2$ with probability $\frac{1}{2}$.
Comment: Hi Jonathan, thanks for your answer! Maybe I didn't state my question well, so sorry if I have confused you. @shane just reminded me that my question, in essence, is a classification problem. I have a set of observations $\{x_i^j\}_{j=1}^{n_i}$ drawn from each distribution (class) $P_i$, and I want to know the probability that a new observation belongs to each of the distribution (class). I now have realized it could be solved by training a classifier.


How many lineups of 20 are possible where Sally is first, second or third, and Adam is somewhere in the line?

Question: The line of 20 is created from 300 students. The next part of the question was to find how many ways there are where Sally is first, second or third. I did a permutation of 299 choose 19 for the lineup (subtracting Sally from both essentially) and then 3 choose 1 for Sally. With the rule of sum, this totalled to (299!/280!)(3).
Now, I am stuck on how to make Adam in the line too. I was thinking the same idea and take (298!/279)(3)(19) where the 19 represents the ways Adam could be in the line. Am I on the right track here?
Comment: Please continue to include your thoughts and efforts (work in progress) in future posts.
You are more likely to receive positive/constructive feedback that way.
Formatting your post helps too.
Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: @Peter "continue to". I posted during a review of "first posts". I will clarify that it is a positive thing in the future.
Answer: Independent of the position of Sally, Adam has $19$ possible positions. So, the total number of possibilities is
$$3\times 19\times \frac{298!}{280!}$$
Answer: You are almost right. First place Sally ($3$ options) then place Adam ($19$ options).
Now $18$ open places are left to be filled. For the first you have $298$ options, for the second $297$ etc.
This results in $$3\times19\times298\times\cdots\times281$$
possibilities.
Answer: Since both Adam and Sally are in the line, we must choose $18$ of the remaining $298$ people to be in the line.  We have three ways of placing Sally so that she is in one of the first three places.  Once Sally's position has been chosen, we can arrange the other $19$ people (including Adam) in $19!$ ways.  Thus, the number of possible arrangements is $$\binom{298}{18} \cdot 3 \cdot 19!$$
Answer: First, we pick the $20$ students. One must be Sally and another must be Adam. We choose $18$ others from the $198$ remaining, as you have, to get $\dbinom{198}{18}.$ Now, Sally can have $3$ possible locations, and Adam can have any position from the remaining $19.$ Our answer is $\boxed{\dbinom{298}{18} \cdot 3 \cdot 19!}.$ Adam's presence does not affect the second factor.
Comment: You reproduced my answer, except that you made a subtraction error.  $300 - 2 = \color{red}{2}98$.
Comment: Did not realize...


How to properly unescape non-ASCII cahracters in location.pathname

Question: I have the following URL in the browser address bar:

example.com/search/city/Germany:Baden-Württemberg

From the console I try to get the pathname of the URL:
location.pathname which returns:

/search/city/Germany:Baden-W%C3%BCrttemberg

I see that the ü character has been transformed (escaped) to %C3%BC sequence.
I want to dysplay this character as is in the HTML document, therefore I tryed with unescapeing it:
unescape(location.pathname) but unfortunatelly what I get is not the string from the URL >
'/search/city/Germany:Baden-Württemberg'
How can I get the URL character ü (from my URL example.com/search/city/Germany:Baden-Württemberg ) via Javascript ?
Thank you!
Comment: Use [`decodeURI()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI)
Comment: By the way, from the documentations of [`unescape()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape) : *"Note: Do not use unescape to decode URIs, use decodeURI instead."*. Sometime (always) reading the documentation helps
Comment: If I knew the answer is there I would have read it. window is pretty big API. You know learning by doing is often effective way.
In general you are right, but the due dates not aways encopas API documentation reading time.
Comment: I voted to close this question because you indicate that you resolved the problem without receiving any answers. If you still need answers, please [edit] the question to indicate that the issue is not fully resolved. If the solution you found would be useful to others, please answer your own question by pressing the "Answer Your Question" button.
Comment: @Hairi well, reading the documentation of the function you used to know why it didn't work as expected would have been a great pointer
Answer: The solution pointed out by @Cid

Use decodeURI()

worked better in this case than unescape which seems not to be the preferred function for such translations.
From  developer.mozilla.org

Usually, decodeURI or decodeURIComponent are preferred over unescape.

Again, all the credits of this answer go to @Cid for his comments on the original questions.


Force close of MDF file

Question: I have an MDF file that is being held open by another computer.
The MDF file sits on a shared folder and the server that normally holds the MDF file open is shut down.
However, when I attempt to open the file using another server I get a sharing violation error.
I cannot turn the first server on again so somehow I need to forcably close the connection to the database so the new server can open it.
Any thoughts?
Answer: The more delicate approach might be to run the computer management console (i.e. compmgmt.msc ) on the server sharing out the file and look in shared folders->sessions or shared folders->open files.  Here you can select the offending file being shared out and close it, without having to reboot, or closing other sessions the other server may need.
Of course, this probably requires more effort, so blunt instruments are sometimes the best!  so rebooting works well too.
Also why are you sharing out mdf files over cifs/smb?  Its supported in sql server 2008 r2, but there are big performance implications.
Answer: Restart the machine hosting the share, or even just stop (and then recreate) the shared folder.
Comment: Shut down the new server and started it again.  Somehow, no idea how, but it was holding the file open.  Might have double clicked on it or something I don't know.  Thanks for answer, pointed me in right direction.

Force close of MDF file


Number of calls to oracle in Randomized Stochastic Gradient (RSG) algorithm

Question: In Stochastic First-and Zeroth-order Methods for Nonconvex, on page 10, the author claims that the number of calls to Stochastic First order Oracle (SFO) for finding an $(\epsilon, \Lambda)$ solution after disregarding a few constant factors, can be bounded by
$$
\mathcal{O}(\frac{1}{\Lambda \epsilon} + \frac{\sigma^2}{\Lambda^2 \epsilon^2})\tag{1}
$$
which apparently is a consequence of $(2.19)$. However, I have the following questions:
1- What is the relation between $\lambda$ and $\Lambda$, because form Markov inequity and $(2.14)$ we have
$$
\text{Prob}\{ \| f(x_R) \|^2 \geq \lambda L \mathcal{B}_N \} \leq \frac{1}{\lambda}\tag{2.19}
$$
So
$$
1 - \text{Prob}\{ \| f(x_R) \|^2 < \lambda L \mathcal{B}_N \} \leq \frac{1}{\lambda}
$$
Since $\| f(x_R) \|^2$ is a continuous random variable, we have equality in the $\text{Prob}$ and
$$
\text{Prob}\{ \| f(x_R) \|^2 \leq \lambda L \mathcal{B}_N \} \geq 1- \frac{1}{\lambda}
$$
Is $\Lambda = \frac{1}{\lambda}$?
2- Is the number of calls the same as expected value of $R$? If so, by choosing constant stepsize pmf of $R$ is uniform and it becomes $N/2$, then how we are getting bound $(1)$?
3- From which formula $(1)$ is derived and what are the steps?
Note: Please answer all the questions I have not partially. Also, please help me to walk through all the steps deriving $(1)$?
Answer: That is a very interesting paper. I will provide a "brief" derivation but the steps in between can be derived rather easily.
1,2,3 - By Markov's bound, you have
$\text { Prob }\left\{\|\nabla f(\bar{x})\|^{2} \leq \epsilon\right\} \geq 1-\Lambda,$
or in other words, by looking at the "complement" of that equation, you get
$\text { Prob }\left\{\|\nabla f(\bar{x})\|^{2} \geq \epsilon\right\} \geq \Lambda.$
Now all that is left to do is to compare the above equation with equation (2.19) in the paper. Therefore, you get
$\epsilon  = \lambda L \mathcal{B}_{N}$
and
$\Lambda = \frac {1}{\lambda}.$
Once you have these equations you are basically there. Now use the above two equations in combination with (2.14) in your paper to write
$L\left(\frac{LD_{f}^{2}}{N}+\left(\tilde{D}+\frac{D_{f}^{2}}{\tilde{D}}\right)\frac{\sigma}{\sqrt{N}}\right)=\epsilon\Lambda.$
Define constants $C_{1}=D_{f}^{2}$ and $C_{2}:=\tilde{D}+\frac{D_{f}^{2}}{\tilde{D}}$  and rewrite the above equation to get
$C_{1}\frac{L}{N}+C_{2}\frac{\sigma}{\sqrt{N}}=\frac{\epsilon\Lambda}{L}.$
This equation is a quadratic in terms of $N$. Solve the quadratic for $N$ and you will get
$N \sim \mathcal{O}\left\{\frac{1}{\Lambda \epsilon}+\frac{\sigma^{2}}{\Lambda^{2} \epsilon^{2}}\right\},$
which is what you are looking for. Good luck!


About transformation of Variables

Question: In a probability chapter of a Python Book, there is the following problem involving a transformation of variables:

I don't fully understand where the value 1/z+1 in Y > X(1/z+1) comes from, and how you evaluate the integral in the interval max(X,X(1/z+1))< Y < 1
Answer: The inequality directly comes from substitution:
$$Z<z\rightarrow \frac{X}{Y-X}<z\rightarrow X(1+z)<zY\rightarrow Y>X(1/z+1)$$
Then, for the integral boundaries, we have two conditions: $Y>X$ and $ Y>X(1/z+1)$, which can be written as $Y>\max(X,X(1/z+1))$ more compactly. Also, since $z>0$ and $X\geq 0$, this maximum is equal to $X(1/z+1)$.
The explanation first integrates the double integral over $Y$ and then $X$. The inner integral was
$$\int_0^1 \{Y>\underbrace{X(1/z+1)}_\alpha\} dY=\int_\alpha^1 dY=1-\alpha=1-\frac{X}{z}-X=\frac{z-X-Xz}{z}$$
Comment: I see it now! Thank you very much!

About transformation of Variables


How to resolve message ' Requires: Commerce_checkout (missing)'?

Question: I have installed the Commerce Checkout Pages module (as the tar.gz file), as shown in this image:

Note the message shown within its description, i.e:
Requires: Commerce_checkout (missing)

Now I want to enable it, but I don't know how I resolve the missing part of the module.
Any help?
Answer: You need to install the Commerce module.
Commerce Checkout is a submodule thereof.
Answer: From the screenprint it looks like you're using the module for which the info file looks like so:
name = Checkout Pages
version = 7.x-1.x-dev
description = Allow user to add custom pages to DrupalCommer checkout.
package = "Commerce (contrib)"

core = 7.x
dependencies[] = commerce_checkout

; Information added by drupal.org packaging script on 2011-10-20
version = "7.x-1.0"
core = "7.x"
project = "dc_co_pages"
datestamp = "1319137230"

So as per this info file, you need to install "Checkout" first (that's why it shows "missing") ... and which is a submodule of Drupal Commerce.
Comment: The .info file is irrelevant, you just need the machine name of the missing module to work this out.
Comment: @Clive With the limited info provided in [the first version of the question](https://drupal.stackexchange.com/revisions/254539/1) (which at first was also tagged with an "8", though somebody different from OPer took the liberty to change the tag to a "7"), I wanted to be sure about what version the screenprint was related to. I.e. the module's description (note the 'DrupalCommer' typo in it ...) and version. Which is why I checked the info file first (while writing my answer), and decided to "share" my research (for which the content of the .info file was relevant) in my answer also.


Swelling delay?

Question: I was watching Steven Wilson's DVD "Get All You Deserve" and was wondering how to create a particular guitar effect. At the end of the song "Raider II," the band is jamming slowly as each member eventually walks off stage.  Guitarist Niko Tsonev is using an effect where he plays a fast riff, and as he plays, the notes seem to collect and swell/fade in a delay I have never heard before. The effect is not echoing each note he plays as he plays it, but rather mashing them all together and swelling them up and out almost a second after they are played.
Here is the link:

The song is almost 24 minutes long, and a great tune! But if you want to get to where I am referencing, go to about the 21:48 mark. The sound quality is not that great, so headphones may be required. You also have to listen through the flute that is playing as well.
Please help! I am exhausting myself over this and I think it should be easy enough to explain...somehow...
Answer: Here is Niko Tsonev explaining the effects he uses on stage with Steve Wilson.

Here is his endorsement page at tc electronics.
If you go to his website, he provides his email address. Why not write to him yourself and ask him to explain how he creates these effects?
Comment: @MarkWhiteaker: You can politely respond to him with a link to this question as reference to make it clear to him what you mean.
Comment: Thank you so much for the clip...at least gets me going in the right direction. Write him myself...actually, that's almost where I started out, but I don't think I communicated the effect in question clearly enough, and I don't think he remembered it well enough, perhaps (The show was in 2012). He responded about the use of whammy bars and pedals. True, he used those, but that's on the opposite end of the effect! I hate to pester him further about it.
Comment: Well, I actually had re-responded to Niko Tsonev a while back asking more about the delay. Figuring I had already asked too much and not hearing back as quick as the first try, I chalked up a lost avenue. He just responded back to me with the answer, I believe. He says he used a Line6 particle reverb. The little looking into I have done so far is very promising, and I am very excited! Totally did not expect to hear back. I truly respect the artist, now on a whole new level!

Swelling delay?


Quero agrupar 3 colunas em apenas uma, separadas por vírgula no R

Question: Meu conjunto de dados é assim:
    x   y   z
A 1.1 1.2 1.3
B 2.1 2.2 2.3

Usando o R, quero agrupar as 3 colunas em apenas uma, separadas por vírgula.
Quero que fique assim:
              x
A 1.1, 1.2, 1.3
B 2.1, 2.2, 2.3

Dados
dados <-
structure(list(x = c(1.1, 2.1), y = c(1.2, 2.2), z = c(1.3, 2.3
)), class = "data.frame", row.names = c("A", "B"))

Answer: Use unite:
library(tidyr)

unite(data = dados, col = x, c(x, y, z), sep = ", ")

#                x
#  A 1.1, 1.2, 1.3
#  B 2.1, 2.2, 2.3

Answer: Uma solução R base com apply.
dados[[1]] <- apply(dados, 1, paste, collapse = ", ")
dados <- dados[1]

dados
#              x
#A 1.1, 1.2, 1.3
#B 2.1, 2.2, 2.3

Dados
dados <- read.table(text = "
    x   y   z
A 1.1 1.2 1.3
B 2.1 2.2 2.3
", header = TRUE)


Redundant Azure federated services

Question: During the recent outage of Azure, a company I am aware of lost it's federated services farm as the underlying VMs lost access to their storage.  I've been asked to suggest ways of adding High Availability to their current, textbook implementation (really, textbook https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/deployment/how-to-connect-fed-azure-adfs ).
About the only way I can think of that would work would be a redundant Federated Services farm, in a different Azure region - but I can't find any MS documentation that implies that this is even possible.  You certainly don't appear to be able to have multiple URIs for federating a domain via multiple federation server farms.
Any ideas people?
Answer: I would recommend looking at Azure Site Recovery to another Azure region (aka Azure to Azure ASR).  There are special considerations for domain controllers but this would not only protect your ADFS instance but would allow you to test fail-over to ensure this solution will protect you in the event of a regional outage.

Redundant Azure federated services


How can I inject services into my entity bundle class?

Question: I have an entity with a JSON field, and I do some complicated processing when the entity is saved.
Right now, I do this processing in hook_ENTITY_presave(), which calls a service I have created in a custom module.
However, since Drupal 9.3, we can create bundle classes to extend entities cleanly.
So I made one for my entity, and I wrote some new getters and setters so I can do $entity->getMyValue() instead of $entity->field_abc->value.
Now, I want to take the next step and inject my service into the entity and move the processing directly into the entity on save.  How can I do that?
Answer: Alas, this is not yet possible.  There is a discussion in the Core issue queue on how to proceed with this.
As noted in the discussion linked above, an alternative to do this now is to use the Typed Entity module, which wraps entities into objects and allows you to do dependency injection.


Is there a way to see all the available variables inside content?

Question: I am using Drupal 9 with twig files
I have a page where in one section I need to show thumbnails of the latest posts. So I created a new view as a block, and placed this block under Content in admin/structure/block/list/
When I inspect with debug on I get these file suggestions -
 FILE NAME SUGGESTIONS:
   * block--views-block--latest-news-block-1.html.twig
   * block--views-block--latest-news-block-1.html.twig
   * block--views-block.html.twig
   * block--views.html.twig
   x block.html.twig

So I created a file name block--views-block--latest-news-block-1.html.twig with the code from block.html.twig.
Inside that file I have -
    {% block content %}
      {{ content }}
    {% endblock %}

Which shows all the content in the block. I need to customize the content in the block though, some things need to be removed, I need to truncate the article text, need to add buttons.
I think I'd be able to do what I want if I could target specific parts of the content. I want to do something like this -

{{ content.title }}

{{ content.body }}

Is there a way to target specific parts of the content like that?

Answer: Normally it works that way but Views templates may be different.

Enable Twig debugging.
Add Devel and Kint: composer require drupal/devel kint-php/kint
Enable Devel: drush -y en devel
Inside the template put {{ kint(content) }}, flush caches, visit the page and you should see what else can be found inside content.


Question regarding SearchAPI and Index performance/scaling

Question: I have a site that will need to deal with thousands of nodes. it's an internal site, not public facing, with a daily concurrent user base of no less than 80 and no more than 100 users.
I am trying to figure out how to deal with search and indexing. The Big problem is I need facets and whatnot, but I also need instant data retrieval. So users can't wait for indexes to catch up. can one index via  SearchAPI near instantly?
On average, there might be 2-300 new nodes created per day, every day, by users, and an additional 5-600 nodes created per day+ through automated imports (Feeds).
I was thinking of just using straight views, and trying to do search filters, but it's not scalable and after a few months to a year it would be quickly unmanageable.
TL:DR: Many many nodes per day need indexed search with facets (SearchAPI and FacetAPI using ElasticSearch). Near instant retrieval required. If a user creates a node, they need to be able to see that node in the index within a few seconds or less.
Alternatively, thinking out loud, could I have it submit the new node to the index on every new node addition?
Answer: Regarding Search, I would suggest to go with external Search System, like ApacheSolr, Elastic Search, Algolia, etc. This will make sure that database will not be overloaded with content index.
I'm working on a project where we currently have almost 2 Lac nodes and around 30-500 nodes created every day. The number of concurrent users are 1-20 max. We're using ApacheSolr (Solr hosted on different server) with Search API and Search API Solr Module and results are retrieved in less than 1-2 Seconds (The Project is internal of Client's Company so can't share the link here).

I was thinking of just using straight views, and trying to do search
  filters, but it's not scalable and after a few months to a year it
  would be quickly unmanageable.

Using view for rendering search results will not help much in terms of instant results. Preferred way will be writing custom code to query based on keyword and show results based on requirement.

Alternatively, thinking out loud, could I have it submit the new node
  to the index on every new node addition?

Indexing of Node after Creation/Updates are managed by module. The search indexing is normally done when running Cron. So setting up your site Cron to run every minute will make sure that the nodes are indexed instantly.
Hope this helps.
Comment: This basically confirms my thoughts on this. Thanks.


Evaluate the limit $ \lim_\limits{n \to \infty} \frac{1^a+2^a\cdots+n^a}{n^{a+1}} $

Question: The exact question is-
Find the real value(s) of $a (a \ne -1)$ for which the limit $$ \lim_{ n \to \infty} \frac{ 1^a+2^a\cdots+n^a}{(n+1)^{a-1}[ (na+1)+(na+2) \cdots+(na+n)]} = \frac{1}{60}$$
I simplified it a bit to get that limit. However,  I got the answer from Wolfram Alpha $\frac{1}{a+1}$ without a solution and an assumption that $|a|<1$ however the answer that I got on further solving (and given) is $a=7$ and $a=-\frac{17}{2}$
How is it solved?
Comment: This page could also be helpful: [Limit of the sequence $\frac{1^k+2^k+...+n^k}{n^{k+1}}$](https://math.stackexchange.com/questions/936924/limit-of-the-sequence-frac1k2k-nknk1). Also https://math.stackexchange.com/questions/150391/evaluate-lim-limits-n-to-infty-frac-sum-k-1n-kmnm1 and https://math.stackexchange.com/questions/478344/what-is-the-result-of-lim-n-to-infty-frac-sumn-i-1-iknk1 for example.
Comment: I think Stolz Cezaro theorem could help
Comment: Yes, thanks for mentioning that. I didn't see that simple Riemann sun albeit it was right there in front of me.
Answer: The expression is equal to
$$\frac{1}{n}\left(  \left(\frac{1}{n}\right)^a +\cdots + \left(\frac{n}{n}\right)^a \right).$$
This is a Riemann sum, so your limit is the integral of an easy function.
Comment: Thanks. How could I miss that! Damn!
Answer: Beside the Riemann sum, consider that
$$\sum_{i=1}^n i^a=H_n^{(-a)}$$ which is a generalized harmonic number.
Using asymptotics
$$H_n^{(-a)}=n^a \left(\frac{n}{a+1}+\frac{1}{2}+\frac{a}{12
   n}+O\left(\frac{1}{n^3}\right)\right)+\zeta (-a)$$ making for the question in title
$$\frac{\sum_{i=1}^n i^a }{n^{a+1}}\sim \frac 1{a+1}+\frac a {2n}$$ So, the limit and also how it is approached.
For the question in text,
$$\sum_{i=1}^n (na+i)=\frac{1}{2} \left((2 a+1) n^2+n\right)$$ and the same approach would lead to
$$\sim \frac {n^a} {(n+1)^a} \frac{2(n+1)}{(1+a)(1+2a)n}\to \frac 2{(1+a)(1+2a) }$$
Comment: I guess, that's not in highschool syllabus
Answer: Useful link related to the first equation;
Evaluate $\lim\limits_{n\to\infty}\frac{\sum_{k=1}^n k^m}{n^{m+1}}$
Limit of the sequence $\frac{1^k+2^k+...+n^k}{n^{k+1}}$
$\lim_{{n}\to {\infty}}\frac{1^p+2^p+\cdots+n^p}{n^{p+1}}=?$
Showing that $\lim_{n \rightarrow \infty}\frac{1^k+2^k+...+n^k}{n^{k+1}}=\frac{1}{k+1}$ using integral
Prove that limit of $\frac{1^p + 2^p + \ldots + n^p}{n^{p+1}}$ is equal to $\frac{1}{p+1}$
$$1^a+2^a+...+n^a\sim\frac{n^{a+1}}{a+1}$$ so we could write this limit :
$$ \lim_{ n \to \infty} \frac{ 1^a+2^a\cdots+n^a}{(n+1)^{a-1}[ (na+1)+(na+2) \cdots+(na+n)]} =\lim_{ n \to \infty}\frac{\frac{n^{a+1}}{a+1}}{{(n+1)^{a-1}[ n^2a+\frac{n(n+1)}{2}]}} = \lim_{ n \to \infty}\frac{2n^{a+1}}{{(a+1)n(n)^{a-1}n[2a+1]}} = \frac{2}{(a+1)(2a+1)}=\frac{1}{60}$$
So $(a+1)(2a+1)=120$ and $a=7,\frac{-17}{2}$
Comment: I add some resources. You could use similar question in the right of your browser too find other similar questions. Please don't forget to mark correct solution question as "tik" to be in access other people. Thanks.
Comment: How do you know/prove that first fact which you used?


Views PDF CSS file not being applied on generated PDF

Question: I've created a pdf display with views_pdf module in views, and under the PDF SETTINGS i've included a CSS File (eg. sites/all/themes/custom/mytheme/css/mytheme.css).
When viewing the page display of the view, the css is being applied, but when viewing the generated pdf, all of the css is missing.
I have tried putting inline css as well but it's not working.
Can someone tell me what is the workaround for this?
Answer: What worked for me is to rewrite the field. For the title field it would be something like:

[title]

And then use this custom class in my CSS file.


Multiple Submit in a Drupal Form

Question: I want a list of the input of my saved database table with buttons to delete or view the content and want to redirect it in the submit function.
With this code snipped i get only the submitted input value of the buttons, but every time is the $form_state['values'] array filled with the 1st form values. Is that the right way or need I another solution?
function myform_block_view($delta = '') {
    $block = array();

    global $user;
    $uid = $user->uid;
    $utime = $user->timezone;

    $query = db_select('mytable', 'm');
    $query->condition('m.uid', $uid, '=');
    $query->fields('m', array('fid', 'uid', 'name', 'created'));
    $query->range(0, 50);

    $results = $query->execute()->fetchAll();

    if($uid) {
        switch ($delta) {
            case 'myblock':
                $block['subject'] = '<none>';
                $block['content'] = _block_content($results);
            break;
        };
    };
    return $block;
}

function _block_content($items) {
    $output = array();

    foreach($items as $item => $item_value) {
        $output[$item] = drupal_get_form('mymodule_form', $item_value);
    };
    return $output;
}

function mymodule_form($form, &$form_state, $i) {

    global $user;
    $uid = $user->uid;
    $utime = $user->timezone;

        $form['value-'.$i->fid] = array( //EDIT
            '#type' => 'value',
            '#value' => $i->fid,
        );
        $form['view-'.$i->fid] = array ( //EDIT
            '#type' => 'submit',
            '#value' => t('view'),
            '#name' => 'view-'.$i->fid,
        );
        $form['delete-'.$i->fid] = array ( //EDIT
            '#type' => 'submit',
            '#value' => t('delete'),
            '#name' => 'delete-'.$i->fid,
        );

    return $form;
}

function mymodule_form_submit($form, &$form_state) {
   dpm($form_state);
   $form_state['rebuild'] = TRUE; //EDIT
}

The dpm output without 'form_build_id' 'form_token' 'form_id' in both,
1st example:
input =>
    view-3 => view
    value3 (NULL)

values =>
    value2
    view-2 => view
    delete-2 => delete

2nd example:
input =>
    view-3 => view
    value3 (NULL)

values =>
    value3
    view-3 => view
    delete-3 => delete

Comment: can you add the result of the dpm?
Comment: I write one of the dpm after the changes of Yogesh. This is the one wich matched with the submit input.
Comment: This dpm makes no sense... can you check that it's most recent after your updates to the code?
Comment: That`s what i get. I add a 2nd dpm output in my question from one submit.
Comment: Can you add a dpm of $i in mymodule_form?
Comment: The $i gives the query from the database and this also for every loop, that is all fine. Only the submit makes me little bit crazy.
Answer: It should be because the way you're generating the form is wrong, form element should be as below:
<?php
function mymodule_form($form, &$form_state, $i) {
  $form['value_' . $i->fid] = array(
    '#type' => 'value',
    '#value' => $i->fid,
  );
  $form['view_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('view'),
    '#name' => 'view_' . $i->fid,
  );
  $form['delete_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('delete'),
    '#name' => 'delete_' . $i->fid,
  );

  return $form;
}
?>

Each element name in $form array should be unique. Check Drupal Form API reference guide for more details. The value, view and delete doesn't contain any form element data like #type, etc. Please check the value of $form_state['values']['op'] in your form submit handler to understand which one is called.
Comment: Ah, you have right! Now I can compare the 'input' with the 'values' in the $form_state array. I forgot the $form_state['rebuild'] = TRUE; in the submit function too. The submit is calling for every loop. I havn`t any 'op' in 'values', also the value doesn`t help, it returns only the value of the current loop in 'input'. Is there not a better solution?
Comment: In submit handler you can check for `$form_state['values']['op']` which will give you which submit button is clicked, suppose for e.g. `delete_2` so you'll have that to identify.
Comment: Really I havn`t any 'op' in $form_state['values'], the values changes all with the fid in the loop. Only the 'input' displays me the clicked button. I can write two of the dpm outputs if you want.

Multiple Submit in a Drupal Form


What are good references on calculating confidence intervals using subsampling or the delete-d jackknife?

Question: I searched for references on using subsampling or the delete-d jackknife to calculate confidence intervals but wasn't able to find much.
Could someone please offer more reference on using subsampling or the delete-d jackknife to calculate confidence intervals?
Answer: The practice in the field seems to be to rely on asymptotic normality of the estimate and to use the jackknife just as an estimate of variance to help calculate standard errors, which are then plugged into a hoped-for normal distribution of the estimate.
If there's reason to think the estimate doesn't have a normal distribution I think a bootstrap of some sort is more appropriate eg for asymmetric confidence intervals.
Some references on using delete-d-jackknife to estimate variance include these articles by Messer and Gamst, Shao and Wu, and Xiquan Shi.  If you are interested in delete-a-group-jackknife (basically a stratified version) then there is a bunch of articles by Kott including (from the help files for Zardetto's EVER library):
Kott, Phillip S. (1998) "Using the Delete-A-Group Jackknife Variance Estimator in NASS Surveys", RD Research Report No. RD-98-01, USDA, NASS: Washington, DC.
Kott, Phillip S. (1999) "The Extended Delete-A-Group Jackknife". Bulletin of the International Statistical Instititute. 52nd Session. Contributed Papers. Book 2, pp. 167-168.
Kott, Phillip S. (2001) "The Delete-A-Group Jackknife". Journal of Official Statistics, Vol.17, No.4, pp. 521-526.
Answer: For subsampling you can look at material in my book or Efron and Tibshirani.  But the best reference that has been over looked so far is the book by Politis, Romano and Wolf.  The original work on this predates the bootstrap and is due mainly to Hartigan in his 1969 paper in JASA.  Here are links to the books.
Subsampling
Bootstrap Methods: A Guide for Practitioners and Researchers
An Introduction to the Bootstrap


Can a $k$-planar graph have quadratically many maximal cliques?

Question: Can a $k$-planar graph have quadratically many maximal cliques?
I know that any planar or $1$-planar graph $G=(V,E)$ has only $O(|V|)$ maximal cliques, but is there anything known about this question for $k>1$?
Answer: As far as I know, this study has only just begun.
The following statement came from Literature [1].

For $k ≥ 3$, not even the maximum number of edges is known for
$n$-vertex $k$-planar graphs, so counting larger cliques is likely to
be an extremely difficult problem.

[1] Gollin J P, Hendrey K, Methuku A, et al. Counting cliques in 1-planar graphs[J]. European Journal of Combinatorics, 2023, 109: 103654.
In fact, Bekos et al. [2] proved that a $3$-planar graph with $n$-vertices has at most $5.5n-10.5$ edges. But we do not know if the bound is tight.
[2] Bekos M A, Kaufmann M, Raftopoulou C N. On the density of non-simple 3-planar graphs[C]//International Symposium on Graph Drawing and Network Visualization. Springer, Cham, 2016: 344-356.
Gollin et al. also give this conjecture:
Conjecture. For $n ≥ 7$, the maximum number of triangles in an $n$-vertex 2-planar graph is at most $(17n − 49)/2$.
The bound in the conjecture  is achieved by the 2-planar graphs formed by stitching copies of $K_7$ together. This stitching is possible since $K_7$ has a $2$-drawing with two facial triangles.

An $n$-vertex 1-planar graph with $4n − 8$ edges is called an optimal 1-planar graph. An open problem for optimal 1-planar graphs that I love is as follows:
Problem. Let $n$ and $t$ be positive integers with $t ∈ \{3, 4, 5\}$ and $n ≥ 10$. What is the maximum number of subgraphs isomorphic to $K_t$
in an $n$-vertex 1-planar graph with $4n − 8$ edges?
To address this problem, I recently worked on the properties of optimal 1-plane graphs, although some are not directly relevant. (Some other progress is being organized)

L.C. Zhang, Y.Q. Huang, The reducibility of optimal 1-planar graphs with respect to the lexicographic product [J]. arXiv preprint arXiv:2211.14733, 2022.


There is issue between tableview and scrollview

Question: When I Scroll the table View.The screens get jumped. I have TableView within View ,View within the Scroll View.
I have refer the following link.
conflict scrolling scrollview and tableview
I couldn't get the clear solution.
Please provide me input on this.
Answer: As the answer to your linked question suggests, you should not put a UITableView inside a UIScrollView as their scrolling will just conflict.  Get rid of the UIScrollView and use a header or footer if you need some more static view at the top or bottom of your UITableView.
Answer: Avoid bounce of ScrollView when we scroll the tableview. I have added the below line of code.It worked for me.
  self.scrollView.delegate = self
     scrollView.contentSize = CGSize(width: self.view.frame.width, height: 500)
     scrollView.showsVerticalScrollIndicator = true
     scrollView.tag = 1

   func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView.tag != 1 {
            self.scrollView.bounces = false
        }
    }

Thanks