Q: libGDX 1.4.1 can't slow down animations This is what I have:
...
private Array<Sprite> fireballFadeOutAnim;
private Array<Sprite> bucketFadeOutAnim;
private TextureAtlas fballAnimSheet;
private TextureAtlas bucketAnimSheet;
private Animation catch_animation;
private Animation visual_feedback;
private float elapsedTime = 0f;

...

@Override
public void create () {

    ...
    fballAnimSheet = new TextureAtlas("animations/fireball_fadeout.txt");
    bucketAnimSheet = new TextureAtlas("animations/bucket_fadeout.txt");
    fireballFadeOutAnim = fballAnimSheet.createSprites("fireball_fadeout");
    bucketFadeOutAnim = bucketAnimSheet.createSprites("bucket_fadeout");

    catch_animation = new Animation(1/15f, fballAnimSheet.getRegions(), Animation.PlayMode.NORMAL);
    visual_feedback = new Animation(1/15f, bucketAnimSheet.getRegions(), Animation.PlayMode.LOOP);

    ...
}

@Override
public void render () {

    ...
    // Set the anim_elipsed_time
    elapsedTime += Gdx.graphics.getDeltaTime();

    ...
    // I try to draw them later on (under the render method) like this:
    // Start and draw animation of fireball catch
    batch.begin();

    batch.draw(catch_animation.getKeyFrame(elapsedTime, true), fireBallRect.getX(), fireBallRect.getY());
    batch.end();
}

I can see both animations happening extremely fast (they look like a white-flash), they do not loop even if the animation mode is set to "LOOP".
What am I doing wrong ? I can't seem to be able to slow them down or to have them LOOP. Thanks much.
Edited:
As requested, I upload all the code
public class MainActivity extends ApplicationAdapter {

    public enum State {
        PAUSE,
        RUN,
        RESUME,
        STOPPED
    }
    public static State state = State.RUN;

    private SpriteBatch batch;
    private OrthographicCamera camera;
    private Stage stage;
    private Texture backgroundImage;
    private Texture bucketImage;
    private Texture fireballImage;
    private Texture heart;
    private TextureRegion criticalTexture;
    private Sprite backgroundSprit;
    private Sprite bucketSprite;
    private Sprite fireballSprite;
    private Sprite heartSprite;
    private Rectangle bucketRect;
    private Rectangle fireBallRect;
    private Rectangle bucketSpriteRect;
    private ShapeRenderer bucketRenderer;
    private ShapeRenderer fireballRenderer;
    private Button pauseButton;
    private Array<Rectangle> fireballArray;
    private Skin progressBarSkin;
    private long lastFireballTime;
    public static Sound bucket_tap;
    public static Sound bucket_drag;
    private Sound fireball_missed_sound;
    private Sound catchFireball;
    private Sound pauseBtnSound;
    private Music bgMusic;
    private float volume = 0.30f;                // music and sfx volume control
    public static int w;
    public static int h;
    private int barLength = 325;
    private int numberOfFails = 10;               // change numberOfFails to increase or decrese
                                                  // the total num. of missed fireballs the player
    private int deductedBarSegment = barLength / numberOfFails;

    private int numOfBallsLeft = numberOfFails;   // use this var to check how many fballs left

    private long fireballFrequency = 1000000000L; // change fireballFrequency to increase or decrease
                                                  // the number of fireballs on the screen

    private int fireballSpeed = 400;              // change the fireballSpeed to increase or decrease
                                                  // the speed at which the fireballs fall

    private InputProcessor gameInputProcessor;    // this sets the game input controller for the bucket
    private InputMultiplexer multiplexer;         // this sets the input processors from the game and UI

    /************************************ Animation Properties ************************************/

    private TextureAtlas fballAtlas;
    private TextureAtlas bucketAtlas;
    private Animation catch_animation;
    private Animation visual_feedback;
    private float elapsedTime = 0f;
    private Actor feedbackPanel;

    /**********************************************************************************************/

    @Override
    public void create () {

        // Parse Test
        //ParseObject testObject = new ParseObject("TestObject");
        //testObject.put("foo", "bar");
        //testObject.saveInBackground();

        // Catch the dynamic size of the screen based on the device that's ran on
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getHeight();

        // Set up the camera
        camera = new OrthographicCamera();
        camera.setToOrtho(false, (float)w, (float)h);

        // Instantiate the batch
        batch = new SpriteBatch();

/***************************** These renders are for debugging only *****************************/

        bucketRenderer = new ShapeRenderer();
        fireballRenderer = new ShapeRenderer();

/**************************************************************************************************/

/******************************************** Stage and HUD ***************************************/

        stage = new Stage();

        pauseButton = new Button(new TextureRegionDrawable(
                new TextureRegion(new Texture(Gdx.files.internal("images/pase_button_red.png")))),
                new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/pase_button_white.png")))));
        pauseButton.setX(flipCoordinates(w, 150));
        pauseButton.setY(flipCoordinates(h, 170));

        pauseButton.act(Gdx.graphics.getDeltaTime());

        stage.addActor(pauseButton);

        pauseButton.addListener(new ChangeListener() {
            @Override
            public void changed (ChangeEvent event, Actor actor) {

                // Do something when the pauseButton is pressed
                // Control multiple touches on the pauseButton
                if(state == State.RUN) {

                    state = State.PAUSE;
                    pauseBtnSound.play();

                    // Set the pauseButton icon to the white version
                    //pauseButton.setColor(Color.WHITE);
                }
                else {
                    state = State.RUN;
                    pauseBtnSound.play();
                }

            }
        });

        // Add the critical_life indicator to the stage as an actor
        criticalTexture = new TextureRegion(new Texture(Gdx.files.internal("images/critical_life.png")));

        feedbackPanel = new Actor() {

            public void draw(Batch batch, float alpha) {

                batch.draw(criticalTexture, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(),
                        getScaleX(), getScaleY(), getRotation());

            }

        };

        feedbackPanel.setBounds(w / 2, h / 2,
                criticalTexture.getRegionWidth(), criticalTexture.getRegionHeight());

        // Set up an Action for the critical life actor

        feedbackPanel.addAction(forever(sequence(scaleTo(2, 2, 0.5f), scaleTo(1, 1, 0.5f), delay(0.5f))));

        feedbackPanel.act(Gdx.graphics.getDeltaTime());
        stage.addActor(feedbackPanel);

/**************************************************************************************************/

/*********************************** Set up the Input Controllers *********************************/

        // The multiplexer helps target several input processes (in this case, the stage and the
        // InputProcessor.class)

        multiplexer = new InputMultiplexer();
        multiplexer.addProcessor(stage);
        multiplexer.addProcessor(new GameInputProcessor());

        // InputAdaptor
        Gdx.input.setInputProcessor(multiplexer);

/**************************************************************************************************/
        backgroundImage = new Texture("images/bg.jpg");
        bucketImage = new Texture("images/bucket_small.png");
        fireballImage = new Texture("images/fireball_small.png");
        heart = new Texture("images/heart.png");

/*************************************** Animations Setup *****************************************/

        fballAtlas = new TextureAtlas("animations/fireball_fadeout.txt");
        bucketAtlas = new TextureAtlas("animations/bucket_fadeout.txt");

        catch_animation = new Animation(0.50f, fballAtlas.getRegions());
        visual_feedback = new Animation(0.15f, bucketAtlas.getRegions());

/**************************************************************************************************/

        // Instantiate all sounds
        bucket_tap = Gdx.audio.newSound(Gdx.files.internal("sounds/bucket_tap.ogg"));
        bucket_drag = Gdx.audio.newSound(Gdx.files.internal("sounds/bucket_drag.ogg"));
        fireball_missed_sound = Gdx.audio.newSound(Gdx.files.internal("sounds/fireball_missed.ogg"));
        catchFireball = Gdx.audio.newSound(Gdx.files.internal("sounds/fastSteam.ogg"));
        pauseBtnSound = Gdx.audio.newSound(Gdx.files.internal("sounds/pauseBtn_sound.ogg"));
        bgMusic = Gdx.audio.newMusic(Gdx.files.internal("sounds/music_bg.mp3"));
        bgMusic.setLooping(true);
        bgMusic.play();   //                  <----------- turn bg music on/off

        // Instantiate the progressBarSkin
        progressBarSkin = new Skin();
        progressBarSkin.add("progressBarBg", new Texture("images/progress-bar_bg.png"));
        progressBarSkin.add("progressBar", new Texture("images/progress-bar_dynamic_red.png"));

        // Create bg sprite
        backgroundSprit = new Sprite(backgroundImage);
        //backgroundSprit.setPosition((float)w / 2, (float)h / 2);
        //backgroundSprit.setSize((float)w, (float)h);

        // Bucket sprite
        bucketSprite = new Sprite(bucketImage);

        // Fireball sprite
        fireballSprite = new Sprite(fireballImage);

        // Heart sprite
        heartSprite = new Sprite(heart);

        // Set the bucketRect into the rect from the bucketSprite (THE GREEN ONE)
        bucketSpriteRect = bucketSprite.getBoundingRectangle();
        bucketSpriteRect.x = w / 2 - 100 / 2;
        bucketSpriteRect.y = 20;
        bucketSpriteRect.setSize(200, 200);

        // Set the collision rectangle (THE RED ONE)
        bucketRect = new Rectangle();
        bucketRect.x = bucketSpriteRect.getX() + 70;   // <---- adjust position left/right
        bucketRect.y = bucketSpriteRect.getY() + 150;  // <---- adjust position up/down
        bucketRect.setSize(100, 10);

        // Set a rectangle for each fireball sprite (THE WHITE ONE)
        fireBallRect = new Rectangle();
        fireBallRect.x = fireballSprite.getX();
        fireBallRect.y = fireballSprite.getY();
        fireBallRect.width = 55;
        fireBallRect.height = 55;

        fireballArray = new Array<Rectangle>();

    }

    @Override
    public void render () {

        // Devide the Render method into a few switch cases based on the game's state
        switch (state) {

            case RUN:

                // Do all the batch drawing here
                Gdx.gl.glClearColor(1, 1, 1, 1);
                Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
                elipsedTime += Gdx.graphics.getDeltaTime();

                batch.setProjectionMatrix(camera.combined);
                batch.begin();
                batch.draw(backgroundSprit, 0, 0, w, h);
                batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
                        bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);

                for(Rectangle fireball: fireballArray) {
                    batch.draw(fireballSprite, fireball.x, fireball.y,
                            fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
                }

                batch.draw(progressBarSkin.getSprite("progressBarBg"), 200, flipCoordinates(h, 170));
                batch.draw(progressBarSkin.getSprite("progressBar"),
                        210, flipCoordinates(h, 162), barLength, 6); // <---- modify x, x, <x>, x to adjust the length of the life-bar
                batch.draw(heartSprite, 95, flipCoordinates(h, 200), 90, 76);

                stage.act(Gdx.graphics.getDeltaTime());
                stage.draw();

                batch.end();

/***************************************Debugging Rectangles************************************/
                // Draw rects around sprites

//        bucketRenderer.begin(ShapeRenderer.ShapeType.Line);
//        bucketRenderer.setColor(Color.GREEN);
//        bucketRenderer.rect(bucketSpriteRect.getX(), bucketSpriteRect.getY(),
//                bucketSprite.getWidth() - 160, bucketSprite.getHeight() -140);
//        bucketRenderer.end();
//
//        bucketRenderer.begin(ShapeRenderer.ShapeType.Line);
//        bucketRenderer.setColor(Color.RED);
//        bucketRenderer.rect(bucketRect.getX(), bucketRect.getY(), 100, 10);
//        //bucketRenderer.point(bucketRect.getX(), bucketRect.getY(), 0f);
//        bucketRenderer.end();
//
//        fireballRenderer.begin(ShapeRenderer.ShapeType.Line);
//        fireballRenderer.setColor(Color.WHITE);
//        fireballRenderer.rect(fireBallRect.x, fireBallRect.y,
//                fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
//        fireballRenderer.end();

                // To avoid sprite flickering, surround batch.draw with a game state check
                if (state != State.PAUSE) {

                    Iterator<Rectangle> iter = fireballArray.iterator();
                    while(iter.hasNext()) {
                        fireBallRect = iter.next();
                        fireBallRect.y -= fireballSpeed * Gdx.graphics.getDeltaTime();

                        // Remove the fireBallRect from the array as soon as it leaves the screen
                        if(fireBallRect.y + 106 < 0) {
                            iter.remove();

                            // The player missed the fireball, play a the fireball_missed_sound
                            fireball_missed_sound.play();

                            // Subtract a ball from the total number allowed to be missed
                            numOfBallsLeft --;

                            // Call life deduction
                            deductLifePoints();

                            // Check to see if this is the last fball left to fail
                            if (numOfBallsLeft == 1) {

                            }

                            // Check to see if life points are 0 or < 0
                            if (numOfBallsLeft <= 0) {

                                // Game over logic
                                barLength = 0;

                                // Set the game state to PAUSED
                                //state = State.PAUSE;
                                //bucketSprite.setColor(Color.RED);
                                batch.begin();
                                batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
                                        bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);
                                batch.end();
                            }
                        }

                        // Collision detector
                        if(bucketRect.overlaps(fireBallRect)) {

                            catchFireball.play(volume);

                            // Start and draw animagion of fireball catch
                            batch.begin();

                            batch.draw(catch_animation.getKeyFrame(elapsedTime, true), fireBallRect.getX(), fireBallRect.getY());
                            batch.end();

                            // Remove the fireball that collides with the bucket
                            iter.remove();
                        }

                    }

                }

                // Touch input controller
                if(Gdx.input.isTouched()) {
                    Vector3 touchPos = new Vector3();
                    touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
                    camera.unproject(touchPos);

                    if(touchPos.y <= 250) {

                        bucketSpriteRect.setX(touchPos.x - 115);
                        bucketRect.setX(touchPos.x - 50);  // <---- adjust position left/right on touch

                    }

                }

                if(TimeUtils.nanoTime() - lastFireballTime > fireballFrequency) {

                    fireBallRect = new Rectangle();
                    fireBallRect.x = MathUtils.random(50, w - 270);
                    fireBallRect.y = h;
                    fireBallRect.width = 75;
                    fireBallRect.height = 75;
                    fireballArray.add(fireBallRect);
                    lastFireballTime = TimeUtils.nanoTime();

                }

/**************************************************************************************************/
                break;
            case PAUSE:

                // Pause the game here
/******************************** Redraw the sprites to avoid flickering **************************/

                batch.begin();
                batch.draw(backgroundSprit, 0, 0, w, h);
                batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
                        bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);

                for(Rectangle fireball: fireballArray) {
                    batch.draw(fireballSprite, fireball.x, fireball.y,
                            fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
                }

                batch.draw(progressBarSkin.getSprite("progressBarBg"), 200, flipCoordinates(h, 170));
                batch.draw(progressBarSkin.getSprite("progressBar"),
                        210, flipCoordinates(h, 162), barLength, 6); // <---- modify x, x, <x>, x to adjust the length of the life-bar
                batch.draw(heartSprite, 95, flipCoordinates(h, 200), 90, 76);
                //pauseButton.draw(batch, 1);
                stage.act(Gdx.graphics.getDeltaTime());
                stage.draw();

                batch.end();

/**************************************************************************************************/

                break;
            case RESUME:

                break;
            default:

                break;
        }

    }

