text:
Q: Getting Started with Unit Testing
Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:

*

*Running the tests becomes automate-able and repeatable

*You can test at a much more granular level than point-and-click testing via a GUI

Rytmis

My question is, what are the current "best practices" in terms of tools as well as when and where to use unit testing as part of your daily coding?
Lets try to be somewhat language agnostic and cover all the bases.

A: The so-called xUnit framework is widely used. It was originally developed for Smalltalk as SUnit, evolved into JUnit for Java, and now has many other implementations such as NUnit for .Net. It's almost a de facto standard - if you say you're using unit tests, a majority of other developers will assume you mean xUnit or similar.

A: A great resource for 'best practices' is the Google Testing Blog, for example a recent post on Writing Testable Code is a fantastic resource. Specifically their 'Testing on the Toilet' series weekly posts are great for posting around your cube, or toilet, so you can always be thinking about testing.

A: Ok here's some best practices from some one who doesn't unit test as much as he should...cough.

*

*Make sure your tests test one
thing and one thing only.

*Write unit tests as you go. Preferably before you write the code you are testing against.

*Do not unit test the GUI.

*Separate your concerns.

*Minimise the dependencies of your tests.

*Mock behviour with mocks.

A: You might want to look at TDD on Three Index Cards and Three Index Cards to Easily Remember the Essence of Test-Driven Development:
Card #1. Uncle Bob's Three Laws

*

*Write no production code except to pass a failing test.

*Write only enough of a test to demonstrate a failure.

*Write only enough production code to pass the test.

Card #2: FIRST Principles

*

*Fast: Mind-numbingly fast, as in hundreds or thousands per second.

*Isolated: The test isolates a fault clearly.

*Repeatable: I can run it repeatedly and it will pass or fail the same way each time.

*Self-verifying: The Test is unambiguously pass-fail.

*Timely: Produced in lockstep with tiny code changes.

Card #3: Core of TDD

*

*Red: test fails

*Green: test passes

*Refactor: clean code and tests

A: The xUnit family are the mainstay of unit testing. They are integrated into the likes of Netbeans, Eclipse and many other IDEs. They offer a simple, structured solution to unit testing.
One thing I always try and do when writing a test is to minimise external code usage. By that I mean: I try to minimise the setup and teardown code for the test as much as possible and try to avoid using other modules/code blocks as much as possible. Well-written modular code shouldn't require too much external code in it's setup and teardown.

A: NUnit is a good tool for any of the .NET languages.
Unit tests can be used in a number of ways:

*

*Test Logic

*Increase separation of code units.  If you can't fully test a function or section of code, then the parts that make it up are too interdependant.

*Drive development, some people write tests before they write the code to be tested.  This forces you to think about what you want the code to do, and then gives you a definite guideline on when you have acheived that.

A: Don't forget refactoring support. ReSharper on .NET provides automatic refactoring and quick fixes for missing code. That means if you write a call to something that does not exist, ReSharper will ask if you want to create the missing piece.


text:
Q: XNA breakout game new level (cant design new patterns of brick) Been having a problem with my breakout game. I have designed a single level and created a basic set of blocks. But I have no idea how to set up new patterns of blocks.
Here is a section of the code within loadcontent:
background = new Background(Content.Load<Texture2D>("prisonCell"));
            paddle = new Paddle(Content.Load<Texture2D>("bat"), screenBounds);
            ball = new Ball(Content.Load<Texture2D>("baseball"), screenBounds);
            brickTexture = Content.Load<Texture2D>("brick");
            menuScreen = Content.Load<Texture2D>("menuScreen");
            gameOverScreen = Content.Load<Texture2D>("gameOver");
            gill14 = Content.Load<SpriteFont>("Gill14");

            BuildWall();

            startGame();
        }

        public void BuildWall()
        {
            bricks = new Brick[brickRows * brickColumns];
            Color brickColour = Color.White;

            int brickCount = 0;

            int paddingTopViewport = brickTexture.Height/* * 3*/;

            for (int row = 0; row < brickRows; row++)
            {
                switch (row)
                {
                    case 0:
                        brickColour = Color.Red;
                        brickValue = 5;
                        break;
                    case 1:
                        brickColour = Color.Orange;
                        brickValue = 4;
                        break;
                    case 2:
                        brickColour = Color.Gold;
                        brickValue = 3;
                        break;
                    case 3:
                        brickColour = Color.Yellow;
                        brickValue = 2;
                        break;
                    case 4:
                        brickColour = Color.Green;
                        brickValue = 1;
                        break;
                    case 5:
                        brickColour = Color.Blue;
                        brickValue = 1;
                        break;

                }

                brickValue = 1;

                for (int column = 0; column < brickColumns; column++)
                {
                    bricks[brickCount] = new Brick(brickTexture,
                    new Rectangle(column * brickTexture.Width,
                    paddingTopViewport + row * brickTexture.Height,
                    brickTexture.Width, brickTexture.Height),
                    brickColour, brickValue);

                    brickCount++;
                }
            }
        }

        private void startGame()
        {
            paddle.SetStartPaddlePosition();

            ball.SetStartBallPosition(paddle.Bounds);
            foreach (Brick brick in bricks)
                brick.IsActive = true;
        }

A: If you want to make designing the level easy, define the layout in a text file with the correct number of columns.  Use a fixed space font and use a different character for each colour/texture you want to support.
Then you can read in the text file and construct the wall.  It makes tweaking a lot easier than trying to code different wall designs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clicking MDI children form doesn't bring it to front This is a winform question in .net.
In a MDI form, if I open several children forms, for some forms, if they are not activated (if you overlap them with the activate one, they are not up to front. Only the activate form is up to front.), clicking them don't bring them to front. This is even true if I click controls on them, such as a textbox. The textbox gets focus and you can intput things, but that form is still not activated.
Interestingly enough, this is not the case for all the children forms I created. Some forms behave correctly but others don't. Did I do something wrong?
I think the correct behavior is that, everytime I click a form, bring it up to front.
Thank you for any suggestion.

A: childForm.MdiParent = Me
childForm.WindowState = FormWindowState.Maximized
childForm.Show()
childForm.Focus()

A: try this
childForm.ShowDialog(Me)


text:
Q: Effects of inner painting in the temperature of room which room will stay warmer for long time in winter night. The room with inner painting black or white?

A: It will make no measurable difference.
Heat in a room is lost by conduction and convection - not (in significant amounts) by radiation.
Radiative heat transport occurs between two objects at different temperatures, so the surface of the wall would have to be colder than the rest of the (objects in the) room for radiative transport to take place.
Assume a black sphere in the middle of the room at temperature $T_1$, and a wall at $T_2$. If the walls are "black" (maximum emissivity at the wavelengths of interest - note this is not just black in the visible since most thermal radiation is in the far IR) we can compute the rate of heat loss as
$$Q = \sigma(T_2^2-T_1^2)\pi r^2$$
For a wall at 0C and a sphere at 20 C, this results in heat transport of about 100 $\rm{W/m^2}$ from the object to the (perfectly black) walls. In reality there are not walls on all sides - so the solid angle is smaller and the rate of heat transport is less - and furthermore the walls are not that cold. Because if they were, there would be significant heat transport from the air.
For this you can refer to this engineering toolbox link. With a very modest rate of air flow you will have a heat transfer of about 20 W per square meter per degree of temperature difference. This would quickly result in a heating up of the wall surface to "something close" to the temperature in the room - at which point the radiative losses are even smaller.
It may already be obvious from the above but let me spell it out: radiative cooling would (very slightly) affect objects in the room; but the air has very little radiative interaction.
At "normal" temperatures, and with a house that is somewhat insulated, you can ignore the radiation component. This is not necessarily true if you have a flimsy tent - you may have come across the aluminized Mylar "emergency blankets" that provide radiative insulation. They do make a difference when that's all there is between you and a cold dark clear sky. Not the same thing at all.

A: The scientific fact is that white reflects the radiant energy rays of the sun and black absorbs them.
Most major paint manufacturers can tell you the Light Reflectance Value (LRV) of any color paint chip. White reflects 80% of the light, black 5%.
So if you want to have a warmer room paint it black since more of the radiant energy of the light will be absorbed to keep the room warmer.


text:
Q: How to make a Javascript AJAX function (w/ JQuery) to work with onclick? I was wondering what the best way was the handle creating a generic javascript function that makes an AJAX request and calling it with 'onclick', keeping in mind I need the loaded ajax results to still work with this function. Also, I'm using JQuery and PHP. Something along the lines of:
<a href="#" onclick="postLike(<?php echo $post_id; ?>);">Like Post

Doesn't seem to work for me though.
Thanks!

A: The best way is binding functions to onclick (or .click in jQuery) event by jQuery .bind, .live or .delegate functions.

A: I'm not sure what your problem is, but this is how I would handle it.  Note that this avoids the issue when the post id is alphanumeric since it appends it to the href and extracts it from there.  Note that the it starts hidden and is displayed only if javascript is enabled (which is required to make it work anyway).
To find your problem you should consider adding an error handler and using Firefox/Firebug to view the requests (and responses) as they are made.
<a class="like" href="#<?php echo $post_id; ?>");" style="display: none'">Like Post

An alternative to support both javascript/non-javascript enabled browsers
Note: your backend code needs to be able to distinguish between AJAX and non-AJAX requests.  Note you can do this using the X_REQUESTED_WITH header (HTTP_X_REQUESTED_WITH) added by jQuery when making AJAX calls.  It is possible to spoof so be careful how you use this check -- like not basing any authentication or authorization decisions on it.  When you get an AJAX request, just return the HTML snippet.  For non-AJAX you'll need to render the entire page again.
<a class="like" href="/domain/likes/like/<?php echo $post_id; ?>");">Like Post

A: First of all if you are using jQuery, you don't need to use onclick attribute of anchor tag(it feels very obtrusive). try this syntax:
<a href="#" id="postLike" <other attributes>>Like Post

A: Here is what I normally do to fix this problem:
In your PHP, when you need to loop out the posts and generate the links, assign unique ids for the anchors, like this:
foreach ($posts as $post) {
    echo "Like Post";
}

Then in your JS code, you can do this:
$(document).ready(function() {
    $('.like-anchors').click(function() {
        var id = $(this).attr('id').substring(10);
        $.get("domain/likes/like/"+id, function(data) {
             $('#post-'+id+'-like').html(data);
        });
    });
});

Note

*

*You are not making use of post or any advance Ajax functions. $.get should be enough. Feel free to comment on this.

*Using href="javascript://" because I don't want the browser to scroll to top

*Even better, you can just assign a global id to the wrapper div, so you won't exhaust your ids. Says if I have post, content, and like button, I would do this:

PHP
<?php foreach($posts as $post): ?>
<div class="post-body" id="post-<?php echo $post['id'] ?>">

        Like This Post

<?php endforeach; ?>

