text:
Q: How do I make a puzzle app in droid without running out of memory? I notice that other puzzle apps from the google play store can go up to as many as 400 separate movable puzzle pieces
I have been attempting to learn how to at least take an image that will represent my puzzle,
Crop certain sections and mask the image space that is left with a puzzle piece design in order to create my individual puzzle pieces
I want to max out with 20 pieces for my app but so far according to my android studio memory log once bitmap factory is done creating one puzzle piece I'm using up around 18mb of memory, after 20 pieces are created along with all the other functions of the app I'm using up 400+mb of memory which I must use "largeHeap=true" to keep from running out of memory, but I'm so close to exceeding those higher limits that the app is super sluggish and enough animated activity will inevitably crash the app
I would love to know what those other play store puzzle apps are doing that I'm not
any input is greatly appreciated
FYI I'm using PNG24 for my images and the dimension on my test image is 556x720
Here is an example if I were to just create one animated-able puzzle piece image
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);//Remove title bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//Hides notification bar
    this.setContentView(R.layout.activity_main);//set content view AFTER ABOVE sequence (to avoid crash)

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mainDisplay = getWindowManager().getDefaultDisplay();
    mainLayout = (ViewGroup) findViewById(R.id.id_layout);

    DisplayMetrics m = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(m);
    int windowHeight = m.heightPixels;
    int windowWidth = m.widthPixels;

    offsetX = (windowWidth / 1440.0f);
    offsetY = (windowHeight / 2560.0f);

    ourContext = this;

    xpos = new float[2];
    ypos = new float[2];

    iv_PuzzleOne();

    bkgdbm = BitmapFactory.decodeResource(getResources(), R.drawable.puzzleimage);

    paintObject = new Paint();
    paintObject.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));

    bm_PuzzleOne();

    thisTimerTask = new ThisClass();
    thisTimer = new Timer();
    thisTimer.scheduleAtFixedRate(thisTimerTask, 16, 16);

    touchpad = new ImageButton(this);
    SetPos(0, 0, 1440, 2560);
    touchpad.setLayoutParams(layoutPositioner);
    touchpad.getBackground().setAlpha(1);
    mainLayout.addView(touchpad);

    touchpad.setOnTouchListener(new View.OnTouchListener() {

        //@SuppressLint("NewApi")
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                xpos[0] = event.getX(); //storing my finger's position coordinates when I first touch the screen into the 1st element
                ypos[0] = event.getY();

                if ((event.getX() > imgx1) && (event.getX() < imgx1 + imagewidth1)
                        && (event.getY() > imgy1) && (event.getY() < imgy1 + imageheight1)) {
                    touching1Puzzle = true;
                    img1.bringToFront();
                }

            }

            if (event.getAction() == MotionEvent.ACTION_MOVE) {

                xpos[1] = event.getX(); //add my finger's new current coordinates into the 2nd element
                ypos[1] = event.getY();

                if (touching1Puzzle) {
                    adjustImg();
                }
            }

            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (touching1Puzzle) {
                    touching1Puzzle = false;
                }

            }

            return false;
        }

    });
}

void bm_PuzzleOne()
{
    //start of 1st puzzle

    foregdimg1 = BitmapFactory.decodeResource(getResources(), R.drawable.puzzlepieceprac);//puzzle cut out (42.48MB) +6.15
    mutableforegdimg1 = foregdimg1.copy(Bitmap.Config.ARGB_8888, true); //(48.32MB) +5.84

    compositeImage1 = Bitmap.createBitmap(mutableforegdimg1);//cuts out foreground info into bkgdimage (54.43MB) +6.11

    imgCanvas1 = new Canvas(compositeImage1); //canvas references puzzle cut out image (54.43MB) +0
    imgCanvas1.drawBitmap(croppedBmp, null, new Rect(0, 0, 1500, 2000), paintObject);//places puzzle image on canvas (54.43MB) +0

    img1.setImageBitmap(compositeImage1);

}

void iv_PuzzleOne()
{
    img1 = new ImageView(ourContext);
    SetPos(imgx1, imgy1, imagewidth1, imageheight1);
    //bkgdimg.setImageResource(R.drawable.c);
    //img1.setBackgroundColor(0xffF07305); //Orange
    img1.setLayoutParams(layoutPositioner);
    mainLayout.addView(img1);

}

void adjustImg()
{
    if (touching1Puzzle)
    {
        if (xpos[1] > xpos[0]) //if the image had slid to the right
        {
            xPositionDifference = xpos[1] - xpos[0]; // find the difference in coordinate value between where my finger was and where it currently is
            imgx1 += xPositionDifference; //add that difference to the current image position ...

            xpos[0] += xPositionDifference; // ... store that difference for the next shift in finger postion

        } else if (xpos[1] < xpos[0]) //if the image had slid to the left
        {
            xPositionDifference = xpos[0] - xpos[1]; // find the difference in coordinate value between where my finger was and where it currently is
            imgx1 -= xPositionDifference; //subtract that difference to the current image position ...

            xpos[0] -= xPositionDifference; // ... store that difference for the next shift in finger postion
        }

        if (ypos[1] > ypos[0]) //if the image had slid to the right
        {
            yPositionDifference = ypos[1] - ypos[0]; // find the difference in coordinate value between where my finger was and where it currently is
            imgy1 += yPositionDifference; //add that difference to the current image position ...

            ypos[0] += yPositionDifference; // ... store that difference for the next shift in finger postion

        } else if (ypos[1] < ypos[0]) //if the image had slid to the left
        {
            yPositionDifference = ypos[0] - ypos[1]; // find the difference in coordinate value between where my finger was and where it currently is
            imgy1 -= yPositionDifference; //subtract that difference to the current image position ...

            ypos[0] -= yPositionDifference; // ... store that difference for the next shift in finger postion

        }
    }

}

class ThisClass extends TimerTask {

    @Override
    public void run() {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if(touching1Puzzle)
                {SetPos(imgx1, imgy1, imagewidth1, imageheight1);
                    img1.setLayoutParams(layoutPositioner);}

            }
        });
    }
}

public void SetPos(float x, float y, float width, float height) {
    layoutPositioner = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutPositioner.topMargin = (int) (offsetY * y);
    layoutPositioner.leftMargin = (int) (offsetX * x);
    layoutPositioner.width = (int) (width * offsetX);
    layoutPositioner.height = (int) (height * offsetY);
}

}
This is what it looks like when I load 5 images
http://s15.postimg.org/ymqspk77v/Screenshot_2016_02_29_07_19_26.png

A: Alright let's see.
First of all you don't need puzzle pieces to be this big, so you can scale them down:
From  http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object. For example, an image with resolution 2048x1536 that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888)

Secondly you should try loading Bitmaps in an AsyncTask to prevent the application from freezing.
Thirdly you can cache your Bitmaps using LruCache to speed things up
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
private LruCache<String, Bitmap> mMemoryCache;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }
    };
    ...
}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

That should be enough but in case it isn't here are all sources and then some extra:
http://developer.android.com/training/displaying-bitmaps/index.html
You can also try using
void bm_PuzzleOne()
{
    //start of 1st puzzle
    BitmapFactory.Options opt = new BitmapFactory.Options();

    //makes a loaded image mutable
    opt.inMutable=true;
    //reduces density to that of screen
    opt.inTargetDensity = this.context.getResources().getDisplayMetrics().densityDpi;
    opt.inScaled=true;

    //makes bitmap half as big
    opt.inSampleSize=2;

    //foregdimg1 = BitmapFactory.decodeResource(getResources(), R.drawable.puzzlepieceprac);//puzzle cut out (42.48MB) +6.15
    mutableforegdimg1 = BitmapFactory.decodeResource(getResources(), R.drawable.puzzlepieceprac,opt)

    compositeImage1 = Bitmap.createBitmap(mutableforegdimg1);//cuts out foreground info into bkgdimage (54.43MB) +6.11

    imgCanvas1 = new Canvas(compositeImage1); //canvas references puzzle cut out image (54.43MB) +0
    imgCanvas1.drawBitmap(croppedBmp, null, new Rect(0, 0, 1500, 2000), paintObject);//places puzzle image on canvas (54.43MB) +0

    img1.setImageBitmap(compositeImage1);

}

instead of
void bm_PuzzleOne()
{
    //start of 1st puzzle

    foregdimg1 = BitmapFactory.decodeResource(getResources(), R.drawable.puzzlepieceprac);//puzzle cut out (42.48MB) +6.15
    mutableforegdimg1 = foregdimg1.copy(Bitmap.Config.ARGB_8888, true); //(48.32MB) +5.84

    compositeImage1 = Bitmap.createBitmap(mutableforegdimg1);//cuts out foreground info into bkgdimage (54.43MB) +6.11

    imgCanvas1 = new Canvas(compositeImage1); //canvas references puzzle cut out image (54.43MB) +0
    imgCanvas1.drawBitmap(croppedBmp, null, new Rect(0, 0, 1500, 2000), paintObject);//places puzzle image on canvas (54.43MB) +0

    img1.setImageBitmap(compositeImage1);

}

A: I suggest using an image loading library such as Glide or Picasso, which handles all the heavy lifting for you.
https://github.com/bumptech/glide
http://square.github.io/picasso/

A: Simply just use vectors instead of images.. you will save much memory for running app and storage. Its supported very well. and you can use SVG resources

A: First of all I should thank @JeD for his great answer, BUT I should mention that I think the answer is different.
Lets begin from the basics...

Each android device has an specific "heap size". it begin from 16mg to 64mg and even 128mg in some devices! (im not sure about 128 mg :D)
So whenever you use a drawable in your view, it takes a specific amount of ram.

Question: How is it calculated?!

Its by the drawables dimension, not the size. For example we have two drawables with 500 KBs of size.
One of them has the dimensions 500*500, the other has 700*700
The second one takes more heap although both sizes were the same!
The formula is this: WIDTH*HEIGHT*4 BYTE (4 comes from ARGB, it takes four bytes for each pixel to store data)
By now, you should understand that you cant use MANY images together! If you want to use LRUCACH as @JeD mentioned, you would lose some of your images as your heap would get full.

Question : So what should we do?!

The answer is using third party engines and canvas!
Game engines like COCOS2D,BOX2D,etc... are also good examples
or also using NDK which makes your app HEAP FREE!!! :D