    /************************************* Implement Dispose **************************************/
    @Override
    public void dispose() {

        batch.dispose();
        bucketRenderer.dispose();
        fireballRenderer.dispose();
        backgroundImage.dispose();
        bucketImage.dispose();
        fireballImage.dispose();
        bucket_tap.dispose();
        bucket_drag.dispose();
        catchFireball.dispose();
        bgMusic.dispose();
        fireball_missed_sound.dispose();
        progressBarSkin.dispose();
        fballAtlas.dispose();
        stage.dispose();

    }

    /************************************* Flip Coordinates Method ********************************/

    public static float flipCoordinates(float height, float xORy) {

        float newPosition = height - xORy;
        return newPosition;
    }

    /************************************** Deduces Life Points ***********************************/
    private void deductLifePoints() {

        barLength -= deductedBarSegment;
    }

    /************************************** Set the Game's state **********************************/
    public void setGameState(State s) {

        this.state = s;
    }

    /******************************** Android's Lyfe-Cycle Overrides ******************************/
    @Override
    public void pause() {

        super.pause();
        this.state = State.PAUSE;

    }

    @Override
    public void resume() {

        super.resume();
        this.state = State.PAUSE;
    }
}

A: The first parameter of the Animation constructor is the frameDuration in seconds. You are passing it 1/15f, which is really fast. Try something greater, like 0.15f.


Q: Countdown timer to specific date I'm trying to make a countdown timer that displays total number of days, hours, minutes and seconds remaining to specific date.
That's what I've up to now created.
protected override void OnCreate (Bundle bundle)
{
  base.OnCreate (bundle);

  SetContentView (Resource.Layout.Main);

  txtDays = FindViewById<TextView> (Resource.Id.txtDays);
  txtHours = FindViewById<TextView> (Resource.Id.txtHours);
  txtMins = FindViewById<TextView> (Resource.Id.txtMins);
  txtSec = FindViewById<TextView> (Resource.Id.txtSec);

  DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00);

  DateTime todaysDateTime = DateTime.Now;
  DateTime formattedDate = todaysDateTime.AddHours (2);

  TimeSpan span = enteredDate.Subtract(formattedDate);

  double totalDays = span.TotalDays;
  double totalHours = span.TotalHours;
  double totalMins = span.TotalMinutes;
  double totalSec = span.TotalSeconds;

  new Thread(new ThreadStart(() =>
                             {
    RunOnUiThread(() =>
                  {
      Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays)));
      Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours)));
      Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins)));
      Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec)));

      txtDays.Text = String.Format ("{0:0}", Math.Truncate (totalDays));
      txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
      txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins));
      txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec));

  });
  })).Start();

}

How to update TextViews every second automatically with Android C#?
EDIT 2:
I have used Timer, it's counting with Console.WriteLine, but the TextViews displays nothing and they don't updating... Somebody an idea how to update TextViews every second?
timer = 0;
      new Thread(new ThreadStart(() =>
                                 {
      Thread.Sleep (1000);
        RunOnUiThread(() =>
                      {
      tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed);
      tmr.Start();
      while (timer < totalSec) ;
      tmr.Stop();

        });
      })).Start();

void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
      txtDays = FindViewById<TextView> (Resource.Id.txtDays);
      txtHours = FindViewById<TextView> (Resource.Id.txtHours);
      txtMins = FindViewById<TextView> (Resource.Id.txtMins);
      txtSec = FindViewById<TextView> (Resource.Id.txtSec);

      DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00);

      DateTime todaysDateTime = DateTime.Now;
      DateTime formattedDate = todaysDateTime.AddHours (2);

      TimeSpan span = enteredDate.Subtract(formattedDate);

      totalDays = span.TotalDays;
      totalHours = span.TotalHours;
      totalMins = span.TotalMinutes;
      totalSec = span.TotalSeconds;

      Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays)));
      Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours)));
      Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins)));
      Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec)));

      txtDays.Text = String.Format ("{0:0}", Math.Truncate (totalDays));
      txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
      txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins));
      txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec));

    }

A: In C# use Timer class and set that to 1 second.

A: Problem solved just added RunOnUiThread within tmr_Elapsed
void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  RunOnUiThread(() =>
                {
  txtDays = FindViewById<TextView> (Resource.Id.txtDays);
  txtHours = FindViewById<TextView> (Resource.Id.txtHours);
  txtMins = FindViewById<TextView> (Resource.Id.txtMins);
  txtSec = FindViewById<TextView> (Resource.Id.txtSec);

  DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00);

  DateTime todaysDateTime = DateTime.Now;
  DateTime formattedDate = todaysDateTime.AddHours (2);

  TimeSpan span = enteredDate.Subtract(formattedDate);

  totalDays = span.TotalDays;
  totalHours = span.TotalHours;
  totalMins = span.TotalMinutes;
  totalSec = span.TotalSeconds;

  Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays)));
  Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours)));
  Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins)));
  Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec)));

  txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
  txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
  txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins));
  txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec));
  });
}