JS
$(document).ready(function() {
    $('.post-like').click(function() {
        var parent = $(this).parent().parent();
        var id = parent.attr('id').substring(5);
        $.get("domain/likes/like/"+id, function(data) {
             parent.children('.post-content').html(data);
        });
    });
});

There are many ways to complete the task. These are just my 2 cents
Cheers


text:
Q: The sample DocuSign OAuth2 client (Java SpringBoot) web app is full of deprecated SpringSecurity classes, is DocuSign going to update these? I used the quickstart tool of DocuSign to generate a sample Java Spring-Boot project with authorization code grant flow, on exploring the code I am seeing a lot of classes that are deprecated by the Spring Security team.
For example, classes/interfaces used in WebSecurityConfig which is extending WebSecurityConfigurerAdapter class, viz. OAuth2ClientContext, OAuth2ClientAuthenticationProcessingFilter and more.
Is the DocuSign team going to update this tool for a more current version of the starter code soon? Furthermore, it would be really nice if a Readme file can be added explaining the sample project a bit.

A: Thank you Raj for pointing it out. We're working on it. Hope to have an update soon.
You can also fork the repo https://github.com/docusign/code-examples-java and make the change and even submit a PR if you want to help (this is open source repo).


text:
Q: Clickable image in WebGrid inside a Controller (via Ajax )? I'm using the MVC3 WebGrid inside my controller.I need to have an image in a column,such that when you click on that image, data is passed to an action inside any controller.I want to do this via Ajax, i.e. clicking on the image shouldn't cause a post back,it should be an Ajax call to an Action on some Controller.And I would like to pass an object (model), not any string,or int, or whatever).
public ActionResult AddInGrid(AjaxModel m)
        {
            if (Session["ajaxmodel"] == null)
            {
                Session.Add("ajaxmodel", a.am);
            }
            List<AjaxModel> list = (List<AjaxModel>)Session["ajaxmodel"];
            list.Insert(0, m);
            Session.Add("ajaxmodel", list);
            WebGrid g = new WebGrid(list);
            IHtmlString s = g.GetHtml();
            string s1 = s.ToString();
            return Json(new { text = s1 });
        }

What should be put inside of GetHtml() method??
EDIT: Here's what I've tried so far, and it isn't working:
I've found out what HTML renders on Ajax.ActionLink and tried to incorporate that
    WebGrid g = new WebGrid(list);
    string link = string.Format(@"Delete",item.fname);
 IHtmlString s = g.GetHtml(g.Columns(g.Column(format:link)));

A: @grid.GetHtml(
    columns: grid.Columns(
        grid.Column(
            columnName: "",
            format:
                @<text>
                    @Ajax.ActionLink(
                        "Delete",
                        "delete",
                        "home",
                        new AjaxOptions {
                            UpdateTargetId = "sometargetdiv",
                            InsertionMode = InsertionMode.Replace
                        }
                    )
                 </text>
        )
    )
)

As far as passing an entire model to the action is concerned, well, you could use the routeValues parameter and pass the different properties as query string parameters:
@Ajax.ActionLink(
    "Delete",
    "delete",
    "home",
    new {
        fname = item.fname,
        lname = item.lname
        .... and so on for each property you want to fetch back
    },
    new AjaxOptions {
        UpdateTargetId = "sometargetdiv",
        InsertionMode = InsertionMode.Replace
    }
)


text:
Q: Deploying a Java Web Service on a server I have been asked to create a JAVAX-WS web service which basically performs some basic computation on the input to return the output. I also need to lookup some values from a database.
I am using this book :
Java Web Services: Up and Running
What I've done so far :
1. Created the main java program containing the methods that perform the computations.
2. Used wsgen and wsimport to generate the various artifacts.
3. Used Endpoint to publish the service on localhost.
What I need to do :
I need to get it running on something like a windows server for .NET services. So that it can serve multiple machines.
I know next to nothing about web services and servers, and have just gone through the first chapter of the aforementioned book so far.
From what all resources I've gone through I believe I could use GlassFish, but I don't know if it serves my purposes.
So if anyone could point to some helpful resources for the same, it would be extremely helpful.
P.S : I have no idea about looking up the required values from the database, so please point to some resource for that as well.

A: Endpoint can also serve requests concurrently, you can enable thread pooling by creating a ThreadPoolExecutor and registering it with the endpoint. See Endpoint.setExecutor(Executor executor)
If you want to deploy your Web Service on GlassFish you should change it into a WAR project, see http://docs.oracle.com/javaee/6/tutorial/doc/bnayl.html


text:
Q: Does ice made out of salt water melt slower than ice made of pure water? I'm trying to make this whole bunch of ice bottles to cool down my little aquarium. What I want in the ice bottles is that, fter freezing the whole bottle full water into ice, I need the ice to melt as slowly as possible. My question is, will the ice melt slower if
the ice is made up of:

*

*Pure tap water

*Salt water (Salt mixing with water)

The reason I ask this because I was taught when I was young that sprinkling salt onto ice cubes will make it melt slower (it lowers the freezing point too.)
But I'm not sure if it is the same thing because this time the salt is mixed with the water.
Anybody could help me?

A: By shifting the melting point to a colder temperature, the surface of your salt water/ice will be below $0C$.  Assuming the environment is warmer than that, the temperature difference will be greater with the salt water ice bottle than the pure water ice.  This implies greater heat transfer and faster melting.
If you want it to melt more slowly, the simple answer would be to put a layer of insulation around the bottle.  The rate of melting is related to the rate of heat transfer.  This means your desire to melt as slowly as possible is equivalent to wanting it to cool the environment as slowly as possible.  Insulation will accomplish this.
You can think of your bottles as having almost a set amount of cooling power, rather like the amount of energy in a battery.  Adding salt doesn't increase the amount of cooling power.  You can slow down how fast the battery is used, but that doesn't make it more useful.  Here you can slow down how fast the ice melts, but that might not make it cool your aquarium more efficiently.

A: No, salt water does not (in that situation) seem to melt slower.  In more detail:
When you freeze the water, you make ice.
When you freeze salt water, you make ice, and (depending on details a bit) either concentrated brine or ice and salt crystals.  There is no (or very little) salt in the ice, it separates out into brine or salt.
OK?
Then, if you supply outside heat, the water will quickly warm to 0 C, and then slowly melt.  The water plus salt will start to melt at a lower temperature, as you suggest.  Since it starts to melt colder, heat will flow into it more quickly.  There will be a little less heat adsorbed per gram of water: there will be both the heat of fusion of water less the heat of solution and heat of mixing of the water with the salt.  This will also cause it to heat up more quickly, but "less effectively" - there will be a little less cooling of the rest of the world.

A: General principles
You should probably just run the experiment over the weekend, but here are the relevant bits of physics:
Typically, saltwater freezes at a lower temperature, so you will probably reach a point where your freezer no longer fully changes the state of the water to solid. You probably want the freezing to happen no matter what.
The reason that you probably want freezing no matter what is because the colder the bottle gets, the faster it will exchange heat with the aquarium. The heat flow will be proportional to the difference in temperatures. Ice has this really nice property that it forms and melts all at one temperature, so you do not have to increase the rate at which cold is pouring out of the system in order to store more coldness in the system. That's a big win.
Whether the water should be salted or not depends heavily on the temperature of your freezer, among other things. Water has about twice the specific heat of ice, so that suggests that you want as much water-stage as possible. So you have two competing things here: first off that the heat transfer is greater for a lower freezing temperature, pushing the freezing temperature up; second, that the water holds more heat than the ice will, pushing the freezing temperature down.
Calculating the maximum time.
The model that you want is something like: from temperature $T_0$ to $T_f$, we have ice; then from temperature $T_f$ to $0~^\circ\text{C}$ we have liquid, then we assume that the water and saltwater will heat up the same amount from then on. Your aquarium is at some temperature $T_1$ and so the heat exchange will go like $\frac{dq}{dt} = k (T_1 - T)$ for some unknown $k$, leading to temperature changes due to $q = c m T$ where $m$ is the mass and $c$ is the specific heat capacity per unit mass. Curves are then looking like $T_\tau(t) = T_1 - (T_1 - \tau) e^{-kt/(cm)}.$
From $T_0$ to $T_f$ requires a time $t_0$ such that $T_{T_0}(t_0) = T_f;$ solving this yields: $$ t_0 = \frac{m ~ c_\text{ice}}{k} ~\log\left(\frac{T_1 - T_0} {T_1 - T_f}\right).$$ Then there is some heat of fusion $h_f$ with timescale $t_f$ given simply by $ m ~h_f = k (T_1 - T_f) t_f,$ so that:$$t_f = \frac{m~h_f}{k (T_1 - T_f)}.$$Finally, heating up to $0~^\circ C$ takes a time$$t_1 = \frac{m ~ c_\text{water}}{k} ~\log\left(\frac{T_1 - T_f} {T_1 - 0~^\circ C}\right).$$The total time is $t^* = t_0 + t_f + t_1$ which is maximized independently of $m/k$ by setting its derivative to zero,$$\frac{k}{m} \frac{dt^*}{dT_f} = \frac {c_\text{ice}} {T_1 - T_f} + \frac{h_f}{(T_1 - T_f)^2} - \frac {c_\text{water}} {T_1 - T_f} = 0$$This is solved by $T_f = T_1 - h_f / (c_\text{water} - c_\text{ice}).$
Now of course the addition of salt will change these parameters, but it's important to see the order of magnitude of what we're talking about here. This critical temperature $T^* = h_f / (c_\text{water} - c_\text{ice})$ is something like (300 kJ/kg) / (200 kJ (kg °C)) ~= 1.5 °C: it is tiny in comparison to $T_1$.
This means that the extra heat capacity gotten from shifting the temperature at which the water freezes is tiny in comparison to the higher heat transfer: you want to push this temperature as high as possible rather than as low as possible. So you want no salt.
What else can you do?
The absolute simplest way to make the ice last longer is to lower the parameter $k$ above. The easiest way to do this is to get some air between the ice and the water. Those foam pads that one wraps around beers might work best for this, but they might also pollute the water and/or be eaten slowly by fish. You might instead try a zip-lock bag or even a combination of the two. Of course, then you will need to weight the bag down so that it stays in the water.