A: Button b[]=new Button[9];
ArrayList list=new ArrayList();
int random;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_three);

    final MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.b2);

   for(int i=0;i<b.length;i++)
   {

       int id=getResources().getIdentifier("b"+i,"id",getPackageName());
       b[i]=findViewById(id);
       b[i].setOnClickListener(this);

   }

   for(int i=0;i<b.length;i++)
   {
       while(true) {

           random = new Random().nextInt(9);
           Log.d("First=", "" + random);

           if (!list.contains(random)) {

               list.add(random);
               Log.d("List=", "" + list.get(i).toString());

               break;

           }
       }
   }

   for(int i=0;i<b.length;i++)
   {

       if(!list.get(i).toString().equals("0"))
       {

           b[i].setText(list.get(i).toString());

       }
       else
       {

           b[i].setText("");

       }

   }

}

public void back(View view) {

    final MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.b2);
    mediaPlayer.start();
    Intent intent = new Intent(three.this,newgame.class);
    startActivity(intent);
    finish();

}

@Override
public void onClick(View v) {

    for(int i=0;i<b.length;i++)
    {

        if(v.getId()==b[i].getId())
        {
            final MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.b2);
            mediaPlayer.start();

        }

    }

    if(v.getId()==b[0].getId())
    {
        if (b[1].getText().toString().equals("")) {
            b[1].setText("" + b[0].getText().toString());
            b[0].setText("");
        }

        if (b[3].getText().toString().equals("")) {
            b[3].setText("" + b[0].getText().toString());
            b[0].setText("");
        }
    }

    if(v.getId()==b[1].getId())
    {
        if(b[0].getText().toString().equals(""))
        {
            b[0].setText(""+b[1].getText().toString());
            b[1].setText("");
        }

        if(b[2].getText().toString().equals(""))
        {
            b[2].setText(""+b[1].getText().toString());
            b[1].setText("");
        }

        if(b[4].getText().toString().equals(""))
        {
            b[4].setText(""+b[1].getText().toString());
            b[1].setText("");
        }

    }

    if(v.getId()==b[2].getId())
    {

        if (b[1].getText().toString().equals(""))
        {

            b[1].setText("" + b[2].getText().toString());
            b[2].setText("");

        }

        if (b[5].getText().toString().equals(""))
        {

            b[5].setText("" + b[2].getText().toString());
            b[2].setText("");

        }
    }

    if(v.getId()==b[3].getId())
    {
        if(b[0].getText().toString().equals(""))
        {
            b[0].setText(""+b[3].getText().toString());
            b[3].setText("");
        }

        if(b[4].getText().toString().equals(""))
        {
            b[4].setText(""+b[3].getText().toString());
            b[3].setText("");
        }

        if(b[6].getText().toString().equals(""))
        {
            b[6].setText(""+b[3].getText().toString());
            b[3].setText("");
        }

    }

    if(v.getId()==b[4].getId())
    {
        if(b[1].getText().toString().equals(""))
        {
            b[1].setText(""+b[4].getText().toString());
            b[4].setText("");
        }

        if(b[3].getText().toString().equals(""))
        {
            b[3].setText(""+b[4].getText().toString());
            b[4].setText("");
        }

        if(b[5].getText().toString().equals(""))
        {
            b[5].setText(""+b[4].getText().toString());
            b[4].setText("");
        }

        if(b[7].getText().toString().equals(""))
        {
            b[7].setText(""+b[4].getText().toString());
            b[4].setText("");
        }

    }

    if(v.getId()==b[5].getId())
    {
        if(b[2].getText().toString().equals(""))
        {
            b[2].setText(""+b[5].getText().toString());
            b[5].setText("");
        }

        if(b[4].getText().toString().equals(""))
        {
            b[4].setText(""+b[5].getText().toString());
            b[5].setText("");
        }

        if(b[8].getText().toString().equals(""))
        {
            b[8].setText(""+b[5].getText().toString());
            b[5].setText("");
        }

    }

    if(v.getId()==b[6].getId())
    {
        if (b[7].getText().toString().equals(""))
        {

            b[7].setText("" + b[6].getText().toString());
            b[6].setText("");

        }

        if (b[3].getText().toString().equals(""))
        {

            b[3].setText("" + b[6].getText().toString());
            b[6].setText("");

        }

    }

    if(v.getId()==b[7].getId())
    {
        if(b[4].getText().toString().equals(""))
        {
            b[4].setText(""+b[7].getText().toString());
            b[7].setText("");
        }

        if(b[6].getText().toString().equals(""))
        {
            b[6].setText(""+b[7].getText().toString());
            b[7].setText("");
        }

        if(b[8].getText().toString().equals(""))
        {
            b[8].setText(""+b[7].getText().toString());
            b[7].setText("");
        }

    }

    if(v.getId()==b[8].getId())
    {
        if (b[7].getText().toString().equals(""))
        {

            b[7].setText("" + b[8].getText().toString());
            b[8].setText("");

        }

        if (b[5].getText().toString().equals(""))
        {

            b[5].setText("" + b[8].getText().toString());
            b[8].setText("");

        }

    }

}

public void reset(View view) {

    final MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.b2);
    mediaPlayer.start();

    Intent intent = new Intent(three.this,three.class);
    startActivity(intent);
    finish();

}

}


text:
Q: How to find the start positions of a substring in a text string in python? The question provides a big string and a substring. And what I have to do is to write a code that can look for the substring from the big string, and output the .start() positions of the substrings found.
For example:
Sample Dataset
GATATATGCATATACTT
ATAT
Sample Output
2 4 10
So I have written a code (shown below), however, I noticed that the code would skip position 4 in the sample data set because half of position 4 is in 2?
Please show me how I can solve this problem. Thanks sooooo much in advance!!!
import re
filename = open(input())
txt=filename.readline()
rlist=[]
text= "ATAT"
for m in re.finditer (text, txt):
    d = m.start()
    d += 1
    rlist.append(d)
print (rlist)

A: length=len(text)
rlist=[]
for i in range(len(txt)):
    if length+i < len(txt):
        if txt[i:i+length] == text:
            rlist.append(i+1)
print (rlist)

try this!
here 1st if condition is used to check array index out of bound exception

A: This will work without using re. Note that I commented out your file import portion so that you can test just the snippet where the text is found.
#filename = open(input())
#txt=filename.readline()
txt='GATATATGCATATACTTATAT'
rlist=[]
text= "ATAT"
index=0
rlist=[]
while index < len(txt):   #loop through the text advancing one character at a time
        index = txt.find(text, index)
        if index == -1:
            break
        rlist.append(index+1)
        index += 1 # increment the index

print(rlist)
Out: [2, 4, 10, 18]

I based this answer on this. What is cool about this solution is that the loop need only run n+1 times, where n is the number of substrings in the text.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Ruby, is scan() the only function that can return multiple results of regular expression matching? Just to know more methods that can accomplish the same thing.

A: split( regex ) returns an array, leaving out all matches. Sometimes it's easier to specify what you don't want to see.

A: There are only two methods in the standard library which match a regular expression multiple times: gsub (and gsub!, of course) and scan. gsub returns a single string, so, yes, scan is the only one the returns multiple results.


text:
Q: Unity networking without a player prefab (C#) I would like to add multiplayer to my game. I use UMA (https://www.assetstore.unity3d.com/en/#!/content/13930) to generate a character in a character creation scene. I then use:
DontDestroyOnLoad(characterController);

To take the player to my main game scene. The UMA generated player cannot be made a prefab, cannot be duplicated or instantiated (not sure why but it doesn't work). So I then via script move the player to the spawn position where they can play the game.
I have made multiplayer games before, but in all of them I use
Network.Instantiate(playerPrefab);

to add the player to the game. The problem here is that I have no idea (nor could I find out online) how to implement multiplayer with a character ALREADY in the scene.
Any help, ideas, advice or suggestions would help me out a lot!

A: You can instantiate only the GameObject that has the scripts to control the player and search for the models generated by UMA which are already in the scene.
By the way, if you're using Unity 5.1 or newer Network.Instantiate is not used anymore. http://docs.unity3d.com/Manual/net-NetworkInstantiate.html


text:
Q: getWidth not returning different value after scaling I'm trying to find what I'm missing when using setScaleX.
    final ImageView iv = (ImageView) findViewById(R.id.imageView);
    ViewTreeObserver vto = iv.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // Start at 60
            Log.d("test", "Before"+String.valueOf(iv.getWidth()));
            iv.setScaleX((float) .5);
            // Still at 60 after scale
            Log.d("test", "After"+String.valueOf(iv.getWidth()));
        }

    });

I would of thought the width would have become 30. How do I get the value of the width after scaling?

A: you can solve it by multiply  by scale x or y
 final ImageView iv = (ImageView) findViewById(R.id.imageView);
    ViewTreeObserver vto = iv.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // Start at 60
            Log.d("test", "Before"+String.valueOf(iv.getWidth()* iv.getScaleX()));
            iv.setScaleX((float) .5);
            // Still at 60 after scale
            Log.d("test", "After"+String.valueOf(iv.getWidth()* iv.getScaleX()));
        }

    });

A: getWidth() returns the width before transforms are applied  to the view (setScaleX, etc...). So this is expected. This is hinted by the documentation of getDrawingRect:
 These bounds do not account for any transformation properties currently set on the view,
 such as setScaleX(float) or setRotation(float).


text:
Q: openboot no signal at the end of boot While performing an opensolaris 8 boot on sparc machine I can see all the messages from the kernel and the openboot, but once the boot is finished the monitor does not display the x login manager and a "no signal" message appears.
I suspect this is a problem with the x server configuration. How can I start it over with a default resolution or get the login manager prompt?

A: Assuming you mean Solaris 8 (there was never an "OpenSolaris 8"), the fbconfig command can be used to adjust the resolution used by most SPARC frame buffers.   To run that, you may need to use boot -s to force going into single user mode to avoid starting the dtlogin manager that in turn starts up X.


text:
Q: python: how to stop For loop at certain list index when push button is pressed I am trying to make a simple game. I have 5 leds connected to each GPIO pin and one push button to another GPIO pin. When the game start, the led will go on/off subsequently that gives perception of running. When the button is pushed I want that only one led is on. The script that I wrote below did that, but the problem is, it is only the led connected to the first GPIO listed in the list (index 0) that on.
I want to know if there is way to break the FOR LOOPS at any list index. With the script below, the break only happens when FOR LOOPS has looped through the index in the list.
Here is my script:
    import RPi.GPIO as GPIO
    import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

Switch=21
GPIO.setup(Switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)

LedList=[5,6,26,13,19]
for i in LedList:
    GPIO.setup(i, GPIO.OUT)

