text:
Q: Three chords inequality and $g'_+(a)\leq \frac{g(a+h)-g(a)}{h}$ How does the three chords inequality lead to the bound on the right derivative?
Recall the three chords inequality is that, for $a<x<b$ and $g$ convex,
$$
\frac{g(x)-g(a)}{x-a}\leq\frac{g(b)-g(a)}{b-a}\leq \frac{g(b)-g(x)}{b-x}
$$

Perhaps we just say that, by rewriting the three chords inequality as
,
$$
\frac{g(x)-g(a)}{x-y}\leq\frac{g(y)-g(a)}{y-a}\leq \frac{g(z)-g(a)}{z-a}
$$
where $x< a < y\leq z$
and the above gives us that the right derivative is decreasing (since it is the formula for right derivative, and it is lower or $y\leq $(

A: The function $\delta:(0,\infty)\to \Bbb R$, $\delta(h)=\frac{g(a+h)-g(a)}h$ is weakly increasing by (the first half of) the three-chord inequality, and $g_+'(a)=\lim_{h\to 0^+} \delta(h)$. Therefore $g_+'(a)\le \delta(h)$ for any single $h>0$.


text:
Q: How can i specify different shapes in ngx-graph template? All
Is there any way to draw other shapes than rectangle? circle, polygon, my own symbol?
Also i am looking for a way to write a sentence next to the shape, besides the text inside it.
Thanks

A: You can use the following code for creating circle instead of rectangle.
   <ngx-graph> <ng-template #nodeTemplate let-node> <svg:circle    [attr.r]="node.width/2" [attr.cx]="node.width/2"    [attr.cy]="node.width/2" [attr.fill]="node.options.color" />     <svg:text alignment-baseline="central" [attr.x]="10"    [attr.y]="node.height / 2">node-label</svg:text> </ng-template>  </ngx-graph>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set constraints in a Matrix - OPTIM in R I have a vector of integers as input values (starting values for optim par)
my.data.var <- c(10,0.25,0.25,0.25,0.25,0.25,
             10,0.25,0.25,0.25,0.25,0.25,
             10,0.25,0.25,0.25,0.25,0.25,
             10,0.25,0.25,0.25,0.25,0.25)

*

*Optimization problem is a min. problem.

*The error function calculates sum of square root of diff in values between
TWO MATRICES (Given Values Matrix vs Calculated Matrix)

*The calculated matrix is the one that uses above integer vector.
Hence, in the error function, I stack the integer vector into a
matrix as my.data.var.mat <- matrix(my.data.var,nrow = 4,ncol = 6,byrow = TRUE)
The constraint that I must introduce is that colSum(my.data.var.mat) <=1
The optim is defined as
sols<-optim(my.data.var,Error.func,method="L-BFGS-B",upper=c(Inf,1,1,1,1,1,Inf,1,1,1,1,1,Inf,1,1,1,1,1,Inf,1,1,1,1,1),
  lower=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))

Error Function is defined as
Error.func <- function(my.data.var){

my.data.var.mat <- matrix(my.data.var,nrow = ncol(my.data.matrix.prod),ncol = ncol(my.data.matrix.inj)+1,byrow = TRUE)

  Calc.Qjk.Value <- Qjk.Cal.func(my.data.timet0,my.data.qo,my.data.matrix.time,
                                 my.data.matrix.inj, my.data.matrix.prod,my.data.var,my.data.var.mat)

  diff.values <- my.data.matrix.prod-Calc.Qjk.Value    #FIND DIFFERENCE BETWEEN CAL. MATRIX AND ORIGINAL MATRIX

  Error <- ((colSums ((diff.values^2), na.rm = FALSE, dims = 1))/nrow(my.data.matrix.inj))^0.5    #sum of square root of the diff

  Error_total <- sum(Error,na.rm=FALSE)/ncol(my.data.matrix.prod)   # total avg error

  Error_total
}

Given Dataset: my.data.matrix.prod , my.data.timet0, my.data.qo, my.data.matrix.time, my.data.matrix.inj
So, my question is how and where should I introduce the matrix col sum constraint? Or the other way to put it as how would OPTIM vary integer vector under Matrix col sum constraint?

A: I realized that nloptr is a better option than optim since my problem consisted of "inequality constraints".
I modified the implementation as I explain in this post here. "multiple inequality constraints" - Minimization with R nloptr package
Hence, closing this thread.


text:
Q: Why can't I publish my site onto GitHub Pages? And why can't I add Jekyll themes? I just committed a html and css file onto my repo, but even 10 minutes later I still keep getting a 404 Not Found error.
I was advised to add a Jekyll theme to the repo, but for some reasons I only have a link that leads me to an informational page on how to add themes rather that letting me actually add it to the repo?
If I'm not mistaken, isn't Jekyll supposed to be built into GitHub Pages? If so why can't I choose a theme? If not, how do I link it to GitHub Pages?

A: Try and, as I mentioned here to:

*

*publish with a custom GitHub Actions workflow

*Using a starter workflow, which does include one for Jekyll.

A: I recently answered a question about an old blog post from 2021 that mentioned the theme-chooser when setting up GitHub pages. As this has been removed from the page, you can add a theme to your page by adding a _config.yml file.

The link to the GitHub docs explains how to set a theme for your site.

Under point 5 the page says:
Add a new line to the file for the theme name.


text:
Q: Select from table while masking a column I'd like to export a table while masking a specific column, something like:
SELECT randomMask(userId), name, location FROM travel_location;

Requirements:

*

*Masked column must be random but consistent for that query. Eg 2345 will always be randomized as abwr for that query.

*Masked column must not be able to be decoded. abwr should not be able to be decoded into 2345 by me after running the query.

*Every query should randomly mask the id differently, 2345 may be masked as abwr this time, but it should be something else next time.

example result:

A: You can use checksum() to get a reasonable random value:
select checksum(userId)

Of course, there are collisions, but that is probably acceptable.
Alas, this will be the same each time you run the query.  To fix that, you could add a random number or use the time:
select checksum(userid + rand())

or:
select checksum(convert(varchar(255), userid) + convert(varchar(255), getdate())

Both rand() and getdate() are guaranteed to be the same on all rows for for each expression they occur in.  However, they will vary from query to query.

A: You can try (works for SQL Server 2016 or more):
ALTER Table travel_location
ALTER COLUMN userId ADD MASKED WITH (FUNCTION='Random(1,100000)')

The users who were not granted to unmask like below wouldn't see the real value after this change.
GRANT UNMASK TO TestUser;


text:
Q: Mustang Library: Converting invalid PDFA3 to valid PDFA3 for building Factur-x I'm trying to create a facturX using Mustang Library in a webservice. This web service accept a xml string and a base64 PDF.
My issue is that i have no "knowledge" about PDF format that is sent to me. In my service layer class, I build my facturx using ZUGFeRDExporterFromA1.
@Override
public FacturxDto createFacturX(FacturxDto facturxDto) {
    context.setContext(facturxDto);
    if (facturxDto.getVersion() == null) {
        facturxDto.setVersion(2);
    }
    if(facturxDto.getPdfDocument() == null) {
        throw new AppServiceException("Pdf is required in the payload");
    }
    if(facturxDto.getXml() == null) {
        throw new AppServiceException("Xml is required in the payload");
    }
    if ((facturxDto.getVersion() < 1) || (facturxDto.getVersion() > 2)) {
        throw new AppServiceException("invalid version");
    }
    try {
        Utils.facturxValidator(facturxDto);
    } catch (SAXException | IOException e) {
        throw new AppServiceException(e.getMessage());
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    log.debug("Converting to PDF/A-3u");

    PDFAConformanceLevel pdfaConformanceLevel = Utils.setPdfaConformanceLevel(facturxDto);
    // System.out.println(Arrays.toString(facturxDto.getPdfDocument().getBytes(StandardCharsets.UTF_8)));
    byte[] xmlData = facturxDto.getXml().getBytes(StandardCharsets.UTF_8);
    byte[] pdfData = Base64.getDecoder().decode(facturxDto.getPdfDocument().getBytes(StandardCharsets.UTF_8));
    try {
        ZUGFeRDExporterFromA1 ze = new ZUGFeRDExporterFromA1()
                .setProducer("Mustang LIB")
                .setCreator("ME")
                .setProfile(facturxDto.getFxLevel())
                .setZUGFeRDVersion(facturxDto.getVersion())
                .setConformanceLevel(pdfaConformanceLevel)
                .ignorePDFAErrors()
                .load(pdfData);

        ze.attachFile("factur-x.xml", xmlData, "text/xml", "Data");

        ze.setXML(xmlData);
        log.debug("Attaching ZUGFeRD-Data");
        ze.disableAutoClose(true);
        ze.export(output);
        byte[] bytes = output.toByteArray();
        InputStream inputStream = new ByteArrayInputStream(bytes);

        byte[] pdfBytes = IOUtils.toByteArray(inputStream);

        String encoded = Base64.getEncoder().encodeToString(pdfBytes);
        // persist data in db and generate id
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        FacturxEntity facturxEntity = modelMapper.map(facturxDto, FacturxEntity.class);
        facturxEntity.setStatus(RequestOperationStatus.SUCCESS.name());
        facturxEntity.setCreatedAt(new Date());
        facturxEntity.setFacturxId(Utils.generateId());

        FacturxEntity storedFacturx = facturxRepository.save(facturxEntity);
        FacturxDto returnValue = modelMapper.map(storedFacturx, FacturxDto.class);
        returnValue.setPdfDocument(encoded);
        return returnValue;
    } catch (IOException e) {
        e.printStackTrace();
        throw new AppServiceException(e.getMessage());
    }
}

My issue is here :
ZUGFeRDExporterFromA1 ze = new ZUGFeRDExporterFromA1()
        .setProducer("Mustang LIB")
        .setCreator("ME")
        .setProfile(facturxDto.getFxLevel())
        .setZUGFeRDVersion(facturxDto.getVersion())
        .setConformanceLevel(pdfaConformanceLevel)
        .ignorePDFAErrors()
        .load(pdfData);

If i don't use ignorePDFAErrors() I do have an exception thrown.
If i use it, my pdf is not PDFA compliant. And it's an issue.
Is there a way to convert on the fly an invalid PDFA to a valid one. Thanks

A: You can e.g. use Mustang's REST API, Mustang Server https://www.mustangproject.org/server/ to correct and export any input PDF file as PDF/A, which also includes files which are already PDF/A-1.
kind regards
Jochen


text: Q: Using a colon after a single word I write instructions for our assembly lines. Frequently, I need to call their attention to something that is not a step, but that they need to know. My usual way of doing this is to write, "Note: Do thus and so." This will be included with the steps, which are in a numbered list, although the note is indented and not numbered. Is my use of a colon here correct, or would another mark such as an em dash be more appropriate? Also, should the following word be upper- or lower-case? I would like to stagger them vertically, but I am limited on room.


text:
Q: Accessing HttpContext.Current.User.Identity.Name in the DbContext I'm going to use the UserName for tracking Created and Modified fields. To do that I have referenced to the System.Web assembly directly inside DbContext:
public void auditFields()
 {
            var auditDate = DateTime.Now;
            foreach (var entry in this.ChangeTracker.Entries<BaseEntity>())
            {
                switch (entry.State)
                {
                    case EntityState.Detached:
                        break;
                    case EntityState.Unchanged:
                        break;
                    case EntityState.Added:
                        entry.Entity.CreatedOn = auditDate;
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.CreatedBy = HttpContext.Current.User.Identity.Name ?? "anonymouse";
                        entry.Entity.ModifiedBy = HttpContext.Current.User.Identity.Name ?? "anonymouse";
                        break;
                    case EntityState.Deleted:
                        break;
                    case EntityState.Modified:
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.ModifiedBy = HttpContext.Current.User.Identity.Name ?? "anonymouse";
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
}

It works, But it's tightly coupling the DbContext with HttpContext which is not a good idea in case we'll expose the DbContext to a non-web environment.
So I use this way:
public class ApplicationDbContext :
        IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>,
        IUnitOfWork
{
    public ApplicationDbContext()
            : base("ConnectionString")
        {
        }
        public ApplicationDbContext(string userName)
            : base("ConnectionString")
        {
            UserName = userName;
        }
    //Other codes
    public string UserName
        {
            get;
            private set;
        }
    public void auditFields()
    {
            var auditDate = DateTime.Now;
            foreach (var entry in this.ChangeTracker.Entries<BaseEntity>())
            {
                switch (entry.State)
                {
                    case EntityState.Detached:
                        break;
                    case EntityState.Unchanged:
                        break;
                    case EntityState.Added:
                        entry.Entity.CreatedOn = auditDate;
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.CreatedBy = UserName ?? "anonymouse";
                        entry.Entity.ModifiedBy = UserName ?? "anonymouse";
                        break;
                    case EntityState.Deleted:
                        break;
                    case EntityState.Modified:
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.ModifiedBy = UserName ?? "anonymouse";
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
    }
}

And in the Ioc config project (I'm using structureMap in another class library):
ioc.For<IUnitOfWork>()
                   .HybridHttpOrThreadLocalScoped()
                   .Use<ApplicationDbContext>()
                   .Ctor<string>().Is(HttpContext.Current.User.Identity.Name);

But when I run the application I'll get this error in above line:
Object reference not set to an instance of an object

It seems that it can't inject HttpContext.
Any idea?

A: Take a look at this link http://techbrij.com/service-layer-entity-framework-asp-net-mvc-unit-testing
The Author's solution looks like yours (but he used AutoFac instead of StructureMap). His "trick" to get the "Name" was Thread.CurrentPrincipal.Identity.Name;
Another thing, IMHO, I think you should use DateTimeOffSet instead of DateTime for the audit date. Using DateTimeOffSet you won't have problems with differents time zone. Like this:
DateTimeOffSet auditDate = DateTime.UtcNow;

A: The following should help
ASP.NET MVC: HTTPContext and Dependency Injection
http://mikehadlow.blogspot.com/2008/08/taking-httpcontext-out-of-mvc-framework.html


text:
Q: Transient current limiting I have a USB powered system. The system on occasion for a short period of time, needs more than 500mA. I have additional caps that can provide this current.
The problem is, despite these caps have enough power in them, during the excess current phase, I see the USB rail goes down 0.2V. This is probably ok for my application but I like to be cautious since I am worried some hosts out there doesn't like this behaviour and may disconnect me from the host.
I am looking for a simple solution where during the transient USB current is limited to 500mA. I have seen some ICs that can do this but I prefer a discrete solution.

A:
I am looking for a simple solution where during the transient USB
  current is limited to 500mA. I have seen some ICs that can do this but
  I prefer a discrete solution.

In order to limit current a circuit needs to measure current. This is usually done with a series resistor in line with the load. But, the resistance has to be small so that it doesn't not "drop" too much voltage in normal operation. A 0.1 ohm series resistor will drop 50mV at 500mA and this is probably acceptable.
However, to measure this small volt drop accurately (in order to determine current), requires a fairly decent amplifier and to make this from discrete components is, in my opinion, foolish.


text:
Q: Open accordion using onfocus on input field I am trying to open accordion on onfocus on input field.I have tried but it is not happening .i want to open accordion  depending onwhich input box is focus
<input type="text" id="rnv" class="form-control"  placeholder="Ex: Roasted Aparagus and Musherooms" onfocus="accordion('rntip',this)">

<textarea class="form-control"  id="in" rows="6" placeholder="Ex: bunch fresh asparagus, trimmed; 2 sprigs fresh rosemary, minced" onfocus="accordion('intip',this)"></textarea>

  Recipe Name

Keep it short.

Include the name of the dish or its main ingredients.

Add a personal touch/get creative.

A: Make sure accordion is referencing the accordion element and not just the string you pass.
Change var accordion = id; to var accordion = $("#"+id);


text:
Q: Logic Apps - Populate a Microsoft Word template changing font size I am using the Populate a Microsoft Word template action in a workflow. I'm populating a few tags throughout a document that is about 3 pages long. In the word template the font is Arial 10 for the entire document. However, when the word template has gone through the workflow and then saved in SharePoint a couple of the tags as well as a couple of random paragraphs change to size 11 font.
I tried changing the font to size 9 in the places it was consistently being sized up but then when the document generated it stayed size 9.
Is there anything I can do to the document or the action in the workflow to ensure the content stays the same when its saved to SharePoint?
Populate a Microsoft Word template action:

A: As John Korchok said in the comments, you should use Word Typestyles instead of local formatting.


text:
Q: Загрузка нескольких фотографий на сервер. Как реализовать передачу нескольких изображений за раз на сервер?
Делал так. Ставил инпут для выбора фотографии. Если пользователь хочет загрузить еще фотографию, то нажимает на клавишу, js строит еще один инпут.
Но потом заметил, что если скрипт(обработчик) не срабатывает, или надо его перезагрузить с этими же параметрами, то сохраняется только первый инпут.
Как этого избежать? И какие другие методы для загрузки нескольких изображений имеются?
A: Не пойму при чем тут загрузка "фотографий на сервер". С помощью JS вы встраиваете в DOM новый элемент (input), но на самом деле, на странице он не прописан и находиться там, как бы виртуально. Естественно, что при перезагрузке его опять не существует. Выходов из этой ситуации несколько: использовать куки, сессии, local storage и т.д.


text:
Q: Statistical significance of a relationship of two categorical fields with more than two classes From my dataset, I have two columns called the cuisine and the restaurant-grade. Each column corresponds to a restaurant. There are 6 different cuisines and 5 different grades. The question that I am asked is to check whether there is a statistically significant relationship between those two.
What I did was to create a crosstable counting occurrence of all. As a result, I have the following table:

Then created an array called f_obs including all the values:
array([[4770,  132,   21,  130,  108],
       [1633,   27,    4,   58,   18],
       [1858,   90,   20,   51,  112],
       [ 778,   24,    3,   13,   20],
       [ 757,   32,    6,   31,   38],
       [ 957,   40,    8,   21,   32]], dtype=int64)

From this point on, I am not sure how I need to process or even on the right track. Can I check the statistically significance of a relationship of two categorical values with more than two classes? Do I need to use chi-square as if there are two classes? If you know, I would also appreciate it if you can provide the python function that can help me! (it should probably be scipy)

A: You can use the following function chi2_contingency from scipy.stats.
Yes, you can perform a chi-squared test of Independence when you have a contingency table that is larger than 2 x 2. I have included an example below which has been taken from  Gentle Introduction to Chi-Square Test for Independence. This would be the approach if you are trying to determine whether the two categorical variables are associated (dependent)
from scipy.stats import chi2_contingency
import pandas as pd
import numpy as np

tshirts = pd.DataFrame(
    [
        [48,22,33,47],
        [35,36,42,27]
    ],
    index=["Male","Female"],
    columns=["Balck","White","Red","Blue"])
tshirts

test = chi2_contingency(tshirts)

chi_squared_test_statistic = test[0]
p_value = test[1]
expected_counts = test[3]


text:
Q: c - Trouble implementing an "add edge" function for a graph I'm currently working on an assignment to implement Prim's and Dijkstra's algorithms with graphs, but I got hung up trying to implement some basic graph functions based on this header:
//APIs for graph representation by adjacency list
typedef struct ADJNODE { //adjacency node
    int vertex;
    int weight;
    struct ADJNODE *next;
} adjnode;

typedef struct GRAPH {
    int vn;            //number of nodes
    adjnode **adjlist; //pointer to an array of pointers of neighbors
} graph;

graph *new_graph(int n);
void add_edge(graph *g, int from, int to, int weight);
int get_weight(graph *g, int from, int to);
void display_graph(graph *g);
void delete_graph(graph *g);

(Note that I can't change the structs or function headers as they were specified this way in my assignment.)
I'm having trouble getting add_edge to work correctly.
My code for it so far:
void add_edge(graph *g, int from, int to, int weight) {
    adjnode *n = g->adjlist[from];
    adjnode *current = n, *prev;

    prev = NULL;
    while (current != NULL) {
        prev = current;
        current = current->next;
    }
    current = malloc(sizeof(struct adjnode*));

    current->next = NULL;
    current->vertex = to;
    current->weight = weight;

    if (prev != NULL)
        prev->next = current;
    else
        g->adjlist[from] = current;

    return;
}

My problem is that when I try to print all the edges (by moving to a point in adjlist and then cycling through that adjnodes next's like a linked-list) I find that every node in adjlist is NULL (if I'm traversing it correctly). I'm not sure if my function isn't actually connecting the new adjnodes to the original graph g or if I'm severely misunderstanding how adjlist is supposed to be used.
I'm assuming adjnode **adjlist works as a pointer to an array of adjnode pointers, which are essentially all heads of their own linked lists (because the number of nodes in adjlist is set based on the number of vertexes in the graph, and I'm assuming the edges are added as "nexts" to each of those base nodes)
This is my professors implementation of the new_graph function if it helps:
//API implementation for graph representation by adjacency list
graph *new_graph(int vertex_number) {
    graph *gp = malloc(sizeof(graph));
    adjnode **np = malloc(vertex_number * sizeof(adjnode*));
    int i;
    for (i = 0; i < vertex_number; i++) {
        np[i] = NULL;
    }
    gp->vn = vertex_number;
    gp->adjlist = np;
    return gp;
}

Note that I'm basing my understanding of adjlist on how he's used the variable np in the for loop.
*Edit
- added some code as suggested in the comments to add_edge
Also, I've noticed the program crashes after calling it a few times:
graph *graph = new_graph(5); //total of 5 vertices (0,1,2,3,4)
add_edge(graph, 0, 1, 7);
add_edge(graph, 1, 0, 7);
add_edge(graph, 0, 2, 3);
add_edge(graph, 2, 0, 3);//crashed here

Based on some output statements it seems to crash right before
current = malloc(sizeof(struct adjnode*));, I'm not sure what's causing that.


text: Q: How to use determiners after the coordinating conjunction AND? I need to say: "Chinatown and Little Italy are the most colourful and liveliest neighbourhoods in New York City". I wonder if I must add the determiner THE before "liveliest".


text:
Q: What if any languages treat undisposed resources as an error? I've seen lots of code like the following example. It's in Python, but the same mistake is made in all languages with managed resources:
f = open('foo.txt', 'rb')
for line in f: print line

That's it. The error is that close(f) wasn't called so the file handle is kept open until some indeterministic time in the future when the runtimes memory management decides to reclaim memory.
Python has with and c# has using to help make resource cleanup easier, but let's disregard those features for a minute. Given that:

*

*It's a programming error not to explicitly close open files.

*The runtime can detect that an open file has not been closed.

Why then doesn't the runtime throw an error instead of being "helpful" and closing the file for the programmer? That would be the fail fast and fail early strategy. Is there a technical reason why it can't? Is there any languages that does it? Has the idea been considered before (I've googled but not found anything)?
Here is how you almost implement the feature in Python:
class mustclose:
    def __init__(self, f):
        self.f = f
    def __del__(self):
        if not self.f.closed:
            raise Exception("You forgot to close() me!")
k = mustclose(open('foo.txt', 'wb'))
#k.f.close()

Two problems: It requires wrappers, Python doesn't like to throw exceptions from destructors.
(Read this https://stackoverflow.com/questions/2807241/what-does-the-expression-fail-early-mean-and-when-would-you-want-to-do-so SO question for background on why failing fast is often desirable)

A: In Java 7 and later, resources that implement AutoCloseable will cause the compiler to emit a warning when a resource is not managed with try-with-resources.
Combined with garbage collection, this goes a long way toward ensuring that resources are freed at some point.
As Robert Harvey mentioned, the operating system also disposes of a process's entire memory space and frees dangling resources. However, this does not necessarily ensure that resources are properly closed (e.g. sending a "goodbye" message on a socket to a remote host to free remote resources). This also relies on the process being shut down. A long-running process might leak resources such as remote connections, file handles, etc.
Java 7's try-with-resources comes as close as close as I have seen toward guaranteeing that even non-local resources are freed during program execution, assuming that developers heed the compiler warnings.

A: While it has almost certainly been considered, it has been discarded because, in the general case, it is impossible to do.
What happens if f is not a local variable, or is returned from the function?
At that point, you have an equivalent to the Halting Problem. There is no way (in the general case) for static analysis to prove one way or another if the file is closed somewhere else in your program (or worse, in someone calling this code in a library).

A:
The runtime can detect that an open file has not been closed.

The only time the runtime can unambiguously determine that an open file should have been closed is upon process shutdown, particularly with event driven frameworks that may reuse open file handles in callbacks, etc. Unless the handle has been scoped (and you said ignore C# using {} and Java Try-With-Resources runtime hints), the runtime CANNOT determine if an error has occurred.
Since the runtime is disposing of the whole process, for system stability purposes, its only real recourse is to close all open stream and release the associated resources.

A: What would happen if a language threw run-time errors e.g. on leaked file handles? Coders would hate it with a flaming passion, and it would go nowhere.
The point of resource management is to aid you in producing a valuable program with less effort. "Valuable" doesn't mean "perfect": a program that leaks a file handle is bad, but often it is nowhere near as bad as a program that deliberately blows up instead of wasting some resources, which might or might not cause problem for your use case.
If the only goal worth aiming at was perfection, them sure, every compiler, run-time and OS should be as ruthless as possible in detecting and terminating processes that commit errors, since they are by definition worthless. Arguably it would be a better world if customers didn't accept anything short of perfection and ruthlessly sued the pants of any vendor who sold them an application with a resource leak in it, but let's be quite clear: this is not such  a world.
That is only the business side of things; others have pointed out that it's not easy to decide whether a handle has truly been leaked or not. Languages with fully automatic garbage collection are in theory capable of adding any desired behaviour to the 'dispose' hook; for instance, Java initially assumed that you would clean up resources in a class's finalize method. This is now widely considered a deplorable mistake, as it turns out having things happen in unpredictable order causes more problems than it solves, particularly if they have effects on the external environment (and not just the strictly process-private memory pool). Ultimately it just wasn't worth making the garbage collection process deterministic just to allow this pattern of resource management, when the language already has finally (and now scoped resources) to achieve the same thing.

A: When a process is terminated, all of the allocated memory gets automatically released back to the operating system, and any open file handles are closed.  That's your safety valve.
The problem, of course, is that the operating system (and your compiler, for that matter) doesn't actually know that your example code is an error.  You have to state, by your intent when you write your code, when and where that file handle gets disposed.  You might have a reason for holding the file handle open.
The using statement and the IDisposable interface in C# are specifically designed to clean up unmanaged resources like file handles.
// FileStream inherits from IDisposable, and implements the Dispose() method.
using (FileStream fs = File.Create(path))
{
    fs.Write(...);
}
// The File Stream is automatically closed here, because the Dispose() method on the
// IDisposable interface is automatically called when the "using" block goes out of scope.

In a managed environment, memory is typically disposed automatically when garbage collection occurs.  Implementing using and IDisposable insures that file handles and other unmanaged resources get properly disposed before the memory is released. You can also state your specific intent by calling Close() explicitly on your files before the enclosing object goes out of scope.
In some situations, such as repositories that return an IQueryable, it can be a hindrance to put a code block in a using statement, because the connection to the database can actually close before the query is executed.
In short, the OS and the compiler can't read your mind.

A: The destructor is called after the object goes out of scope.
If f is global, then that means at program exit.
Someone could use that resource f again, and the compiler / runtime is not generally in a position to know for sure that that cannot happen in any particular case.
Its good practice to scope variables as tightly as possible, and avoid globals.  But these dynamic languages are also used as scripting languages, and scoping can be verbose and detract form readability too.
You can typically have thousands of handles open, and all are closed automatically by the OS on process exit (graceful or otherwise) anyway, so programmers are very rarely bitten by unnecessarily-long-lived resources.

A: Runtime errors are not a tool to discipline programmers. they are an ultima ratio to deal with unexpected errors which, if not handled, would leave an unstable state. Which is not the case with open file handles. In the grand scheme of things, it doesn't matter when they get closed.
Should the compiler issue a warning, if it finds unmanaged resources going out of scope without dispose? Probably. But it is still the programmers decision whether it is acceptable to let the GC handle finalisation at an arbitrary time, or whether those handles need to be closed now.


text:
Q: How to HIDE text with CSS? Have this code:

    $16,750,000  (Fee Simple)

How do I hide the text "(Fee Simple)" from displaying?
Want the Price to show but not the "Fee Simple" text

A: You can use a font-size trick like this:

h4.ihf-price {
  font-size: 0;
}

h4.ihf-price span {
  font-size: initial;
}

   $16,750,000  (Fee Simple)

Or use color trick if you want to maintain the same content width of h4:

h4.ihf-price {
  color: #fff; /* Should be the same as background */
}

h4.ihf-price span {
  color: initial;
}

   $16,750,000  (Fee Simple)

A: Hide text in the entire element. Show text only in the nested element.

.ihf-price {
  font-size: 0;
}

.ihf-for-sale-price {
  font-size: 16px;
}

   $16,750,000  (Fee Simple)

OR

.ihf-price {
  visibility: hidden;
}

.ihf-for-sale-price {
  visibility: visible;
}

   $16,750,000  (Fee Simple)


text:
Q: How can I deploy a new web application to a subdirectory of an IIS site and not have to click "Convert To Application"? I'm trying to write an automated deployment application that runs on one box but deploys to a remote QA server. Basically each time a branch is created in source control my automated deployment tool will deploy the application. Right now the code all deploys but IIS doesn't like the nested web.config files unless I use the "Convert to Application" function.
Notice in the below screenshot that for the Test-Site which was just created for the new "Test-Site" branch that the folders "Analyze", "Investigate", "Measure" and "Score" aren't applications like the RevECurrent and RevENew have above for those folders. Without actually clicking "Convert To Application" for each folder how do I make the web.config files not generate errors whenever I deploy a new subdirectory like "Test-Site"?

A: Check the System.Web.Administration namespace, it will allow you to interact with IIS. I have used it to add/remove bindings, add sites, etc... I would assume it would let you create application folders under a Web Site as well.


text:
Q: Getting a reactjs SPA spidered without using node.js I'm building a reactjs based website that others will be deploying. It takes the form of a single page app with URL routing /#like=this and the final websites will be content rich. All of the content needs to be visible to search engine bots. Is there a way to do this (even a hacky one) that doesn't require isomorphic server-side rendering? In particular, I can't expect the end users to be able to serve pages with node/express.

A:
Is there a way to do this (even a hacky one) that doesn't require isomorphic server-side rendering?

No

In particular, I can't expect the end users to be able to serve pages with node/express.

Nodejs has nothing to do with this. The client does not know where the content is rendered.


text:
Q: Is there any way to reduce time complexity of the function given below? This is the function to calculate the factorial of very large numbers. This works perfectly fine but the time complexity is quite high. How to reduce time complexity?
This function is called once.
Current time to find factorial 0f 1 million is 40 000ms;
Expected time: 10 000ms
static void calcfactorial(unsigned int n)
{
    unsigned int carry, i, j;
    len = factorial[0] = 1;
    for (i = 1; i < LEN; i++)
        factorial[i] = 0;
    for (i = 2; i <= n; i++)
    {
        carry = 0;
        for (j = 0; j < len; j++)
        {
            factorial[j] = factorial[j] * i + carry;
            carry = factorial[j] / 10;
            factorial[j] = factorial[j] % 10;
        }
        while (carry)
        {
            factorial[len++] = carry % 10;
            carry = carry / 10;
        }
    }
}

A: Since you only need a four-fold improvement in time, the following may suffice:

*

*Use a wider (unsigned) integer type, such as uint64_t.

*Instead of calculating in base ten, use the largest power of ten, B, such that B•N fits in the integer type1, where N is the number you are computing the factorial of. For example, for 64-bit integers and 1,000,000!, you could use base 1013.

*When doing multiplications, do not multiply by every digit in the product array, as the loop for (j = 0; j < len; j++) does. All digits beyond the first start as zero, and they slowly become non-zero as work progresses. Track the highest non-zero digit, and do multiplications only up to that digit, until the product carries into the next digit.

*Similarly, the low digits become zero as the work progresses, due to accumulating factors of the base in the factorial. Track the lowest non-zero digit, and start work there.

A program demonstrating these is below.
A significant cost in this program is the divisions by the base. If you switch to a power-of-two base, these become bitwise operations (shifts for division and bitwise AND operations for remainders), which are much cheaper. This should speed up computing the factorial considerably. However, the final product will have to be converted to decimal for output. That will have a lower cost than computing entirely in decimal, so it is a win.
After that, you might consider this answer in Computer Science Stack Exchange. It suggests restructuring the factorial as powers of primes and using repeated squaring to compute the powers of primes, which are then multiplied.
This answer suggests using n! ≈ sqrt(2πn)•(n/e)n, which would require more sophisticated mathematics and programming.
Footnote
1 The purpose of using a power of ten is then the result can be directly printed from its base-B digits.
Demonstration
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/*  Define T to be an unsigned integer type.  The larger the better up to the
    widest type supported efficiently (generally the widest type for which the
    processor has arithmetic instructions).

    Define PRIuT to be a printf conversion specifier to print a type T as an
    unsigned decimal numeral.
*/
typedef uint64_t T;
#define PRIuT   PRIu64

//  Return the base-10 logarithm of x, rounded down.
static unsigned ilog10(T x)
{
    unsigned log = 0;
    for (; 10 <= x; x /= 10)
        ++log;
    return log;
}

//  Return 10**x.
static T iexp10(unsigned x)
{
    T power = 1;
    for (; 0 < x; --x)
        power *= 10;
    return power;
}

int main(void)
{
    //  Set the value we want the factorial of.
    static const T N = 1000000;

    //  Set the maximum value of T by using wrapping.
    static const T MaximumT = -1;

    /*  Determine the maximum number of decimal digits we can use easily:

            Given a number with Digits decimal digits, Digits*N will be
            representable in a T.
    */
    unsigned Digits = ilog10(MaximumT/N);

    /*  Set Base to 10**Digits.  This is the numerical base we will do
        arithmetic in -- like base ten, but more efficient if it is bigger.
    */
    T Base = iexp10(Digits);

    /*  Set an array size that is sufficient to contain N!

        For 1 < N, N! < N**N, so the number of digits in N! is less than
        log10(N**N) = N * log(10).  Since we are using ilog10, which rounds
        down, we add 1 to it to round up, ensuring we have enough room.

        Then we divide that number of digits by the number of digits we will
        have in each array element (and round up, by subtracting one before the
        division and adding one after), and that is the number of array
        elements we allocate.
    */
    size_t S = (N * (ilog10(N)+1) - 1) / Digits + 1;
    T *Product = malloc(S * sizeof *Product);
    if (!Product)
    {
        fprintf(stderr,
            "Error, unable to allocate %zu bytes.\n", S * sizeof *Product);
        exit(EXIT_FAILURE);
    }

    /*  Initialize the array to 1.  L and H remember the index of the lowest
        and highest non-zero array element, respectively.  Since all the
        elements before L or after H are zero, we do not need to use them in
        the multiplication.
    */
    Product[0] = 1;
    size_t L = 0, H = 0;

    //  Multiply the product by the numbers from 2 to N.
    for (T i = 2; i <= N; ++i)
    {
        //  Start with no carry.
        T carry = 0;

        /*  Multiply each significant base-Base digit by i, add the carry in,
            and separate the carry out.  We start separately with the lowest
            non-zero element so we can track if it becomes zero.
        */
        while (1)
        {
            T t = Product[L] * i + carry;
            carry = t / Base;
            if ((Product[L] = t % Base))    //  Leave when digit is non-zero.
                break;
            ++L;    //  If digit is zero, increase L.
        }
        for (size_t j = L+1; j <= H; ++j)
        {
            T t = Product[j] * i + carry;
            carry = t / Base;
            Product[j] = t % Base;
        }

        //  If there is a final carry out, put it in a new significant digit.
        if (0 != carry)
            Product[++H] = carry;
    }

    /*  Print the result.  The first base-Base digit is printed with no
        leading zeros.  All subsequent base-Base digits are printed with
        leading zeros as needed to ensure exactly Digit decimal digits are
        printed.
    */
    printf("%" PRIuT, Product[H]);
    for (size_t j = H; 0 < j--;)
        printf("%0*" PRIuT, Digits, Product[j]);
    printf("\n");

    free(Product);
}


text:
Q: Haskell Stack and C Libraries II This is a follow-up of this post (unfortunately).
I am trying to stack build a project where Main.hs has some FFI calls to a proprietary C library, libMyLib.so, located in /usr/local/lib (which is included in LD_LIBRARY_PATH).
When run in GHCi (outside stack) with the command ghci /usr/local/lib/ -lMyLib, everything works fine.
However when running stack build, I have a linking-related issue :
me@user:~/myproject$ stack build

myproject-0.1.0.0: build
Preprocessing library myproject-0.1.0.0...
In-place registering myproject-0.1.0.0...
Preprocessing executable 'myproject-exe' for myproject-0.1.0.0...
Linking .stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/myproject-exe/myproject-exe ...
/usr/bin/ld: .stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/myproject-exe/myproject-exe-tmp/Main.o: undefined reference to symbol 'mycfunction'
/usr/local/lib/libMyLib.so.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

--  While building package myproject-0.1.0.0 using:
      /home/me/.stack/setup-exe-cache/x86_64-linux/setup-Simple-Cabal-1.22.5.0-ghc-7.10.3 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.22.5.0 build lib:myproject exe:myproject-exe --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1

Here is an extra of the associated cabal file:
library
  hs-source-dirs:      src
  exposed-modules:     Lib
  build-depends:       base >= 4.7 && < 5
  default-language:    Haskell2010
  extra-libraries:     MyLib

executable myproject-exe
  hs-source-dirs:      app
  main-is:             Main.hs
  ghc-options:         -threaded -rtsopts -with-rtsopts=-N
  build-depends:       base, bytestring, safe, split
                     , myproject
  default-language:    Haskell2010

Running stack exec env shows that the LD_LIBRARY_PATH points to the right directory (LD_LIBRARY_PATH=/usr/local/lib), and just to make sure I have added this directory to the .yaml file (extra-lib-dirs: [/usr/local/lib]).
I have played with various GCC compile options, e.g. -pthread instead of -threaded..., via the .cabal file parameters or directly via stack build (stack build --ghc-options="-foo..."), but to no avail.
My question: where else should I look? What kind of test should I run to find the origin of the issue (apparent linking problem)?
== EDIT ==
There were two versions of the same C library installed, and one has a dependency on another C library, say libOther.so.
When I finally realized that, I added it to the cabal file and that worked fine :
extra-libraries:     Other, MyLib


text:
Q: Ubuntu - .desktop file linked to Python script - script works but logging doesn't I have a Python script placed in the Exec of Start.desktop as follows:
[Desktop Entry]
Version=1.0
Type=Application
Terminal=true
Name=Start
Exec=/home/user/Desktop/script.py
Comment=startup

Double-clicking the icon brings up my GUI and the Terminal with the script's output and all is well.
But unfortunately the script does not add to the existing log file script.log!
When I run my script from the command line python script.py the script does add to the log file. I am very confused here!
I have my logging setup to print to the Terminal and the log file as follows:
logging.basicConfig(
    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %
        (message)s",
    handlers=[
        logging.FileHandler('script.log'),
        logging.StreamHandler()
    ], level=logging.DEBUG, datefmt="%Y-%m-%d %H:%M"
)

In my attempts I tried creating a wrapper wrapper.sh with the following:
#!usr/bin/env bash
script.py > script.log

...and then placed wrapper.sh in the Exec section of Start.desktop. No luck there; running this setup erased my log file completely and added no new entries.
For what it's worth I made sure permissions were OK using chmod +x and chmod +r on Start.desktop and script.py (not sure if that matters here). All the output from the file is logging.debug('stuff') lines.

A: After some digging I couldn't find much so I double-checked all my paths and such.
I tried providing a full path to the log file inside script.py such that:
logging.basicConfig(
    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %
        (message)s",
    handlers=[
        logging.FileHandler('/home/user/Desktop/script.log'),
        logging.StreamHandler()
    ], level=logging.DEBUG, datefmt="%Y-%m-%d %H:%M"
)

and with that my issue was resolved.
Must be due to the .desktop file not having a reference for any sort of current directory, whereas running script.py from the same directory as the script.log is fine because they are in the same directory.


text:
Q: Circular table problem I've looked other questions that might help solve my problem, but haven't found any people who've used my method to solve it. The problem goes like this: Suppose there are 7 men and 5 women, and they have to be seated around a circular table in such a way that no two women are seated together. Here's how i reason: We first choose 5 men. There are ${7\choose 5}$ ways of doing this. We then sit them at the table. There are $4!$ ways of doing this (since we divide by the number of rotations). Now we have to arrange the 5 women to sit between the men. There are $5!$ ways of doing this, once the 5 men are already seated. So far, we've seated 5 men and 5 women and haven't left two women seating together. Now, we are left with two men that are still standing, and here's were the tricky part comes: the 6th man has no restrictions to seat, and can seat between any pair of consecutive people who are already seated. So this man has 10 ways of doing such thing. Now, the 7th man, because of the same reasons, has 11 places to seat once the 6th man has seated (the 6th man creates a new possible place once he seats). So now, the number of total ways is $${7\choose 5} \cdot4! \cdot 5! \cdot10\cdot11$$ Ugh, i said "seated" and "ways" a lot of times. Sorry for the tediousness. Anyways, is my reasoning right?

A: Although less chivalrous, I'd seat the men first in 6! ways, insert 5 chairs for the women in the 7 gaps in ${7\choose5}$ ways, and seat the women in 5! ways.
$6!\cdot{7\choose 5}\cdot5! = 1814400$ ways

A: No, it's not right; you counted lots of configurations several times, because you could have chosen other groups of $5$ men and arrived at the same configuration. Also you can't easily correct for this overcounting, since depending on whether you added the two extra men in the same group of men or in two different groups of men, you overcounted by a factor or $4$ or $3$ respectively. You could sort that out with some bookkeeping, but this is more straightforward:
Seat the $5$ women, in $4!$ cyclically distinct ways. Put $5$ men's places between them, and distribute $2$ extra men's places over those $5$ "bins", in $\binom62=15$ different ways. Then distribute the men in $7!$ different ways over their $7$ seats, for a total of $4!\cdot15\cdot7!=1814400$ possibilities.
Note that this is $3\frac23$ times less than your count, consistent with the above argument that you overcounted some cases by a factor of $3$ and some by a factor of $4$.


text:
Q: combobox with different datacontext for ItemsSource and SelectedItem So i have a combobox as the CellEditingTemplate of a datagrid and selected item is bound to the datacontext of that row as expected, but i need the combobox to be populated from a ObservableCollection outside of the context of the datagrid from the ViewModel.
How could i acheive this?
Thanks

A: In this case the most likely scenario is to specify a Source for your binding on the ComboBox.
<Grid.Resources>
   <local:SomeTypeThatHasAEnumerableProperty x:Key="HolderOfEnumerable" />
</Grid.Resources>
...
<ComboBox ItemsSource="{Binding EnumerableProperty, Source={StaticResource HolderOfEnumerable}}" ....>


text:
Q: list comprehension with iteration Suppose i have a list L which consists of integer elements. I want to construct a list T which for each index i in 0..len(L) contains the item L[i]  provided it is larger than 0 using List comprehension in python.
I tried the following command to do this
T=[L[i] if L[i]>0 for i in range(len(L))]

but i keep getting an error of invalid syntax. How would i do this correctly using List comprehensions in python?

A: Your syntax is wrong :
L = [1,2,-4,5,-6,7,8,9]
T = [L[i] for i in range(len(L)) if L[i]>0]

Output:
[1, 2, 5, 7, 8, 9]

Also you can just iterate through the elements of the list per se, no need to use a range. Like this : T = [i for i in L if i>0]
Remember :
When only if is there the syntax is [expression for var in list if ...]
When both if and else is there the syntax is [expression1 if ... else expression2 for var in list]

A: You need to write the filter after the iteration part. So:
   T=[L[i] for i in range(len(L)) if L[i]>0]
#     \__/ \_______ ____________/ \___ ___/
#     yield        v                  v
#               iteration           filter

Right now Python thinks that you want to write a ternary operator, like:
T=[L[i] if L[i] > 0 else 0 for i in range(len(L))]
This is incorrect: here you would evaluate L[i] if L[i] > 0 else 0 for every element, and you would thus add a 0 for every item L[i] where the element is less than or equal to zero.
That being said, you can write your list comprehension more elegant (and faster), with:
T = [l for l in L if l > 0]
So instead of iterating over indices, we iterate over the elements l in L. We also filter on l and yield l in case the filtering is successful.

A: While you can use a list comprehension to solve this problem, you can also use filter with a lambda function:
final_l = list(filter(lambda x:x > 0, L))


text:
Q: Delphi - accesing non UI units from inside a thread I have the following situation.
We develop in DelphiXE.
We are putting the majority of our functions in a DATAMODULE.
function1 (database, transaction, paramInteger) : float
for example
function1 take parameters database (TIBDATABASE), the transaction TIBTRANSACTIOn and aditiona parameter integer. and return a float
function  GetLastPretAch(DIBase : TIBDatabase; Tran : TIBTransaction; const aID : Integer) : Double;
var workQuery : TIBQuery;
begin
  try
    workQuery := TIBQuery.Create(Application);
    try
      workQuery.Close;
      workQuery.Database    := DIBase;
      workQuery.Transaction := Tran;
      workQuery.SQL.Clear;
      workQuery.SQL.Add('SELECT * FROM GETLASTPRETACH(-1, :AARTNR)');
      workQuery.ParamByName('AARTNR').AsInteger := aID;
      workQuery.Open;
      Result := workQuery.FieldByName('LASTPRET').AsFloat;
    except
      on e : Exception do begin
        raise EMagisterException.Create(TranslateIbError(e));
      end;
    end;
  finally
    FreeAndNil(workQuery);
  end;
end;

Now I want to use this functions from a thread. is this thread safe?
inside execute procedure like
  ID := GetLastPretAch(database, transaction, 1);

is or not thread safe?

A: The answer to your question is Yes, you can use that function from inside a worker thread's execute procedure. You might want to consider refining your SQL to only SELECT the field LASTPRET instead of SELECT *.
For an extended discussion on what "thread safe" means refer to this SO question
What does threadsafe mean?

A: Looks like you're using IBX Components which, the last time I looked were most definitely NOT thread-safe. If you switched to a data access layer that was thread-safe, you should be fine with that code. FYI UIB (Unified Interbase components) are thread-safe.


text:
Q: Changing the PropertyGrid's Description and Category attributes at runtiome I'm working on a business application that use the PropertyGrid. My project leader want me to localize the texts in the PropertyGrid at runtime. Hurray!!! irony
I have tried many days to localize the PropertyGrid. But I have trouble changing the attributes Description and Category at runtime. Changing the DisplayName works fine.
I have made a simple example to reproduce the issue: Create a Windows Form application and from the ToolBox add a PropertyGrid and a Button with default settings.
Here is the class I would like to display in the PropertyGrid:
class Person
{
    int age;

    public Person()
    {
        age = 10;
    }

    [Description("Person's age"), DisplayName("Age"), Category("Fact")]
    public int Age
    {
        get { return age; }
    }
}

In the Form's constructor; I create the Person object and display it in the PropertyGrid.
    public Form1()
    {
        InitializeComponent();
        propertyGrid1.SelectedObject = new Person();
    }

The button is used to change the DisplayName, Description and Category attributes at runtime.
    private void button1_Click(object sender, EventArgs e)
    {
        SetDisplayName();
        SetDescription();
        SetCategory();

        propertyGrid1.SelectedObject = propertyGrid1.SelectedObject;  // Reset the PropertyGrid
    }

The SetDisplayName() method works fine and actually changes the DisplayName of the property in runtime!
    private void SetDisplayName()
    {
        Person person = propertyGrid1.SelectedObject as Person;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(person)["Age"];
        DisplayNameAttribute attribute = descriptor.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
        FieldInfo field = attribute.GetType().GetField("_displayName", BindingFlags.NonPublic | BindingFlags.Instance);
        field.SetValue(attribute, "The age");
    }

SetDescription() and SetCategory() methods are almost identical to the SetDisplayName() method, except for some type changes and strings to access the private member of each attributes.
    private void SetDescription()
    {
        Person person = propertyGrid1.SelectedObject as Person;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(person)["Age"];
        DescriptionAttribute attribute = descriptor.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
        FieldInfo field = attribute.GetType().GetField("description", BindingFlags.NonPublic |BindingFlags.Instance);
        field.SetValue(attribute, "Age of the person");
    }

    private void SetCategory()
    {
        Person person = propertyGrid1.SelectedObject as Person;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(person)["Age"];
        CategoryAttribute attribute = descriptor.Attributes[typeof(CategoryAttribute)] as CategoryAttribute;
        FieldInfo[] fields = attribute.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        FieldInfo field = attribute.GetType().GetField("categoryValue", BindingFlags.NonPublic | BindingFlags.Instance);
        field.SetValue(attribute, "Info");
    }

Both SetDescription() and SetCategory() methods compile and run but don't effext the ProperytGrid. After the last line of each method you can use the IntelliSense to see that the the Attribute object (DescriptionAttribute and CategoryAttribute) has a member that has changed.
After running these three methods and resetting the PropertyGrid (see button1 click method); the PropertyGrid has only changed the DisplayName attribute. The Description and the Category attributes are unchanged.
I would really like some help to solve this issue. Please any suggestion or solutions?
Note 1:
I don't want any responses saying that this is impossible and the attributes can only be set at design time. That is not true! This article from CodeProject.com show an example how to localize the PropertyGrid and to change the attributes in runtime. Unfortunately I have problem scoping the example for those parts I need to solve this issue.
Note 2:
I would like to avoid using resouce files. This is due to the localization is located in different language files. Each file contain a bunch of indices, each with a string value. All indices and string values are loaded into Dictionary object. To access a string the index is used to access it. I most, unfortunately, use this solution.
Best regards,
/Mc_Topaz

A: Here is a good article for Globalized-property-grid
You can give many resource file for the Person ,than will the propery-grid will localize.
Here is three step:

*

*inherit from GlobalizedObject

*Give the resource file for Person with the same name (eg.Person.zh-cn.resx)

*change the thread's cuture which you want to display.

You can try ,Good Luck!

A: What you could do is reuse the DynamicTypeDescriptor class described in my answer to this question here on SO: PropertyGrid Browsable not found for entity framework created property, how to find it?
like this:
  public Form1()
  {
      InitializeComponent();

      Person p = new Person();

      DynamicTypeDescriptor dt = new DynamicTypeDescriptor(typeof(Person));
      propertyGrid1.SelectedObject = dt.FromComponent(p);
  }

  private void button1_Click(object sender, EventArgs e)
  {
      DynamicTypeDescriptor dt = (DynamicTypeDescriptor)propertyGrid1.SelectedObject;
      DynamicTypeDescriptor.DynamicProperty dtp = (DynamicTypeDescriptor.DynamicProperty)dt.Properties["Age"];

      dtp.SetDisplayName("The age");
      dtp.SetDescription("Age of the person");
      dtp.SetCategory("Info");

      propertyGrid1.Refresh();
  }

A: xudong125 answer solves the issue! I managed to work around the resource files solution by using a static source instead. It's to complicated to explain...
But creating classes implementing ICustomTypeDescriptor and PropertyDescriptor is the way to go.
The key was to override DisplayName, Description and Category methods in the sub class of the PropertyDescriptor class. In these overriden methods I pointed to a public static source and managed to get the strings I wanted.
/Mc_Topaz

A: I have a different reason to change the property description and found a fairly crude but much simpler solution for just correcting the description that is shown in the grid. Advantage for me was that the class of the object shown in the property grid required much less change.
My situation was the following: I have two boolean properties A and B, where B only can be used if A is set. If A is False, I want to make B read-only and set its description to something like "This property can only be used if you set 'A' to True". In the object code I set the Description attribute of B to this message, similar to how Mc_Topaz does that.
To only set the description that is shown for the selected property to its correct current value, I use the following SelectedGridItemChanged event handler for my PropertyGrid named pgConfig:
    private void pgConfig_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
    {
      GridItem giSelected = e.NewSelection;
      if ((giSelected != null) && (giSelected.PropertyDescriptor != null))
      {
        string sDescription = GetCurrentPropertyDescription(giSelected.PropertyDescriptor.Name);
        if ((sDescription != null) && (sDescription != giSelected.PropertyDescriptor.Description))
        {
          MethodInfo miSetStatusBox = pgConfig.GetType().GetMethod("SetStatusBox", BindingFlags.NonPublic | BindingFlags.Instance);
          if (miSetStatusBox != null)
            miSetStatusBox.Invoke(pgConfig, new object[] { giSelected.PropertyDescriptor.DisplayName, sDescription });
        }
      }
    }

In the code sample, GetCurrentPropertyDescription is a private function that retrieves the current property description of the object being shown in the property grid (m_da.Config in my case):
    private string GetCurrentPropertyDescription(string sPropertyName)
    {
      PropertyDescriptor oPropDescriptor = TypeDescriptor.GetProperties(m_da.Config.GetType())[sPropertyName];
      if (oPropDescriptor != null)
      {
        DescriptionAttribute oDescriptionAttr = (DescriptionAttribute)oPropDescriptor.Attributes[typeof(DescriptionAttribute)];
        if (oDescriptionAttr != null)
          return oDescriptionAttr.Description;
      }
      return null;
    }

My solution is less suitable than huoxudong125's if you want full globalization, but if you just want dynamic descriptions for some of your properties without changing the inheritance of the object being shown, it is an option.
Disadvantage of my method is that the underlying cached PropertyDescriptor objects of the grid are never updated, so SetStatusBox will always be called twice if a property with changed description is selected, which is inefficient.

A: The solution of huoxudong125 is one possible solution. I'd like to offer another one (but without talking about how to change the culture stuff at runtime - you can google that yourself ;) ). For myself I started with using localized subclasses for DisplayName, Description and Category.
As we know, DisplayName does update to current culter when PropertyGrid is updated, but Description and Category do not. I think the reason for this is on reflection level, when PropertyGrid requests category and description. As you can see, those values are cached on first read but displayName is not. To tackle that I developed two solution (where the first one is weird and I do not understand why that works myself..). Both revolve around an extra TypeDescriptionProvider
The base
First goes the custom TypeDescriptionProvider, which can be bound to any class via attribute:
internal class UpdateableGlobalizationDescriptionProvider<TTargetType> : TypeDescriptionProvider
{
    private static TypeDescriptionProvider defaultTypeProvider = TypeDescriptor.GetProvider(typeof(TTargetType));

    public UpdateableGlobalizationDescriptionProvider() : base(defaultTypeProvider) { }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        var result = base.GetTypeDescriptor(objectType, instance);
        return new ForcedGlobalizationTypeDescriptor(result);
    }
}

First solution
This one revolves around "just get it done"... Add a CustomTypeDescriptor implementation, which wraps original PropertyDescriptor instances with the custom ones:
internal class ForcedGlobalizationTypeDescriptor : CustomTypeDescriptor
{
    readonly ICustomTypeDescriptor inner;

    public ForcedGlobalizationTypeDescriptor(ICustomTypeDescriptor typeDescriptor) : base(typeDescriptor)
    {
        inner = typeDescriptor;
    }

    public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        // First solution
        var result = base.GetProperties(attributes);
        var transformed = result.OfType<PropertyDescriptor>().Select(d => new ForcedPropertyDescriptor(d)).ToArray();
        return new PropertyDescriptorCollection(transformed);
    }
}

and outer the PropertyDesciptor simply returns values from the wrapped PropertyDescriptor. The simplest implementation for PropertyDescriptor I found - tell me, if there is a shorter one, please.
internal class ForcedPropertyDescriptor : PropertyDescriptor
{
    private PropertyDescriptor innerDescriptor;
    public ForcedPropertyDescriptor(PropertyDescriptor descriptor) : base(descriptor)
    {
        innerDescriptor = descriptor;
    }
    // important:
    public override string Category => base.Category;
    public override string Description => base.Description;

    public override Type ComponentType => innerDescriptor.ComponentType;
    public override bool IsReadOnly => innerDescriptor.IsReadOnly;
    public override Type PropertyType => innerDescriptor.PropertyType;
    public override bool CanResetValue(object component) => innerDescriptor.CanResetValue(component);
    public override object GetValue(object component) => innerDescriptor.GetValue(component);
    public override void ResetValue(object component) => innerDescriptor.ResetValue(component);
    public override void SetValue(object component, object value) => innerDescriptor.SetValue(component, value);
    public override bool ShouldSerializeValue(object component) => innerDescriptor.ShouldSerializeValue(component);
}

I think it works, because for every read of category or description there is a new ForcedPropertyDescriptor, which has not cached the value, yet. At the same time this is a drawback: for like every request on the Category or Description propery a new instance of ForcedPropertyDescriptor is created, while Microsoft's implementation seems to cache craeated PropertyDescriptors somewehere.
Second solution
To avoid that instance creation every time, I simply stored every seen ProperyDescriptor created by ForcedGlobalizationTypeDescriptor in a set. And as soon as a localization change appears, that set gets called to reset it's items cached values:
internal class DescriptorReset
{
    public static DescriptorReset Default { get; } = new DescriptorReset();
    private HashSet<MemberDescriptor> descriptors = new HashSet<MemberDescriptor>();

    public void Add(MemberDescriptor descriptor)
    {
        descriptors.Add(descriptor);
    }

    private void RunUpdate()
    {
        if (descriptors.Count == 0)
            return;
        FieldInfo category, description;
        category = typeof(MemberDescriptor).GetField(nameof(category), BindingFlags.NonPublic | BindingFlags.Instance);
        description = typeof(MemberDescriptor).GetField(nameof(description), BindingFlags.NonPublic | BindingFlags.Instance);
        foreach (var descriptor in descriptors)
        {
            category.SetValue(descriptor, null);
            description.SetValue(descriptor, null);
        }
    }
}

The RunUpdate method uses Reflection to reset inner fields to null, so on the next call to corresponding properties the localized values are read again.
All you need now is some magic to call RunUpdate at the right moment. For myself I have a class in my core solution, which provides a method to set a new CultureInfo. When called, it sets the default ui culture and the default culture to the new CultureInfo and raises two events: the first one is to update all internal logic and the second one is for everything based on internal logic, like the GUI.
And since I do not know where and how long Microsoft's PropertyDescriptors are stored, I created a HashSet with WeakReference (based on WeakHashTable) to store corresponding references.
Usage
Simply append the DescriptionProvider class to your class shown in PropertyGrid:
[LocalizedDescription(nameof(MyClass), typeof(MyTextResource))]
[TypeDescriptionProvider(typeof(ForcedGlobalizationTypeDescriptor<MyClass>))]
class MyClass
{
    // ...

The way your LocalizedDescription works, depends on you...


text:
Q: Use dart json_serializable to map an object field to JSON flat keys (one to many mapping) I have a dart object that includes a field of type Money, which itself is composed of amount and currency:
@JsonSerializable()
class Account {

  final String id;
  final String type;
  final String subtype;
  final String origin;
  final String name;
  final String status;
  final String currency;
  final Money balance; <== value object
  ...
}

Money looks something like this:
class Money {
  final int amount;
  final String currency;

  const Money(this.amount, this.currency);
  ...
}

The above is to be mapped for use by sqflite, therefore the target JSON must be a flat JSON, like:
{
  "id": String,
  "type": String,
  "subtype": String,
  "origin": String,
  "name": String,
  "status": String,
  "currency": String,
  "balanceAmount": int;      <== value object
  "balanceCurrency": String; <== value object
}

I understand I can use JsonKey.readValue to extract a composite object from the entire JSON object prior to decoding.
But how can I do the opposite? Grab the two values from the Money instance and map them to balanceAmount and balanceCurrency?
Nothing in the search I did on json_serializable api docs, GitHub issues, or StackOverflow appears to respond to this in particular: how to map one field to two (or more) target keys?

A: this solution would be better if the generated code used full json in "balance"
like this:

Money.fromJson(json)

But I don't know how to do that :(
import 'package:project/test/money.dart';
import 'package:json_annotation/json_annotation.dart';

part 'account.g.dart';

@JsonSerializable()
class Account {
  final String id;
  final String type;
  final String subtype;
  final String origin;
  final String name;
  final String status;
  final String currency;
  @JsonKey(fromJson: _dataFromJson)
  final Money balance; // <== value object

  Account({
    required this.id,
    required this.type,
    required this.subtype,
    required this.origin,
    required this.name,
    required this.status,
    required this.currency,
    required this.balance,
  });

  static Money _dataFromJson(Object json) {
    if (json is Map<String, dynamic>) {
      return Money(amount: json["balanceAmount"], currency: json["balanceCurrency"]);
    }

    throw ArgumentError.value(
      json,
      'json',
      'Cannot convert the provided data.',
    );
    // return Money(amount: 0, currency:"");
  }

  factory Account.fromJson(Map<String, dynamic> json) => Account(
        id: json['id'] as String,
        type: json['type'] as String,
        subtype: json['subtype'] as String,
        origin: json['origin'] as String,
        name: json['name'] as String,
        status: json['status'] as String,
        currency: json['currency'] as String,
        balance: Money.fromJson(json),
      );
  Map<String, dynamic> toJson() => _$AccountToJson(this);
}

// {
//   "id": String,
//   "type": String,
//   "subtype": String,
//   "origin": String,
//   "name": String,
//   "status": String,
//   "currency": String,
//   "balanceAmount": int;      <== value object
//   "balanceCurrency": String; <== value object
// }


text:
Q: jQuery - animate not working right? I have this code :
function move() {

    $(document).mousemove(function(e){
         var x = e.pageX;
        $('.linkHover').animate({'right': '=' + x + 'px'}, 'slow');
   });

    }

and the HTML is :

I want to change the position for DIV with class linkHover when mouse over header links but it's not working.
How I can let the linkHover DIV follow mouse cursor when become on linksColl DIV?
NOTE : I want to follow only horizontal not vertical

A: SzamDev,
Try this JS
function move() {
    $(document).mousemove(function(e){
        var x = e.pageX;
        $('.linkHover').animate({right:x}, 'slow');
    });
}

also, if I understand you right, I did something very similar. Try plotting the X co-ord for each LI, then adding to an array, With the mouse over, set a JS call with an index of the li you wish to animate to. This worked perfectly for me.
var dotLocations = [0, 55, 170, 290, 410];
    function showFeature(a) {
        $("#featureDot").animate({
            left: dotLocations[a]
        }, 150, function () { /* animation complete */ });
    }

In this example the featureDot was a div with a small red dot in it, when "showFeature" was called the dot moved to be located under the li/button I clicked/hovered.
Hope this helps,
Chris.

A: Animate taks a number, you can leave out the px
$(document).mousemove(function(e){
   var x = e.pageX;
   $('.linkHover').animate({'right': x}, 'slow');
});

It appears you want to set the right value to x so using = is invalid and causes your error.
Code example on jsfiddle.

A: Change a line :
$('.linkHover').animate({'right': '=' + x + 'px'}, 'slow');

to
$('.linkHover').animate({'right': x}, 'slow');

and make sure you've used position of class linkHover absolute, relative or fixed
and good luck


text:
Q: Getting last row of table in SAS SQL Hello I am doing the following data step where I extract the last line of a table.
How can I do the same in a proc sql, I am hoping it will be much quicker if I can access directly the last row?
data refTable;
    set vhd(keep= v69c1ec v69dhec v69nbms fixing where=(fixing = 'continu')) end=eof;
    if eof then output;
    by v69dhec v69nbms;
run;

Thanks

A: No, it is not possible to reproduce this behavior in SQL.  There is no natural sense of "row order" in SQL.  Note that you are NOT accessing the "last line of a table"; you are getting the last qualifying row after the application of a WHERE clause.
If you really were getting the last row, a much faster SAS technique would be to use the POINT= and NOBS= options, something like this:
data refTable;
    get_me = nobs;
    set vhd(keep=v69c1ec v69dhec v69nbms fixing) point=get_me nobs=nobs;
    output;
    stop;
run;

Notice this only works if you do NOT include a WHERE clause!

A: As far as I know, you cannot access the last row using proc sql directly.  The process would be to order the data and then choose the first row, using outobs = 1.
This question here explains how to get the last row efficiently in SAS.  Basically, ask SAS how many records are in the data set and then skip ahead directly to that one.


text:
Q: Extract PathParam From The URL I want to extract pathparam from url; This is my url below

www.url.com/api/customer/897979/agent/6758/platform/win

Here  cutomer_id=897979 and agent_id=agent and platform_id=win
My Class extends AbstractFactoryFilter
 @Override
public GatewayFilter apply(Object config) {
    return (exchange, chain) -> {

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {

        }));
    };
}

I tried using the below,But it return null
    RequestPath path = exchange.getRequest().getPath();

I also tried something like this
 private HashMap<String, String> getPathParameters(String uri, String strUrlTemplate) {

    UriTemplate template = new UriTemplate(strUrlTemplate);
    Map<String, String> parameters = new HashMap<>();
    Boolean value = template.match(uri, parameters);
    return new HashMap<>(parameters);

}

UPDATE :
I want to extract cutomer_id=897979 and agent_id=agent and platform_id=win
from the below url
www.url.com/api/customer/897979/agent/6758/platform/win
I am using AbstractFragemtFilter
public class FragmentFilter extends AbstractGatewayFilterFactory


text:
Q: Laravel Select category Automatically Based on Time I have a table
Categories

*

*ID

*Name

*Start_time(Timestamp)

*End_time(Timestamp)

I want to show the categories based on time automataically.Like I have categories Breakfast,lunch,dinner etc.I want when user comes to website it will automatically shown that category based on current time.To get current time I am using Carbon api.
To get all categories on main page I am using:
Controller:
public function index()
{
     $Foods=Food::paginate(4);
     $now =Carbon::now();
     $Category=DB::table('Categories')
         ->where('Start_time', '<', $now)
         ->where('End_time', '>', $now)
         ->get();
    return view('welcome', compact('Foods','Category'));
}

public function categ($Category_id)
{
   $category = Categories::with('food')->findOrFail($Category_id);
   return view('category', compact('category'));
}

Routes:
Route::get('/','DetailsController@index');
Route::get('category/{Category_id}', 'DetailsController@categ');

welcome.blade.php:
@foreach ($Category as $categories)
<button
style="font-size:14px; width: 230px; height: 30px; background-color: #00A30C; color:white; font-style: italic; text-align: center; font-size: 15px; margin: 0 auto;">
<a  href="category/{{$categories->Category_id}}">{{$categories->CategoryName}} </a></button>

@endforeach

But with the above query this return "[ ]".How I can get category based on current time?is there any mistake in the query?I am new to laravel plz help me.Thanks


text:
Q: --- SkImageDecoder::Factory returned null I am trying to insert and retrieve image data from SQLite Database.
I have the following codes. Image is inserted correctly but when I try to retrieve, Logcat shows  --- SkImageDecoder::Factory returned null error. Please help me
This class is used to create and insert database
    ImageView img;
    String picpath;
    Bitmap bmp;
    Canvas cnvs;
    Random r;
    int x, y, height, width;
    ByteArrayOutputStream blob;
    //SQL sql;
    Paint paint;
    String name, no;
    Uri data;
    SQLiteDatabase db;
    String[] filePath = {MediaStore.Images.Media.DATA};
    ;
    Cursor cur;
    TextView txt;
    int colIndex;
    ContentValues ctv;
    byte[] imgData;

    public static final String DB_NAME = "New.db";
    public static final String TABLE_NAME = "Sample";
    public static final int DB_VERSION = 1;

    public static final String NAME = "Name";
    public static final String NO = "No";
    public static final String IMG = "Img";
    public static final String PIXELX = "PosX";
    public static final String PIXELY = "PosY";

    public void create() {
        db = openOrCreateDatabase(DB_NAME, Context.MODE_WORLD_WRITEABLE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + NAME + " TEXT NOT NULL," + NO + " TEXT PRIMARY KEY," + IMG + " BLOB," + PIXELX + " INTEGER ," + PIXELY + " INTEGER );");
        db.close();
    }

    public void insert() {
        db = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        db.execSQL("DELETE FROM " + TABLE_NAME);
        ctv.put(NAME, name);
        ctv.put(NO, no);
        try {
            FileInputStream img_file = new FileInputStream(picpath);
            BufferedInputStream bis = new BufferedInputStream(img_file);
            imgData = new byte[bis.available()];
            bis.read();
            ctv.put(IMG, imgData);
            long val = db.insert(TABLE_NAME, null, ctv);
            Toast.makeText(this.getBaseContext(), "Image Saved", Toast.LENGTH_SHORT).show();
            if (val < 0)
                Toast.makeText(this.getBaseContext(), "Image not Saved", Toast.LENGTH_SHORT).show();
            bis.close();
        }
        catch (Exception e) {
            e.getMessage();
        }
        db.close();
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        ctv = new ContentValues();
        img = (ImageView) findViewById(R.id.imageView1);

        r = new Random();
        paint = new Paint();
        x = r.nextInt(100);
        blob = new ByteArrayOutputStream();
        create();

        Intent i = getIntent();
        name = i.getStringExtra("name");
        no = i.getStringExtra("no");
        //Open Button
        Button open = (Button) findViewById(R.id.button3);
        open.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent gal_open = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(gal_open, 1);

            }
        });
        txt = (TextView) findViewById(R.id.textView1);

        Button shuffle = (Button) findViewById(R.id.button2);
        shuffle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                bmp = Bitmap.createBitmap(img.getHeight(), img.getWidth(), Bitmap.Config.RGB_565);
                cnvs = new Canvas(bmp);

                height = img.getMeasuredHeight();
                width = img.getMeasuredWidth();
                x = r.nextInt(height);
                y = r.nextInt(width);
                paint.setColor(Color.RED);

                txt.setText(x + "," + y);
                cnvs.drawBitmap(BitmapFactory.decodeFile(picpath), 0, 0, null);
                cnvs.drawRect(x, y, x + 20, y + 20, paint);
                img.setImageBitmap(bmp);

            }
        });

        Button ok = (Button) findViewById(R.id.button1);
        txt = (TextView) findViewById(R.id.textView1);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                create();
                insert();

                startActivity(new Intent(getApplicationContext(), MainActivity.class));
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intentData) {
        super.onActivityResult(requestCode, resultCode, intentData);
        if (requestCode == 1 && resultCode == RESULT_OK && intentData != null) {

            bmp = Bitmap.createBitmap(img.getHeight(), img.getWidth(), Bitmap.Config.RGB_565);
            cnvs = new Canvas(bmp);
            height = img.getMeasuredHeight();
            width = img.getMeasuredWidth();
            x = r.nextInt(height);
            y = r.nextInt(width);
            paint.setColor(Color.RED);

            data = intentData.getData();

            cur = getContentResolver().query(data, filePath, null, null, null);
            cur.moveToFirst();

            colIndex = cur.getColumnIndex(filePath[0]);
            picpath = cur.getString(colIndex);
            cur.close();

            txt = (TextView) findViewById(R.id.textView1);
            txt.setText(x + "," + y);
            cnvs.drawBitmap(BitmapFactory.decodeFile(picpath), 0, 0, null);
            cnvs.drawRect(x, y, x + 20, y + 20, paint);
            img.setImageBitmap(bmp);
        }
    }

The code to retrieve data is
public class Login extends Activity {
    //SQL sql;
    User user;
    String name;
    TextView no;
    ImageView img;
    int imgx, imgy;
    View touchlistener;
    SQLiteDatabase db;
    byte[] imgData1;
    Cursor cur;
    int pixelx, pixely;
    public static final String DB_NAME = "New.db";
    public static final String TABLE_NAME = "Sample";
    public static final int DB_VERSION = 1;

    public static final String NAME = "Name";
    public static final String NO = "No";
    public static final String IMG = "Img";
    public static final String PIXELX = "PosX";
    public static final String PIXELY = "PosY";

    @SuppressLint("NewApi")
    public void retrieve() {
        img = (ImageView) findViewById(R.id.imageView1);

        db = openOrCreateDatabase(DB_NAME, Context.MODE_WORLD_WRITEABLE, null);
        cur = db.query(true, TABLE_NAME, new String[]{NAME, NO, IMG, PIXELX, PIXELY}, null, null, null, null, null, null, null);
        cur.moveToFirst();
        imgData1 = cur.getBlob(cur.getColumnIndex("Img"));
        img.setImageBitmap(BitmapFactory.decodeByteArray(imgData1, 0, imgData1.length));
        Toast.makeText(getApplicationContext(), "Image Retreived", 100).show();
        cur.close();
        db.close();
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        retrieve();
    }
}


text:
Q: Batch file - loop through first n lines of text file I'm trying to determine the format of a text file by looping through the first 10 lines, perform some regex matching and then compare the results at the end. I can easily loop through the entire file, but I only want the first N lines (in this case 10)
I'm familiar with other languages, but the idiosyncrasies of this batch file is throwing me for a loop so to say.
Here is what I have so far:
@echo off
setlocal enableDelayedExpansion
set /A REGEXCOUNTER=0
set /A COUNTER=0
for /F %A in (%submitfile%) do (
  set /A COUNTER=COUNTER+1
  rem echo %A
  setlocal enableDelayedExpansion
  echo(%A|findstr /r /c:"[0-9].*" >nul && (
  set /A REGEXCOUNTER=REGEXCOUNTER+1
  echo %COUNTER% - %REGEXCOUNTER% - FOUND - %A
      rem any commands can go here
  ) || (
      echo NOT FOUND
      rem any commands can go here
  )

  rem LOOP END

  if %COUNTER% GEQ 10 do (goto loop_over)
  )
)
:loop_over
echo "END HERE!"

I've got counters set up that incrementally tick up to count my matches and how many times it's looped. However here is some sample output of variable values:
110 - 0 - FOUND - 003
220 - 0 - FOUND - 2
330 - 0 - FOUND - 1
440 - 0 - FOUND - 029

The loop counter variable is increasing by ten for each loop and the regex match counter is not going up at all. I'm pretty sure this has something to do with variable scope but I'm not sure where to begin.

A: This should fix all the issues I talked about in my comments above.
@echo off
setlocal enableDelayedExpansion
set /A REGEXCOUNTER=0
set /A COUNTER=0
for /F %%A in (%submitfile%) do (
  set /A COUNTER=COUNTER+1
  rem echo %%A
  echo(%%A|findstr /r /c:"[0-9].*" >nul && (
  set /A REGEXCOUNTER=REGEXCOUNTER+1
  echo !COUNTER! - !REGEXCOUNTER! - FOUND - %%A
      rem any commands can go here
  ) || (
      echo NOT FOUND
      rem any commands can go here
  )

  rem LOOP END

  if !COUNTER! GEQ 10 goto loop_over
  )
)
:loop_over
echo "END HERE"

A: *

*The extra setlocal within the loop should be removed. Once setlocal enabledelayedexpansion has been executed, it remains in effect until a setlocal disabledelayedexpansion is executed or until the batch terminates.

*Each %A (the loop-control metavariable must be %%A (one % if run from the command-line, two if within a batch file)

*If you change the value of a variable within the loop, then you need to refer to the changed value as !varname!, not %varname% which is the original value (search SO for delayed expansion). set /a always works on the current variable value.


text:
Q: How to add links to header top in magento 2 How to add links to header top in magento 2.
i have tried to
<?xml version="1.0"?>  <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">  <referenceBlock name="header.links"> <block class=vendor\HelloWorld\Block\Link" name="add-new-header-link"> <arguments> <argument name="label" xsi:type="string" translate="true">New Link</argument> <argument name="path" xsi:type="string" translate="true">new-link</argument> </arguments> </block> </referenceBlock>

but that does not seems to work

A: First you need to create a custom module for that you can follow this tutorial:-
https://www.mageplaza.com/magento-2-module-development/
after above step now you need to follow few more steps:-
Step 1: We will create a CMS page. For example, we create a "Custom Link" page  with an URL such as //domain.com/custom_link.
Step 2:  Create a default.xml file in the following path:  app\code\Vendor\Module\view\frontend\layout with the following content:
<?xml version="1.0"?>
<page xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceBlock name="header.links">
            <block class="Vendor_name\Module_name\Block\Link" name="some_link" >
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Custom link</argument>
                    <argument name="path" xsi:type="string">test</argument>
                </arguments>
            </block>
        </referenceBlock>

</page>

For more details, the previous xml is used to register a Block Class in "Vendor_name\Module_name\Block\Link" . Then, set Label and URL path for it in the arguments tag.
Step 3:  Create the Block class Link with the following content:
<?php
namespace Vendor\Module\Block;
class Link extends \Magento\Framework\View\Element\Html\Link
{
    /**
     * Render block HTML.
     *
     * @return string
     */
    protected function _toHtml()
    {
        if (false != $this->getTemplate()) {
            return parent::_toHtml();
        }
        return '
getLinkAttributes() . ' >' . $this->escapeHtml($this->getLabel()) . '
';
    }
}

Now just run the below command from your magento root directory

*

*<root>php bin/magento setup:upgrade

*<root>php bin/magento setup:static-content:Deploy -f

*<root>php bin/magento cache:clean
YOUR done!


text:
Q: YUI Compressor Errors - jQuery Autotype I'm trying to use the YUI Compressor to get all my javascripts minified and into a single file.
I'm using this javascript file: https://github.com/mmonteleone/jquery.autotype/blob/master/jquery.autotype.js
I have a local copy obviously. But when I run that particular file through the YUI Compressor I get the following errors:
[INFO] Using charset UTF-8
[ERROR] 20:32:missing formal parameter
[ERROR] 21:32:missing formal parameter
[ERROR] 21:71:syntax error
[ERROR] 22:30:syntax error
[ERROR] 25:13:syntax error
[ERROR] 26:22:syntax error
[ERROR] 27:36:identifier is a reserved word
[ERROR] 28:13:syntax error
[ERROR] 29:21:syntax error
[ERROR] 53:29:invalid property id
[ERROR] 53:30:syntax error
[ERROR] 54:30:syntax error
[ERROR] 55:22:syntax error
[ERROR] 62:29:invalid property id
[ERROR] 62:30:syntax error
[ERROR] 63:30:syntax error
[ERROR] 64:22:syntax error
[ERROR] 106:33:invalid property id
[ERROR] 106:34:syntax error
[ERROR] 107:34:syntax error
[ERROR] 108:44:syntax error
[ERROR] 109:26:syntax error
[ERROR] 151:29:invalid property id
[ERROR] 151:30:syntax error
[ERROR] 152:30:syntax error
[ERROR] 160:34:missing name after . operator
[ERROR] 163:33:missing name after . operator
[ERROR] 165:13:syntax error
[ERROR] 167:9:syntax error
[ERROR] 168:29:syntax error
[ERROR] 209:54:missing name after . operator
[ERROR] 218:9:syntax error
[ERROR] 219:30:syntax error
[ERROR] 220:27:missing ; before statement
[ERROR] 221:24:syntax error
[ERROR] 230:13:syntax error
[ERROR] 231:19:syntax error
[ERROR] 233:17:syntax error
[ERROR] 235:13:syntax error
[ERROR] 283:1:syntax error
[ERROR] 1:0:Compilation produced 40 syntax errors.
org.mozilla.javascript.EvaluatorException: Compilation produced 40 syntax errors.
at com.yahoo.platform.yui.compressor.YUICompressor$1.runtimeError(YUICompressor.java:154)
at org.mozilla.javascript.Parser.parse(Parser.java:392)
at org.mozilla.javascript.Parser.parse(Parser.java:337)
at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:533)
at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:131)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)