A: To a simplified, less dichotomous version of the question, that is, "Which melts faster? Ice from mostly pure water or ice from a salt water solution?"
Would a layman-friendly answer not be:
"It depends a great deal on the temperature outside of the ice"? (This is the same as saying the two different solutions have different specific freezing/melting temperatures and therefore different rates of melting at different temperatures, only less technical and more applicable for the layman).
Examples of the scope and scale involved if needed:
If it is just barely over approximately 21 degrees fahrenheit, ice from relatively pure water does not melt as it has a melting point of 32 degrees, while ice from "ideal" (lowest possible salt water freezing temperature) salt water will start to melt. Therefore, under these circumstances, salt water melts faster than "pure" water. Between 21 and 32 degrees is an ideal time to apply salt to ice on roads and sidewalks. Applying it at lower temperatures will be a waste of salt unless the temperatures increase soon while the salt remains. Applying at higher temperatures than 32 could still help with specific patches of ice where temps locally reach 21 to 32 but could otherwise be fairly inefficient, used to melt what is already melting.
If it is well over 21 degrees, say room temperature, there may well be a difference, in either direction, in part dependant on the volume and shape of the ice, in part dependant on the specific solution being frozen and temperature respective solutions are frozen at, but it could be relatively insignificant as it is well over the freezing/melting points of both "pure" water and salt water. Therefore, here, they could melt seemingly at the same rate or either/or depending on other factors.
If it is under 21 degrees, both will stay frozen solid. Therefore, neither is melting, so in a sense they are both (not) melting at the same rate. (You can experience this in the winter when attempting to melt ice with salt but it is about 10 below...doesn't really work as expected given salt's reputation!).
If the salt solution is frozen at just under 21 degrees but the "pure" water is frozen at only just under 32 degrees, and both are out in, say, 40 degree temperatures at the same time, it may very well be that the salt water melts considerably slower than the "pure" water, but having more to do with their respective temperatures at beginning of melt (21 and 32 -- easy to gauge if you check the respective solutions in the freezer every 10 minutes waiting for them to become solid ice) than their melting/freezing rates assuming same temperature of frozen solution at beginning of melt (say 20 and 20 -- hard to gauge without precise thermometer and thermostat control, as "pure" water ice at 32 and "pure" water ice at 21 will both be frozen solid and thus mostly indistinguishable). Therefore, occassionally "pure" water melts faster than salt water.

A: Fast and slow are rate of temperature changes
But most cooling situations we want the most heat (energy) removal values
and that is in Joules or BTU for a given mass.
That value is based on the heat of fusion for phase change from solid to liquid, plus the heat for heating the liquid above freezing, and heating the solid below freezing.  For water, the phase change energy is about 75 times the specific heat of water. For simplification we can neglectg the small amount of energy involved in heating the liquid or the solid in the narrow range of typical cooling (refrigerating foods etc) and look at the  energy in the phase change.
I believe that potable water will have a heat of fusion of 333 J/gm.  So most of the cooling will occur at a steady temperature of 0C.
I also believe that gel and other forms of package ice, have a freezing temperature of less than 0C....which means the temperature plateau will occur at a lower than 'water freezing'.  Also the additives generally lower the heat of fusion, meaning that they are have less cooling capacity per unit (mass).  Two issues here.
A.  From a purely theromdynamic cooling need, Ice is better than gels, for a given mass.  It would be the cheaper form considering shipping weight.  There may be chemical systems that provide more capacity.
B.  If you have a product with water, that should not be frozen, then do not use gels as the temperature where the phase change energy absorbtion will occur below 'water freezing' temperature, possibly causing the product with water to freeze or solidify.  That is an issue in transporting medications  such as Insulin with water content, that can be damaged by 'freezing"


text:
Q: Return class labels and index from a pytorch dataloader I want to return class labels and index of each class from pytorch dataloader. The dataset I am using has 14 folders (i.e. 14 classes) and each folder has 100 images. I am using this code:
data_loader_train = torch.utils.data.DataLoader(
    dataset_train,
    sampler=sampler_train,
    batch_size=args.batch_size,
    num_workers=args.num_workers,
    pin_memory=args.pin_mem,
    drop_last=False,
)

The link to this code is https://github.com/AnikChaudhuri/image-retrieval-transformers/blob/main/main.py
What changes do I need to make to return class labels and indexes?


text:
Q: efficient use of R data.table and unique() Is there a more efficient query than the following
DT[, list(length(unique(OrderNo)) ),customerID]

to refine a LONG format table with customer id's, order number and product line items, meaning that there will be duplicate rows with the same order id if a customer has purchased more than 1 item in that transaction.
Trying to work out unique purchases. length() gives a count of all order id's by customer ID including duplicates, looking for just the unique number.
Edit from here:
Here is some dummy code. Ideally what i am looking for is the output from the first query using the unique().
df <- data.frame(
             customerID=as.factor(c(rep("A",3),rep("B",4))),
             product=as.factor(c(rep("widget",2),rep("otherstuff",5))),
             orderID=as.factor(c("xyz","xyz","abd","qwe","rty","yui","poi")),
             OrderDate=as.Date(c("2013-07-01","2013-07-01","2013-07-03","2013-06-01","2013-06-02","2013-06-03","2013-07-01"))
             )

DT.eg <- as.data.table(df)
#Gives unique order counts
DT.eg[, list(orderlength = length(unique(orderID)) ),customerID]
#Gives counts of all orders by customer
DT.eg[,.SD, keyby=list(orderID, customerID)][, .N, by=customerID]

         ^
         |
  This should be .N, not .SD  ~ R.S.

A: if you are trying to count the number of unique purchases per customer, use
 DT[, .N, keyby=list(customerId, OrderNo)][, .N, by=customerId]

A: As of version 1.9.6 (on CRAN 19 Sep 2015), data.table has gained the helper function uniqueN() which is equivalent to length(unique(x)) but much faster (according to data.table NEWS).
With this,
DT.eg[, list(orderlength = length(unique(orderID)) ),customerID]

and
DT.eg[,.N, keyby=list(orderID, customerID)][, .N, by=customerID]

can be rewritten as
DT.eg[, .(orderlength = uniqueN(orderID)), customerID]

   customerID orderlength
1:          A           2
2:          B           4


text:
Q: Get current position of servo with MicroPython on a Raspberry Pi Pico I am running MicroPython on a Raspberry Pi Pico. I can set the position of the servo by changing the duty cycles:
from machine import Pin, PWM

servo = PWM(Pin(0))
servo.freq(50)
servo.duty_u16(1350) # sets position to 0 degrees

I may have missed something, but I have read through the docs and couldn't find any way to read the current position of the servo. Is there any way to do this?

A: Most servos do not provide any sort of position information. You know what the position is because you set it. You can write code that will keep track of this value for you. For example,  something like:
from machine import Pin, PWM

class Servo:
    min_duty = 40
    max_duty = 1115

    def __init__(self, pin):
        servo = PWM(Pin(pin))
        servo.freq(50)
        self.servo = servo

        self.setpos(90)

    def setpos(self, pos):
        '''Scale the angular position to a value between self.min_duty
        and self.max_duty.'''

        if pos < 0 or pos > 180:
            raise ValueError(pos)

        self.pos = pos
        duty = int((pos/180) * (self.max_duty - self.min_duty) + self.min_duty)
        self.servo.duty(duty)

You would use the Servo class like this:
>>> s = Servo(18)
>>> s.pos
90
>>> s.setpos(180)
>>> s.pos
180
>>> s.setpos(0)
>>> s.pos
0
>>>

In your question, you have:
servo.duty_u16(1350)

I'm suspicious of this value: at 50Hz, the duty cycle is typically between 40 and 115 (+/1 some small amount at either end), corresponding to ≈ 1ms (duty=40) to 2ms (duty=115).


text:
Q: Clear memory when new ViewController is presented I have some buttons in my app interface that act like this
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextVC = storyBoard.instantiateViewControllerWithIdentifier("customVC") as! customVC
self.presentViewController(nextVC, animated:true, completion:nil)

When user presses them - the new ViewController is shown and everything is ok except one thing - I think that previous ViewController is still in memory. How can i clear it?