#test
GPIO.output(LedList, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(LedList, GPIO.LOW)

def runlight():
    for i in LedList:
        print "L.e.d ",i
        GPIO.output(i, GPIO.HIGH)
        time.sleep(0.2)
        if input_state==True:
            GPIO.output(i, GPIO.LOW)
            time.sleep(0.1)

        elif input_state==False:
            print "button pressed at ",i
            GPIO.output(i, GPIO.HIGH)
            break
try:
    while True:
        input_state=GPIO.input(Switch)
        runlight()

except KeyboardInterrupt:
    pass
GPIO.cleanup()

I am new in python, thanks for your help.


text:
Q: How to check if drop-down is selected in JavaScript I have a validator function looping through to check and see if all inputs have been filled out, but I also need to check if the dropdown's have been selected as well. I would like to write that into the same function.
    function validateSave (){
        // reset status
       var good = true
       $('.errormessage-left').removeClass('active-left')
       $('input').removeClass("warning")
       $('input').each(function(){
           if ($(this).val() == "") {
           console.log("found an empty");
           good = false
           $(this).addClass("warning")
           $('.errormessage-left').addClass('active-left'),
           $('.modal').addClass('modal-active');
        }
    })
    console.log(good)
    return good
    }

What's the best way to go about this?

A: You can use val() on a dropdown (<select> element) just like an input element, so just include it in your selector
$('input, select').each(function(){

A: You can do this :
Assuming the first element is :"please choose..."
if ($(".myDDL").get(0).selectedIndex>0)...
or
if ($(".myDDL").prop('selectedIndex')>0)...

A: you should be able to add this to your loop:
if ($(this).prop('type')=='select-one'){
   if ($(this).prop('selectedIndex')==0){
      console.log("found an empty");
      good = false
      $(this).addClass("warning")
      $('.errormessage-left').addClass('active-left'),
      $('.modal').addClass('modal-active');
   }
}

A: Try this:
$('input').each(function(){
           if($(this).prop('selected') == true){
              // selected item
           }
});

A: Assuming your HTML looks something like this:
<input type="text" name="whatever">
<select>
    <option value="">Choose One...</option>
    <option value="choice1">Choice 1</option>
    <option value="choice2">Choice 2</option>
    <option value="choice3">Choice 3</option>
</select>

Then your jQuery can figure it out like this
$('input, select').each(function(){
    if($(this).val() == ''){
        alert('Cannot be blank!');
    }
    else{
       //proceed
    }
}


text:
Q: Not Receiving data from Device if Socket is not closed I am sending data from a device every min through TCP/IP socket.
I am 1. Opening client socket. 2. Sending Packet. 3. Closing Socket.
I am closing socket for every packet. If I didnt close the client socket I was unable to receive data.
Any suggestions

A: When you close a socket, you also flush it's buffered data.  If you have buffered data you should expect to not see all (possibly any) data if you don't flush() or close() the stream.
In your case, I suspect you just need to flush() the output.


text:
Q: Reputation gain greater than actual rep How can I have reputation change greater than my reputation?
What is the "change" field even for?

A: The "+3579" in your screenshot is the change in rank, not the change in reputation. Therefore, prior to the last "tick" of the list (I think in that case it's weekly), your rank was around 4.5k - you have moved up 3579 ranks to the new rank of 1080.
The reputation change is only shown with the "week reputation" column and the such.


text:
Q: How to check the Google Play store app version I am trying out the In-App Billing V3 from Google play. In the document below mentioned guidelines were given. I am not sure how to use the method isBillingSupported. Could you point me to any sample code.

A: You can check the version of the GooglePlayStore app in your device like this:
PackageManager mPm = getPackageManager();
try{
    PackageInfo info = mPm.getPackageInfo("com.android.vending", PackageManager.GET_META_DATA);
    int versionCode = info.versionCode;
    String versionName = info.versionName;
}
catch( PackageManager.NameNotFoundException e) {
    // Play Store not installed
}

I don't know how to send the isBillingSupported request, but I found this example on GitHub. I think it is what you are looking for.


text:
Q: Use splint to detect always false if logic flow Can a flag can be set with splint to detect this logic fault?
if((a > 0) && (a == 0)){...}

The 2nd variable a is a typo. It's supposed to be b.
I've tried +ifempty and +ifblock and it turns out that they are for something else. Any suggestions? Or is it beyond splint?

A: PVS-Studio can find such an error using the V560 diagnostic. Example: https://godbolt.org/z/JA-Kmm


text:
Q: Specifying solution build order in the MonoDevelop I have a C# solution being developed with MonoDevelop, there are a number of projects.
When the solution is being built, I need to make sure some project A is built after some other project B in the same solution.
I can add reference to project B into project A, that's called Project-To-Project reference. This approach does not fit my requirements as B's output gets copied into A's target folder. So, I can not use P2P reference.
According to this, http://monodevelop.com/Documentation/Solutions_and_Projects_explained, solution file (*.sln) supports "specifying build order".
Can anyone provide me with any info on how I can specify projects build order on the solution level, without using P2P references?
TIA


text:
Q: How do I build an OpenMDAO group that uses MuxComp to combine individual variables into an array? I'd like to create an OpenMDAO om.Group that rearranges a some scalar variables into arrays. I'd like it to have a certain set of named inputs and outputs, like
class IonMixMux(om.Group):
    r"""Multiplex ion data into arrays

    Inputs
    ------
    nA : float
        m**-3, Species A density
    nB : float
        m**-3, Species B density
    nC : float
        m**-3, Species C density
    AC : float
        kg, Mass of species C

    Outputs
    -------
    n : array
        m**-3, Species densities
    A : array
        kg, Species masses
    """

The output n should equal [nA, nB, nC], and the output A should equal [1, 2, AC], since species A and B always have masses 1 and 2, respectively.
As I understand it, joining values together into an array can (only?) be done using MuxComp. However, I'm not sure how to build a Group that does this. Normally I make a Group of ExplicitComponents that have their own inputs and outputs, which then may be promoted so that it looks like the Group itself has these inputs or outputs.
I'm not sure how to make the promotion of named inputs without having a subcomponent to the group, and also not sure how to set individual indices of an OpenMDAO array.
Is this in fact not a job for MuxComp at all? Can I instead simply build an ExplicitComponent that build arrays 'from scratch'?

A: This is currently not within the capability of MuxComp, which assumes that an array output n has some number of inputs named n_0, n_1, n_2, ...
We could consider adding this capability to the API if it's a very common use-case, but it's pretty easy to build an ExplicitComponent for this case and build the output arrays in compute.  The partials in this case are all linear and so can be specified in setup with declare_partials:
self.declare_partials(of='A', wrt='AC', rows=[0], cols=[2], val=1.0)

self.declare_partials(of='n', wrt='nA', rows=[0], cols=[0], val=1.0)
self.declare_partials(of='n', wrt='nB', rows=[1], cols=[0], val=1.0)
self.declare_partials(of='n', wrt='nC', rows=[2], cols=[0], val=1.0)


text:
Q: Cannot edit calendar events for invitations received by mail (Nextcloud, via Thunderbird/CalDAV) When I create events myself, everything works smoothly and I can easily edit them at any time.
However, I cannot edit events events if the event was placed into the calendar by accepting an email invitation (in contrast to self-created events).
I updated the troubleshooting section based on further testing in the meantime, esp. regarding relevance of primary location of event in local vs. CalDAV calendar. Update 2: added Android experience.
It seems there are actually two separate problems, one in TB and one in NC:

*

*genuine within Thunderbird mail and calendar, since the problem occurs also without any Nextcloud component involved

*within Nextcloud, since invitation-based events cannot be shown and edited even on the NC web surface (indefinetly spinning wheel shown instead of event [rightmost Fig], but I cannot differentiate if this is an additional genuine Nextcloud problem, or if NC just fails to report an error secondary of the way Thunderbird writes the data to the calendar.

*Android: of note, I can easily edit the events I could neither modify in TB nor in NC!

Setup:

*

*Win-10

*Thunderbird 91.9.0 (32 bit)

*Nextcloud CalDAV calendars (that work nicely otherwise), hosted by an academic institution (usually very helpful, thanks!) and not under my administrative control.

*Android 12, Samsung One UI 4.1, Stock Samsung mail app

I tried to

*

*Right mouse click -> "edit" is grayed out [left Fig.]. Likewise, double-click - open - Window is lacking the expected "edit" button.

*change accept status (i.e. to rejected) since TB may protect me from changing accepted events without notice to the organizer -> cannot edit even after rejection or tentative.

*change event to task and back to event (now duplicated event) -> now I can edit the duplicated event, but I loose information, e.g. for an event series, as this keeps only a single one event.

*The problem is (in contrast what I previously thought) independent of where I save the event when accepting it (primarily local or CalDAV). But there is a difference for a potential workaround (case (a) and (b), cannot use a second level of indentation here):

*(a) If placed into WebCAL, I can copy-paste the event from CalDAV    calendar to local calendar -> possible to edit, but it    looses information: e.g. the start date is changed to the one occurrence I grapped for copy-paste, and the end date is set in the    original event to a specific date in 2023, but after copy-paste to   local calendar, the end date is set to "no end date").

*(b) In contrast, when I safe it directly to a local calendar, I can neither edit it in the local calendar nor after copy-pasting to a CalDAV calendar.

*All calendars are writable, there is no lack of disk space, and I can edit other self-created events in the same calendars.
When I go to my Nextcloud calendar web surface, I can edit self-created events by mouseclick [middle Fig.], but I cannot even display (or edit) accepted events, I see only a spinning wheel indicating "work in progress", but it never finishes [right Fig.] (tested on current Firefox and Chrome browser, on two different Win-10 computers so far). Therefore, I cannot exclude the problem is on the Nextcloud/CalDAV side, although this is not exactly the same as in TB (TB: can display everything but not edit; NC web: cannot even display the (existing and synchronizing) event).
I have found some more or less similar problems in other questions, but no applicable solution so far (e.g. the problem was a non-writable calendar etc., that does not seem to be my problem).
I appreciate that Android/Samsung mail app can do what neither TB nor NC accomplish, constituting a seemingly flawless "emergency workaround", but still painful to use your mobile to edit what the ergonomic desktop keyboard and screens cannot...
I am grateful for solutions:

*

*problem is primary Nextcloud vs primary Thunderbird mail/calendar interaction? Do you experience the same problem on Nextcloud web (known bug irrespective of server installation, or probably locally specific to our instance), and or on TB?

*Workaround without the risk of loosing information, esp. on events with lots of adjacent information or event series

*at best, of course, a real solution to stop this problem


text:
Q: why the page is not refreshed after redirection to 'RedirectToRouteResult'? My filter is as follows
public class SessionExpireAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        string userExpire = string.Empty;
        userExpire = new UserControllerHelper().FetchDataFromCookie(CookieField.UserRoleId.ToString());
        if (userExpire == "")
        {
            filterContext.HttpContext.Response.Clear();
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "Area", "" } });
        }
        base.OnActionExecuting(filterContext);
    }
}