Q: Python: how do I create a list of combinations from a series of ranges of numbers For a list of numerical values of n length, e. g. [1, 3, 1, 2, ...], I would like to create a list of the lists of all possible combinations of values from range[x+1] where x is a value from the list. The output might look something like this:
for list[1, 3, 2] return all possible lists of range[x+1] values:
    # the sequence of the list is unimportant
[
[0,0,0],[1,0,0],[0,1,0],[0,2,0],[0,3,0],[0,0,1],[0,0,2],[1,1,0],
[1,2,0],[1,3,0],[1,0,1],[1,0,2],[0,1,1],[0,2,1],[0,3,1],[0,1,2],
[0,2,2],[0,3,2],[1,1,1],[1,2,1],[1,3,1],[1,1,2],[1,2,2],[1,3,2]
]

So in this example I am looking for all variations of [e1, e2, e3] from e1 in [0,1], e2 in [0,1,2,3] and e3 in [0,1,2]

A: Python's itertools module has a tool that does what you need:
import itertools
p = itertools.permutations([0, 1, 2, 3])
p_as_list = list(p)

Edit: As your needs are fairly specific you could benefit from having your own function that does something alike this one: (note I haven't got the implementation down just yet, maybe someone might refine this):
def magic_permutations (*args):
    lists = []
    larg = len(args)
    for i in range(larg):
        lists.append([])
    i = 0
    for nums in args:
        for num in nums:
            if i >= larg:
                i = 0
            lists[i].append(num)
            i += 1
    return lists

Edit: I misunderstood your question the first time, so I'll apologize for that. I'll however leave this be.

A: Use itertools.product with a dynamically-specified list of iterators:
vals = [1,3,2]
for item in itertools.product(*[range(x+1) for x in vals]):
    print item

Output:
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)

A: To obtain the exact sequence shown in the question (albeit in a different order, but that's not a problem) use this function:
import itertools as it

def combs(lst):
    return [list(e) for e in it.product(*(range(x+1) for x in lst))]

The result is as expected:
combs([1, 3, 2])

=> [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2],
    [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 3, 0], [0, 3, 1], [0, 3, 2],
    [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2],
    [1, 2, 0], [1, 2, 1], [1, 2, 2], [1, 3, 0], [1, 3, 1], [1, 3, 2]]

A: for ii in itertools.product(range(2),range(4),range(3):
    print ii
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)

A: It's not in the same order, but I think this is what you wanted:
def xrangeCombinations(input):
    if len(input) > 1:
        for i in xrange(input[-1] + 1):
            for j in xrangeCombinations(input[:-1]):
                yield j + [i]
    else:
        for i in xrange(input[-1] + 1):
            yield [i]

for i in xrangeCombinations([1, 3, 2]):
    print i

Produces the output:
[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 2, 0]
[1, 2, 0]
[0, 3, 0]
[1, 3, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]
[0, 2, 1]
[1, 2, 1]
[0, 3, 1]
[1, 3, 1]
[0, 0, 2]
[1, 0, 2]
[0, 1, 2]
[1, 1, 2]
[0, 2, 2]
[1, 2, 2]
[0, 3, 2]
[1, 3, 2]

This solution might be slower than alternatives so if speed is an issue you should probably improve it.

A: Using numpy if you don't mind getting tuples in the end:
>>> import numpy as np
>>> e1=np.array([0,1])
>>> e2=np.array([0,1,2])
>>> e3=np.array([0,1,2,3])
>>> g=np.meshgrid(e1,e2,e3) #you need numpy ver>1.7.0, change the order of final result by changing the order of e1, e2, e3
>>> zip(*[item.flatten() for item in g])
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]


Q: Ways to dynamically render a real world 3d environment in Unity3D Using Unity3D and C# I am attempting to display a 3d version of a real world location. Inside my Unity3D app, the user will specify the GPS coordinates of a location, then my app will have to generate a 3d plane(anything doesn't have to be a plane) of that location. The plane will show a 500 metre by 500 metre 3d snapshot of that location.
How would you suggest I achieve this in Unity3D? What methodology would you use to achieve this?
NOTE: I understand that this is a very difficult endevour(to render real world locations dynamically in Unity3d) so I expect to perform many actions to achieve this. I just don't know of all the technologies out there and which would be best for my needs
For example:

Suggested methodology 1:

*

*Prompt user to specify GPS coords

*Use Google earth API and HTTP to programmatically obtain a .khm file
  describing that location(Not sure if
  google earth provides that capability

*

*does it?)

*Unzip the .khm so I have the .dae file

*Convert that file to a .3ds file using ??? third party converter(is
  there a converter that exists?)

*Import .3ds into Unity3D at runtime as a plane(is this possible)?

  Suggested methodology 2:

*

*Prompt user to specify GPS coords

*Use Google earth API and HTTP to programmatically obtain a .khm file
  describing that location(Not sure if
  google earth provides that capability

*

*does it?)

*Unzip the .khm so I have the .dae file

*Parse .dae file using my own C# parser I will write(do you think its
  possible to write a .dae parser that
  can parse the .dae into an array of
  Vector3 that describe the height map
  of that location?)

*Dynamically create a plane in Unity3D and populate it with my
  array/list of Vector3 points(is it
  possible to create a plane this way?)
  Maybe I am meant to create a mesh
  instead of a plane?

Can you think of any other ways I could render a real world 3d environment in Unity3D?

A: No service available has a detailed 3d map of an area given gps coordinates. Google has a super simple height map that they draw and then map their aerial pictures onto, but even if you could get programmatic access to that it would look terrible if you were at street level. If you're okay with a horrid level of detail (like you're going to be viewing this from high up or something) maybe it would be feasible, but not as any kind of first person street level experience.


Q: Fill Datagridview in each new identical TabPages I have TabControl with 1 TabPages and contains DataGridView.
I create TabPages2 from TabPages1 with code :
    Dim Frm As New TabFormPage
    Dim MoreTabs As TabPage = Frm.TabPage1
    Dim i As Integer
    For i = 1 To TabControl1.TabPages.Count
        MoreTabs.Text = "TabPage" & i + 1
    Next i
    TabControl1.Controls.Add(MoreTabs)
    Frm.Dispose()

TabPages2 Controls identical to TabPages1
If I fill DataGridView with BackgroundWorker in TabPages1 , it was working . But if I fill DataGridView in every New TabPages ( eg TabPages2 ) from different sources , it was not working (DataGridView in TabPages2/each New TabPages is empty/nothing) . It always fills Tabpages1 DataGridView
How to fill every DataGridView in every New TabPages with identical controls ?
Here's my code to fill DataGridview :
    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FPathTab + ";Extended Properties=Excel 12.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [" & CSheetTab1 & "]'", MyConnection)

        DtSet = New System.Data.DataSet
        DtSet.Clear()
        MyCommand.Fill(DtSet)
    End Sub
    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        DataGridView1.DataSource = DtSet.Tables(0)
        dv = DtSet.Tables(0).DefaultView
        MaxRecords = DtSet.Tables(0).Rows.Count
        MyConnection.Close()
        DataGridView1.Columns("F20").Visible = False
        DataGridView1.Columns("F21").Visible = False
        DataGridView1.Columns("F22").Visible = False
    End Sub

Thanks for your help


Q: has anyone figured out a way to use the back-facing camera on android in any browser with getusermedia? I can’t seem to find the settings anywhere. I also tried searching the phone to set front-facing as default but had no luck. I’m using an xiaomi 1s if that helps.sorry ,my english is poor


Q: Subdomain overwiting CodeIgniter session I have 2 CodeIgniter installations, 1 on mydomain.com another on sub.mydomain.com.
I am trying to get sub.mydomain.com to be able to access the CI session created by mydomain.com. I have edited the cookie section of both config files to:
$config['cookie_prefix']    = "";
$config['cookie_domain']    = ".mydomain.com";
$config['cookie_path']      = "/";
$config['cookie_secure']    = FALSE;

Now if I go to mydomain.com setting the session and then go to sub.mydomain.com it seems to overwrite the session with a new one rather than being able to read from the existing session.
Am I missing something here?

A: This was driving me crazy for hours but the solution (as usual) was simple. I had forgotten to make sure
$config[‘encryption_key’]

was the same for both applications!
Working great now


Q: Guidance with a translation in Linq to Xml Can someone help with an explanation of what does this mean:
... .Select(Func<XElement, XElement>selector)

Please an example of what should go in as parameter will be appreciated.
Also found it a little bit difficult naming this question. Suggestion will also be appreciated.

A: It's a function taking XElement as argument and returning an XElement, so for instance:
public XElement someFunction(XElement argument)
{
    XElement someNewElement = new XElement();
    ... // do something with someNewElement, taking into account argument
    return someNewElement;
}

Func<XElement, XElement> variableForFunction = someFunction;

.... .Select(variableForFunction);

I'm not interely sure if you have to assign it to a variable first, you could probably just do this:
... .Select(variableForFunction);

give it a try (and let me know if it works :) )
oh and for more information, here's the msdn article, it also explains how to use delegates:
Func<XElement, XElement> variableForFunction = delegate(XElement argument)
    {
        ....//create a new XElement
        return newXElement;
    }

and how to use lambdas, for instance:
Func<XElement, XElement> variableForFunction = s => {
    ....;//create an XElement to return
    return newXElement;
}

or, in this instance, use the lambda directly:
.... .Select( s => {
    ....;//create an XElement to return
    return newXElement;
})

edited it following Pavel's comment


Q: If the address of a function can not be resolved during deduction, is it SFINAE or a compiler error? In C++0x SFINAE rules have been simplified such that any invalid expression or type that occurs in the "immediate context" of deduction does not result in a compiler error but rather in deduction failure (SFINAE).
My question is this:
If I take the address of an overloaded function and it can not be resolved, is that failure in the immediate-context of deduction?
(i.e is it a hard error or SFINAE if it can not be resolved)?
Here is some sample code:
struct X
{
  // template<class T> T* foo(T,T); // lets not over-complicate things for now
  void foo(char);
  void foo(int);
};