I've looked through their code a bit and can't figure out why it's getting this error. Any help would be greatly appreciated.

A: I figured it out. I used http://closure-compiler.appspot.com/home which is a web based Google Closure tool, which from what I've seen essentially does the same thing as YUI only their web tool gave MUCH more verbose errors than the YUI error log, and I was able to determine that it had failed because the author of the script often uses the reserved variable name of char. Modifying my local version every instance of char to 'chara' (lame I know) it worked just fine.


text:
Q: PHP False return even after it is true Below is my index.php file source code:
<?php
include "app/global.php";

$page = $_GET['page'];
echo $page;
?>

My app/global.php:
<?php
global $url;
$url = 'localhost/tpl';
$theme = 'default';

include 'classes/class.template.php';
$tpl = new Template($url, $theme);
?>

My class.template.php:
<?php
class Template {
    public function __construct($url, $theme) {
        if(file_exists($url . '/app/themes/' . $theme . '/header.php')) {
            include $url . '/app/themes/' . $theme . '/header.php';
        } else {
            echo "File not found!";
        }
    }
}
?>

So my problem is, if I am trying to check if the file exists, the location is:
http://localhost/tpl/app/themes/default/header.php

When I access it with a link it works, but it returns false when I try to check it with PHP. What do you think could be the solution for this?