This is getting redirected but the page is not refreshed. The expired url is still in the address bar.
I tried using the following code :
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl);

But that's not at all redirected.
Thanks in advance

A: try like this:
   filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(
                new { area = "", controller = "Error", action = "Index", id = UrlParameter.Optional, message = "CodeError", ErrorMessage = filterContext.Exception.GetBaseException().Message }));


text:
Q: Material Autocomplete in FormGroup - typescript In my project, I want to use Material Autocomplete for country. Country get all from my ws. I was able to show all states, but what I want is to select the state to send ws. So, I want to put it in the formgroup.
component.html
<form [formGroup]="registerUserForm" (ngSubmit)="onRegisterUser()" class="col s12" materialize>

      <input formControlName="username" id="username" type="text" class="validate" placeholder="Enter Username" minlength="3" maxlength="20"
        required="" [ngClass]="{invalid: invalidInputs}">

      <input formControlName="email" id="email" type="email" class="validate" placeholder="Enter Email" required="" aria-required="true"
        [ngClass]="{invalid: invalidInputs}">

  <input formControlName="country_id" id="country_id" matInput placeholder="Select Country" aria-label="State" [matAutocomplete]="auto"
    autoActiveFirstOption [formControl]="myControlCountry">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let country of filteredOptionsCountry | async" [value]="country.name">
      {{ country.name }}
    </mat-option>
  </mat-autocomplete>

    <button id="register_user_button" type="submit" class="btn waves-effect waves-light">
      Register
    </button>
    <button id="cancel_button" (click)="onCancel()" class="btn waves-effect waves-light grey lighten-4 black-text">
      Cancel
    </button>

</form>

component.ts
export class AddUserFormComponent implements OnInit {
     countryes: Country[];
  registerUserForm: FormGroup;

  filteredOptionsCountry: Observable<Country[]>;
  myControlCountry: FormControl = new FormControl();

  constructor(private fb: FormBuilder,
    private router: Router,

    private cs: CountryService)
{

    this.registerUserForm = new FormGroup({
      'username': new FormControl(),
      'email': new FormControl(),
      'country_id': new FormControl(),
    });

  }

  ngOnInit() {

    this.registerUserForm = this.fb.group({
      'username': ['', Validators.compose([Validators.required, Validators.minLength(5)])],
      'country_id': ['', Validators.required],
      'email': ['', [Validators.required, ValidationService.emailValidation]],
    });

    this.filteredOptionsCountry = this.myControlCountry.valueChanges.pipe(
      startWith(''),
      map(val => this.filterCountry(val))
    );

    this.cs.getAllCountry().subscribe(
      countryes => {
        this.countryes = countryes.map((country) => {
          return new Country(country);
        });
      }
    );

  }

  onRegisterUser() {
    this.loading = true;
    this.invalidInputs = true;

    let newUser = new User(
      this.registerUserForm.value
    );

    this.userService.createUser(newUser).subscribe(
    );
  }

  onCancel() {
    this.router.navigate(['/main/users']);
  }

  //Country

  filterCountry(val: string): Country[] {
    if (val) {
      let filterValue = val.toLowerCase();
      console.log(this.countryes)
      return this.countryes.filter(country => country.name.toLowerCase().startsWith(filterValue));
    }

    return this.countryes;
  }

}

In html code I use also formControlName="country_id" id="country_id"  but don't work nothing.  More over, I use and ReactiveFormsModule. Can you suggest me any solution? Thank you!