template<class U> struct S
{
  template<int> struct size_map
  { typedef int type; };

// here is where we take the address of a possibly overloaded function
  template<class T> void f(T,
      typename size_map<sizeof(&U::foo)>::type* = 0);

  void f(...);
};

int main()
{
  S<X> s;

// should this cause a compiler error because 'auto T = &X::foo' is invalid?
  s.f(3);

}

Gcc 4.5 states that this is a compiler error, and clang spits out an assertion violation.
Here are some more related questions of interest:
Does the FCD-C++0x clearly specify what should happen here?
Are the compilers wrong in rejecting this code?
Does the "immediate-context" of deduction need to be defined a little better?
Thanks!

A: template<class T> void f(T,
    typename size_map<sizeof(&U::foo)>::type* = 0);

This doesn't work, because U does not participate in deduction. While U is a dependent type, during deduction for f it's treated like a fixed type spelled with a nondependent name. You need to add it to the parameter list of f
/* fortunately, default arguments are allowed for
 * function templates by C++0x */
template<class T, class U1 = U> void f(T,
    typename size_map<sizeof(&U1::foo)>::type* = 0);

So in your case because U::foo does not depend on parameters of f itself, you receive an error while implicitly instantiating S<X> (try to comment out the call, and it should still fail). The FCD says at 14.7.1/1

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the deﬁnitions or default arguments, of the class member functions, member classes, static data members and member templates;

That is, if you implicitly instantiate S<X> the following function template declaration will be instantiated
template<class T> void S<X>::f(T,
  typename size_map<sizeof(&X::foo)>::type* = 0);

Analysis on that template declaration will then find that it can't resolve the reference to X::foo and error out. If you add U1, the template declaration will not yet try to resolve the reference to U1::foo (since U1 is a parameter of f), and will thus remain valid and SFINAE when f is tried to be called.


Q: C# Progress Bar is not showing progress I have a progress bar on my program and I am trying to add value to it after each "DataTable" has been processed, however it only updates after everything is done.
here is the code:
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach(DataSet ds in allDataSets)
{
    foreach(DataTable dt in ds.Tables)
    {
        foreach (DataRow dr in dt.Rows)
        {
           insertIntoDatabaseCurrentRecord(dr);
        }
     }
     pbMain.Value = pbMain.Value + (33 / totalFiles);
     c++;
}
cn.Close();
cn.Dispose();

Is there a way to force the bar to show progress after each table is finished like it is finished?  At the moment, I only see the progress once loops finish, I see the line  go from empty to full.  There are about 18000 records per DataTable, so I should be able to see it because it takes about a minute for it to process all the records.

A: Assuming all this is happening in the UI thread, then it's not going to update because you are keeping the thread busy with processing your loop. You need to spawn off a background thread to do the processing so that it doesn't hang your UI thread. Then you will need to have the part where you actually set the progress bar pushed back to your UI thread using Contol.Invoke.
See here: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx for both an example of threading (although there are many ways you can do this) and Control.Invoke.

A: Use BackgroundWorker:
BackgroundWorker _worker;

// executes on another thread
void worker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = (BackgroundWorker)sender;

    int c = 0;
    OdbcConnection cn = openOdbcDB();
    foreach (DataSet ds in allDataSets)
    {
        foreach (DataTable dt in ds.Tables)
        {
            foreach (DataRow dr in dt.Rows)
            {
                insertIntoDatabaseCurrentRecord(dr);
            }
        }
        // do not update UI elements here, but in ProgressChanged event
        //pbMain.Value = pbMain.Value + (33 / totalFiles);
        c++;

        worker.ReportProgress(c); // call ProgressChanged event of the worker and pass a value you can calculate the percentage from (I choose c, since it is the only calculated value here)
    }
    cn.Close();
    cn.Dispose();
}

// gets called on your main thread
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // update the progressbar here.
    // e.ProgressPercentage holds the value passed in DoWork.
}

A: Since your loops are blocking the active thread, you will have to use another Thread (clean way) or simply use Application.DoEvents() on WinForms:
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach(DataSet ds in allDataSets)
{
    foreach(DataTable dt in ds.Tables)
    {
        foreach (DataRow dr in dt.Rows)
        {
           insertIntoDatabaseCurrentRecord(dr);
           Application.DoEvents(); //Quick and dirty
        }
     }
     pbMain.Value = pbMain.Value + (33 / totalFiles);
     c++;
}
cn.Close();
cn.Dispose();


Q: Snap to Ticks and move Ticks position in Custom Range slider I am very new to this and i am trying to figure out how to solve my issue.
I am trying to design an Range slider for controling the speed of an machine application.
I have been searching here for many hours now but i can not find the right result for my issue.
The code i am adding here is something i have found other pages so it might not be best solution.
I would like to do 3 different things with it to start with.

*

*First issue is that i would like the handle to snap to the ticks i have made, is it possible to do that with code so if i change my Ticks the handle will stil snap to the new ticks?

*Is it possible to have more ticks between 0 and 10% so i have like 2% steps there up to 10% and when the handle is there it will then snap to the 2% steps and when its above 10% it will snap to the other 10% step interval.

*Is it possible to move the Ticks inside the slider instead and have the labels in the middle?
I would like to have the ticks both in the bottom and in the top and then the labels in the middle. I have attached a picture of what i am aiming for.

Many thanks
Range slider idea!
Link to my Code
https://www.w3schools.com/code/tryit.asp?filename=GT1V8EFG2RUA

A:

function toggleStep(element) {
  if (element.value >= 10) { element.step = 10; }
  else { element.step = 2; }
}

/**
 * Sniffs for Older Edge or IE,
 * more info here:
 * https://stackoverflow.com/q/31721250/3528132
 */
function isOlderEdgeOrIE() {
  return (
    window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    !!navigator.userAgent.match(/Trident.*rv\:11\./) ||
    window.navigator.userAgent.indexOf("Edge") > -1
  );
}

function valueTotalRatio(value, min, max) {
  return ((value - min) / (max - min)).toFixed(2);
}

function getLinearGradientCSS(ratio, leftColor, rightColor) {
  return [
    '-webkit-gradient(',
    'linear, ',
    'left top, ',
    'right top, ',
    'color-stop(' + ratio + ', ' + leftColor + '), ',
    'color-stop(' + ratio + ', ' + rightColor + ')',
    ')'
  ].join('');
}

function updateRangeEl(rangeEl) {
  var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);

  rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#00FF00', '#c5c5c5');
}

function initRangeEl() {
  var rangeEl = document.querySelector('input[type=range]');
  var textEl = document.querySelector('input[type=text]');

  /**
   * IE/Older Edge FIX
   * On IE/Older Edge the height of the <input type="range" />
   * is the whole element as oposed to Chrome/Moz
   * where the height is applied to the track.
   *
   */
  if (isOlderEdgeOrIE()) {
    rangeEl.style.height = "20px";
    // IE 11/10 fires change instead of input
    // https://stackoverflow.com/a/50887531/3528132
    rangeEl.addEventListener("change", function(e) {
      textEl.value = e.target.value;
    });
    rangeEl.addEventListener("input", function(e) {
      textEl.value = e.target.value;
    });
  } else {
    updateRangeEl(rangeEl);
    rangeEl.addEventListener("input", function(e) {
      updateRangeEl(e.target);
      textEl.value = e.target.value;
    });
  }
}

initRangeEl();
.slidecontainer {
  width: 500px;
  margin-left:15px;
}

input[type="range"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  width:100%;
  height: 50px;
  padding: 0;
  border: solid 2px #000000;
  border-radius: 8px;
  outline: none;
  cursor: pointer;
}

datalist {
  display: flex;
  margin-left: 2px;
  margin-top: -50px;
}

datalist option {
  flex-basis: 10%;
  border-left: 1px solid #000;
}
datalist option:nth-child(-n+5) {
  flex-basis: 2%;
}
datalist option:last-child {
  display: none;
}

/*Chrome thumb*/

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  -webkit-border-radius: 5px;
  /*16x16px adjusted to be same as 14x14px on moz*/
  height: 45px;
  width: 45px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 2px solid #000000;
  opacity: 0.4;
  cursor: pointer;
  border-radius: 8px;

}

/*Mozilla thumb*/

input[type="range"]::-moz-range-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  -moz-border-radius: 5px;
  height: 14px;
  width: 14px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}

/*IE & Edge input*/

input[type=range]::-ms-track {
  width: 300px;
  height: 6px;
  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
  background: transparent;
  /*leave room for the larger thumb to overflow with a transparent border */
  border-color: transparent;
  border-width: 2px 0;
  /*remove default tick marks*/
  color: transparent;
    margin-left:15px;
}

/*IE & Edge thumb*/

input[type=range]::-ms-thumb {
  height: 14px;
  width: 14px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}

/*IE & Edge left side*/

input[type=range]::-ms-fill-lower {
  background: #000000;
  border-radius: 2px;
    margin-left:15px;
}

/*IE & Edge right side*/

input[type=range]::-ms-fill-upper {
  background: #000000;
  border-radius: 2px;
}

/*IE disable tooltip*/

input[type=range]::-ms-tooltip {
  display: none;
}

input[type="text"] {
  border: none;
}

.sliderticks {
  display: flex;
  justify-content: space-between;
  padding: 0 50px;
}

.sliderticks p {
  position: relative;
  display: flex;
  justify-content: center;
  text-align: center;
  width: 1px;
  background: #D3D3D3;
  height: 10px;
  line-height: 40px;
  margin: 0 0 20px 0;
}

Custom Range Slider

Drag the slider to display the current value.

<input type="range" value="10" min="0" max="100" oninput="toggleStep(this)" list="sliderticks"   />

 <datalist id="sliderticks">
   <option>0</option>
   <option>2</option>
   <option>4</option>
   <option>6</option>
   <option>8</option>
   <option>10</option>
   <option>20</option>
   <option>30</option>
   <option>40</option>
   <option>50</option>
   <option>60</option>
   <option>70</option>
   <option>80</option>
   <option>90</option>
   <option>100</option>
 </datalist>