A: try this,
  self.presentViewController(vc, animated: true, completion: {() -> Void in
        self.dismissViewControllerAnimated(false, completion: { _ in })

Hope this will help :)

A: To avoid jump in animations I use this code:
self.setViewControllers([New_View_Controller_Class()], animated: true)


text:
Q: Run python script from PyCharm. Import in Pycharm It seems like Pycharm 1.5.3 makes some magic, or I missed something.
I have following file structure:
/sp
/sp/tools.py
/sp/test/main.py

Files contain following code
main.py:
__author__ = 'username'
import tools
import sys

def test1():
    print locals()
    print globals()
    print sys.path
    print test1

if __name__ == '__main__':
    test1()

tools.py:
class SettingsDictionary(dict):
    def __init__(self, seq, **kwargs):
        dict.__init__(self, seq, **kwargs)

When I run main.py this is written in console:
C:\Python27\python.exe D:/Workspace/Python/sp/test/main.py
{}
{'test1': <function test1 at 0x0143D0B0>, '__warningregistry__': {("Not importing directory 'C:\\Program Files\\JetBrains\\PyCharm 1.5.3\\helpers\\tools': missing __init__.py", <type 'exceptions.ImportWarning'>, 2): True}, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'D:/Workspace/Python/sp/test/main.py', '__author__': 'p.grechishkin', 'sys': <module 'sys' (built-in)>, '__name__': '__main__', '__package__': None, 'tools': <module 'tools' from 'D:\Workspace\Python\sp\tools.pyc'>, '__doc__': None}
['D:\\Workspace\\Python\\sp\\test', 'C:\\Python27\\lib\\site-packages\\simplejson-2.1.6-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\django_staticfiles-1.1.2-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\django_appconf-0.4-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\suds-0.4-py2.7.egg', 'C:\\Program Files\\JetBrains\\PyCharm 1.5.3\\helpers', 'D:\\Workspace\\Python\\sp', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\win32', 'C:\\Python27\\lib\\site-packages\\win32\\lib', 'C:\\Python27\\lib\\site-packages\\Pythonwin']
<function test1 at 0x0143D0B0>

Process finished with exit code 0

I don't understand why import function knows about this module 'tools': .
When I run this script from windows cmd - everything is okay. I get 'ImportError: No module named tools'

A: The import work in the example you provided because your python path contains D:\\Workspace\\Python\\sp which is where your tools module is.
When you run a module from standard python interpreter, it only adds the path to current module in sys.path.

A: You're missing an __init__.py in the /sp directory.  Create a file with that name, and you should be able to import.


text:
Q: How to make a Batch File Move another File? I am trying to make a batch script that moves a file into a startup folder and I want to make it universal
Currently I have this but I want to make it work on any user's computer (C:\users\USERNAME)
Here is the code
@echo off
color A0

echo Startup...
echo Startup..
echo Startup.
echo Startup
echo Startup.
echo Startup..
echo DONE
echo your name is %name%

move C:%user%\Desktop\Directory 1\dile.txt C:%user%\Desktop\Directory 1\file folder 1

:end
cmd /k

The file is called dile.txt located in a folder called Directory 1 on the desktop and I want to make it move to a folder called file folder 1 inside the Directory 1 folder. Is there a way to do this while making it work on anyone's computer?

A: %USERNAME% can be used to grab the active user account. Try something like this. Make sure to enclose paths in quotes when folders have spaces in their names.
@echo off
color A0

echo Startup...
echo Startup..
echo Startup.
echo Startup
echo Startup.
echo Startup..
echo DONE
echo your name is %USERNAME%

move "C:\Users\%USERNAME%\Desktop\Directory 1\file.txt" "C:\Users\%USERNAME%\Desktop\Directory 1\file folder 1\"

:end
cmd /k

A: Just for the sake of providing something a little bit different:
@Echo Off & SetLocal EnableExtensions
Set /P "=Startup . " 0< NUL
For /L %%G In (1,1,5) Do (Set /P "=. " 0< NUL
    %SystemRoot%\System32\PATHPING.EXE 127.0.0.1 -n -q 1 -p 500 1> NUL)
Echo(&Echo Your name is %UserName%
%SystemRoot%\System32\Robocopy.exe "%UserProfile%\Desktop\Directory 1" "%UserProfile%\Desktop\Directory 1\file folder 1" "dile.txt" /Mov 1> NUL 2>&1
Pause

This uses some animated text, %UserProfile%, instead of C:\Users\%UserName%, and robocopy instead of Move. Using RoboCopy, allows for the creation of your destination directory, if it does not already exist.


text:
Q: Titanium - iOS App internalization I would like to clarify some points concerning the "iOS App internalization"
This is my situation (the app.xml is for internalization the name of the app)

*

*If the language of the device is set to (for example) German , in this case the language set to the app is English

*If i have only the it folder , and the language of the device is set to (for example) German , in this case the language set to the app is Italian
So everything is right . ( or not? )
Now , the important point is : how to change the default language of the app (the default language is set to en - english). I searched for a solution ( for now no one had a solution , i looked everywhere , but i haven't found a solution) , and i think i found the solution now.
Adding this key to the tiapp.xml
<ios>
    <plist>
        <dict>
            <key>CFBundleDevelopmentRegion</key>
            <string>it_IT</string>
        </dict>
    </plist>
</ios>

In this way, following the point 1 , now the language is set to it - italian and not to en - english


text:
Q: change the who of google calendar event with gdata framework $gdataCal= new Zend_gdata_calendar($client);
//on retrouve l'event a partir de eventURL stocké lors de la création
$event = $gdataCal->getCalendarEventEntry($id_event);
$who= $gdataCal->newWho();// $who objet de type Zend_Gdata_Extension_Who

//les nouvelles valeurs du who
$email ="cn21lqqt8jeb9qgulpra6bj948%40group.calendar.google.com";
$rel = 'http://schemas.google.com/g/2005#event.organizer'  ;
$valueString ='alain developpeur';
$who->setEmail($email);
$who->setRel($rel);
$who->setValueString($valueString);
//$who->setDom($who_old[0]->getDOM());//bizarre mais???
//méthode magic ou setteurs
//$event->who= array($who);
$event->setWho($who);
//on affiche les propriétés du nouveau who pour voir les changements

echo'
lemail  est   :  '.$who->getEmail();

echo'
la value string est   :  '.$who->getValueString();

echo'
la rel est   :  '.$who->getRel();

//on sauve on spécifie le type de classe dans lequel on veut sauver
// $event->save(Zend_Gdata_EventEntry);???

 $event->save(Zend_Gdata_App_Entry);

A: Not sure what do you wish to know because of your comments on French. To share event with $email you should use:
$who = $gdataCal->newWho();
$who->setEmail($email);
$newEvent->setWho(array($who));


text:
Q: Easy to use PNG lib? Could someone recommend me a simple, easy to use PNG library either for c++ or .NET? All it needs to do is: load big PNG images (say 20000x20000), and tell me what color each pixel has.
Bitmap class in .NET can't load big images, throws an OutOfMemory exception.
I spent reasonable time on google looking through c++ libs, but all of them does much more than I need, and their usage is too complicated for me.

A: The defacto standard library for PNG files is LibPNG.  It's not the best designed API in the world, but if you just work through the steps in one of their tutorials, it's pretty hard to mess up.
You'll probably find it easiest to wrap their API in a few simple functions (or class) of your own.  Once you have that done, you should be good to go.

A: Try this:
http://nothings.org/stb_image.c
You can use it instead of zlib aswell.

A: If C# is an option, try PNGCS. It was done (by myself, in Java originally) for this scenario, it allows you to read and write line by line, no need to have all data in memory.
I have tested that it can read and write huge files (30000 x 30000 pixels, more than 2GB in disk), at least in Java

A: For C++:
Depending on the license you are able to use you may have a look at:
DeVIL: http://openil.sourceforge.net/(a bit outdated but a still good choice) (Linux, Win)
ImageMagick: http://www.imagemagick.org/script/index.php (well maintained, all platforms)
both support a variety of input and output formats.
EDIT: now also on Github: https://github.com/DentonW/DevIL


text:
Q: Newbie Java: creating and writing a txt file with numbers in word format? Getting ready for my first exam in Java and having a certain problem with a method. The following problem is just one method of four that will be combined into a single Java file.

Problem:
Write the code to create a new file called "exam1.txt" and print the
following text to the file:
Line OneLine TwoLine Three

This is what I have so far:
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class problem2 {

    public static void main(String[] args) throws FileNotFoundException {
        String exam1 = "Exam1.txt";

        PrintWriter printWriter = new PrintWriter(exam1);
        for(int n = 0; n < 4; n++){
            printWriter.printf("Line %d\n", n);
        }
        printWriter.close();

    }

}

What I'm stuck on is figuring out how to convert the numbers into the actual words; for example, "1" into "One". Was my choice of the for loop even correct for this problem? I know how to do it the long way by printing out each line but figured I'd learn the correct way.

A:
What I'm stuck on is figuring out how to convert the numbers into the
  actual words.

Here is code to convert number to word. This will help you
import java.util.Scanner;

class NumberToString
{

    public enum hundreds {OneHundred, TwoHundred, ThreeHundred, FourHundred, FiveHundred, SixHundred, SevenHundred, EightHundred, NineHundred}
    public enum tens {Twenty, Thirty, Forty, Fifty, Sixty, Seventy, Eighty, Ninety}
    public enum ones {One, Two, Three, Four, Five, Six, Seven, Eight, Nine}
    public enum denom {Thousand, Lakhs, Crores}
    public enum splNums { Ten, Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen}
    public static String text = "";

    public static void main(String[] args)
    {
        System.out.println("Enter Number to convert into words");
        Scanner sc = new Scanner(System.in);
        long num = sc.nextInt();
        int rem = 0;
        int i = 0;
        while(num > 0)
        {
            if(i == 0){
                rem = (int) (num % 1000);
                printText(rem);
                num = num / 1000;
                i++;
            }
            else if(num > 0)
            {
                rem = (int) (num % 100);
                if(rem > 0)
                    text = denom.values()[i - 1]+ " " + text;
                printText(rem);
                num = num / 100;
                i++;
            }
        }
        if(i > 0)
            System.out.println(text);
        else
            System.out.println("Zero");
    }

    public static void printText(int num)
    {
        if(!(num > 9 && num < 19))
        {
            if(num % 10 > 0)
                getOnes(num % 10);

            num = num / 10;
            if(num % 10 > 0)
                getTens(num % 10);

            num = num / 10;
            if(num > 0)
                getHundreds(num);
        }
        else
        {
            getSplNums(num % 10);
        }
    }

    public static void getSplNums(int num)
    {
        text = splNums.values()[num]+ " " + text;
    }

    public static void getHundreds(int num)
    {
        text = hundreds.values()[num - 1]+ " " + text;
    }

    public static void getTens(int num)
    {
        text = tens.values()[num - 2]+ " " + text;
    }

    public static void getOnes(int num)
    {
        text = ones.values()[num - 1]+ " " + text;
    }
}

A: There's no "right" way to do this, but I would recommend that you separate the concerns here, as that's generally good practice as you get into higher-order methods.  You're trying to do two things here: convert an int into a String, and then format the resulting String(s) into a series of lines written into a file.  Put each of those pieces of functionality into separate methods: one that converts ints to their String representation (however you end up implementing that), and one that does all the file-writing stuff and calls the int-conversion method in the process.
And I disagree with @arshajii's statement that maybe you should just write three println() statements, which would duplicate functionality (the formatting of the printf() statement would be duplicated) while co-mingling the concerns.  I might well do that in some code I write in the real world (depending on the situation), but that's not how I'd approach an exam in an intro to programming course, and it's not the general mindset I'd suggest for a student just learning good development practices.
As far as the actual problem that I know you're asking (how do I turn the ints into their corresponding String value), since you have a short, well-defined set of values, you could use a switch statement...


text:
Q: Search youtube channel for specific video id's I have a large array of video id's. (Over 100) I need to determine which videos belong to the oauth'd user. Looking through the Youtube API docs it doesn't look like they have a way to get videos by ID for a channel. I see how to get all videos for a channel but that looks like it limits the results. Is there an efficient way to do this that I'm missing?
Ideally I'd like to say grab all videos with this id that belong to this channel. I'd accept a way to just get all videos for the users channel so I can compare the array of videos with my array of id's.
Using Laravel socialite and the PHP google api client.

A: You can either

*

*Get videos by IDs using the videos:list API endpoint. The id parameter takes up to 50 comma-separated videoIDs.

or

*Get all videos in a channel using the channels:list API endpoint. The id parameter takes up to 50 comma-separated channelIDs. Each page of results has up to 50 videos.

If you already have the videoIDs, option 1 would be best.

A: I have figured it out if you want to get the video with particular video id
https://www.youtube.com/watch?v=hcMzwMrr1tE

if you want the thumbnails for the particular video
https://storage.googleapis.com/yt-trends-top-ten-lists-2022/thumbs/**hcMzwMrr1tE**.jpg
put the video id you will get the details you can use google api like this


text:
Q: My Powerlevel10k doesn't work right (I use omz) usually the powerlevel10k configurator asks you what style of powerlevel10k you want to run (lean classic etc.) when you press p10k configure. They didn't present me those options instead my they just asked me some other questions like if I wanted to display time and so on.
After that they defaulted my terminal to this:

Why doesn't it look like the usual powerlevel10k? And why doesn't it show me my icons even though I installed their MesloLGS Nffont

A: From the Powerlevel10k FAQ:

Some prompt styles are missing from the configuration wizard
[snip]
If there is no UTF-8 locale on the system, configuration wizard won't offer prompt styles that use
Unicode characters. Fix: Install a UTF-8 locale. Verify with locale -a.
[snip]

Command locale -a lists all installed locales. If you run it, you'll notice that there is no UTF-8 locale. So you need to install one. How you do that depends on your OS. Google "Install locale on your OS".


text:
Q: What is the best way to keep javascript libraries up-to-date in rails? I am currently develoing a Rails application which makes heavy use of some javascript libraries, including jquery, backbone.js and d3.js. For jquery, there is the jquery-rails gem, for backbone, we have backbone-rails. But nothing like this exists for d3.js.
I copied the javascript from d3.js to my repository, this feels a bit unclean to me though, because when d3 gets updated, I have to copy it again (and I have to notice, that d3 got updated!). I thought about git submodules, but I have to pull them manually every time I check out the repository. May be there is way to let bundler check out a specific release of the d3 repository?
How do you handle updating third-party javascript libraries in rails? Is there a preferred way?

A: Not sure why you got downvoted for this...
But I'm going to have to agree with the comment that says to do it manually.  I wouldn't leave it out of your repository - no call for that; you want to keep your current version around - but I'd not recommend having it update automatically.
That's for stability.  If you make "heavy use" of JS like you say, a quirk - or even a bugfix for a bug you worked around - in the latest version of a library could play havoc with your code.  We got bit by something like this when jQuery tweaked how it treated attr() and prop() between two versions.
So if you always update your libraries manually:

*

*You always know when they change, and that you have to do some thorough testing before making the changes public.

*You can stay with an older version of the library if you want to - for performance, or to give you time to work around the latest quirks, or whatever.

Hope that helps!

A: Why not create a d3-rails gem if there isn't one?  The convention now seems to be to put these javascript libraries in their own gems with jquery-rails now included in Rails 3.1. It's more work now but it might payoff for you down the road.  You would be helping the community and it would make for easy updates within your app.


text:
Q: Подключить сетевой каталог Стоит у меня Dr. Web на рабочей машине ubuntu, хочу проверить файлы на рабочем сервере debian 7, как мне к нему подключиться? смонитровать сетевую папку, что бы DW увидел этот каталог.

A: Предположим, что доступ к серверу есть, а это значит, что есть доступ по ssh. Если его нет, лучше его получить.
Создайте где-нибудь (например, в домашнем каталоге) папку, пусть это будет "share". Потом в консоли пишите
sshfs [user@]host:[dir] ~/share

[user@]host Вы должны знать, иначе как к серверу подключаетесь. dir - каталог для проверки. просто / указывать крайне не рекомендую.
Может так случится, что sshfs нет, тогда его всегда можно доставить - apt install sshfs.
Все, теперь просто проверяете папку как обычную.

*

*NB1: если подключение к серверу не по локалке (а к примеру сервер где то далеко), будет сильно тупить.

*NB2: лучше снести антивирь с  рабочей машины - он скорее всего бессмысленный.

*NB3: для проверки серверов есть другие способы (в зависимости от провеямого материала).

Если вдруг нет доступа, нужно добавить себя в группу fuse
sudo usermod -aG fuse <username>


text:
Q: Delete Files Without Popup's Using Delphi I am using the below code to delete the contents of a folder, the only issue I have now is that if 1 of the files is in use, it pops a confirmation dialog, and then starts showing the progress to the user of the software.
Since these are temp files user's are completely baffled by the popup and keep asking about it.
Is there some way to tweak it, so that if a file is in use or cannot be deleted, that the code will just move on to the next file and ignore this one until the next attempt.
Code
procedure DelFilesFromDir(Directory, FileMask: string; DelSubDirs: Boolean);
var
  SourceLst: string;
  FOS: TSHFileOpStruct;
begin
  FillChar(FOS, SizeOf(FOS), 0);
  FOS.Wnd := Application.MainForm.Handle;
  FOS.wFunc := FO_DELETE;
  SourceLst := Directory + '\' + FileMask + #0;
  FOS.pFrom := PChar(SourceLst);
  if not DelSubDirs then
    FOS.fFlags := FOS.fFlags OR FOF_FILESONLY;
  FOS.fFlags := FOS.fFlags OR FOF_NOCONFIRMATION;
  SHFileOperation(FOS);
end;

A: In order to avoid showing any dialog when an error is encountered, you should add FOF_NOERRORUI as an additional flag.
Also, if you want to hide information about the file operation progress entirely, you can add the FOF_NO_UI flag instead.
You can read more about the possible flags in the official SHFileOperation() documentation.


text:
Q: .htaccess mod-rewrite conditional statements and sending GET request? Not necessarily a problem, just something that I am not yet knowledgeable enough to do. I have an .htaccess file that I am using for url rewriting. This is what I have now.
ErrorDocument 404 /inc/error_documents/404.php
ErrorDocument 503 /inc/error_documents/503.php

# For security reasons, Option followsymlinks cannot be overridden.
#Options +FollowSymLinks
Options +SymLinksIfOwnerMatch
RewriteEngine ON

RewriteRule ^home$ /index.php [nc]
RewriteRule ^(about|contact|giving-tree)/?$ /$1.php [nc]

RewriteRule ^giving-tree/([0-9+]?)/?$ giving-tree.php?ageBegin=$1 [nc]
RewriteRule ^giving-tree/([0-9+]?)/([0-9+]?)/?$ giving-tree.php?ageBegin=$1&ageEnd=$2 [nc]
RewriteRule ^giving-tree/([0-9+]?)/([0-9+]?)/([0-9+]?)/?$ giving-tree.php?ageBegin=$1&ageEnd=$2&page=$3 [nc]

What I want to be able to do is make some of the parts in the 3 bottom rules optional. I know that I can accomplish this with RewriteCond, but I'm not sure how. What I need is basically this:
RewriteCond %{HTTP_HOST} ^hearttohandparadise.org/giving-tree
RewriteRule /beginAge-([0-9+]) #make it send GET request with beginAge as the variable
RewriteRule /endAge-([0-9+]) \?beginAge=$1 #make it send GET request with endAge as the variable

etc... etc...
Is there any way to accomplish this just by relying on .htaccess? or am I just fantasizing?
Forgive me is I sound stupid.

A: No, it's a perfectly valid idea. You'd basically want to allow the user to write the URI in an unstructured manner, without a strict order imposed, right? Like, I could write giving-tree/page-6/endAge-23?
If so, this is what you're looking for:
RewriteRule /beginAge-([0-9]+) giving-tree.php?beginAge=$1 [QSA,NC]
RewriteRule /endAge-([0-9]+) giving-tree.php?endAge=$1 [NC,QSA]
RewriteRule /page-([0-9]+) giving-tree.php?page=$1 [NC,QSA]

You see, if any part of the URI matches the expression "/beginAge-([0-9]+)", it'll be redirected to giving-tree.php?beginAge=$1; the magic is done by the QSA, Query String Append, option, which, well, appends any existing query string to the resulting URI. So as more and more matches are found and more and more GET parameters added, the query string just grows.
If you want a stricter thing, where some parameters are optional, but their order is fixed, then it's uglier by magnitudes:
RewriteRule /(beginAge-)?([0-9]+)/?(endAge-)?([0-9]+)?/?(page-)?([0-9]+)? giving-tree.php?beginAge=$2&endAge=$4&page=$6 [NC]

I just made everything optional by using the ? operator. This one may use some prettifying/restructuring.
(Alternatively, you could just do this:
 RewriteRule ^giving-tree/([^/]+)/?$ process.php?params=$1 [nc]

That is, grabbing the entire part of the URI after the giving-tree part, lumping the whole thing into a single parameter, then processing the thing with PHP (as it's somewhat better equipped to string manipulation). But the first version is certainly more elegant.)
By the way, are you sure about the ([0-9+]?) parts? This means "One or no single character, which may be a digit or the plus sign". I think you meant ([0-9]+), i.e. "one or more digit".


text:
Q: Используя || вывести сообщение об ошибке если пользователь не введет возраст или нажмет отмену Используя || вывести сообщение об ошибке если пользователь не введет возраст или нажмет отмену. Через if или switch - легко, а через или - не пойму((
function error(){alert("Error!");}
function displayDate(age){
    var date = new Date();
 alert(`You year of birdth ${date.getFullYear() - age}`);
}
var age = Number(prompt("How are you old?"));
age==""||age==null||error();
displayDate(age);
// if(age==""||age==null){
//     alert("Error!");
// }
// else{
//     var date = new Date();
// alert(`You year of birdth ${date.getFullYear() - age}`);
// }

A: Вообщем вот решение:

function error() {
   return'Error!';
}
var age = Number(prompt("How are you old?")) || error();
console.log(age);

Все очень просто, если вы введете в prompt число, то вернет число, в случае отмены, ввода строки, пустоты, вернет то, что находится в error().

A: Странная задача конечно, как вариант можно сделать так :

const error = () => console.log("Error!")

const displayDate = age => console.log(`You year of birdth ${new Date().getFullYear() - age}`)

const doIt = () => {
  const age = +prompt("How are you old?")
  age && displayDate(age) || !age && error()
}

doIt()

A: Логическое ИЛИ в классическом программировании работает следующим образом: "если хотя бы один из аргументов true, то возвращает true, иначе – false". В JavaScript это не совсем так. Если значение не логического типа – то оно к нему приводится в целях вычислений. Например, число 1 будет воспринято как true, а 0 – как false. JavaScript вычисляет несколько ИЛИ слева направо. При этом, чтобы экономить ресурсы, используется так называемый «короткий цикл вычисления».
Допустим, вычисляются несколько ИЛИ подряд: a || b || c || .... Если первый аргумент – true, то результат заведомо будет true (хотя бы одно из значений – true), и остальные значения игнорируются.
Это особенно заметно, когда выражение, переданное в качестве второго аргумента, имеет сторонний эффект – например, присваивает переменную. При запуске примера ниже присвоение x не произойдёт:
var x;

true || (x = 1);

alert(x); // undefined, x не присвоен

…А в примере ниже первый аргумент – false, так что ИЛИ попытается вычислить второй, запустив тем самым присваивание:
var x;

false || (x = 1);

alert(x); // 1

Я думаю, вы должны вывести сообщение об ошибке тогда, когда
age == undefined
а не null.
А Ваш запрос должен выглядеть так:
undefined == age || error();


text:
Q: styling a table header with a border box this is the style I want for my table

The header row got a border at the bottom. And this is my table

table {
  border: 1px solid #bbbbbb;
}

th {
  border-bottom: 1px solid #bbbbbb;
}

    Col 1
    Col 2

    1.
    Foo

    2.
    Bar

As you can see, the horizontal line is dashed. How can I get a full line? I tried styling the header table row like

#header{
  border-bottom: 1px solid #bbbbbb;
}

    Col 1
    Col 2

but then nothing happens.

A: Edit your CSS so it looks like this:

table {
  border: 1px solid #bbbbbb;
  border-spacing: 0
}

th {
  border-bottom: 1px solid #bbbbbb;
}

    Col 1
    Col 2

    1.
    Foo

    2.
    Bar

The added part is border-spacing.


text:
Q: R, Confusion Matrix in percent In R how to get Confusion Matrix in percent (or fraction of 1).
The "caret" package provides useful function but shows absolute number of samples.
library(caret)
data(iris)
T <- iris$Species
P <- sample(iris$Species)
confusionMatrix(P, T)
Confusion Matrix and Statistics
             Reference
Prediction   setosa versicolor virginica
setosa         15         16        19
versicolor     19         16        15
virginica      16         18        16

A: The caret function is nice if you want all the summary statistics.  If all you care about is the 'percentage' confusion matrix, you can just use prop.table and table.  Also, for future reference, strictly programming questions should be posted to stackoverflow not CrossValidated.
prop.table(table(P,T))
> prop.table(table(P,T))
            T
P                setosa versicolor  virginica
  setosa     0.11333333 0.10666667 0.11333333
  versicolor 0.09333333 0.13333333 0.10666667
  virginica  0.12666667 0.09333333 0.11333333

If you would like to keep the summary statistics from caret, just you prop.table on the confusion matrix object.
prop.table(caret::confusionMatrix(P,T)$table)


text:
Q: Problem with installation of Gin via 'go get github.com/gin-gonic/gin' I am trying to install Gin but facing the following issues in the Ubuntu terminal:
/go/src$ go get github.com/gin-gonic/gin
package github.com/gin-gonic/gin: no Go files in /home/user/go/src/github.com/gin-gonic/gin

When I use -u the error is a bit another:
/go/src$ go get -u github.com/gin-gonic/gin
package github.com/gin-gonic/gin: directory "/home/user/go/src/github.com/gin-gonic/gin" is not using a known version control system

I tried a hard installation:
sudo apt-get install -y golang-github-gin-gonic-gin-dev

but there is a lot of inconvenience like lib/pq disappears when saving- mean mod.go doesn't permit installation and when running main.go in Gin project -> facing the following issue:
Lec13$ go run main.go
routes/routes.go:4:2: package Lec13/controllers is not in GOROOT (/usr/local/go/src/Lec13/controllers)

Maybe someone knows the way to figure this issue out?
Thanks in advance.

A: If you are sure go is installed in your system, you can try to add golang to your $path variables.
export PATH=$PATH:$HOME/go/bin

And then you can try again.


text:
Q: Require function not recognized after upgrade from node 12 to 14 I upgraded my node version from 12 to 14.5.0 (I needed to use es6 classes and syntax and I found that node 14 supports it) using this link
But when I try to run my node js app after the update it shows this :
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js command`

const path = require("path");
             ^

ReferenceError: require is not defined
    at file:///./NodeJsClient/app.js:1:14
    at ModuleJob.run (internal/modules/esm/module_job.js:140:23)
    at async Loader.import (internal/modules/esm/loader.js:162:24)
[nodemon] app crashed - waiting for file changes before starting...

Do I need to update nodemon or npm ? How do I fix this?
My npm verion is 6.14.5

A: nodejs is attempting to load your app.js file as an ESM module file, but it isn't an ESM module file - it's a CommonJS module file.  There is no require() in an ESM module file which is why you get the error.
Since your file is a CommonJS module, it seem likely that apparently have some directive that is telling node to try to load your file as an ESM module.  The most likely place that would be is in your package.json file where you should make sure you have:
type: "commonjs"

not
type: "module"


text:
Q: Comparando um elemento do array com uma string Preciso criar uma função que receba um array e compare com uma string, fora do array, retornando true se, e somente se, existir a ocorrência de pelo menos duas vezes da string fora do array. A saída deve ser semelhante a isso:
Str2(["a", "b", "a", "c"], "c");
//=> "false"

Str2(["a", "b", "a", "c"], "a");
//=> "true"

A função abaixo, deveria fazer isso, mas sempre retorna false".
var Str2 = function(strs, str){
    var i, a = 0;

    for(i=0; strs.length; i++){
        if (str == strs[i] ) {
            a = a + 1;
            if (a > 1) {return "true";}
            else {return "false";}
        }
    }
}

A: É só tirar o falsede dentro do laço. Se ele chegar na contagem de 2, ele pode encerrar a execução retornando true. Mas se ele não atingir essa condição, ele tem que ficar tentando até o fim, ele não pode retornar false dentro do laço. Se ele sair do laço, significa que a contagem nunca atingir 2, então pode retornar false.

let str2 = function(strs, str) {
    var a = 0;
    for (let i = 0; i < strs.length; i++) {
        if (str == strs[i]) {
            a++;
            if (a > 1) return "true";
        }
    }
    return 'false';
}
console.log(str2(["a", "b", "a", "c"], "c"));
console.log(str2(["a", "b", "a", "c"], "a"));

Coloquei no GitHub para referência futura.

A: O problema ai é que dentro da primeira execução ele verifica:
a > 1 ?

Mas na primeira execução nunca vai ser maior que 1, logo como você coloca o else. Ele sempre cai no else. O certo é verificar isso depois.
Segue exemplo https://jsfiddle.net/dk86foxb/
var Str2 = function(strs, str){
    var i, a = 0;
    for(i=0; i < strs.length; i++){
        if (str == strs[i] ) {
            a = a + 1;
        }
        if (a > 1) {
            return "true";
        }
    }
    return 'false';
}

A: Acho que na tua lógica o return false devia estar no final do loop, pois só aí vais saber que não há repetições.
Mas o teu problema é outro, é que tens esse loop com erros:
#1 - Deve ser i < strs.length; e não somente ; length;.
#2 - A primeira iteração vai ter o i com valor 1 e isso dá false em i > 1) então vai para o else...
Corrigido seria:
var Str2 = function (strs, str) {
    var i, a = 0;
    for (i = 0; i < strs.length; i++) {
        if (str == strs[i]) {
            a++;
            if (a > 1) return "true";
        }
    }
    return "false";
}

jsFiddle: http://jsfiddle.net/9xwajvrm/1/
Repara ainda noutro possível problema, é que estás a retornar Strings e não Booleanos. Nota que "false" e false não é a mesma coisa...
Tendo dito isto sobre o teu código eu sugiro usares o .filter() que faz exatamente o que queres. Assim:
var Str2 = function(strs, str){
    return strs.filter(function(el){
        return el == str;
    }).length > 1;
}

jsFiddle: http://jsfiddle.net/9xwajvrm/


text:
Q: Creating a location overlay on a MapView by pushing a button Currently, my app has a mapview that creates a new MyLocationOverlay in the onCreate function.
locationOverlay = new MyLocationOverlay(this, map);
locationOverlay.runOnFirstFix(centerAroundFix);
map.getOverlays().add(locationOverlay);

I'm trying to create a button that does this optionally, much like google maps.  This is what I have so far.
ImageButton locButton = (ImageButton)findViewById(R.id.googlemaps_select_location);

locButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        locationOverlay = new MyLocationOverlay(ctx, map);
        locationOverlay.runOnFirstFix(centerAroundFix);
        map.getOverlays().add(locationOverlay);
    }
});

The only thing I had to change was the 'this' to 'ctx'.  I set ctx = this in the onCreate() function.  I've also tried using getApplicationContext() instead of ctx
Using the debugger, I break on the onClick() function and can step through it.  After hitting run, I telnet to the emulator and use the geo fix command to issue a fix to the emulator.  Unfortunately, centerAroundFix() is never called.  Not sure what I'm doing wrong, here...

A: I resolved this by moving
locationOverlay = new MyLocationOverlay(ctx, map)
to the onCreate() function.
Perhaps locationOverlay get garbage collected if it's inside the onClick() function?


text:
Q: ReferenceError: Behance is not defined I am trying to start working with the Behance API, I have following scripts included:
bundles.Add(new ScriptBundle("~/x1").Include("~/scr/jquery.js", "~/scr/jqueryui.js",));
bundles.Add(new ScriptBundle("~/x2").Include("~/scr/backbone.js", "~/scr/underscore.js", "~/scr/be.js"));

In be.js:
Behance = {
api_url : 'http://www.behance.net/v2/',
api_key: 'asgasgasgasga9s8g…'
};

Then on my page I have this:
@Scripts.Render("~/x1")
@Scripts.Render("~/x2")

<script>
// Set your API key in be.js
//Behance.api_key = // have set this in be.js

// Users
BehanceUser = new Behance.UserModel({ user: 'UserName' });
BehanceUser.fetch();
BehanceUser.getProjects();
BehanceUser.getCollections();
BehanceUser.getWips();
</script>

But I am receiving following errors in my Chrome console:
Uncaught TypeError: Cannot call method 'each' of undefined
Uncaught ReferenceError: Behance is not defined

Can anybody tell me where I am making a mistake?


text:
Q: Cross server EXEC I have a several linked servers, with mass of DB's and tons of views and tables.
The database names are like random set of letters and numbers and does not make any sense for me.
Need to find on which server is certain view.
DECLARE @servers AS TABLE (srv_name NVARCHAR(300), srv_providername NVARCHAR(300), srv_product NVARCHAR(300), srv_datasource NVARCHAR(300), srv_pstring NVARCHAR(300), srv_location NVARCHAR(300), srv_cat NVARCHAR(300) );
INSERT INTO @servers EXEC sp_linkedservers

DECLARE @sql nvarchar(MAX) = N''

SELECT @sql +=
N'SELECT
    ''' + QUOTENAME(srv_name) + ''' AS [Server],
    QUOTENAME(name) AS [DB]
FROM ' + QUOTENAME(srv_name) + '.[master].[sys].[databases]
WHERE HAS_PERMS_BY_NAME(name, ''DATABASE'', ''SELECT'') = 1
UNION ALL
'
FROM @servers

SET @sql = LEFT(@sql, LEN(@sql) - 11);
EXEC @sql

And it fails on EXEC. Says that query is not valid, but if i copy-paste the query an run it - works well.
Need to perform this exec, to generate temp table w/ servers and available databases, to query sys.all_object of each DB on each server
The output on my localhost w/ 1 server
> (1 row(s) affected) Msg 203, Level 16, State 2, Line 17 The name
> 'SELECT
>     '[localhost]' AS [Server],
>     QUOTENAME(name) AS [DB] FROM [localhost].[master].[sys].[databases] WHERE HAS_PERMS_BY_NAME(name,
> 'DATABASE', 'SELECT') = 1 ' is not a valid identifier.

A: Same error I also made.
So just execute like this:
exec sp_executesql @sql


text:
Q: Custom UISlider Создаю кастомный слайдер для плеера. Назначил картинку для тумблера, но из за того, что он узкий, нельзя докрутить его до конца. Как убрать это ограничение?

A: убедитесь, что изображение обрезано так, как вам надо и нет прозрачных блоков. Другими словами, оно 3х10 а не 10х10


text:
Q: Linux Device Driver, kernel thread can't open file? I'm writing a Linux Driver with Linux Kernel Modules when, user can write and when user calls close, driver has to flush content into a file in another directory with same name of the device file.
I have this problem: when a process calls close, the driver can open a file and flush all its content correctly; when the process is killed (for example, from the terminal with a kill), device driver fails to execute filp_open becuse fs->CURRENT is set to NULL. So, I was trying to start a kernel thread to do this work.
When I try opening a file in the same directory, for example filp_open("myfile"...), it works correctly. But if I have to open a file in another directory, so filp_open("dirA/myfile"), filp_open returns -2. But this not going to happen when I call filp_open from the main thread.
This is my code:
static int thread_fn(void *unused){
  struct thread_data* td = (struct thread_data *) unused;
  if(td == NULL)
     printk(KERN_INFO "td is null\n");
  struct file* filp=filp_open("/dirA/myfile",O_RDWR,0666);
  if(filp == NULL || (IS_ERR(filp)))
    printk(KERN_INFO "filp is null!\n");
  else
    printk(KERN_INFO "filp is not null!\n");

  size_t filp_size = filp->f_inode->i_size;
  printk(KERN_INFO "size on release: %ld\n",filp_size);
  if(filp_size > td->size){
    printk(KERN_INFO "truncating file\n");
    truncate_setsize(filp->f_inode, td->size);
  }

  inode_lock(filp->f_inode);
  //file_write(filp,/*file->f_pos*/0,td->data,td->size);
  inode_unlock(filp->f_inode);

  printk(KERN_INFO "Thread Stopping\n");
  do_exit(0);
  return 0;
}

This is my device_release function:
static int device_release(struct inode *inode, struct file *file)
{
   if(my_data->buffer == NULL)
      return -ENOMEM;

  struct thread_data* td=alloc_mem(sizeof(struct thread_data));
  td->filename=my_data->filename;
  td->data=my_data->buffer;
  td->size=my_data->size;

  thread_st = kthread_run(thread_fn, (void *)td,"Thread!");
  if (thread_st)
    printk(KERN_INFO "Thread Created successfully\n");
  else
    printk(KERN_ERR "Thread creation failed\n");

  return 0;
}

What's the problem? I can't understand, it could be an OS problem? I have also tried with set_fs/get_fs but it didn't work.

A: I have an update: if I put flag O_CREAT, filp_open doesn't return error, but file isn't created; so, kernel thread cannot operate on file?


text:
Q: ANDROID STUDIO: I need help in converting a code in java that returns an int from MYSQL database into a string (SHAREDPREFERENCES) So, I have a database that returns 2 integer-type values (1 = USD  and 3 = GHS). I wrote an API PHP code that returns the integer values and would like to convert their corresponding String (USD and GHS) in Java.
The line of code that returns the int in java (android studio) is
creditnav.setText(SharedPrefManager.getInstance(MainActivity.this).getUser().getCurrency());

I would like to return the result of the above line of code into their corresponding strings.
How do I go about it? Any help would be much appreciated.

A: Try this
int currencyCode = SharedPrefManager.getInstance(MainActivity.this).getUser().getCurrency();
if (currencyCode == 1) {
    creditnav.setText("USD");
}
if (currencyCode == 3) {
    creditnav.setText("GHS");
}

A: You could edit the getCurrency() and add a switch/if else statement and return a string, or create another method getCurrencyString()
switch (currencyInteger) {
  case 1 :
      return "USD";

  case 2 :
      return "GHS";

  default:
      // Handle this
      break;
}

A: try to use this one if it may help you :).
 String creds=SharedPrefManager.getInstance(MainActivity.this).getUser().getCurrency();

if (creds.getText().toString.equals("1")) {
  creditnav.setText("USD");
}
else if (creds.getText().toString.equals("3")) {
   creditnav.setText("GHS");

}


text:
Q: How to feed the input images into ensemble of DNN models? I am trying to ensemble 5 transfer learning pre-trained DNN models (the base models trained on imagenet) using the code below
def define_stacked_model(members):
    # update all layers in all models to not be trainable
    for i in range(len(members)):
        model = members[i]
        for layer in model.layers:
            # make not trainable
            layer.trainable = False
            # rename to avoid 'unique layer name' issue
            layer._name = 'ensemble_' + str(i+1) + '_' + layer.name
    # define multi-headed input
    ensemble_visible = [model.input for model in members]
    # concatenate merge output from each model
    ensemble_outputs = [model.output for model in members]
    merge = concatenate(ensemble_outputs)
    hidden = tf.keras.layers.Dense(10, activation='relu')(merge)
    output = tf.keras.layers.Dense(1)(hidden)
    model = tf.keras.Model(inputs=ensemble_visible, outputs=output)
    # plot graph of ensemble
    plot_model(model, show_shapes=True, to_file='model_graph.png')

    # compile
    model.compile(optimizer='adam',
                   loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                   metrics=["accuracy"])
    return model

# define ensemble model
stacked_model = define_stacked_model(members)
stacked_model.summary()

each model accept input image with size 160X160.  I read the images using:
IMG_WIDTH=160
IMG_HEIGHT=160
def create_dataset(img_folder):

    img_data_array=[]
    class_name=[]

    for dir1 in os.listdir(img_folder):
        for file in os.listdir(os.path.join(img_folder, dir1)):

            image_path= os.path.join(img_folder, dir1,  file)
            image = cv2.imread( image_path, cv2.IMREAD_COLOR)
            image = cv2.resize(image, (IMG_HEIGHT, IMG_WIDTH),interpolation = cv2.INTER_AREA)
            image = np.array(image)
            image = image.astype('float32')
            image /= 255
            img_data_array.append(image)
            class_name.append(dir1)
    return img_data_array, class_name
# extract the image array and class name
img_data, class_name = create_dataset(TRAIN_DIR)

target_dict={k: v for v, k in enumerate(np.unique(class_name))}

target_val=  [target_dict[class_name[i]] for i in range(len(class_name))]
target_val = np.array(list(map(int,target_val))[0:300], np.float32)

note: I used 300 images only because of the availability of the memory.
after that I stacked the images using:
stacked_img_data = np.dstack([img_data[0:300],
                    img_data[0:300],
                    img_data[0:300],
                    img_data[0:300],
                    img_data[0:300]])

and finally trained the ensemble model using:
history = stacked_model.fit(x = stacked_img_data, y = target_val, epochs=10)

I faced this error:
ValueError: Layer model expects 5 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 160, 800, 3) dtype=float32>]

I think the above method is close to the correct way. but I am not sure how to solve the issue.

A: Well you can make this work only by changing this history = stacked_model.fit(x = stacked_img_data, y = target_val, epochs=10) to this
   history = stacked_model.fit(x = [img_data[0:300],img_data[0:300],img_data[0:300],img_data[0:300],img_data[0:300]], y = target_val, epochs=10)

That being said you can also do this
input = tf.keras.layers.Input(shape=(160,160,3))
ensemble_outputs = [model(input) for model in members]
.
.
model = tf.keras.Model(inputs=input, outputs=output)

and only pass the image one time


text:
Q: MySQL and the ST_IsValid function returns error I am running MySQL // Percona 5.7 and I added a Polygon to my table:
DROP TABLE IF EXISTS `test_table`;
CREATE TABLE `test_table` (`uid` int(11) unsigned NOT NULL AUTO_INCREMENT,`geom` geometry NOT NULL, PRIMARY KEY (`uid`), SPATIAL KEY `i_geomidx` (`geom`) );
INSERT INTO `test_table` (`uid`, `geom`) VALUES ('1',ST_GeomFromGeoJSON('{"type": "FeatureCollection","features": [{"type": "Feature","properties": {},"geometry": {"type": "Polygon","coordinates": [[[-91.2,45.4],[-79.8,49.8],[-69.0,43.4],[-88.2,32.6],[-91.2,45.4]]]}}]}',1,4326));
SELECT uid FROM test_table  WHERE ( St_intersects(geom,St_geomfromGeoJSON('{"type": "Point", "coordinates": [-80.8,43.7], "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}',1,4326)));
SELECT St_IsValid(geom) FROM test_table;

The first test with the intersect works like a charm but the ST_IsValid function returns the error:
ERROR 1210 (HY000): Incorrect arguments to st_isvalid

But the MySQL help states:
SET @ls1 = ST_GeomFromText('LINESTRING(0 0)');
SELECT ST_IsValid(@ls1);

Any ideas someone?

A: MySQL version 5.7 says:

ST_IsValid() works only for the Cartesian coordinate system and
  requires a geometry argument with an SRID of 0.

The geometries you created use an SRID of 4326.
The behaviour changed for MySQL 8.0.


text:
Q: Не могу получить элемент через id Есть у меня контент для инфо окна маркера:
var contentString = '
'
                + '

' + order.description + '
'
                + '
Address: '+order.address+'
Customer: '+order.user+'Order page

<button type="button" class="btn btn-success" onclick="presenter('+i+'); return false;">Call</button>

';

Но икак не могу достучатся к элементу "CallButton". При віполнении
document.getElementById('callButton');

Возникает ошибка

Uncaught SyntaxError: Unexpected identifier
  Подскажите почему не видно этот элемент?


text:
Q: Dismiss AlertDialog without clicking on button I'd like to dismiss an AlertDialog window, but not when clicking on the "ok" or "cancel" button, but when an action is called.
In fact, I'd like to create the dialog in onResume function that way :
@Override
public void onResume() {
    super.onResume();
    alert = new AlertDialog.Builder(this);
    alert.setTitle("Stay stuck to a tag");
    alert.create().show();
}

and then exit it when a function is called, like
private void dismissMyDiag() {
    alert.dismiss();
}

Of course I've seen the way to do that with the onclick event by that's not what I want to do.
Is it possible to do such a thing ? And if not, what king of dialog box allows me to do that ?
Thank you !

A: Get the alertDialog like this
AlertDialog dialog;
 alert = new AlertDialog.Builder(this);

dialog=alert.create().show();

Then call
private void dismissMyDiag() {
    dialog.dismiss();
}

A: try this way:
final AlertDialog d = new AlertDialog.Builder(context)
                .setView(v)
                .setTitle(R.string.my_title)
                .setPositiveButton(android.R.string.ok,
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface d, int which) {
                                //Do nothing here. We override the onclick
                            }
                        })
                .setNegativeButton(android.R.string.cancel, null)
                .create();

        d.setOnShowListener(new DialogInterface.OnShowListener() {

            @Override
            public void onShow(DialogInterface dialog) {

                Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
                b.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        // TODO Do something

                        //Dismiss once everything is OK.
                        d.dismiss();
                    }
                });
            }
        });

A: i know it's old Question but may Hope This will help Some One.
You Can also Can Create A Custom Class For Alert Dialog And Access it hole project
Can Show and hide any where
package (Your_Pakage_Name);
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatDialogFragment;

public class AlertDailogbox extends AppCompatDialogFragment {

    String Title = null;
    String Msg = null;
    String TAG = "Alert Dialog Box";

    public AlertDailogbox(String title, String msg) {
        Title = title;
        Msg = msg;

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(Title)
                .setMessage(Msg)
                .setIcon(R.drawable.ic_alert) //set icon if you want
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });

        return builder.create();
    }
}

Call in Your Project (Activity)
Make an Global Variable of alertDialog Class
private AlertDailogbox alertDailogbox;

function to show Dialog
private void showMsgDailog(String Title,String Msg){
    alertDailogbox = new AlertDailogbox(Title,Msg);
    alertDailogbox.setCancelable(false);
    alertDailogbox.show(getSupportFragmentManager(),"alert Dailog");
}

End For Dismiss
if(alertDailogbox != null)
       alertDailogbox.dismiss();

alerDailogeBox is not null check is nessary other wise application can crash


text:
Q: Set the QTabWidget background to be transparent by stylesheet but useless in VS2013 I set a picture as background in the mainframe and add two widgets on it: a QTableWidget and a QTabWidget.

*

*I have set the background of tablewidget to be transparent by stylesheet
in vs2013. The table's background shows the picture I set but the horizontalheader section is still white:

TaskInfWidget_->setStyleSheet("QTableWidget{background:transparent;}\
                           QTableWidget::item{border-top:1px solid grey;border-bottom:none;border-right:none;border-left:none;}\
                           QHeaderView::section{background:transparent;color:black; font-family:宋体;font-size:15px;font-weight:200;\
                                                    border:none;}");

*But when I add a tablewidget in a tabwidget and set the stylesheet of the tabwidget, it doesn't work:

QTabWidget *tab_widget=new QTabWidget;
QTableWidget *table = new QTableWidget(10, 1);
tab_widget->addtab(table,"hahaha");

tab_widget>setStyleSheet("QTabWidget::pane{background:transparent}\
            QTabBar::tab{background-color:transparent;height:30px;}\
            QTabBar::tab:selected{background-color:rgb(55,112,183)}\
            QTabBar::tab:hover{color:rgb(235,97,0);}");
table->setStyleSheet("QTableWidget{background:transparent;\
                         border:3px solid rgb(30,77,135);\
                         selection-background-color:rgb(30,77,135);}");

I have set QTabWidget::pane{background:transparent} and QTableWidget{background:transparent}, but the background of the tablewidget is still white, not the picture of the mainframe.
This is my first time to ask question here. This question has bothered me several days. Who can tell me the reason?


text:
Q: A simple windows Batch file to run java m new to java. I want to run java from windows batch file. I have a compiled class- Main.class in a directory. I want to run this with a batch file put in the same directory.
I have a system variable set to JAVA_HOME=C:\Program Files\Java\jdk1.7.0_06\bin
And what if I want to compile the class with batch file first ?

A: Execution:
@echo off
"%JAVA_HOME%\java.exe" Main
PAUSE

Compiling would be replacing the line with
"%JAVA_HOME%\javac" Main.java

Optional Stuff:
echo off turns off echo of the commands to cmd
pause is so that the cmd window doesn't close immediately at the end of execution(so you can read the output of your command)

A: Compile Your Code Using:
javac Main.java

Run Your Code Using:
java Main =>starts your code

To Get More Info About The javac tool(output name,disable warnings, etc...) Press Here.

A: javac cfm jar Main.jar Main.class manifest.txt

Make a manifest.txt containing:
Main-Class: Main

followed by a newline character to work properly (hit Enter once).
And make a batch file in the same folder of output containing:
@echo off
 set jarpath="Main.jar"
 java -jar %jarpath% %CD%Config.txt
 PAUSE

Run the batch! :)


text:
Q: ui select angularjs set maxlength for input value (ui select match) I want an extra attribute just like "Placeholder" is passing from ui select match. I want to set maxlength of select input. I can set it through select.min.js adding attribute maxlength="" but i think making change to lib. file is not a solution.
Just like i have adde maxlength="500" in input
please help me around.
Thanks

A: You can limit your collection using the angular's limitTo filter. Look at the limitTo reference.

A: As per my understanding, you are using ui-select with tagging (as combo-box).
in this to achieve your desired functionality:
go to ui-select plugin.js and edit the template "select2/select.tpl.html" (for theme select2):
ng-attr-maxlength="{{$select.tagging.isActivated ? 50 : ''}}"
add the above line to template as shown here:
<input type=\"search\" ........... ng-attr-maxlength=\"{{$select.tagging.isActivated ? 500 : ''}}\">

if you want to restrict input search itself then directly add maxlength attribute:
<input type=\"search\" ........... maxlength=\"500\">

Hope this helps. :-)

A: You can change attribute through templateCache
.run(function($templateCache) {
        $templateCache.put("bootstrap/select-multiple.tpl.html","

<input maxlength='5' type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-expanded=\"{{$select.open}}\" aria-label=\"{{$select.baseTitle}}\" ng-class=\"{\'spinner\': $select.refreshing}\" ondrop=\"return false;\">

");
    })

Original templates can be find on bottom of file select.js


text:
Q: How to add correct cancellation when downloading a file with the example in the samples of the new Parallel Programming library I have downloaded the last samples of the Parallel Programming team, and I don't succeed in adding correctly the possibility to cancel the download of a file.
Here is the code I ended to have:
var wreq = (HttpWebRequest)WebRequest.Create(uri);

// Fire start event
DownloadStarted(this, new DownloadStartedEventArgs(remoteFilePath));

long totalBytes = 0;

wreq.DownloadDataInFileAsync(tmpLocalFile,
                             cancellationTokenSource.Token,
                             allowResume,
                             totalBytesAction =>
                             {
                                 totalBytes = totalBytesAction;
                             },
                             readBytes =>
                             {
                                 Log.Debug("Progression : {0} / {1} => {2}%", readBytes, totalBytes, 100 * (double)readBytes / totalBytes);
                                 DownloadProgress(this, new DownloadProgressEventArgs(remoteFilePath, readBytes, totalBytes, (int)(100 * readBytes / totalBytes)));
                             })
    .ContinueWith( (antecedent ) =>
                      {
                          if (antecedent.IsFaulted)
                              Log.Debug(antecedent.Exception.Message);

                          //Fire end event
                          SetEndDownload(antecedent.IsCanceled, antecedent.Exception, tmpLocalFile, 0);
                      }, cancellationTokenSource.Token);

I want to fire an end event after the download is finished, hence the ContinueWith.
I slightly changed the code of the samples to add the CancellationToken and the 2 delegates to get the size of the file to download, and the progression of the download:
return webRequest.GetResponseAsync()
    .ContinueWith(response =>
                      {
                          if (totalBytesAction != null)
                              totalBytesAction(response.Result.ContentLength);

                          response.Result.GetResponseStream().WriteAllBytesAsync(filePath, ct, resumeDownload, progressAction).Wait(ct);
                      }, ct);

I had to add the call to the Wait function, because if I don't, the method exits and the end event is fired too early.
Here are the modified method extensions (lot of code, apologies :p)
public static Task WriteAllBytesAsync(this Stream stream, string filePath, CancellationToken ct, bool resumeDownload = false, Action<long> progressAction = null)
{
    if (stream == null) throw new ArgumentNullException("stream");

    // Copy from the source stream to the memory stream and return the copied data
    return stream.CopyStreamToFileAsync(filePath, ct, resumeDownload, progressAction);
}

public static Task CopyStreamToFileAsync(this Stream source, string destinationPath, CancellationToken ct, bool resumeDownload = false, Action<long> progressAction = null)
{
    if (source == null) throw new ArgumentNullException("source");
    if (destinationPath == null) throw new ArgumentNullException("destinationPath");

    // Open the output file for writing
    var destinationStream = FileAsync.OpenWrite(destinationPath);

    // Copy the source to the destination stream, then close the output file.
    return CopyStreamToStreamAsync(source, destinationStream, ct, progressAction).ContinueWith(t =>
    {
        var e = t.Exception;
        destinationStream.Close();

        if (e != null)
            throw e;
    }, ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);
}

public static Task CopyStreamToStreamAsync(this Stream source, Stream destination, CancellationToken ct, Action<long> progressAction = null)
{
    if (source == null) throw new ArgumentNullException("source");
    if (destination == null) throw new ArgumentNullException("destination");

    return Task.Factory.Iterate(CopyStreamIterator(source, destination, ct, progressAction));
}

private static IEnumerable<Task> CopyStreamIterator(Stream input, Stream output, CancellationToken ct, Action<long> progressAction = null)
{
    // Create two buffers.  One will be used for the current read operation and one for the current
    // write operation.  We'll continually swap back and forth between them.
    byte[][] buffers = new byte[2][] { new byte[BUFFER_SIZE], new byte[BUFFER_SIZE] };
    int filledBufferNum = 0;
    Task writeTask = null;
    int readBytes = 0;

    // Until there's no more data to be read or cancellation
    while (true)
    {
        ct.ThrowIfCancellationRequested();

        // Read from the input asynchronously
        var readTask = input.ReadAsync(buffers[filledBufferNum], 0, buffers[filledBufferNum].Length);

        // If we have no pending write operations, just yield until the read operation has
        // completed.  If we have both a pending read and a pending write, yield until both the read
        // and the write have completed.
        yield return writeTask == null
                         ? readTask
                         : Task.Factory.ContinueWhenAll(new[]
                                                            {
                                                                readTask,
                                                                writeTask
                                                            },
                                                        tasks => tasks.PropagateExceptions());

        // If no data was read, nothing more to do.
        if (readTask.Result <= 0)
            break;

        readBytes += readTask.Result;

        if (progressAction != null)
            progressAction(readBytes);

        // Otherwise, write the written data out to the file
        writeTask = output.WriteAsync(buffers[filledBufferNum], 0, readTask.Result);

        // Swap buffers
        filledBufferNum ^= 1;
    }
}

So basically, at the end of the chain of called methods, I let the CancellationToken throw an OperationCanceledException if a Cancel has been requested.
What I hoped was to get IsFaulted == true in the appealing code and to fire the end event with the canceled flags and the correct exception.
But what I get is an unhandled exception on the line
response.Result.GetResponseStream().WriteAllBytesAsync(filePath, ct, resumeDownload, progressAction).Wait(ct);
telling me that I don't catch an AggregateException. I've tried various things, but I don't succeed to make the whole thing work properly.
Does anyone of you have played enough with that library and may help me?
Thanks in advance
Mike

A: This is pretty much the behavior I would expect. I've not been able to get my head entirely around your code but I suspect that if you look at the AggregateException.InnerExceptions property you'll find a TaskCancelled or OperationCancelledException in there. Cancelling the token causes an exception to be thrown by cancelled task which is typically caught by the calling code as it waits for the task to complete and this is wrapped in an aggregate.
The following links have more detail.
http://msdn.microsoft.com/en-us/library/dd997396.aspx
http://msdn.microsoft.com/en-us/library/dd997364.aspx
I'm not going to write more as I'm not 100% convinced I understand your code.