A: We can use "controls" to get the value of formControName from the form group
Solutions:
HTML code:
<form [formGroup]="SearchForm">
<mat-form-field fxFlex="14" appearance="outline">
    <mat-label>Number</mat-label>
    <input type="text"
           aria-label="Number"
           matInput
           formControlName="numberName"
           [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

ts code:
SearchForm = new FormGroup
({
numberName: new FormControl(''),
numers: new FormControl('')
});
Options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;

constructor(){}
ngOnInit(){
this.onValueChanged();
}

public onValueChanged(){
this.filteredOptions = this.SearchForm.controls.numberName.valueChanges.pipe(
startWith(''),
map((value:any) => this._filter(value)));
}

private _filter(value: string): string[]{
const filterValue = value.toLowerCase();
return this.Options.filter(option => option.toLowerCase().includes(filterValue));
}

A: Solution:
Html code:

      <input formControlName="country_id" id="country_id" matInput placeholder="Select Country*" aria-label="State" [matAutocomplete]="auto"
        autoActiveFirstOption [formControl]="country_id">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayWith">
        <mat-option (onSelectionChange)="updateForm($event, country.country_id, 'country_id')" *ngFor="let country of filteredOptionsCountry | async"
          [value]="country.name">
          {{ country.name }}
        </mat-option>
      </mat-autocomplete>

Ts code:
export class AddUserFormComponent implements OnInit {
  countryes: Country[];
  registerUserForm: FormGroup;
  areWeWaiting = false;
  countryid = 0;

  filteredOptionsCountry: any;
  country_id: FormControl = new FormControl();
  constructor(private fb: FormBuilder,
    private router: Router,
    private cs: CountryService,
 {
    this.registerUserForm = new FormGroup({
      'country_id': new FormControl(),
       });
  }

  ngOnInit() {

    this.filteredOptionsCountry = this.country_id.valueChanges.pipe(
      startWith(''),
      map(val => this.filterCountry(val))
    );

    );

    this.cs.getAllCountry().subscribe(
      countryes => {
        this.countryes = countryes.map((country) => {
          return new Country(country);
        });
      }
    );
  }

  onRegisterUser() {
    this.areWeWaiting = true;
    let newUser = this.registerUserForm.value
    newUser.country_id = this.countryid;
    let user = new User(newUser);
    this.userService.createUser(user).subscribe(
      result => {
        if (result === true) {
          Materialize.toast('User saved successfully', 4000);
        } else {
          this.areWeWaiting = false;
        }
      },
      error => {
        this.areWeWaiting = false;
       }
      );
  }

  //Country

  filterCountry(val: string): Country[] {
    if (val) {
      let filterValue = val.toLowerCase();
      console.log(this.countryes)
      return this.countryes.filter(country => country.name.toLowerCase().startsWith(filterValue));
    }
    return this.countryes;
  }

  updateForm(ev: any, idd: any, componentid: any) {

    if (ev.isUserInput) {
      if (componentid === 'country_id') {
        this.countryid = idd;
        this.registerUserForm['controls']['country_id'].setValue(ev.source.value);
      }  else {
        console.log('ooops');
      }
    }
  }
  displayWith(value: any): string {
    return typeof value === 'string' ? value : (value == null ? '' : value.text);
  }
}


text:
Q: reading data from xml and storing it in variable ,when i am printing variable in console getting error like variable is unassigned in C# Here I am attaching code which I am using
 {
  //reading data from file
  XmlTextReader reader = new XmlTextReader(FileLocation);
  string s1;
  while (reader.Read())
    {
      //checking whether node name is Esig ang storing Esig value
      if (xtr.NodeType==XmlNodeType.Element&&xtr.Name=="Esig")
       {
         s1=xtr.ReadElementString();
        }
     }

   Console.WriteLine(s1);
  }

A: Local variables aren't initialized. You have to manually initialize them.
Members are initialized, for example:
public class X
{
    private string _userName; // This WILL initialize to zero
    ...
}

But local variables are not:
public static void SomeMethod()
{
    string userName;  // This is not initialized and must be assigned before used.

    ...
}

Hence you need to initialize local variable first and then use it.
Your Code will be like
string s1 = string.Empty;

More details are here on Microsoft LINK


text:
Q: cURL Command in linux to return http response code Please i want to use the cURL command in linux OS to return as a result just the http response code which is "200" if it is okey
am using that command:
curl -I -L domain.com

but this is returning for me a full text like this
HTTP/1.1 **200** OK
Date: Thu, 27 Feb 2014 19:32:45 GMT
Server: Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 PHP/5.4.19
X-Powered-By: PHP/5.4.19
Set-Cookie: PHPSESSID=bb8aabf4a5419dbd20d56b285199f865; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding,User-Agent
Content-Type: text/html

so please i just need the response code and not the whole text
Regards

A: curl -s -o out.html -w '%{http_code}' http://www.example.com

A: Running the following will supress the output so you won't have any cleanup.
curl -s -o /dev/null -w '%{http_code}' 127.0.0.1:80

Example above uses localhost and port 80


text:
Q: Why is "messenger" the term instead of "messager"? Just wondering how we got from message to messenger instead of message to *messager?
When and why did this happen with this word? I'm not really interested in the rule so this isn't a duplicate, more interested in this word specifically.

A: Both messenger and passenger derive from Anglo-Norman French messager and passager. Those latter are also the standard modern French.
According to the OED etymology the 'intrusive n'before g is a late Middle English development in words such as messenger, passenger, harbinger, nightingale etc. See below:

The β forms show the common late Middle English development of an
  intrusive n before g (representing both /dʒ/ and /ɡ/ : see E. J.
  Dobson Eng. Pronunc. 1500–1700 (ed. 2, 1968) II. §438, and compare
  forms s.vv. passenger n., harbinger n., nightingale n.1), probably
  strongly reinforced by similar Anglo-Norman and Picard forms with -n-
  . Forms with ma- probably reflect Anglo-Norman massager (compare forms
  s.v. message n.); such forms continue to be found (chiefly in East
  Anglian texts) into the 16th cent.


text:
Q: 3 Table SQL JOIN with CASE I need the h.target_date to replace the d.deadline where h.flux_id is equal to the parameter :docId (a primary key of a table).
I have worked on the below query which doesn't do the job.
   $sqlsteptarget = "SELECT
                            h.target_date,
                            h.flux_id,
                            d.deadline,
                          CASE
                            WHEN h.target_date is null THEN h.target_date = d.deadline
                          END AS date_cible
                          FROM
                            public.flux_historique AS h
                          LEFT JOIN public.flux as f
                            INNER JOIN public.document as d
                            ON d.id = :docId
                          ON h.flux_id = f.id
                          WHERE
                             f.id_system_droit_id = d.id_system_droit_id
                          ";
        $stmtfh = $conn->prepare($sqlsteptarget);
        $stmtfh->execute(['docId' => $docId]);
        $data3 = $stmtfh->fetchAll();

Any help is appreciated.

A: Here is the code, when you are using CASE you can use operator (=) after WHEN only. You can't use it after the THEN.
   $sqlsteptarget = "SELECT
                            h.target_date,
                            h.flux_id,
                            d.deadline,
                          CASE
                            WHEN h.target_date is null THEN  d.deadline
                          END AS date_cible
                          FROM
                            public.flux_historique AS h
                          LEFT JOIN public.flux as f
                            INNER JOIN public.document as d
                            ON d.id = :docId
                          ON h.flux_id = f.id
                          WHERE
                             f.id_system_droit_id = d.id_system_droit_id
                          ";
        $stmtfh = $conn->prepare($sqlsteptarget);
        $stmtfh->execute(['docId' => $docId]);
        $data3 = $stmtfh->fetchAll();

A: Maybe something like this
SELECT
    h.target_date,
    h.flux_id,
    COALESCE(h.target_date,d.deadline) AS date_cible
  FROM
    public.flux_historique AS h
  LEFT JOIN public.flux as f
    INNER JOIN public.document as d
    ON d.id = :docId
  ON h.flux_id = f.id
  WHERE
     f.id_system_droit_id = d.id_system_droit_id

Of course, you can do that only if at least one of the both (target_date or deadline) is not null in all case

A: try this
 $sqlsteptarget = "SELECT   h.target_date, h.flux_id, d.deadline,
if(h.target_date is null,d.deadline,h.target_date)  AS date_cible
  FROM
  public.flux_historique AS h
  LEFT JOIN public.flux as f
  INNER JOIN public.document as d ON f.id_system_droit_id =
   d.id_system_droit_id
  AND h.flux_id = f.id
  WHERE d.id = :docId;                              ";
            $stmtfh = $conn->prepare($sqlsteptarget);
            $stmtfh->execute(['docId' => $docId]);
            $data3 = $stmtfh->fetchAll();


text:
Q: Display different aspx file in a popup in asp I am currently developing an ASP.net application. I am generating a table (standard HTML table not GridView) and populating it with data from a MySQL Database. One column of the table has hyperlinks which should link to a dynamic aspx web page that will display certain information based on the database.
When the user clicks on the hyperlink I want to display a pop up that hovers over the top of the original content, not opening a new browser window just displaying like a popup window which will darken the contents of the background content.
I have tried to google search this but did not find anything.
Thanks for any help you can provide.

A: Try: LightBox

A: The AjaxControlToolkit has a control for this. See http://www.asp.net/ajax

A: You can use the dialog control from the jquery UI library if you want to use jquery:
http://jqueryui.com/demos/dialog/


text:
Q: What's the old saying that means "the written word is more powerful than the spoken" I'm looking for that old saying that means "the written word is more powerful than the spoken"
It suggests that getting an idea on paper and publishing it can reach many more people (because of books, newspapers, magazines etc) than simply saying it one time

A: You have the Latin proverb:

Verba volant, scripta manent. Literally translated, it means "spoken words fly away, written words remain".

(Wikipedia)


text:
Q: Segfault when trying to access fields in an object in vector This seems like the most straightforward thing ever, yet it keeps segfaulting no matter what I try. Sorry if it is obvious and easy to search, I've been searching for about 2 hours on countless vector segfault threads, nobody seems to have this exact issue.
class A
{
protected:
    std::vector<B> myVector = std::vector<B>(1);
    void doStuff();
};

void A::doStuff()
{
    myVector.push_back(B());
    myVector[0].initiate();
}

class B
{
public:
    int a;
    B();
    void initiate();
};

B::B()
{
}

void B ::initiate()
{
    a = 0; //**this is where segfault happens**
}

Also, what if I were to put a vector in B as well? Does the vector of Bs have to completely re-allocate every time I make one of the components have a larger internal vector? Or will that segfault too? In either case, is there a way to allocate a fixed amount of memory per vector slot or something for objects that I expect to grow???
Edit:
"A".h
#ifndef PLATE_H
#define PLATE_H

#include "Column.h"
#include <vector>

class World;
class Plate
{
protected:
    World* myWorld;
    std::vector<Column> vColumns = std::vector<Column>(1);

"A".cpp:
void Plate::initiate(unsigned short xDim, unsigned short yDim, World * world)
{
    myWorld = world;
    dMass = 0;

    for (int x = 0; x < xDim; x++) {
        for (int y = 0; y < yDim; y++) {
            vColumns.push_back(Column());
            std::cout << vColumns.size();
            vColumns[x + y*xDim].initiate(5,myWorld->cMantleDensity,myWorld); //%%%%%%% 5 is temporary
            dMass = dMass + vColumns[x + y*xDim].getDensity() * vColumns[x + y*xDim].getNumGoxels();
        }
    }
}

"B".h:
#ifndef COLUMN_H
#define COLUMN_H
#include <vector>
#include "Goxel.h"

class World;
class Column
{
protected:
    World* myWorld;
    std::vector<Goxel> vGoxels;
    unsigned char cCrumple;
    unsigned char cVolcanism;
    unsigned short sThickness;
    short sRootDepth;
    float fDensity;
public:
    Column();
    void initiate(unsigned short, unsigned char,World* const);

"B".cpp:
void Column::initiate(unsigned short thick, unsigned char mantleDensity,World* world)
{
    myWorld = world;
    cCrumple = 0;
    cVolcanism = 0;
    sThickness = thick;
    fDensity = 58; //basalt
    sRootDepth = (short)(-((sThickness * fDensity) / mantleDensity));

    for (int i = 0; i < thick; i++)
    {
        vGoxels.push_back(Goxel());
        vGoxels[i].quickInitiate((char)(((i-1)*58) / 20));
    }
}

A: Do this:
$ gdb a.out
> run
*segfault*
> where

The debugger will show you a nice stack trace of where the segfault actually is so that you don't have to guess.


text:
Q: SwiftUI Textfields and Ints I started today to use SwiftUI an I want to code a small calculator. Therefore I want a textfield where the user can write a number. But the usual textfields only accepts strings
what can I do ?

A: If you want to force the TextField keyboard to be numeric, just do this:
TextField("Input", text: $input)
    .keyboardType(.decimalPad)

where the keyboardType is a UIKeyboardType.

A: with SwiftUI 2.0 you could use something like this:
struct ContentView: View {
@State var theInt: Int?
@State var text = ""

var body: some View {
    VStack {
        TextField("enter a number", text: $text)
            .onChange(of: text) {
              let txt = $0.filter { "-0123456789".contains($0) }
              if allowed(txt) {
                 theInt = Int(txt)
                 text = txt
              } else {
                text = String(txt.dropLast())
              }
            }
    }
}

func allowed(_ str: String) -> Bool {
    let num = str.starts(with: "-") ? String(str.dropFirst()) : str
    return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: num))
}
}


text:
Q: When I am adding content type to Task List , not able to see all content type group When I am trying to add content type to Task List. It is not showing all groups.
I am able to see folder content type group in sharpoint 2010.


text:
Q: BOINC: Run several tasks in each time, ubuntu/debian I've setted a BOINC on my Ubuntu 12.04 Server, but it runs only 1 task at the same time.
How to set limit of tasks, running in each time?
Thanks

A: As stated by zero323, each tasks runs in one CPU. The default available CPU number is 1, so you will have to change this in BOINC preferences.
Go to  BOINC manager > Tools > Computing preferences > Processor usage
Find On multiprocessor systems, use at most and replace the value to your desirable percentage of processors (If you want them all, use 100%. If you have a quad-core machine, you will have 4 tasks running at a time)
I also recommend you to take a look at Use at most option, since each CPU will have this percentage of usage. Keep an eye on your CPUs core temperature using the command sensors


text:
Q: How to do a "select customer.name, count(order._id) ..." from joined tables in greenDAO I would like to do a query such as the following:
    select customers.name, count(orders._id)
    from customers, orders
    where customers._id = orders.customer_id

So that I can get the customer name and how many orders they have.
Can this be done with a greenDAO querybuilder (preferred) or will I have to do it with a standard database query?

A: This is not possible with greenDAO, since their model encourages object-related queries: "greendao is an ORM-framework. This means it maps your table-rows to object." -- Select multiple columns from two tables using greendao


text:
Q: What is basic unit of ui of jetpack compose? Android xml basic unit of ui is View.
Flutter basic unit of ui is Widget.
Then, What is basic unit of Jetpack Compose?
I'm thinking about what to end compose ui function name with.
Like. SearchView, SearchWidget, SearchCompose, SearchUI, SearchComponent etc...
What do you all think?

A: It depends on what you're trying to accomplish. If you need a basic view to display background for instance, Surface will do the job. If you'd like an empty view to space your items – although padding would do the same – then you could use Spacer


text:
Q: Elegant way of duck-typing strings, symbols and arrays? This is for an already existing public API that I cannot break, but I do wish to extend.
Currently the method takes a string or a symbol or anything else that makes sense when passed as the first parameter to send
I'd like to add the ability to send a list of strings, symbols, et cetera.  I could just use is_a? Array, but there are other ways of sending lists, and that's not very ruby-ish.
I'll be calling map on the list, so the first inclination is to use respond_to? :map.  But a string also responds to :map, so that won't work.

A: How about treating them all as Arrays? The behavior you want for Strings is the same as for an Array containing only that String:
def foo(obj, arg)
  [*arg].each { |method| obj.send(method) }
end

The [*arg] trick works because the splat operator (*) turns a single element into itself or an Array into an inline list of its elements.
Later
This is basically just a syntactically sweetened version or Arnaud's answer, though there are subtle differences if you pass an Array containing other Arrays.
Later still
There's an additional difference having to do with foo's return value. If you call foo(bar, :baz), you might be surprised to get [baz] back. To solve this, you can add a Kestrel:
def foo(obj, arg)
  returning(arg) do |args|
    [*args].each { |method| obj.send(method) }
  end
end

which will always return arg as passed. Or you could do returning(obj) so you could chain calls to foo. It's up to you what sort of return-value behavior you want.

A: A critical detail that was overlooked in all of the answers: strings do not respond to :map, so the simplest answer is in the original question: just use respond_to? :map.

A: Since Array and String are both Enumerables, there's not an elegant way to say "a thing that's an Enumberable, but not a String," at least not in the way being discussed.
What I would do is duck-type for Enumerable (responds_to? :[]) and then use a case statement, like so:
def foo(obj, arg)
  if arg.respond_to?(:[])
    case arg
    when String then obj.send(arg)
    else arg.each { |method_name| obj.send(method_name) }
    end
  end
end

or even cleaner:
def foo(obj, arg)
  case arg
  when String then obj.send(arg)
  when Enumerable then arg.each { |method| obj.send(method) }
  else nil
  end
end

A: Perhaps the question wasn't clear enough, but a night's sleep showed me two clean ways to answer this question.
1:   to_sym is available on String and Symbol and should be available on anything that quacks like a string.
if arg.respond_to? :to_sym
    obj.send(arg, ...)
else
    # do array stuff
end

2:    send throws TypeError when passed an array.
begin
  obj.send(arg, ...)
rescue TypeError
  # do array stuff
end

I particularly like #2.  I severely doubt any of the users of the old API are expecting TypeError to be raised by this method...

A: Let's say your function is named func
I would make an array from the parameters with
def func(param)
  a = Array.new
  a << param
  a.flatten!
  func_array(a)
end

You end up with implementing your function func_array for arrays only
with func("hello world") you'll get a.flatten! => [ "hello world" ]
with func(["hello", "world"] ) you'll get a.flatten! => [ "hello",  "world" ]

A: Can you just switch behavior based on parameter.class.name? It's ugly, but if I understand correctly, you have a single method that you'll be passing multiple types to - you'll have to differentiate somehow.
Alternatively, just add a method that handles an array type parameter. It's slightly different behavior so an extra method might make sense.

A: Use Marshal to serialize your objects before sending these.

A: If you don't want to monkeypatch, just massage the list to an appropriate string before the send. If you don't mind monkeypatching or inheriting, but want to keep the same method signature:
class ToBePatched
    alias_method :__old_takes_a_string, :takes_a_string

    #since the old method wanted only a string, check for a string and call the old method
    # otherwise do your business with the map on things that respond to a map.
    def takes_a_string( string_or_mappable )
        return __old_takes_a_string( string_or_mappable ) if String === string_or_mappable
        raise ArgumentError unless string_or_mappable.responds_to?( :map )
        # do whatever you wish to do
    end
end

A: Between those 3 types I'd do this
is_array = var.respond_to?(:to_h)
is_string = var.respond_to?(:each_char)
is_symbol = var.respond_to?(:to_proc)

Should give a unique answer for [], :sym, 'str'


text:
Q: primefaces redirection and action at the same using DefaultMenuItem I woud like to use the redirection and action at the same using  DefaultMenuItem
My code is
MenuModel menuModel = new DefaultMenuModel();

DefaultSubMenu menu = new DefaultSubMenu("menu");

DefaultMenuItem item = new DefaultMenuItem("new Menu");

item.setCommand("redirection"); // redirection is configured in faces-config.xml

item.setCommand("#{myBean.init}");

menu.addElement(item)

menuModel.addElement(menu);

but it does not work
(it worked previsouly when there was no
 item.setCommand("#{myBean.init}");

)
Apparently, having two setCommand gives some problems
but I need the inialization when I click on the button.
Could you help me ?

A:  item.setCommand("#{myBean.init}");

In your manage bean myBean you can have init method like
public String init(){

   //do your business logic.

   return "idToBeNavigatedTo";

}

Above will process your business Logic and redirect to url which is mapped for the action id you return in faces-config.xml


text:
Q: WSS 3.0 Cannot create list instance I have created three features - fields, content types and lists. I deployed the solution and everything was fine. However, I deleted my list instance from the Lists section in my site. Now I cannot create it again. I tried to deploy the solution again but no instance was created. How can that be done?
<ListInstance Id="2" Title="My Content List" FeatureId="91F7775A-C3FF-11DF-939A-4D4CE0D72085" Description="This is my list instance." TemplateType="100" OnQuickLaunch="False" Url="Lists/MyContentt">

A: Try this:

*

*Deactivate the feature

*Retract and delete the solution

*Change the ListInstance Id to a GUID and repackage your solution

*Add and deploy the solution

*Reactivate the feature

Good luck!


text:
Q: Training process to fine-tune a LLM to answer questions regarding movies in dialogue I'm trying to fine-tune a GPT2 pre-trained model so that it can talk about movies in a dialogue manner (inspired by ChatGPT). And Im not quite sure on how to go about doing it.
This was my initial idea but I'm not entirely confident that it is the way to go:

*

*Freeze most of the initial attention blocks and fine-tune the rest on lots of movie plots and information (release year, cast, etc). In order to acquire knowledge;

*Freeze most of the initial attention blocks and fine-tune on a dataset of questions-answers regarding movies (using only the questions and answers, discarding the context since the knowledge should have been acquired in step 1). Using a prompt format that will simulate the conversations, for example: <|startofuserinput|> who dies at the end of the spider-man 3? <|endofuserinput|> \n####\n Harry, Peter's friend dies at the end of spider-man 3 to help Peter. <|endofresponse|>

*Use the resulting model to keep generating responses to the user, taking into account the most recent prompt as well as the conversation history.

Is there anything inherently wrong with this method, any obvious flaw? If so, how should I proceed to accomplish such a task?


text:
Q: SET ASP.NET MVC4 button value I'm a newbie.
My problem is that i have a button and i want to set the value by a ASP.NET variable.
<input type="button" id="mybt" value="<%=Student.Name %>" />
This code is not working.

The code:
<%var Products = (IEnumerable<Demo.Models.Product>)ViewBag.Products;%>

            ID
            Name
            Price

        <%foreach(var product in Products)
          {  %>

              <%=product.Id %>

              <%=product.Name%>

              <%=product.Price %>

              <input type="button"   value='<%=product.Id%>' />
            <%} %>

A: Instead of <%=Student.Name %> use this:  @Student.Name
Provided that "Student" is the model name and "Name" is the property you want.
The reason for this is because <%= %> works for aspx but not the razor view engine which is probably what you have chosen for your MVC solution.


text:
Q: Passing exception stack traces from C++ to Python (via Cython) Problem
I have a logging and infra system which I can't (and don't want to modify), in Python, that relies on the Tracebacks of the exceptions.
I have C++ code wrapped with Cython. This C++ code can potentially raise exceptions (std::runtime_errors). Cython gives the ability to translate exception (e.g. with except +). However, and that makes sense of course, the translation only translates the exception type and message.
In my case, I would want to translate the stack trace in the C++ exception (which I can recover to a string), into a Python's Traceback. Obviously, the translation is not fully meaningful, but it allows me to "cheat" and continue (or replace) the stack trace in Python with something that represents the stack trace in C++.
Assuming I can parse the C++ exception's stack trace into meaningful values, I wonder what's the best way to achieve that. I have one idea listed below, and I will be happy to get your opinions on it or share alternatives.
I'll add that this whole thing feels very flaky, but I'm both curious about it and want to avoid doing stuff like putting the C++ stack trace in the Python's exception message.
My Idea
So after looking a bit, I found that CPython has a method that is called _PyTraceback_Add. Specifically it's signature is void _PyTraceback_Add(const char *funcname, const char *filename, int lineno) and looks like it adds the values (funcname, filename and lineno) into the current trace. Link to implementation: https://github.com/python/cpython/blob/66f77caca39ba39ebe1e4a95dba6d19b20d51951/Python/traceback.c#L257
My thoughts were to use that right when I raise the Python exception in Cython. Then, I could use the exception string from C++ and insert the values into the existing trace.
However, this method seems to be private in CPython and I'm not sure it will be sound to rely on it in production code.
Are there any good alternatives to this solution?
Thanks!