A: Hope the code below solves your needs:

document.querySelectorAll('.range input[type="range"]').forEach((range) => {
  range.tickmarks = [...range.list.options].map((el) => parseFloat(el.value));
  range.list.insertAdjacentHTML('afterend', `<div class="range-value"></div>`);
  range.max = parseFloat(range.tickmarks[range.tickmarks.length - 1]);
  let q = (range.clientWidth - 40) / range.max;
  range.addEventListener('input', function(ev) {
    if (this.hasAttribute('ticks-only')) {
      this.value = range.tickmarks.map((x) => x).sort((x, y) => Math.abs(x - this.value) - Math.abs(y - this.value))[0];
    }
    this.parentElement.style.backgroundSize = `${(this.value * range.clientWidth) / range.max}px 100%, 100% 100%`;
    this.list.nextElementSibling.textContent = this.value;
    this.list.nextElementSibling.style.left = `${20 + this.value * q}px`;
  });
  range.tickmarks.forEach((el, i) => {
    range.list.options[i].label = el % 10 ? ' ' : el;
    range.list.options[i].style.left = 20 + el * q + 'px';
  });
  range.dispatchEvent(new Event('input', {bubbles: true}));
});
.range {
  position: relative;
  height: 52px; width: 500px;
  border-radius: 0.125em;
  overflow: hidden;
  font: 16px/1em sans-serif;
  background-image: linear-gradient(to right, #7bad23, #39594c), linear-gradient(to bottom, #84929d, #46576d);
  background-size: 0 100%, 100% 100%;
  background-repeat: no-repeat;
  box-shadow: 0 0 0 0.125em #7f8c97, 0.0625em 0.125em 0.3125em 0em #93a2bd, -0.125em -0.1875em 0.3125em 0em #0e1116, inset 0 0 1.25em -0.3125em #0e1116;
}

datalist {
  position: relative;
  display: block;
  height: 100%; width: 100%;
  pointer-events: none;
}

.range datalist option {
  position: absolute !important;
  display: grid;
  place-items: center;
  height: 100%;
  padding: 0;
  transform: translatex(-50%);
  font: bold 12px/1em monospace !important;
  text-shadow: 1px 0 0.16666667em #fff5;
}

.range datalist option::before,
.range datalist option::after {
  content: "";
  position: absolute;
  left: 50%;
  height: 100%; width: 0;
  box-shadow: 0 0 0 0.08333333em #0008;
}
.range datalist option::before { bottom: calc(50% + 1em); }
.range datalist option::after { top: calc(50% + 1em); }

input[type="range"] {
  appearance: none;
  position: absolute;
  top: 0; left: 0; z-index: 1;
  margin: 0;
  height: 100%; width: 100%;
  box-sizing: border-box;
  font: inherit;
  background-color: transparent;
  cursor: pointer;
}

input[type="range"]::-webkit-slider-thumb {
  appearance: none;
  display: block;
  width: 2.5em; height: 2.5em;
  border: none;
  border-radius: 0.75em;
  background-color: #99c7;
  box-shadow: 0 0 0.125em 0 #282850dd, inset 0 0 0.125em 0.125em #282850dd;
  transition: background-color 0.5s ease-out 0.5s;
}
input[type="range"]:active::-webkit-slider-thumb {
  background-color: #fff8;
  transition: background-color 0.5s ease-out;
}

.range-value {
  position: absolute;
  top: 0; left: 0; z-index: 2;
  display: grid;
  place-items: center;
  height: 100%;
  transform: translatex(-50%);
  font: bold 12px/1em monospace !important;
  text-shadow: 0 0 0.16666667em #fff;
  opacity: 0;
  pointer-events: none;
  transition: opacity 1s ease-in;
}
input[type="range"]:focus-visible~.range-value,
input[type="range"]:active~.range-value,
input[type="range"]:hover~.range-value {
  opacity: 1;
  transition: opacity 0.5s ease-out;
}

body { margin: 0; height: 100vh; background-color: #42516c; display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; }

  <input type="range" list="high">
  <datalist id="high">
    <option value="0">
    <option value="2">
    <option value="4">
    <option value="6">
    <option value="8">
    <option value="10">
    <option value="20">
    <option value="30">
    <option value="40">
    <option value="50">
    <option value="60">
    <option value="70">
    <option value="100">
  </datalist>

With "ticks-only" attribute

  <input type="range" list="bass" ticks-only>
  <datalist id="bass">
    <option value="0">
    <option value="10">
    <option value="15">
    <option value="20">
    <option value="30">
    <option value="40">
    <option value="50">
    <option value="60">
    <option value="70">
    <option value="72">
    <option value="74">
    <option value="76">
    <option value="78">
    <option value="80">
    <option value="100">
    <option value="175">
    <option value="200">
  </datalist>

Note! This code only works for "webkit" (tested in Chrome). Firefox does not work correctly with the "position" property when parent and child elements are set to "absolute".


Q: Why AVL sort is not in place? I was recently told that AVL sort is not in place. Can anyone please explain it? From the below code, I am not sure where I assign extra space when sorting. In this code, when a data structure is built or an element are inserted, elements are ordered by their key.
Reference for the claim: They are using this claim to motivate "binary heap"
[1].https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r08.pdf
Reference for code:
[2]. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r06.pdf
[3]. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r07.pdf
def height(A):
    if A: return A.height
    else: return -1

class Binary_Node:
    def __init__(self, x):
        self.item = x
        self.parent = None
        self.left = None
        self.right = None
        self.subtree_update()

    def subtree_update(self):
        self.height = 1 + max(height(self.left), height(self.right))

    def subtree_iter(self):
        if self.left: yield from self.left.subtree_iter()
        yield self
        if self.right: yield from self.right.subtree_iter()

    def subtree_first(self):
        if self.left: return self.left.subtree_first()
        else: return self

    def subtree_last(self):
        if self.right: return self.right.subtree_last()
        else: return self

    def sucessor(self):
        if self.right: return self.right.subtree_first()
        while self.parent and (self is self.parent.right): #A is parent's left child and A's parent exists
            self = self.parent
        return self.parent

    def predecessor(self):
        if self.left: return self.left.subtree_last()
        while self.parent and (self is self.parent.left):
            self = self.parent
        return self.parent

    def subtree_insert_before(self, A):
        if self.left:
            self = self.left.subtree_last()
            self.right, A.parent = A, self
        else:
            self.left, A.parent = A, self
        self.maintain()

    def subtree_insert_after(self, A):
        if self.right:
            self = self.right.subtree_first()
            self.left, A.parent = A, self
        else:
            self.right, A.parent = A, self
        self.maintain()

    def delete(self):
        if not self.left and not self.right: # when self is leaf
            if self.parent:
                A = self.parent
                if A.left is self: A.left = None
                else: A.right = None
                self.parent = None

        if self.left:
            self.item, self.left.subtree_last().item = self.left.subtree_last().item, self.item
            self.left.subtree_last().delete()

        else:
            self.item, self.right.subtree_first().item = self.right.subtree_first().item, self.item
            self.right.subtree_last().delete()

    def subtree_delete(self):
        if self.left or self.right:
            if self.left: B = self.predecessor()
            else: B = self.sucessor()
            self.item, B.item = B.item, self.item
            return B.subtree_delete()

        if self.parent:
            if self.parent.left is self: self.parent.left = None
            else: self.parent.right = None
            self.parent.maintain()
        return self

    def subtree_rotate_right(self):
        assert self.left
        B, E = self.left, self.right
        A, C = B.left, B.right
        B, self = self, B
        self.item, B.item = B.item, self.item
        B.left, B.right = A, self
        self.left, self.right = C, E
        if A: A.parent = B
        if E: E.parent = self
        B.subtree_update()
        self.subtree_update()

    def subtree_rotate_left(self):
        assert self.right
        A, D = self.left, self.right
        C, E = D.left, D.right
        self, D = D, self
        self.item, D.item = D.item, self.item
        self.left, self.right = A, C
        D.left, D.right = self, E
        if A: A.parent = self
        if E: E.parent = D
        self.subtree_update()
        D.subtree_update()

    def skew(self):
        return height(self.right) - height(self.left)

    def rebalance(self):
        if self.skew() == 2:
            if self.right.skew() < 0:
                self.right.subtree_rotate_right()
            self.subtree_rotate_left()
        elif self.skew() == -2:
            if self.left.skew() > 0:
                self.left.subtree_rotate_left()
            self.subtree_rotate_right()

    def maintain(self):
        self.rebalance()
        self.subtree_update()
        if self.parent: self.parent.maintain()

class Binary_Tree:
    def __init__(self, Node_Type = Binary_Node):
        self.root = None
        self.size = 0
        self.Node_Type = Node_Type

    def __len__(self): return self.size
    def __iter__(self):
        if self.root:
            for A in self.root.subtree_iter():
                yield A.item

    def build(self, X):
        A = [x for x in X]
        def build_subtree(A, i, j):
            c = (i + j) // 2
            root = self.Node_Type(A[c])
            if i < c:
                root.left = build_subtree(A, i, c - 1)
                root.left.parent = root
            if j > c:
                root.right = build_subtree(A, c + 1, j)
                root.right.parent = root
            return root
        self.root = build_subtree(A, 0, len(A) - 1)

class BST_Node(Binary_Node):
    def subtree_find(self, k):
        if self.item.key > k:
            if self.left: self.left.subtree_find(k)
        elif self.item.key < k:
            if self.right: self.right.subtree_find(k)
        else: return self

        return None

    def subtree_find_next(self, k):
        if self.item.key <= k:
            if self.right: return self.right.subtree_find_next(k)
            else: return None

        elif self.item.key > k:
            if self.left: return self.left.subtree_find_next(k)
            else: return self

        return self

    def subtree_find_prev(self, k):
        if self.item.key >= k:
            if self.left: return self.left.subtree_find_prev(k)
            else: return None
        elif self.item.key < k:
            if self.right: return self.right.subtree_find_prev(k)
            else: return self

        return self

    def subtree_insert(self, B):
        if B.item.key < self.item.key:
            if self.left: self.left.subtree_insert(B)
            else: self.subtree_insert_before(B)

        elif B.item.key > self.item.key:
            if self.right: self.right.subtree_insert(B)
            else: self.subtree_insert_after(B)

        else:
            self.item = B.item

class Set_Binary_Tree(Binary_Tree):
    def __init__(self): super().__init__(BST_Node)

    def iter_order(self): yield from self

    def build(self, X):
        for x in X: self.insert(x)

    def find_min(self):
        if self.root: return self.root.subtree_first()

    def find_max(self):
        if self.root: return self.root.subtree_last()

    def find(self, k):
        if self.root:
            node = self.root.subtree_find(k)
            if node:
                return node.item

    def find_next(self, k):
        if self.root:
            node = self.root.subtree_find_next(k)
            if node:
                return node.item

    def find_prev(self, k):
        if self.root:
            node = self.root.subtree_find_prev(k)
            if node:
                return node.item

    def insert(self, x):
        new = self.Node_Type(x)
        if self.root:
            self.root.subtree_insert(new)
            if new.parent is None: return False

        else:
            self.root = new

        self.size += 1
        return True

    def delete(self, k):
        assert self.root
        node = self.root.subtree_find(k)
        assert node
        ext = node.subtree_delete()
        if ext.parent is None: self.root = None
        self.size -= 1
        return ext.item

A: Wikipedia defines an in-place algorithm as follows:

In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However, a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. An in-place algorithm updates its input sequence only through replacement or swapping of elements.

So one of the properties of an algorithm that is called "in-place" is that it does not copy all input values into an newly allocated data structure. If an algorithm creates a binary search tree (like AVL), for which node objects are created that are populated with the input values, then it cannot be called in-place by the above definition, even if at the end of the process the values are copied back into the input array.
As a comparison, heap sort does not have to create a new data structure, as the input array can be used to reorganise its values into a heap. It merely has to swap values in that array in order to sort it. It is therefore an in-place algorithm.


Q: Unhandled exception is not being caught by the handlers We have registered for the unhandled exceptions in the following way. The application is a remoting server. If an unhandled exception is thrown from the remoting server it is not handled by the unhandled exception handlers. What could be the problem?
[STAThread]

[Obfuscation(Exclude = true)]
static void Main(string[] args)
{

    Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
    .
    .
    .

    Application.EnableVisualStyles();
    Application.Run(form);

}

A: Hope this method helps you 'Application.SetUnhandledExceptionMode'. It instructs the application how to respond to unhandled exceptions.
static void Main(string[] args)
{

    Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    Application.EnableVisualStyles();
    Application.Run(form);

}

A: If it's a remoting server and the exception is happening as part of client interaction, then the exception will be sent to the client without causing the server to crash.


Q: OPENSSL error: could not find native static library `C`, perhaps an -L flag is missing? I get the following error when I try to run the below code for a DTLS client server program using rust through visual studio code and its terminal. I have already installed openssl libraries using vcpkg and set the environment variables. I have also installed the c/c++ extensions for vscode.
Error: error: could not find native static library C, perhaps an -L flag is missing?

How do I resolve this error? My DTLS code is given below along with build.rs and cargo.toml
MAIN.rs
use openssl::ssl::SslMethod;
use std::{
io::{Read, Write},
net::UdpSocket,
thread,
time::Duration,
};

use udp_dtls::{Certificate, DtlsAcceptor, DtlsConnector, Identity, SrtpProfile};
use udp_dtls::{DtlsAcceptorBuilder, UdpChannel};

fn main() {
let buffer = include_bytes!("../test/identity.p12");
let identity = Identity::from_pkcs12(buffer, "mypass").unwrap();

let root_ca = include_bytes!("../test/root-ca.der");
let root_ca = Certificate::from_der(root_ca).unwrap();

let acceptor = DtlsAcceptor::builder(identity).build().unwrap();
let connector = DtlsConnector::builder()
    .add_srtp_profile(SrtpProfile::Aes128CmSha180)
    .add_srtp_profile(SrtpProfile::AeadAes256Gcm)
    .add_root_certificate(root_ca)
    .build()
    .unwrap();

let server = UdpSocket::bind("127.0.0.1:0").unwrap();
let client = UdpSocket::bind("127.0.0.1:0").unwrap();

let server_addr = server.local_addr().unwrap();
let client_addr = client.local_addr().unwrap();

let server_channel = UdpChannel {
    socket: server,
    remote_addr: client_addr,
};

let client_channel = UdpChannel {
    socket: client,
    remote_addr: server_addr,
};

let guard = thread::spawn(move || {
    let mut dtls_server = acceptor.accept(server_channel).unwrap();

    let mut count = 0;

    while true {
        let mut received = [0; 5];

        dtls_server.read_exact(&mut received);

        println!(
            "{:?} {:?}",
            count,
            String::from_utf8_lossy(received.as_ref())
        );

        count = count + 1;
        thread::sleep(Duration::from_millis(2));
    }
});

let mut dtls_client = connector.connect("foobar.com", client_channel).unwrap();

while true {
    let mut buf = [0; 5];

    let buf = b"hello";
    dtls_client.write_all(buf);

    thread::sleep(Duration::from_millis(30));
}
}

CARGO.toml
[package]
name = "udp-dtls"
version = "0.1.0"
authors = ["Timon Post <https://github.com/TimonPost>"]
edition = "2018"
description = "DTLS abstraction ontop of UDP"
repository = "https://github.com/TimonPost/udp-dtls"
documentation = "https://docs.rs/udp-dtls/"
license = "MIT"
keywords = ["DTLS", "UDP", "connection", "openssl", "ssl"]
exclude = ["target", "Cargo.lock"]
readme = "README.md"

[dependencies]
openssl = "0.10.19"
openssl-probe = "0.1.2"
log = "0.4.6"
bytes = "0.4.11"

[features]
vendored = ["openssl/vendored"]

BUILD.rs
use std::fs::File;
use std::io::Write;
use std::process::Command;
use std::env;
fn main() -> std::io::Result<()> {

if let Ok(v) = env::var("DEP_OPENSSL_VERSION_NUMBER") {
    let version = u64::from_str_radix(&v, 16).unwrap();

    if version >= 0x1_01_01_00_0 {
        println!("cargo:rustc-cfg=openssl111");
    }
}

let certs_dir = "src/certs";
let keys_dir = "src/keys";
let scratch_dir = "openssl-temp";
let server_ext = &format!("{}/server_ext", scratch_dir);
let client_ext = &format!("{}/client_ext", scratch_dir);

for dir in &[certs_dir, keys_dir, scratch_dir] {
    // create if dir does not exist
    match std::fs::create_dir(dir) {
        _ => {}
    }
}

let mut file = File::create(server_ext).unwrap();
file.write(b"basicConstraints=CA:false\nkeyUsage=critical,keyEncipherment")?;

let mut file = File::create(client_ext).unwrap();
file.write(b"basicConstraints=CA:false\nkeyUsage=critical,digitalSignature")?;

// Generate self-signed CA
Command::new("openssl")
    .args(&[
        "req",
        "-x509",
        "-newkey",
        "rsa:2048",
        "-subj",
        "/CN=ca",
        "-nodes",
        "-keyout",
        &format!("{}/ca-key.pem", keys_dir),
        "-out",
        &format!("{}/ca-cert.pem", certs_dir),
        "-addext",
        "keyUsage=critical,keyCertSign",
    ])
    .output()?;

// Generate server key and CSR
Command::new("openssl")
    .args(&[
        "req",
        "-newkey",
        "rsa:2048",
        "-subj",
        "/CN=server",
        "-nodes",
        "-keyout",
        &format!("{}/server-key.pem", keys_dir),
        "-out",
        &format!("{}/server-csr.pem", scratch_dir),
    ])
    .output()?;

// Sign server CSR
Command::new("openssl")
    .args(&[
        "x509",
        "-req",
        "-CAcreateserial",
        "-CA",
        &format!("{}/ca-cert.pem", certs_dir),
        "-CAkey",
        &format!("{}/ca-key.pem", keys_dir),
        "-in",
        &format!("{}/server-csr.pem", scratch_dir),
        "-out",
        &format!("{}/server-cert.pem", certs_dir),
        "-extfile",
        server_ext,
    ])
    .output()?;

// Generate client key and CSR
Command::new("openssl")
    .args(&[
        "req",
        "-newkey",
        "rsa:2048",
        "-subj",
        "/CN=client",
        "-nodes",
        "-keyout",
        &format!("{}/client-key.pem", keys_dir),
        "-out",
        &format!("{}/client-csr.pem", scratch_dir),
    ])
    .output()?;

// Sign client CSR
Command::new("openssl")
    .args(&[
        "x509",
        "-req",
        "-CAcreateserial",
        "-CA",
        &format!("{}/ca-cert.pem", certs_dir),
        "-CAkey",
        &format!("{}/ca-key.pem", keys_dir),
        "-in",
        &format!("{}/client-csr.pem", scratch_dir),
        "-out",
        &format!("{}/client-cert.pem", certs_dir),
        "-extfile",
        client_ext,
    ])
    .output()?;

std::fs::remove_dir_all(scratch_dir)?;

Ok(())
}

For further reference please check this link for full code: https://github.com/TimonPost/udp-dtls


Q: Wordpress if logged out, Laravel if logged in Well, the title explains it well... I do use Laravel for a control panel and Wordpress as the frontend facing the "outside world".
I need to use the same URL for both, I've accomplished it partially processing Wordpress as a Laravel view, but I have troubles with the Laravel namespaces/autoload and the Wordpress functionality.
It's easy to do what I need with .htaccess considering default routes... But the main trouble is with the index. The idea is to have the / route with Wordpress by default and with Laravel when logged in. Any ideas?

A: Well, sadly nobody answered. But I did it. Simply I did use a cookie to know where am I.
On laravel's www/index.php
if($_COOKIE['laravel']||$_SERVER['REQUEST_URI']=='/login'){
    require __DIR__ . '/../private/bootstrap/autoload.php';
    $app = require_once __DIR__ . '/../private/bootstrap/start.php';
    $app->run();
}else{
    define('WP_USE_THEMES', true);
    require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' );
}

On controllers/UserController.php function login()
if(Input::has('remember'))
   setcookie ('laravel','yes!');
else
   setcookie ('laravel','right!',time()+60*60*24*30);

On controllers/UserController.php function logout()
setcookie('laravel', null, -1);

Hope it helps somebody :)


Q: maven download plugin to add downloaded resource to jar I am using download-maven-plugin to download some of resources to be used in my project. The download is successful and I can use the downloaded file.
However, what I want is to include the downloaded file in the JAR.
Note : The resource file will be included in the JAR when it was pre-downloaded before running the build, but if it is not present (e.g. deleted or I want to update it perhaps) the resource file is not included in the JAR.
Basically what I want is to include the recently downloaded file (from mvn clean install) in the output JAR.
        <plugin>
            <groupId>com.googlecode.maven-download-plugin</groupId>
            <artifactId>download-maven-plugin</artifactId>
            <version>1.4.0</version>
            <executions>
                <execution>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>wget</goal>
                    </goals>
                    <configuration>
                        <url>https://downloadurl</url>
                        <outputFileName>error.json</outputFileName>
                        <outputDirectory>${project.resources.dir}/commons</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Same thing happens when I use maven-ant-run plugin.
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>download-files</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <get src="https://downloadurl"
                                 dest="${project.resources.dir}/commons/data.json"
                                 verbose="true"
                                 usetimestamp="true"/>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: Just download it to ${basedir}/target/classes before packaging phase. You don't need it to be in sources in order to include it to JAR.

A: Solved!
I changed the phase to process-resources..
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>download-files</id>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <get src="https://downloadUrl"
                                 dest="${project.resources.dir}/commons/error.json"
                                 verbose="true"
                                 usetimestamp="true"/>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>


Q: Can not import copy_reg I am hosting my Web2py app on PythonAnyware and have an issue importing copy_reg which web2py apparently needs. In previous versions this was no issue.
The trace back is as follows:
Traceback (most recent call last):

File "/home/richdijk/web2py/gluon/restricted.py", line 220, in restricted
  exec ccode in environment
File "/home/richdijk/web2py/applications/im/models/db.py", line 78, in <module>
  auth.define_tables(username=False, signature=False)
File "/home/richdijk/web2py/gluon/tools.py", line 1784, in define_tables
   format='%(first_name)s %(last_name)s (%(id)s)'))