A: You do not want to include a URL! You will want to include a local file. http://localhost/tpl/app/themes/default/header.php may be a URL via which the file can be accessed via HTTP, but you want to use the file path on disk instead. For example
/var/www/tpl/app/themes/default/header.php

A: localhost is the hostname, not part of the path, therefore you shouldn't include it in $url.

A: Fixed it. The location was wrong.

A: file_exists works for absolute path. You have written url. It must be something like "D:/wamp/www/your_project/your_file"


text:
Q: Send multiple parameter in ajax request using javascript So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;

but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {

            var closeReason = document.getElementById("SectionClousureReason");
            var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
            var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;

                var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
                ajaxRequest(url);
                return;

    }

edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
        strURL = url;
        var xmlHttpRequest = false;
        var self = this;
        // Mozilla, Safari
        if (window.XMLHttpRequest) {
            self.xmlHttpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        self.xmlHttpRequest.open("POST", strURL, true);
        self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.xmlHttpRequest.onreadystatechange = function() {
            if (self.xmlHttpRequest.readyState == 4) {
                if (self.xmlHttpRequest.status == 200) {
                    var htmlString = self.xmlHttpRequest.responseText;
                    var parser = new DOMParser();
                    var responseDoc = parser.parseFromString(htmlString, "text/html");
                    window.close();
                } else {
                    ajaxFailedCount++;
                    // Try for 1 min (temp fix for racing condition)
                    if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
                    else {alert("Refresh failed!")};
                }
            }
        }
        self.xmlHttpRequest.send(null);
    }

A: You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
    PAGE_ID: 'BPCLA',
    ACTION: 'closeAssessment',
    SAVE_FLAG: 'true',
    closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
    closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};

Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
    return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');

url += urlParams;
ajaxRequest(url);

Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so.  In that case, you can loop over the form elements and build the above params object.
var params = {
    PAGE_ID: 'BPCLA',
    ACTION: 'closeAssessment',
    SAVE_FLAG: 'true'
};

var form = document.getElementById('yourForm'),
    elem = form.elements;

for(var i = 0, len = elem.length; i < len; i++){
    var x = elem[i];
    params[x.name] = x.value;
}

A: Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
    page_id: 'BPCLA',
    action:  'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';

for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );

uri = uri + uri_params.join( '&' );
console.log( uri );

Or consider using POST to transport your parameters, as many browsers have limitations on the query string.

Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.