A: Well the function seems to be using only public API's, so can just do the same steps instead.
With that said, it looks unlikely to change anytime soon.
Also, it seems somebody's already doing exactly what you're doing: see issue #24743.


text:
Q: pkgdown and R Markdown templates For a package containing multiple R Markdown templates, is it possible to include the rendered versions of these templates (skeleton.Rmd) as vignettes / articles in the package documentation website (set up using pkgdown). I'd like to get a a nice overview of all the templates which are available in the package.
I want to avoid creating new vignettes which copy/paste the code from the R Markdown templates to vignettes/articles. Ideally, I'd just like to link them to the templates (skeleton.Rmd in the inst/rmarkdown/templates directory).
Any suggestions on how I can achieve this?
Thanks!

Originally posted on 2020-08-19 on Posit Community but without response.


text:
Q: How to change User_Agent in PyQt4 QtWebkit Right now it looks like this:
Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.34 (KHTML, like Gecko) Qt/4.8.1 Safari/534.34

But I would like to change it to something like this:
Nokia5320XpressMusic/GoBrowser/1.6.0.70

A: The easiest way is to subclass QWebPage and override the userAgentForUrl - method, then you can tell the QWebView to use your implementation using setPage.


text:
Q: How to configure CXF in Spring Boot setting disableCNCheck to true in HttpConduit TLSClientParameters There is a Spring Boot application that use Camel cxf component declared in class annotaed with @Configuration and containing the next code:
@Bean
public CxfEndpoint cxfEndpoint() {
    CxfEndpoint cxfEndpoint = new CxfEndpoint();
    cxfEndpoint.setAddress(address);
    cxfEndpoint.setWsdlURL(wsdlLocal);
    cxfEndpoint.setDataFormat(DataFormat.PAYLOAD);
    cxfEndpoint.setUsername(username);
    cxfEndpoint.setPassword(password);
    return cxfEndpoint;
}

How can HttpConduit be overwritten to set disableCNCheck to true?
Y tried this one with no success:
@Bean
public HTTPConduit http(SpringBus bus) {

//        URL wsdl = getClass().getResource(wsdlLocal);
//        ServiceClass service = new     ServiceClass(wsdl);
//        Interface interface = service.getPort(Interface.class);

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(ServiceClass.class);
    factory.setAddress(address);
    factory.setBus(bus);
    Interface interface = factory.create(Interface.class);

    Client client = ClientProxy.getClient(interface);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    TLSClientParameters tls = new TLSClientParameters();
    tls.setDisableCNCheck(true);
    http.setTlsClientParameters(tls);
    return http;
}

This is the exception:
Caused by: java.io.IOException: The https URL hostname does not match the Common Name (CN) on the server certificate in the client's truststore.  Make sure server certificate is correct, or to disable this check (NOT recommended for production) set the CXF client TLS configuration property "disableCNCheck" to true.


text:
Q: Which AI algorithms can be used to play probabilistic games with possibly incomplete information? The minimax algorithm and Monte-Carlo tree search (MCTS) can be used to implement agents which play deterministic (i.e., non-probabilistic) games, like chess or tic-tac-toe, that have complete information of the game.
Are there general methods that work for games with incomplete information and/or games with a probabilistic component (e.g., poker or bridge)?