File "/home/richdijk/web2py/gluon/dal.py", line 8223, in define_table
   table = self.lazy_define_table(tablename,*fields,**args)
File "/home/richdijk/web2py/gluon/dal.py", line 8260, in lazy_define_table
   polymodel=polymodel)
File "/home/richdijk/web2py/gluon/dal.py", line 1122, in create_table
   sql_fields_old = pickle.load(tfile)
File "/home/richdijk/web2py/gluon/custom_import.py", line 92, in custom_importer
  return base_importer(pname, globals, locals, fromlist, level)
ImportError: No module named copy_reg

Does anybody know the resolution for this?
Thank you

A: For future reference:
Most often you should clear the cache and sessions. Use the appadmin interface to have a gui for this. This solved the issue for me more than once.
Sessions are pickled files which might lead to these problems. For example if you synchronize between different platforms, python versions and maybe sometimes even between upgrades on web2py (though i'm not certain on the latter).


Q: Run an activity in background I'm using an activity to get MMS attachment once a MMS is received. I have completed the MMS listener for this and it will call the activity, which will use getContentResolver() to grab the attachment. I want the activity to run in the background, without showing the empty UI to the user. Is there anyway to do it?

A: You will want to use a service to make this happen. It is basically an activity without a view.  Check out the link below for more info.
http://developer.android.com/guide/topics/fundamentals/services.html


Q: git reset --mixed delete newly added file? I'm working with git on Github with a C++ project.
I have done the following in this order:

*

*Codding existing and new .cpp and .h files. Also added a big .stl file.

*Add the new files to git

*Create commit "A" with this changes

*Tried to push commit "A" to Github. It didn't let me push the commit because a file of 121MB had been added, which is more than the Github limit.

*Used the git reset --mixed command so that I could undo the commit "A" containing the large file, add that file to .gitignore, and recreate a commit without that file.

Now the changes contained in files that were already tracked have remained and I can re-commit them, but the newly added files in commit "A" are all gone.
Isn't the git reset --mixed command just undoing the commits without changing the files?
Is there any way to recover these files that I had just added to git and that have been deleted?

A: Apparently, the action that hides behind your IDE's "reset commit" isn't git reset --mixed, and it resulted in files being deleted from your disk.

As said in the comments : you can use the reflog to find past commits.

*

*run git reflog to spot the sha for commit A (the faulty commit with the 121MB file)

*use whatever action you see fit to get files back from that commit :

*

*git reset A

*git checkout A -- file1 file2

*git restore -s A -W -- . or git restore -s A -W -- file1 file2

*...


Q: how can i add an attribute onClick oto my links generated automatically? I would like to add an attribute onClick to my links generated automatically with jquery.
I select the parent div and then search if it has a link child, then add the attribute onClick.
It works on localhost but not on server
there is my code :
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function () {
    if ($(this).children('a').hasClass('holder_notify_drop_link')) {
        $(this).on('click', function (e) {
            var url = $(this).children('a').attr('href');
            $(this).children('a').attr('onClick', "openFrame('" + url + "','yes')");
            e.preventDefault();
        });
    };)
};