A: Yes.  You're asking several questions at once, though.
The simplest possibility is a game like backgammon, which includes probability, but full information.  The extension to minimax is straightforward, and called expectiminimax.
Incomplete information is usually called "partial observability," and exists in games like kriegspiel, which is a variant of chess where you cannot see the opponent's pieces.  Here, the extension to tree search is that your tree depends on sequences of percepts instead of individual board states.  As you might imagine, this blows up the tree very quickly.
Card games are usually both at the same time, and need both techniques.
Note that these simple extensions only just scratch the surface.  In the same way that chess and go require more than just simple search trees, partially observable random games require more than extensions.  When the actions have probabilistic results (i.e., chance of failure) then you're into deep academic research territory.


text:
Q: How to convert an IplImage to Mat? I am trying to understand how to make this conversion but I still have the same error. I need to convert IN JAVA an ipl image into mat to get the pyrDown of the image.
Here the error: Type mismatch: cannot convert from opencv_core.IplImage to Mat
public class Image {
    IplImage i;
    public void downsample(){
        System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
        Mat Out= new Mat();
        Mat in(i); //  error in this line
        //Down sample the image by factor of 2
        Imgproc.pyrDown(in, Out);
    }
}

A: Convert IplImage to Mat is simple.

IplImage iplImage= cvLoadImage("image.png");
Mat matImage = new Mat(iplImage);

vice versa

A: Code that works for me:
    CvMat mat = cvLoadImageM (filename, iscolor);

If color: iscolor=1
If grey: iscolor=0
For example:
CvMat mat = cvLoadImageM("./image.png", 1);


text:
Q: How to configure `eth0` to retry `dhclient` when unplugged and replugged? I'm working on a linux gadget.
I want it to get DHCP if I plug in the network cable after it has booted up already or if the network cable unplugged and replugged.
One solution is to run a script such as this (which works, btw):
#!/bin/bash

NET_STATUS='different'

while true
do
  NEW_NET_STATUS=`ifconfig | grep RUNNING | grep -v LOOPBACK`
  if [ "${NEW_NET_STATUS}" = "${NET_STATUS}" ]
  then
    echo "no change"
    sleep 1
    continue
  fi
  NET_STATUS=${NEW_NET_STATUS}
  if [ "${NET_STATUS}" ]
  then
    echo "cable plugged in"
  else
    echo "cable unplugged"
  fi
  sleep 1
done

However, I've got a feeling deep down in my little toe that tells me that there's a better way to deal with hotplug events for the ethernet cable.

A: netplug
netplug is the solution that I went with. ifplugd may work just as well.
Installation
sudo apt-get install netplug

Interface Configuration
cat /etc/netplug/netplugd.conf
eth*

Event Configuration
cat /etc/netplug/netplug
#!/bin/sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin
export PATH

dev="$1"
action="$2"

case "$action" in
in)
    echo "$dev : $action : plugged in" >> /tmp/netplug.log
    ;;
out)
    echo "$dev : $action : unplugged" >> /tmp/netplug.log
    ;;
probe)
    echo "$dev : $action : probed" >> /tmp/netplug.log
    ;;
*)
    echo "$dev : $action : I feel violated" >> /tmp/netplug.log
    exit 1
    ;;
esac

Testing
/etc/init.d/netplug stop
/etc/init.d/netplug start

cat /tmp/netplug.log
eth0 : probe : probed
eth1 : probe : probed
...
eth15 : probe : probed
eth0 : in : plugged in

A: ifplugd handles this situation very well:

ifplugd is a Linux daemon which will automatically configure your ethernet device when a cable is plugged in and automatically unconfigure it if the cable is pulled. This is useful on laptops with onboard network adapters, since it will only configure the interface when a cable is really connected.
ifplugd interfaces with your distribution's native network configuration utilities.
Some features:

*

*Uses your distribution's native ifup/ifdown programs.

*[...]

*Supports the Linux SIOCETHTOOL (newer, aka ethtool API), SIOCGMIIREG (older, aka mii-diag/mii-tool API) and SIOCDEVPRIVATE (oldest, aka mii-tool API) ioctl()s for getting link status. Release 0.24 introduces support for link detection with the IFF_RUNNING interface flag.

*[...]

*Can be configured to ignore short "unplugged" periods (-d option) or short "plugged" periods(-u option)

*[...]

*Compatibility mode for network devices which do not support cable detection (-F option)

A: I would suggest using ifplugd over netplugd as it works better and is actively maintained.

ifplugd is a Linux daemon which will automatically configure your
  ethernet device when a cable is plugged in and automatically
  unconfigure it if the cable is pulled. This is useful on laptops with
  onboard network adapters, since it will only configure the interface
  when a cable is really connected.

A: Using this software of mine for network configuration, it's very easy.
http://code.google.com/p/badvpn/wiki/NCD
The following NCD program will do. It also shows how you can extend the configuration, in this case by running something when the network goes up/down.
process eth0 {
    # Set device.
    var("eth0") dev;

    # Wait for device to appear, set it up, and wait for cable to be plugged in.
    net.backend.waitdevice(dev);
    net.up(dev);
    net.backend.waitlink(dev);

    # DHCP configuration.
    # net.ipv4.dhcp() will block here until it obtaines an IP address.
    # It doesn't check the obtained address in any way,
    # so as a basic security measure, do not proceed if it is local.
    net.ipv4.dhcp(dev) dhcp;
    ip_in_network(dhcp.addr, "127.0.0.0", "8") test_local;
    ifnot(test_local);

    # Assign IP address to interface, as obtained by DHCP.
    net.ipv4.addr(dev, dhcp.addr, dhcp.prefix);

    # Add default route.
    net.ipv4.route("0.0.0.0", "0", dhcp.gateway, "20", dev);

    # Add DNS servers.
    net.dns(dhcp.dns_servers, "20");

    # Run an external program when network comes up or goes down.
    list("/some/program/to/run/when/up", "argument") do;
    list("/some/program/to/run/when/down", "argument") undo;
    run(do, undo);
}