How can i do this ?

A: Make sure you include jQuery:

IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {

$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
  e.preventDefault();
});
};
)};

});

A: Here's a working example http://jsfiddle.net/g248G/.
HTML:

    Stackoverflow.com

        Google.com

Javascript:
function openFrame(URL, option) {
    window.open(URL);
}

$(document).ready(function() {

    $('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
        $(this).children('a').each(function() {
            var $link = $(this);
            if ($link.hasClass('holder_notify_drop_link')) {
                var URL = $link.attr('href');
                $link.on('click', function(event) {
                    event.preventDefault();
                    openFrame(URL, 'yes');
                });
            }
        });
    });

});

A: Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
    ev.preventDefault();

    openFrame($(this).prop('href'), 'yes');
});


Q: Difference between 2 DTD tag I want to know what is difference between this 2 ELEMENT tag :
<!ELEMENT bank (account*, customer*, depositor*)>

and
<!ELEMENT bank (account | customer | depositor )*>

thanks.

A: In a nutshell, the first ELEMENT declaration is saying the child elements have to be in a specific order. The second ELEMENT declaration is saying the child elements can be in any order.
The following means: a bank element containing zero or more account elements, followed by zero or more customer elements, followed by zero or more depositor elements. (In that specific order.)
<!ELEMENT bank (account*, customer*, depositor*)>

The following means: a bank element containing zero or more account or customer or depositor elements (in any order).
<!ELEMENT bank (account | customer | depositor )*>

The ',' means "followed by" and the '|' means "or". The '*' means zero or more. Also, a '+' means one or more (at least one).

A: It denotes a regular expression. Though I'm not very good at that, I think the second  tag accepts sub-element of either account or customer or depositor.


Q: Parsley Form Validation Error Okay,
I'm still a javascript student so I need some help. I'm using parsley.js for form validation and then jquery ajax to submit the form. I keep getting this luke warm message in the console to bind parsley to an existing element. I've followed all the instructions but continue to get  a warning.
How can I get rid of the warning?
Code can be seen here: http://madmen6raphics.com/clients/marble/
thanks in advance.
Here is the code:
HTML:
<form action='mail_form.php' data-parsley-validate id='newsletter_signup' method='post' name='newsletter_signup' novalidate>
            <fieldset>
              <legend>Joing our mailing list!</legend>
              name:
              <input data-parsley-minlength='5' id='name' name='name' placeholder='John Doe' required type='text'>
              email:
              <input id='email' name='email' placeholder='johndoe@me.com' required type='email'>
              <input name='Submit' type='submit'>
            </fieldset>
          </form>

javascript:

$('#newsletter_signup').parsley();

A: You are getting two errors of

You must bind Parsley on an existing element.

but those errors are not related to the code you posted.
In your ...js/site.js you have the following code:
$(document).ready(function() {
    $('.slider').flexslider({controlNav: false,slideshowSpeed: 3000,directionNav: true});
    $('input').iCheck({checkboxClass: 'icheckbox_square-yellow',radioClass: 'iradio_square-yellow',increaseArea: '20%'});
    $('#newsletter_signup').parsley();
    $('#request_a_quote').parsley();
    $('#contact').parsley();
    var form = $('#newsletter_signup');
    (...)

You are binding parsley to three elements with the following ids: newsletter_signup, request_a_quote and contact.
The thing is, in the current page you only have the element newsletter_signup. If you do a console.log($('#request_a_quote')) you will see an empty object.
So, to fix your issue, you need to remove the code that binds parsley to non-existent elements. Or you could change your code in order to bind parsley only if the element exist. Something like this:
$(document).ready(function() {
    $('.slider').flexslider({controlNav: false,slideshowSpeed: 3000,directionNav: true});
    $('input').iCheck({checkboxClass: 'icheckbox_square-yellow',radioClass: 'iradio_square-yellow',increaseArea: '20%'});
    if ($('#newsletter_signup').length > 0 )
        $('#newsletter_signup').parsley();
    if ($('#request_a_quote').length > 0 )
        $('#request_a_quote').parsley();
    if ($('#contact').length > 0 )
        $('#contact').parsley();
    var form = $('#newsletter_signup');
    (...)


Q: WPF DataGrid selected row stays highlighted even when user clicks another control Is it possible to turn off the selected row highlighting when a user clicks another control in the window?
Thanks in advance.

A: You could set the SelectedIndex to -1 in the LostFocus event, thus losing the selected item and removing the highlight.


Q: Quickstart.py - failed to connect to all addresses I installed the Python libraries on my local PC, I also added my GA-4 Property ID. When I attempt to run the script I get the following error, note that the error actually makes sense because the IP Address failing doesn't have a valid SSL certificate:
Traceback (most recent call last):
  File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 72, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 946, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 849, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.UNAVAILABLE
        details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED"
        debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED {grpc_status:14, created_time:"2022-11-28T18:41:22.060505311+00:00"}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 51, in <module>
    sample_run_report("")
  File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 43, in sample_run_report
    response = client.run_report(request)
  File "\\usalbodd01\bod_Share\BODS_Tools\google\analytics\data_v1beta\services\beta_analytics_data\client.py", line 511, in run_report
    response = rpc(
  File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\gapic_v1\method.py", line 154, in __call__
    return wrapped_func(*args, **kwargs)
  File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 74, in error_remapped_callable
    raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED

Have any of you run into this when attempting to run the quickstart.py script locally?
Regards,
Greg
I attempted to run the script after following the "TODOS". I installed the Google certificates locally. I then tested the IP Address the script is failing on, the address is not secured.
Your connection isn't private
Attackers might be trying to steal your information from 142.250.190.10 (for example, passwords, messages, or credit cards).
NET::ERR_CERT_AUTHORITY_INVALID


Q: mootools Fx.slide not working IE6 I have some javascript that is built on top of mootools that is basically giving a div some show/hide functionality.
window.addEvent('domready', function(){
/*var mySlide = new Fx.Slide('customise_text').hide()
var mySlide2 = new Fx.Slide('customise_link').hide()
$('customise').addEvent('click', function(e){
    $('customise').addClass('active');
    mySlide.toggle(); //show-hide login panel
    mySlide2.toggle(); //show-hide login panel
    e.preventDefault();
});*/

/*$('moodal_close').addEvent('click', function(){
    alert("1");
});*/
//alert("hello")
var vertical_slide = $('vertical_slide');
var checkoutVerticalSlide = $('vertical_slide_checkout');
var v_toggle_checkout = $('v_toggle_checkout');

if(!vertical_slide || !checkoutVerticalSlide || !v_toggle_checkout) {
    return;
} else {

    var status = {
        'true': 'open',
        'false': 'close'
    };
    //-vertical
    var myVerticalSlide = new Fx.Slide('vertical_slide').hide();
    $('v_toggle').addEvent('click', function(e){
        e.preventDefault();
        myVerticalSlide.toggle();
    });

    // When Vertical Slide ends its transition, we check for its status
    // note that complete will not affect 'hide' and 'show' methods
    myVerticalSlide.addEvent('complete', function() {
        if(status[myVerticalSlide.open] == 'open')
        {
            $('v_toggle').addClass('open');
        } else {
            $('v_toggle').removeClass('open');
        }
    });

    var checkout_status = {
        'true': 'open',
        'false': 'close'
    };

    var checkoutVerticalSlide = new Fx.Slide('vertical_slide_checkout').hide();
    $('v_toggle_checkout').addEvent('click', function(e) {
        e.preventDefault();
        checkoutVerticalSlide.toggle();
    });

    checkoutVerticalSlide.addEvent('complete', function() {
        if(status[checkoutVerticalSlide.open] == 'open')
        {
            $('v_toggle_checkout').addClass('open');
        } else {
            $('v_toggle_checkout').removeClass('open');
        }
    });
}

In IE6 I get page loaded with errors and get an error of Object does not support this method or property

A: This could be due to the fact that IE6 does not support the preventDefault method.
Where you make use of this method (e.preventDefault()), replace the call with the following
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }

See if that works for you :)
While it feels warm and fuzzy to be able to support all browsers, IE6 is not a warm and fuzzy kind of browser. You will keep running into problems if you want to fully support IE6, I'm afraid.


Q: Pandas merge columns, but not the 'key' column This may seem like a stupid question, but this has been bugging me for some time.
df1:
imp_type    value
1           abc
2           def
3           ghi

df2:
id          value2
1           123
2           345
3           567

Merginge the 2 df's:
df1.merge(df2, left_on='imp_type',right_on='id')

yields:
imp_type    value    id    value2
1           abc      1     123
2           def      2     345
3           ghi      3     567

Then I need to drop the id column since it's essentially a duplicate of the imp_type column. Why does merge pull in the join key between the 2 dataframes by default? I would think there should at least be a param to set to False if you don't want to pull in the join key. Is there something like this already or something I'm doing wrong?

A: I agree it would be nice if one of the columns were dropped. Of course, then there is the question of what to name the remaining column.
Anyway, here is a workaround. Simply rename one of the columns so that the joined column(s) have the same name:
In [23]: df1 = pd.DataFrame({'imp_type':[1,2,3], 'value':['abc','def','ghi']})

In [27]: df2 = pd.DataFrame({'id':[1,2,3], 'value2':[123,345,567]})

In [28]: df2.columns = ['imp_type','value2']

In [29]: df1.merge(df2, on='imp_type')
Out[29]:
   imp_type value  value2
0         1   abc     123
1         2   def     345
2         3   ghi     567

Renaming the columns is a bit of a pain, especially (as DSM points out) compared to .drop('id', 1). However, if you can arrange for the joined columns to have the same name from the very beginning, then df1.merge(df2, on='imp_type') would be easiest.


Q: Inno Setup for Windows service? I have a .Net Windows service. I want to create an installer to install that windows service.
Basically, it has to do the following:

*

*Pack installutil.exe (Is it required?)

*Run installutil.exe MyService.exe

*Start MyService

Also, I want to provide an uninstaller which runs the following command:
installutil.exe /u MyService.exe

How to do these using Inno Setup?

A: Here's how i did it:
Exec(ExpandConstant('{dotnet40}\InstallUtil.exe'), ServiceLocation, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

Apparently, Inno setup has the following constants for referencing the .NET folder on your system:

*

*{dotnet11}

*{dotnet20}

*{dotnet2032}

*{dotnet2064}

*{dotnet40}

*{dotnet4032}

*{dotnet4064}

More information available here.

A: You can use
Exec(
    ExpandConstant('{sys}\sc.exe'),
    ExpandConstant('create "MyService" binPath= {app}\MyService.exe start= auto DisplayName= "My Service" obj= LocalSystem'),
    '',
    SW_HIDE,
    ewWaitUntilTerminated,
    ResultCode
    )

to create a service. See "sc.exe" on how to start, stop, check service status, delete service, etc.

A: You don't need installutil.exe and probably you don't even have rights to redistribute it.
Here is the way I'm doing it in my application:
using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;

static void Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        string parameter = string.Concat(args);
        switch (parameter)
        {
            case "--install":
                ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                break;
            case "--uninstall":
                ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                break;
        }
    }
    else
    {
        ServiceBase.Run(new WindowsService());
    }
}

Basically you can have your service to install/uninstall on its own by using ManagedInstallerClass as shown in my example.
Then it's just matter of adding into your InnoSetup script something like this:
[Run]
Filename: "{app}\MYSERVICE.EXE"; Parameters: "--install"

[UninstallRun]
Filename: "{app}\MYSERVICE.EXE"; Parameters: "--uninstall"

A: If you want to avoid reboots when the user upgrades then you need to stop the service before copying the exe and start again after.
There are some script functions to do this at Service - Functions to Start, Stop, Install, Remove a Service

A: have a look at topshelf
http://topshelf-project.com/

*

*it lets you develop your service as a console application

*adds a start/stop service as an API to your service...

*... that you can call from InnoSetup
[Run] Filename: "{app}\myservice.exe"; Parameters: "stop"  ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "uninstall" ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "install -description ""myservice""" ; Flags : waituntilterminated


Q: libpcap or PF_PACKET? I understand this question has been discussed many times: Should I use libpcap or PF_PACKET (the data link socket) to capture packets?
Based on my research, libpcap is suggested over PF_PACKET almost everywhere, mainly due to its portability.
However, for my current project (which is used in a production system), portability is not a concern at all, all I care about is performance (speed, packet loss ratio). My program is running on CentOS 5.10 (kernel 2.6.18)
As far as I know, libpcap put a timestamp on each packet. Does this cause big performance loss?
Are there other factors that make libpcap unsuitable in a high-speed network?

A:
As far as I know, libpcap put a timestamp on each packet.

No, libpcap gets a timestamp for the packet from the OS packet capture mechanism that it uses - which, on Linux is...
...PF_PACKET sockets.
The Linux kernel time stamps incoming packets.  PF_PACKET sockets have multiple ways of reading from them:

*

*regular socket receives, for which you can either get a time stamp with an explicit ioctl (so you can avoid fetching it to userland, but you can't avoid the kernel time stamping the packet in the first place; libpcap, when using regular socket receives, always asks for the time stamp);

*memory-mapped access, which always supplies the time stamp.

Libpcap uses memory-mapped access whenever it's available; if you care about capture performance, you probably want to do so as well.  It's not easy to use, however.


Q: How to use python to export the bake image form blender I want to make some operationi automatic.But I met some trouble in export the image after I bake it.At first I try to use "bpy.ops.object.bake_image()" to bake the image.But the result image can not be active in uv editor.
The bake was success,but the result image didn't appear in the uv editor.It need selected so that I could export the file.
So I search the document ， and found the other command "bpy.ops.object.bake()".It have a parameter "save_mode",but I still met some obstacle in using this command.It always point me out that " RuntimeError: error: No active image found in material "material" (0) for object "1.001" ".
Here is the official document about this two command:
https://docs.blender.org/api/blender_python_api_2_78a_release/bpy.ops.object.html?highlight=bake#bpy.ops.object.bake
Can anyone try to give me some solution or some advice that how can I make this thing right.

A: Many of blenders operators require a certain context to be right before they will work, for bpy.ops.image.save() that includes the UV/Image editor having an active image. While there are ways to override the current context to make them work, it can often be easier to use other methods.
The Image object can save() itself. If it is a new image you will first need to set it's filepath, you may also want to set it's file_format.
img = bpy.data.images['imagename']
img.filepath = '/path/to/save/imagename.png'
img.file_format = 'PNG'
img.save()