Note that this will not only handle the network cable being plugged in or out, but also the network interface itself appearing and disappearing (useful if it's USB).
The advantage of using NCD compared to other software like ifplugd is that its design alows for great flexibility. It basically allows you to program your own network config, as opposed to being limited to a limited set of hardcoded capabilities.
UPDATE: I've made Ubuntu packages for BadVPN and NCD. I've updated the wiki with installation and usage instructions for Ubuntu too: http://code.google.com/p/badvpn/wiki/NCD#Running_it


text:
Q: Regions, Mesh Regions, and Graphics This behavior seems inconsistent to me:
ConicHullRegion[{{0, 0}}, {{1/3, 2/3}, {2/3, 1/3}}];
{Graphics[%], Show[%]}
ConvexHullMesh[{{0, 0}, {1/3, 2/3}, {2/3, 1/3}}];
{Graphics[%], Show[%]}

I would like to display these two regions in a consistent way, but I don't really understand the underlying graphical difference between the two resulting Mathematica objects.


text:
Q: Restrict access to view for unique user in Django w/o providing username and password I'm trying to limit access to a Django view for a unique user, but shouldn't require the user to register. The use case is a link would be sent to a customer to view a page with private information that only he/she can see, but doesn't require them to register with the site. I'm thinking using some type of token might be the way to go but I'm not sure. What is the best way to solve this?

A: Here is typically how such a use case is implemented:

*

*A new entry is created in a model with a unique (and long) random token and a foreign key to the user information

*A URL endpoint consisting of the random token in the path or part of query parameters is sent via email.

*The view for that URL looks up the entry in the model and retrieves the corresponding user information.

*Optionally, the entry is deleted so that the URL cannot be reused in case the email falls into wrong hands.


text:
Q: Getting BibTex to work in the first place I've been writing my thesis for a month now, and haven't gotten any further than fighting with bibliography-related issues. I've boiled down all the problems I'm having into something very simple with BibTex.
It seems I can't get BibTex to work at all. To test, I've done a very basic LaTeX document, a very basic bibliography file. Please find attached screenshots of them.
I'm using TeXworks (what else is there for Mac?). In the screenshots you can see that the PDF I get is unable to connect my citations from the .tex file to the .bib file. Why is this?


text:
Q: Android - Change payment method popup is empty https://dl.dropboxusercontent.com/u/876916/img/Android_payment_method_empty.png - Screenshot
Two weeks ago some users with different Android 4+ versions started to report an issue (3-4 users each week). All of them was going to do first purchase on Market, but they didn't enter payment method before.
So when such user pressing in-app purchase, market asking them to enter payment method info, but there is no "Enter Credit or Debit card number" button in appearing popup.
I can not reproduce this issue (tried 6 different devices with 6 different 4+ android versions, even 4.4.4 and 5.0). After this we asked one user to try different application, and he said that this bug is appearing in other apps too!
There are no any information about this on the internet. So does anyone know other method to show "Enter Credit or Debit card number" button? Or maybe someone had same problem and solved it?


text:
Q: Calling awt Frame methods from subclass This question is about Frames, Java and Processing.
This questions sounds pretty convoluted but its really not. I'll try keep this to a simple minimum. I'm creating a small ball in a maze game to get my head around physics and rendering. It's been a good experience so far but I've hit a bit of a brick wall.
The general layout I decided on was to contain PApplets within a AWT Frame and have the Frame close. The reason for this is because I was told that you should only have on instance of a Papplet at a time.
PApplet is the Applet class in Processing, a rendering library.
I have 3 classes here including the main
public class Menu extends PApplet
{
//images and buttons
PImage background, playbtn1, playbtn2, hsbtn1, hsbtn2, abbtn1, abbtn2, exbtn1,     exbtn2;
FBox pBtn, hBtn, eBtn;

FWorld menu;

//simple constructor
public Menu()
{

}

public void setup()
{
    size(600, 400);
    smooth();
    Fisica.init(this);
    menu = new FWorld();

    //loading and placing images
    background = loadImage("MenuAlt.jpg");
    System.out.println(background);
    playbtn1 = loadImage("play1.gif");
    playbtn2 = loadImage("play2.gif");
    hsbtn1 = loadImage("high1.gif");
    hsbtn2 = loadImage("high2.gif");
    exbtn1 = loadImage("exit1.gif");
    exbtn2 = loadImage("exit2.gif");

    //loading and placing buttons
    pBtn = new FBox(120, 150);
    pBtn.setPosition(135, 215);
    pBtn.setDrawable(false);
    hBtn = new FBox(120, 150);
    hBtn.setPosition(295, 215);
    hBtn.setDrawable(false);
    eBtn = new FBox(120, 150);
    eBtn.setPosition(455, 215);
    eBtn.setDrawable(false);

    //add item to world
    menu.add(pBtn);
    menu.add(hBtn);
    menu.add(eBtn);
}

public void draw()
{
    image(background, 0, 0);
    image(playbtn1, 80, 140);
    image(hsbtn1, 237, 135);
    image(exbtn1, 400, 140);

    mouseOver();
    menu.draw();
}

//close this frame an open a new level, high score or exit
//depending on what the use clicks
public void mousePressed()
{
    FBody pressed = menu.getBody(mouseX, mouseY);
    if (pressed == pBtn)
    {
        System.out.println("play game");
        this.getParent().getParent().getParent().getParent().setVisible(false);

        ExampleFrame x = new ExampleFrame(new Level("level1.txt"));
        x.setLocation(this.getParent().getParent().getParent().getParent().getLocation());
    }
    if (pressed == hBtn)
    {
        System.out.println("high scores");
        this.getParent().getParent().getParent().getParent().setVisible(false);

        /* these are just for finding the parent
 System.out.println(this.getName());
 System.out.println(this.getParent().getName());
 System.out.println(this.getParent().getParent().getName());
 System.out.println(this.getParent().getParent().getParent().getName());
 System.out.println(this.getParent().getParent().getParent().getParent().getName());
         */
        ExampleFrame x = new ExampleFrame(new HighScores()); //for testing, you can change this to new menu()
        x.setLocation(this.getParent().getParent().getParent().getParent().getLocation());
    }
    if (pressed == eBtn)
    {
        System.out.println("exit");
        System.exit(0);
    }
}

the exampleFrame class
public class ExampleFrame extends JFrame
{
    PApplet app;

    public ExampleFrame(PApplet emApp)
    {
        super("Ball Maze Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);

        app = emApp;
        setSize(615,438);
        setVisible(true);

        setLayout(new BorderLayout());

        add(app, BorderLayout.CENTER);
        app.init();
    }
}

the main
public class Main
{
    public static void main(String[] args)
    {
        ExampleFrame x = new ExampleFrame(new Menu());
    }
}

What needs to happen when mousePressed == ebtn is all the stuff in the Frame will be removed and a Highscores Screen will be loaded. highscores is almost the same as menu. There is no need to post code as there is enough here.
The second class is the one which acts as a frame and holds the PApplet
Bottom line, has anyone have any idea how to call the Frame methods from the PApplet or another way to remove all PApplets contents and load another PApplet in?

A:
What needs to happen when mousePressed == ebtn is all the stuff in the Frame will be removed and a Highscores Screen will be loaded

The demo. below of a nested CardLayout adds an ActionListener instead of a MouseListener.  It reacts to both mouse and keyboard input.
There are a multitude of other ways to include more than one GUI element in the same screen space.  Off the top of my head, JTabbedPane, JSplitPane, JDesktopPane/JInternalFrame, popping the high scores in a JDialog or JOptionPane..
Screenshots

CardLayoutDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CardLayoutDemo {

    public static void main(String[] args) {

        Runnable r = new Runnable () {
            public void run() {
                final JRadioButton game = new JRadioButton("Game", true);
                JRadioButton highScores = new JRadioButton("High Scores");

                ButtonGroup bg = new ButtonGroup();
                bg.add( game );
                bg.add( highScores );

                JPanel buttons = new JPanel(new
                    FlowLayout(FlowLayout.CENTER, 5, 5));
                buttons.add( game );
                buttons.add( highScores );

                JPanel gui = new JPanel(new BorderLayout(5,5));
                gui.add(buttons, BorderLayout.SOUTH);

                final CardLayout cl = new CardLayout();
                final JPanel cards = new JPanel(cl);
                gui.add(cards);
                cards.add(new JLabel("Level 1"), "game");
                cards.add(new JLabel("High Scores"), "scores");

                ActionListener al = new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        if (game.isSelected()) {
                            cl.show(cards, "game");
                        } else {
                            cl.show(cards, "scores");
                        }
                    }
                };
                game.addActionListener(al);
                highScores.addActionListener(al);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

A: In order to answer How to call the Frame methods from the PApplet?, I have modified your code snippet to bare minimum. In this modified version when the user click mouse button a System.out is fired.
Now there are two ways in which you can access your Frame object. But before that let me state these two points:

*

*When you create a PApplet like new ExampleFrame(new Menu()); and add it in your JFrame like this add(app, BorderLayout.CENTER); then a complex hierarchy of windows/panels are created.

Like this:
javax.swing.JPanel
    javax.swing.JLayeredPane
        javax.swing.JRootPane
            test.ExampleFrame

*

*PApplet provides a public field for setting and accessing your frame object. And amazingly it is called frame :). You can set it before calling app.init();
>>Code
** Checkout the comments in the code**
Modified ExampleFrame.java
import java.awt.BorderLayout;
import javax.swing.JFrame;
import processing.core.PApplet;

public class ExampleFrame extends JFrame
{
    private static final long serialVersionUID = 4792534036194728580L;
    PApplet app;

    public ExampleFrame(PApplet emApp)
    {
        super("Ball Maze Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);

        app = emApp;
        setSize(615,438);
        setVisible(true);

        setLayout(new BorderLayout());

        add(app, BorderLayout.CENTER);

        // Setting my frame object
        app.frame = this;
        app.init();
    }

    // Sample Method
    public void sampleMethod(String msg)
    {
        System.out.println("I think '"+ msg +"' called me !!");
    }
}

Modified Menu.java
import java.awt.Container;

import processing.core.PApplet;
import processing.core.PImage;

public class Menu extends PApplet
{
    private static final long serialVersionUID = -6557167654705489372L;

    PImage background;
    static String tab = "";

    //simple constructor
    public Menu()
    {

    }

    public void setup()
    {
        size(600, 400);
        smooth();

        background = loadImage("C:/temp/background.jpg");
    }

    public void draw()
    {
        image(background, 0, 0);
    }

    public void mousePressed()
    {
        Container p = getParent();
        tab = "";

        // FIRST WAY OF ACCESSING PARENT FRAME
        while(p != null)
        {
            //printParentTree(p);
            if(p instanceof ExampleFrame)
            {
                ExampleFrame myframe = (ExampleFrame)p;
                myframe.sampleMethod("First Way");
                break;
            }
            p = p.getParent();
        }

        // SECOND WAY OF ACCESSING PARENT FRAME
        if(frame != null && (frame instanceof ExampleFrame))
        {
            ExampleFrame myframe = (ExampleFrame)p;
            myframe.sampleMethod("Second Way");
        }
    }

    void printParentTree(Container p)
    {
        System.out.println(tab+p.getClass().getName());
        tab +='\t';
    }
}

Checkout the public void mousePressed() method.
For completeness, I am also including Main.java.
public class Main {
    public static void main(String[] args){
        new ExampleFrame(new Menu());
    }
}

Now to answer Remove all PApplets contents and load another PApplet in
Well I have not tested it. But you can add a JPanel to your JApplet and do all your drawing on that i.e creating child controls etc. When feel like redrawing then call JPanel.removeAll(). Which as per javadoc:

Removes all the components from this
  container. This method also notifies
  the layout manager to remove the
  components from this container's
  layout via the removeLayoutComponent
  method.

After this call repaint on the JPanel. Try it out, it might work :).


text:
Q: Ho to set multistore configuration in Magento 2 to have domain.com and domain.com/storecode/ In Magento 2,
How to have the default store to be set on domain.com
and other stores to be in directory structure urls like:
domain.com/uk, domain.com/de, ..
First approach:
There is the admin configuration Admin > Stores > Configuration > GENERAL > Web > Url Options > Add Store Code to Urls = Yes.
But it's a global configuration and can't be set on website level or store level.
Now, what I can have is domain.com/[default_store_code]/*.
Actually if I visit domain.com it will render urls inside the page as domain.com/[default_store_code]/path_to_category, ..
Is it something that I miss here ?
In Nginx specifically I'm interested about.
I don't want to add declarations in Nginx conf to redirect domain.com/defaut_store_code/* to domain.com/*.
I don't like it and I don't believe there should be an additional redirect just to stay on domain.com/* URL.
Second approach:
Another approach that i'm looking at is to set Add Store Code to Urls = No and have in admin configuration Base Url set to domain.com in default store configuration level.
And on store uk configuration level to have Base Url set to domain.com/uk/
The last part it would be to write something in Nginx conf to set store codes and website code by url. Like if I'm on domain.com/uk/* than set MAGE_RUN_CODE to uk
Update:
I'm testing the second approach with Add Store Code to Urls = No.
I'm using in Nginx the conf bellow to make Magento 2 aware of the store codes.
The static resources like css, js and .html were not working. I set in global configuration Base URL for Static View Files = http://domain.com/static/
and Base URL for User Media Files http://domain.com/media/
Inspired from here: Magento 2 multi website url setup
# in http context of conf
map $request_uri $MAGE_RUN_CODE {
    default   default;
    ~^/uk  uk;
}

map $request_uri $MAGE_RUN_TYPE {
    default   store;
}

server {
    set $MAGE_MODE developer;
    fastcgi_param  MAGE_MODE $MAGE_MODE;

    listen 8080;
    server_name domain.com;
    set $MAGE_ROOT /[../path to magento 2];

    # I have tried several try_files and didn't do nothing

    include /[../path to magento 2]/nginx.conf.sample;

    #location ~ (index|get|static|report|404|503)\.php$ {
    #   fastcgi_param  MAGE_RUN_CODE $MAGE_RUN_CODE;
    #   fastcgi_param  MAGE_RUN_TYPE $MAGE_RUN_TYPE;
    #}
}

This works for me if I put it in the file /[../path to magento 2]/nginx.conf.sample
    # Search 'location' line bellow and add the 2 fastcgi_param lines from bellow
    location ~ (index|get|static|report|404|503)\.php$ {
       ......
       fastcgi_param  MAGE_RUN_CODE $MAGE_RUN_CODE;
       fastcgi_param  MAGE_RUN_TYPE $MAGE_RUN_TYPE;
    }

Further I'm looking in Magento 2 why it doesn't like to have a directory path before the controller part in URL. And I'll also explore those try_files in conf.
Update 2
I've added as an experiment in \Magento\Store\App\Request\PathInfoProcessor::process()
if ($store->isUseStoreInUrl()) {
    ..
} else {
    if ($store) {
       $this->storeManager->setCurrentStore($storeCode);
       $pathInfo = '/' . (isset($pathParts[1]) ? $pathParts[1] : '');
       return $pathInfo;
    }
}

Store switcher on the page doesn't work well but it rendered the pages ok:
homepage,category page, product page.
It still needs solid research until it's good.
Thank you