text:
Q: How to fix "Requested array size exceeds VM limit" error in Java? Is there an log option that can let tomcat log the bad query instead just throwing this ?

SEVERE: java.lang.OutOfMemoryError: Requested array size exceeds VM limit

(Tried log level to FULL, but only capture the above)
This is not enough information to further debug
Alternatively, if this can be fixed by allocated more memory by tweaking the following?

-Xms1024M -Xmx4096M -XX:MaxPermSize=256M

Update

-Xms6G -Xmx6G -XX:MaxPermSize=1G -XX:PermSize=512M

(the above seems works better, keep monitoring)

A: You will get this exception because you are trying to create an Array that is larger than the maximum contiguous block of memory in your Java VMs heap.
https://plumbr.eu/outofmemoryerror/requested-array-size-exceeds-vm-limit
What is the solution?
The java.lang.OutOfMemoryError: Requested array size exceeds VM limit can appear as a result of either of the following situations:
Your arrays grow too big and end up having a size between the platform limit and the Integer.MAX_INT
You deliberately try to allocate arrays larger than 2^31-1 elements to experiment with the limits.
In the first case, check your code base to see whether you really need arrays that large. Maybe you could reduce the size of the arrays and be done with it. Or divide the array into smaller bulks and load the data you need to work with in batches fitting into your platform limit.
In the second case – remember that Java arrays are indexed by int. So you cannot go beyond 2^31-1 elements in your arrays when using the standard data structures within the platform. In fact, in this case you are already blocked by the compiler announcing "error: integer number too large" during compilation.
But if you really work with truly large data sets, you need to rethink your options. You can load the data you need to work with in smaller batches and still use standard Java tools, or you might go beyond the standard utilities. One way to achieve this is to look into the sun.misc.Unsafe class. This allows you to allocate memory directly like you would in C.

A: If you want to find out what causes OutOfMemory, you can add
-XX:+HeapDumpOnOutOfMemoryError

to your java opts.
The next time you get out of memory, you will get a heap dump file that can be analyzed with "jhat" that is located inside jdk/lib. Jhat will show you what objects exist in your heap and how much memory they consume.

A: I suspect you might be using sorts on a large index. That's one thing I definitely know can require a large array size with Lucene. Either way, you might want to try using a 64-bit JVM with these options:
-Xmx6G -XX:MaxPermSize=128M -XX:+UseCompressedOops

The last option will reduce 64-bit memory pointers to 32-bit (as long the heap is under 32GB). This typically reduces the memory overhead by about 40%, so it can help stretch your memory significantly.
Update: Most likely you don't need such a large permanent generation size, certainly not 1G. You're probably fine with 128M, and you'll get a specific error if you go over with Java 6. Since you're limited to 8G in your server you might be able to get away with 7G for the heap with a smaller perm gen. Be careful about not going into swap, that can seriously slow things down for Java.
I noticed you didn't mention -XX:+UseCompressedOops in your update. That can make a huge difference if you haven't tried it yet. You might be able to squeeze a little more space out by reducing the size of eden to give the tenured generation more room. Beyond that I think you'll simply need more memory or fewer sort fields.

A: I use this in catalina.sh
JAVA_OPTS="-Dsolr.solr.home=/etc/tomcat6/solr -Djava.awt.headless=true -server -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m -XX:MaxPermSize=256m -XX:+DisableExplicitGC"

I never had mem problems on Tomcat/solr with 30M small documents. I had problems with the solrJ indexing client though. I had to use -Xms8G -Xmx8G for the Java client, and add documents by chunks of 250K documents.

A: Out of memory! See if there is an array out of bounds, or loop the system resources are swallowed up!

*

*java.lang.OutOfMemoryError: Java heap space
In the JVM, if 98% of the time is available for the GC Heap size and less than 2% of the time to throw this exception information.
JVM heap setting is the java program is running JVM memory space can be used to deploy the settings. JVM at startup automatically set Heap size value, the initial space (ie-Xms) is the physical memory of 1 / 64 , The maximum space (-Xmx) is the physical memory of 1 / 4. JVM can be used to provide the-Xmn-Xms-Xmx and other options can be set.

*Requested array size exceeds VM limit: This is because the application of the array size exceeds the size of heap space, such as a 256M of heap space in the array to apply for a 512M

A: Upgrade solr to a newer version seems have sort this problem, likely newer version has a better heap memory management.


text:
Q: Similarity between sets with different size Is there a distance measure like jaccard for sets with different sizes? For example A=['a','b','c'] and B=['a','d']
I would like to include the total intersection as well as the order.
The implementation of jaccard similarity score in Pythons Sklearn only supports lists of same shape.

A: The Jaccard coefficient does allow for different set size, but its interpretation becomes less intuitive.
Here is an application for R.
jaccard <- function(a, b) {
      intersection = length(intersect(a, b))
      union = length(a) + length(b) - intersection
      return (intersection/union)
    }

jaccard(a,b)

And here is one for Python:
def jaccard(list1, list2):
    intersection = len(list(set(list1).intersection(list2)))
    union = (len(list1) + len(list2)) - intersection
    return float(intersection) / union

jaccard(a,b)

(code from here)
Another option is the Sørensen–Dice coefficient. The nominator is twice the intersection set, and the denominator is the sum of the cardinality of both sets. To apply it, just change the two codes above accordingly.
The overlap coefficient, or Szymkiewicz–Simpson coefficient is one alternative that does not care about different set sizes. As long as one subset is contained in the other, the coefficient is one. To apply it, just change the two codes above accordingly.
Disregarding the dimension of the large set might not be ideal though. Since the index only cares about the proportion of the small set in the large one, value is the same regardless of the dimension of the latter (10, 1000, 1000000).
I'm sure there are many more metrics. The comment by @whuber is correct. There are many metrics. It depends on what you are after.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Putting \the\wd inside a group makes it produce 0.0pt The following is a minimal example demonstrating some behavior of latex that I don't understand. I'm using xelatex, but the behavior in pdflatex seems to be the same.
\documentclass{article}

\newsavebox\myboxregister
\newwrite\outputfile
\openout\outputfile=test.txt

\begin{document}

{ %%% Removing the {...} fixes the code.

\savebox{\myboxregister}{aaa}%
\usebox{\myboxregister}%
\write\outputfile{\the\wd\myboxregister}%

} %%% Removing the {...} fixes the code.

\closeout\outputfile

\end{document}

The output to the file test.txt is 0.0pt, which is not the correct width for the box register. If I comment out the curly braces as indicated in the comments, the output is the correct value of about 15 pt.
How would I fix this? I want to be able to do this kind of thing inside various environments.

A: \write is a delayed action that happens when the page is shipped out, by which time the group is ended. You can use \immediate\write to write to the file at that point, In that case you should also use \immediate\openout

A: You can expand the contents of \write at point of usage.
\documentclass{article}

\newsavebox\myboxregister
\newwrite\outputfile
\openout\outputfile=\jobname-wd.txt

\begin{document}

{ %%% Removing the {...} fixes the code.

\savebox{\myboxregister}{aaa}%
\usebox{\myboxregister}%
\write\outputfile\expandafter{\the\wd\myboxregister}%

} %%% Removing the {...} fixes the code.

\closeout\outputfile

\end{document}

Contents of the written file:
15.00005pt


text:
Q: Drawing a tetrahedron in OpenTK I made a simple spinning tetrahedron application with OpenTK. My problem is that the last face is missing. I guess because I'm making a wrong order of vertices.
        GL.Begin(BeginMode.Triangles);

        GL.Color3(Color.Silver);
        GL.Vertex3(-0.269f, -0.5f, -0.5f);
        GL.Vertex3(0.598f, -0.5f, 0f);
        GL.Vertex3(-0.269f, -0.5f, 0.5f);

        GL.Color3(Color.Honeydew);
        GL.Vertex3(-0.269f, -0.5f, -0.5f);
        GL.Vertex3(0.0f, 0.5f, 0f);
        GL.Vertex3(-0.269f, -0.5f, 0.5f);

        GL.Color3(Color.Moccasin);
        GL.Vertex3(-0.269f, -0.5f, 0.5f);
        GL.Vertex3(0.598f, -0.5f, 0f);
        GL.Vertex3(0.0f, 0.5f, 0f);

        GL.Color3(Color.IndianRed);
        GL.Vertex3(0.598f, -0.5f, 0f);
        GL.Vertex3(-0.269f, -0.5f, 0.5f);
        GL.Vertex3(0.0f, 0.5f, 0f);

        GL.End();

What is the correct order to get the tetrahedron? Should I use another BeginMode?
Thanks in advance,
Daniel

A: if you look for the Tetrahedron::draw() function on this page it provides a list of coords and opengl calls that seem to be working for them.
Namely, this kind of thing:
P1 = {0.0, -1.0, 2.0};
P2 = {1.73205081, -1.0, -1.0};
P3 = {-1.73205081, -1.0, -1.0}
P4 = {0.0, 2.0, 0.0};
coords = {{P1, P2, P3}, {P1, P3, P4}, {P1, P4, P2}, {P2, P4, P3}}


text:
Q: How to properly set a bool property in an obj-c repo from a Swift project? Odd question and odd situation. I am using a repo from GitHub (M13PDFKit) in my swift project. It presents more cleanly that the others i have peeked at. Trouble is, the bool settings that i manage in Swift prior to my present() seem to have absolutely no effect. No errors but the (internally-set) defaults of YES are not being overridden by my swift-project setting of = false.
I am currently at a loss for how to proceed to correct this.
I have not explored the bridging scenario as the repo is functioning properly (with the exception of these settings of course).
I have tried a few variants, wondering if i can fool the compiler, which might somehow not be making the obj-c bool false from the swift false. I have tried a few variants, both of which don't seem to work. The code in the repo is hit, just no values other than the defaults set therein are seen:
pdfKBasicPDFViewerFullSCreen.setValue(false, forKey: "_enableBookmarks")
pdfKBasicPDFViewerFullSCreen.enableOpening = false

Likely a simple issue, i am just not seeing it. Thoughts?


text:
Q: Hadoop Cluster Cannot Remove TaskTracker node, The Hadoop Version is :
[hadoop@L-6140-BBS: ~/src/hadoop/conf]$ hadoop version
Hadoop 0.20.1+169.89

And I run the mradmin freshNodes,But it looks no this command
[hadoop@L-6140-BBS: ~/src/hadoop/conf]$ hadoop mradmin -refreshNodes
efreshNodes: Unknown command
Usage: java MRAdmin
       [-refreshServiceAcl]
       [-help [cmd]]

Generic options supported are
-conf <configuration file>     specify an application configuration file
-D <property=value>            use value for given property
-fs <local|namenode:port>      specify a namenode
-jt <local|jobtracker:port>    specify a job tracker
-files <comma separated list of files>    specify comma separated files to         be copied to the map reduce cluster
-libjars <comma separated list of jars>    specify comma separated jar files to include in the classpath.
-archives <comma separated list of archives>    specify comma separated archives to be unarchived on the compute machines.

The general command line syntax is
bin/hadoop command [genericOptions] [commandOptions]


text:
Q: Which project's responsibility should it be, to reference DLLs needed by a referenced DLL? Looking through the web config files for a large solution (50+ projects) I've begun maintaining, I see a reference pattern I don't quite understand
At least 10 of the projects in this solution  send emails and hence depend on another project (also in the solution) that produces Mailing.dll
In turn that Mailing project uses Azure queues and some other things. The mailing solution references Microsoft.WindowsAzure.Storage, but not Microsoft.WindowsAzure.Diagnostics (hereafter referred to as WA.D)
I see in the 10 projects that use Mailer/send emails, the references include various versions and source locations of WA.D and every web config file has a binding redirect for WA.D. Compilation warnings about choosing, or unable to choose a version are seen
If I strip out the references from the 10 projects, and strip the binding redirects I get the ASP.NET yellow screen of death complaining that it can't find the WA.D.dll - this was expected because it realises a situation where the WA.D.dll isn't in the output bin directory. In all the cases I looked at, the YSOD was referring to a call to a mailer.dll method as the point of failure, but debug stepping into the mailer would eventually arrive at a call to some windows azure related queue operation
Now, if I reference WA.D.dll from the Mailer project, then everything works again: Mailer builds, a sole version of WA.D dll appears, the other projects function, there aren't any build complaints about multiple versions of assemblies. Mailer genuinely appears to be the thing that relies on a dll that relies on WA.D
The 10 projects don't appear to have a direct dependency on WA.D themselves anywhere else
I'm hence slightly puzzled why the original devs would have not set a reference to WA.D on Mailer (the thing that most directly uses it) and instead set a reference on N number (at least 10) of other projects, that required Mailer but in doing so allowed a mish mash of versions and even inconsistent binding redirects to creep in (some redirects would point requests for 2.9 to 2.2 dll)
Is there an advantage to this approach (top level project that uses mailer, is responsible for referencing WA.D) or should I switch things over so that the lowest possible level of DLL (mailer) is responsible for referencing the assemblies it needs?
Is this project relatively isolated in its affliction because of something peculiar about the azure SDK?
ps; if it's relevant, owing to the fact that we've had issues with the deploy targets not having Azure SDK installed I'm using a set of unofficial NuGet packages that include just the specific Azure DLLs required for this project. Some of this might have come out of the fact that these DLLs aren't officially available on their own
Edit:
Abbreviated solution explorer representation:
Now:
Website1
+-References
  +-WindowsAzure.Diagnostics
  +-Mailer
+-Web.config --dependency/redirect to windowsazure.diagnostics

Website2
+-References
  +-WindowsAzure.Diagnostics
  +-Mailer
+-Web.config --dependency/redirect to windowsazure.diagnostics

Website3
+-References
  +-WindowsAzure.Diagnostics
  +-Mailer
+-Web.config --dependency/redirect to windowsazure.diagnostics

Mailer --seems to be what really requires windowsazure.diagnostics
+-References
 +-WindowsAzure.Storage

Also seems to work:

Website1
+-References
  +-Mailer
+-Web.config --dependency/redirect to windowsazure.diagnostics

Website2
+-References
  +-Mailer
+-Web.config --dependency/redirect to windowsazure.diagnostics

Website3
+-References
  +-Mailer
+-Web.config --dependency/redirect to windowsazure.diagnostics

Mailer
+-References
 +-WindowsAzure.Storage
 +-WindowsAzure.Diagnostics
 +-app.config


text:
Q: Calling a c++ function on Rstudio on a MAC and getting (clang: error: unsupported option '-fopenmp') I know how to code but I really do not know my way around a computer.
I have a program that I have to run for my master thesis. It is a code with multiple collabs and runs perfectly on Linux. However, it is a very complex simulational code and therefore it takes time to run for multiple parameters. I've been using my Linux at the university to run it but would like to run some of it on my personal computer (MAC OS). It works by using the R language to call upon c++ functions as follows (being filename a code on c++).
On a Rstudio script:
Sys.setenv("PKG_CPPFLAGS" = "-fopenmp -DPARALLEL")
system("rm filename.so")
system("rm filename.o")
system ("R CMD SHLIB filename.cpp")
dyn.load("filename.so")

After system ("R CMD SHLIB filename.cpp") I get error:

clang: error: unsupported option '-fopenmp'
make: *** [filename.o] Error 1

I've researched on the subject and found this
Enable OpenMP support in clang in Mac OS X (sierra & Mojave)
I've Installed LLVM, yet I do not know how to use it in this case.
How do I use it in this case?
Thank you in advance.

A: "Don't do it that way."   Read up on R and Rcpp and use the proper tools (especially for packaging and/or compiling) which should pick up OpenMP where possible. In particular,

*

*scan at least the Rcpp Introduction vignette

*also look at the Rcpp Attributes vignette
"Just say no" to building the compilation commands by hand unless you know what you are doing with R and have read Writing R Extensions carefully a few times. It can be done, I used to show how in tutorials and workshops (see old slides from 12-15 years ago on my website) but we first moved to package inline which helps here, and later relied on the much better Rcpp Attributes.
Now, macOS has some extra hurdles in which tools work and which ones don't.  The rcpp-devel mailing list may be of help, the default step is otherwise to consult the tutorial by James.
Edit: And of course if you "just want the above to work" try the obvious step of removing the part causing the error, i.e. use
Sys.setenv("PKG_CPPFLAGS" = "")

as your macOS box appears to have a compiler but not OpenMP (which, as I understand it, is the default thanks to some "surprising" default choices at Apple -- see the aforementioned tutorial for installation help.)


text:
Q: discord.js { split: true } will not split I try to split more than 2000 chars from a file, but the
{ split: true }
seem not to work, any here know what I'm doing wrong.. here my full code:
const Discord = require("discord.js");
const fs = require('fs');
const date = require('date-and-time');
const readLastLines = require('read-last-lines');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const now = new Date();

var settings = require("./settings.js");
var channel = require("./settings.js");
var playlist = "text.txt"

bot.on("ready", function () {
    console.log("ready");
//  console.log("Stream ready - Starting live Playlist...." + date.format(now, 'DD/MM/YYYY'));
//      bot.channels.cache.get(settings.discord_channel).send("Stream ready - Starting live Playlist...." + date.format(now, 'DD/MM/YYYY'));
});

fs.watchFile(playlist, (eventType, filename) => {
readLastLines.read(playlist, 255)
        .then((lines) => bot.channels.cache.get(settings.discord_channel).send(lines, { split: true }));
});

bot.login(settings.bot_token);

A: The split option for MessageOptions was removed in v13. You now have to import the Util class and use it's splitMessage() method.
You'll need to split the message into chunks and then asynchronously loop through each chunk, awaiting the sending of each.
const { Util } = require('discord.js');

// Your code

readLastLines.read(playlist, 255)
   .then(async lines => {
      const channel = bot.channels.cache.get(settings.discord_channel);

      // Splitting and sending
      const messageChunks = Util.splitMessage(lines, {
         maxLength: 2000,
         char: ' '
      });

      messageChunks.forEach(async chunk => {
         await channel.send(chunk);
      });
   });


text:
Q: CASE Statement to COALESCE in SQL I have a COALESCE statement in SQL as follows.
How can I use COALESCE function in SQL?
I have so far coded as
COALESCE(IFRM.NAME + '_' + IFRM.TAG,  + '_' +ISNULL('_'+ LFRM.NAME, ''))+ '-->' + '_'+ ITO.NAME +'_'+ ITO.TAG +ISNULL('_'+ LTO.NAME, '') AS TEST,

Mine yields:
TEST
DAL_L-->_JBU_U_HAL
JBU_U-->_UAE_E
AAL_L-->_KLM_M_ASA
(null)
(null)

below are the tables I use for the CASE Statement
Main:
ID  FRM_IAD_ID  TO_IAD_ID   FRM_ATL_ID  TO_ATL_ID   FRM_ORD_ID  TO_ORD_ID   FRM_LAX_ID  TO_LAX_ID
9014    3215        1618                                                                1149
9014    1618        1407                                                    1149
9051    1600        1601                                                                1137
9051    1601                              1688                              1137
9059    6108                                                    9764

IAD:
ID  Name    tag
1407    UAE E
1600    AAL L
1601    KLM M
1618    JBU U
3215    DAL L
6108    EVA A

ATL:
ID  Name        Tag
1688    Japan Airlines

ORD:
ID  name    Tag
9764    QTR

LAX:
ID  Name    Tag
1137    ASA
1149    HAL

A: Here is a method that uses COALESCE() and STUFF():
(STUFF(COALESCE('_' + IFRM.NAME, '') + COALESCE('_' + IFRM.TAG, '') + COALESCE('_' + LFRM.NAME, ''),
       1, 1, ''
      ) + '-->' +  -- if you want spaces, use `' --> '`
 STUFF(COALESCE('_'+ ITO.NAME, '') + COALESCE('_' + ITO.TAG, '') + COALESCE('_' + LTO.NAME, ''),
       1, 1, '')
) AS TEST,

The idea is to prepend '_' to all components, and then to remove the first one using STUFF().
I note that the CASE has spaces around the arrow.  Your sample code does not.
Some other databases support a function such as CONCAT_WS(), which makes this much simpler.

A: You don't need to convert Case to Coalesce.  Coalesce is just shorthand for a case statement in which each value is tested for null.  Your case statement structure is preferred over trying to jam it into a Coalesce statement and you will not be able to cleanly test multiple fields in the Coalesce structure.
It looks like you may be asking how to prevent returning null from your Case statement.  You'll need to add an Else statement that always evaluates to a not-null value.
Incidentally, the final element of a Coalesce statement is also handled as an Else clause.  There is no requirement that Coalesce returns a not-null value.  A null can be returned as long as a data type is assigned.


text:
Q: divide uint64_t data containing N decimal digits into two uint32_t and trim the output in C I need to divide two parts into high 8 decimal digits , low 8 decimal digit
I will not write all the details of the code. (e.g. memory allocation etc)
focusing for N decimal digits as input with data type uint64_t* and divide into two 8 decimal digits for first 8 digits, next 8 digits (data type uint32_t), so if there are more digitis, it will be just trimmed.
(Please understand I am a newbie. so if there are wrong in the code, appreciate explanation, only criticism without explanation will not help the newbies)
The code expected to work like this:
Assumption: uint8_t* data_64b as input contains already N decimal digits.
e.g.1)

*

*1234567803456789 as input (16 decimal digits) in uint64_t*
data_64bits

*Then , the output will be 12345678, or 03456789 based on the id.

e.g.2)

*

*the input data has 17 decimal digits: 98765432155555553

*Then I assume that the last 1 digit '3' should be thrown out.

*And output will be each 8 digits either 98765432 or 15555555
based on id

The code:
// @Input: unit8_t id                       input identifier
// @input: uint64_t* data_64bits   input parameter , assume it contains N decimal digits number
// @output: uint32_t* data_32bits  output parameter to return the divided each 8 decimal digits
dataFrom64To32bits( uint8_t id, uint64_t* data_64bits, uint32_t* data_32bits )
{
    uint8_t* data_64bits;    /* 64bits */

#if 0
/* [A] My original thoughts, but I have told this is not necessary.
because the data contains decimal digits
[Q1] really don't need this? */

    uint32_t 4BytesLSB;
    uint32_t 4BytesMSB;

    4BytesLSB = data_64bits & 0xFFFFFFFF;                 /* obtains the 4 LSB */
    4BytesMSB = (data_64bits & 0xFFFFFFFF00000000) >> 32; /* obtains the 4 MSB */
#endif

#if 1
    /* [B] I have got advice like this,
and have told that it will be enough doing like this
for 8 decimal digits for high part, low part to divide.
[Q2] Does this really make sense? and will give the result? */
    if(id == id_highpart)
    {
        *data_32bits = ( *data_64bits / 100000000 ) % 100000000;
    }
    else if(id == id_lowpart)
    {
        *data_32bits = *data_64bits % 100000000;
    }
#endif
}

Dose it make sense?
A part told that is not necessary.
B part adviced for the expected result
Please look at [Q1], [Q2] in the code.
Additional,
which is the right for throwing out the rest from the certain part in the code? trim or something else?
Thanks in advance

A:
Additional, which is the right for throwing out the rest from the
  certain part in the code? trim or something else?

To discard digits after the 16th, divide by 10 until there are no more (before extracting the parts):
    while (*data_64bits > 9999999999999999ll) *data_64bits /= 10;


text:
Q: If a group of 9 kids have won a total of 100 trophies, then at least one of the 9 kids has won at least 12 trophies. How would I go about proving this statement using contradiction?
This is what I have so far:
p: A group of 9 kids have won a total of 100 trophies
q: At least one of the 9 kids has won at least 12 trophies.
p → q
Then by contradiction: p → q ≡ p ^ ¬q, such that (¬q: Not one of the 9 kids has won at least 12 trophies)
After this I'm stuck am I suppose to show more proof and how would I write my conclusion?

A: This would be a basic application of the pigeonhole principle, but let's take it from a more logical standpoint.
You want to show at least one kid has won twelve trophies by contradiction. So instead suppose the opposite: all kids have not won twelve or more trophies, i.e. all kids have won eleven or fewer trophies.
How can we show this is false? Well, we know we have $9$ kids, and in the worst case scenario each has won $11$ trophies. $100$ have been awarded. What is the contradiction here?
Solution:

 The contradiction is that, if no kid has won $12$ trophies, then all of them have won at most $11$ trophies. That means $9 \cdot 11 = 99$ trophies (or fewer) have been awarded, contradicting that $100$ have been awarded since $99 < 100$.

More on the pigeonhole principle can be found elsewhere. It is used a lot in problems like these, and even this has a similar flair to it:

*

*Wikipedia: https://en.wikipedia.org/wiki/Pigeonhole_principle

*Art of Problem Solving: https://artofproblemsolving.com/wiki/index.php/Pigeonhole_Principle

*Brilliant: https://brilliant.org/wiki/pigeonhole-principle-definition/


text:
Q: HTML JSon POST C# Tenho a seguinte class:
public class Ticket
{
    public string name { get; set; }

    public string content { get; set; }

    public int itilcategories_id { get; set; }

}

E a seguinte tarefa:
static async Task<Uri> CreateTicketAsync()
{
client.DefaultRequestHeaders.Clear();

List<Ticket> tickets = new List<Ticket>();
tickets.Add(ticket);

var parametro = new
{
     input = tickets.ToArray()
 };

 var jsonContent = JsonConvert.SerializeObject(parametro);
 var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");

 contentString.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 contentString.Headers.Add("Session-Token", session_token);

 HttpResponseMessage response = await client.PostAsync("apirest.php/Ticket/", contentString);

            return response.Headers.Location;
 }

No content do ticket é passado HTML, mas ele é convertido para JSON para poder ser enviado pelo Post, o que faz com que ele não apareça corretamente no website para o qual é enviado. Alguém sabe como resolver o problema?

Os n que aparecem em cima não deveriam de aparecer e entre aquelas categorias deveria existir parágrafo.
HTML: antes de ser convertido
<!DOCTYPE html>\r\n  \r\n<meta http-equiv=\"\"Content-Type\"\" content=\"\"text/html; charset=utf-8\"\"> \r\n
Foi recebida a seguinte informacao relativa a umasubscricao JASMIN:

\r\nUtilizador CIS: {1}
Nome: {0}
Morada: {2}
Codigo Postal: {3}
NIF: {4}
Email: {5}
Parceiro: {6}

\r\n
Subscricao Ant: {7}
Contrato CIS Ant: {8}

\r\n
Solucao: {9}
Subscricao: {10}
Contrato CIS: {11}
Inicio: {12}
Fim: {13}
Pagamento: {14} {15}
Ref MB: {16}

\r\n",

Qualquer dúvida avisem!


text:
Q: Decorating a method with a class I am trying to decorate an instance method with a decorator class, but it fails to pass on the instance as self to the decorated callable.  Wrapping into @wraps does not work either, because the wrapped method is not available yet while building the decorator class:
#!/usr/bin/env python3
"""Trying to decorate a method."""

class Wrap:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **kwargs):
        print("self: {self}\n*args: {args}\nkwargs: {kwargs}".format(
            self=self, args=args, kwargs=kwargs))
        self.func(self=args[0], a=3.141)

class A:
    @Wrap
    def aaa(self, a=None):
        print("My instance: {}\na = {}".format(self, a))

a = A()

a.aaa(1000)
# My instance: 1000
# a = 3.141
## The object "a" is not passed on, rendering aaa effectively a static method.

a.aaa(a, 1000)
# My instance: <__main__.A object at 0x7fe371579be0>
# a = 3.141
## The expected result for the first attempt.

How can I access a inside __call__, without passing it explicitly?


text:
Q: Wordpress function/plugin to count number of rows in mySQL table I have additionals table in my Wordpress database that contain a lists of companies, link, description, etc. I'm using this plugin (http://wpdatatables.com/) to render the table in WP and it works great.
One feature it doesn't have is a way to count of the number entries (rows) in the table. I'd like to get this count and display it in a page on wordpress. For example, count all the rows in table X and display here (with a shortcode or something else) so I could have "TABLE X has 1,912 companies".
I came across this as a way to get started, but not sure if it'll work for what I need and then I'm not sure how to actually get the result into a post/page.
<?php
$myvar = $wpdb->get_results("SELECT COUNT(*) FROM company_table WHERE name=*");

if($myvar == 0)
{
// no rows, do whatever.
}
else
{
// at least 1 row, do something else.
}
?>

or this:
global $wpdb;
$wpdb->get_results( 'SELECT COUNT(*) FROM table_name' );
echo  $wpdb->num_rows . 'Rows Found';

How can I get the row count and display it on a page from this point (or some other recommended started point)?
UPDATE
Okay, I made a plugin with a shortcode like this and can get it to appear in my page correct, but it's rendering the wrong number of rows. It's only showing 1 row, when it should be several hundred.
function row_count_shortcode() {
global $wpdb;
$wpdb->get_results( 'SELECT COUNT(*) FROM inno_db' );
echo  $wpdb->num_rows . 'Rows Found';
}
add_shortcode( 'row_count', 'row_count_shortcode' );

Any idea what the issue might be?
Thanks

A: Change get_results() to get_var()
$num_rows = $wpdb->get_var('SELECT COUNT(*) FROM inno_db');

A: Trying to use num_rows() will ALWAYS return 1 (assuming the SQL is valid) even if the count was zero, because your SQL result set from the SELECT COUNT(*) ... query will always return a result set with one row.
You need to actually read the COUNT value from the result set or just do regular SELECT * ... (or better to actually SELECT primary_key ... on InnodDB table) and use num_rows(). Don't use both COUNT() and num_rows().


text:
Q: Rails 3 ActiveRecord Query questions I've implemented "following" function. Showing "people user A is following" was simple, but showing "people who are following user A" is giving me troubles.
I have follow_links, which have id, user_id, and follow_you_id column. When user A begins following user B, the columns will be like (user_id = A, follow_you_id = B).
To show users that A(@user) is following, I can simply do
@follow_yous = @user.follow_yous

But I'm not sure how to show users who are following A(@user)
To do this, I first found all the related links.
@follow_links = FollowLink.where(:follow_you_id => @user.id)

Now I thought I could just do @follow_mes = @follow_links.users, but it says user is an undefined method. So I guess I can either call user.follow_yous or follow_you.users.
My next approach was
@follow_links = FollowLink.where(:follow_you_id => @user.id)
@follow_mes = User.where(:id => @user.id, :include => @follow_links)

I intended to find all the User objects that had the provided @follow_links objects, but I think the syntax was wrong. I couldn't find a decent solution after a bit of research. I'd appreciate any help.
Update:
FollowLink model
  belongs_to :user
  belongs_to :follow_you, :class_name => "User"

A: You can use joins like this:
@users = User.joins(:follow_links).where(:follow_links => { :follow_you_id => @user.id })

A: you can use following:
@follow_links = FollowLink.where(:follow_you_id => @user.id)
@follow_links.collect(&:user) # :user should be the name of your relation to user in your followlink model
=> [User1, User2,...]


text:
Q: Microsoft SQL database project in Visual Studio 2019/2022 - How to deploy varying security principals/permissions dependent on target environment I have database projects targeting Microsoft Azure SQL instances. The projects were created through and are managed by Visual Studio 2019 and Visual Studio 2022. The projects are deployed to multiple environments; engineering, user acceptance testing and production. Depending on the target the services and therefore the principals will vary, sometimes the permissions do as well (although we try to stick to PoLP).
Problem:
It is possible to create security definitions in the project but then all of these are deployed to all database targets. This is unworkable.
Possible Solution:
Reference the environment in the post-deployment-script by getting the server name and use this to either execute or not execute the statements that produce the security objects. This is horrible. If these security principals needed to be referenced to build the project then the build would fail.
Other thoughts:
Perhaps all the object definitions can be supplied as you would expect them to be. When running a publish the objects that are associated environment could have build enabled and the objects that are not could have build disabled. This could perhaps be achieved with a pre-build script. I don't know if this is possible.


text:
Q: Jumping to function in Vim I have ctags and I would jump to functions by placing my curson to a function and pressing ctrl ]. However, I find this sometimes to be inconvenient.
For instance, if my cursor is nowhere near a function I want to jump to, then it would be frustrating.
Is there a command in ctags or vim to just automatically jump to a function by typing its name and pressing a button? It would be way better if it was fuzzy and predicts the function for you. So for instance, if I want to go to a function called process_input(), then I would type out that function and press g or something.

A: The :tag <identifier> command is equivalent to Ctrl-] when the cursor is over <identifier>. See
:help CTRL-]

So you can type
:tag process_input

to jump to that function's tag. Further, the :tag command uses tab completion, so you can instead type
:tag pro<Tab>

and Vim will complete as much of that name as it can. Hit <Tab> again and Vim will cycle through the matches. If you prefer to see a list of possible matches, you can set the 'wildmode` option to something else, e.g.,
:set wildmode=longest,list

See
:help 'wildmode'

A: You can jump to a specific known tag with the :tag command. For example:
:tag process_input


text:
Q: javascript Reg Backwards not works I want to match a number in a string:
'abc@2003, or something else @2017'
I want to get result [2003, 2007] with match function.
let strReg = 'abc@2003, or something else @2017';
let reg = new RegExp(/(?=(@\d+))\1/);
strReg.match(reg)  //[ '@2003 ', '@2017 ' ]
let reg1 = new RegExp(/(?=@(\d+))\1/)
strReg.match(reg1) //null, but I expect [2003, 2007]

the result mains '\1' match after '?=', ?=()\1 works, ?=@()\1 not.
javascript only supports backwards, how should I do to match '@' but ignore it?

A: I take it that you want an array of the results, so...
var s = "abc@2003, or something else @2017 not the 2001 though";
var re = /@(\d+)/g;
var result = [];
var match = re.exec(s);
while (match !== null) {
    result.push(parseInt(match[1]));
    match = re.exec(s);
}

console.log(result);

Outputs:

Array [ 2003, 2017 ]

match(0) is the entire match, match(1) is the captured group.
Also, see How do you access the matched groups in a JavaScript regular expression?
Inspired by javascript regex - look behind alternative?, if you want to do it as almost a one-liner:
var re = /(\d+)(?=@)/g; /* write the regex backwards */
var result = [];
s.split('').reverse().join('').match(re).forEach(function (el) { result.push(parseInt(el.split('').reverse().join(''))); });
console.log(result.reverse());

Caveat: Who wrote this programing saying? "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."

A: Small change to your code does the job as follows:
/@(\d+)/g

number followed by @ will be remembered as you required.


text:
Q: identifying general phrases in a particular dialect I am looking for an algorithm or method that would help identify general phrases from a corpus of text that has a particular dialect (it is from a specific domain but for my case is a dialect of the English language) -- for example the following fragment could be from a larger corpus related to the World or Warcraft or perhaps MMORPHs.

players control a character avatar within a game world in third person or first person view, exploring the landscape, fighting various monsters, completing quests, and interacting with non-player characters (NPCs) or other players. Also similar to other MMORPGs, World of Warcraft requires the player to pay for a subscription, either by buying prepaid game cards for a selected amount of playing time, or by using a credit or debit card to pay on a regular basis

As output from the above I would like to identify the following general phrases:

*

*first person

*World of Warcraft

*prepaid game cards

*debit card

Notes:

*

*There is a previous questions similar to mine here and here but for clarification mine has the following differences:
a. I am trying to use an existing toolkit such as NLTK, OpenNLP, etc.
b. I am not interested in identifying other Parts of Speech in the sentence
c. I can use human intervention where the algorithm presents the identified noun phrases to a human expert and the human expert can then confirm or reject the findings however we do not have resources for training a model of language on hand-annotated data

A: Nltk has built in part of speech tagging that has proven pretty good at identifying unknown words. That said, you seem to misunderstand what a noun is and you should probably solidify your understanding of both parts of speech, and your question.
For instance, in first person first is an adjective. You could automatically assume that associated adjectives are a part of that phrase.
Alternately, if you're looking to identify general phrases my suggestion would be to implement a simple Markov Chain model and then look for especially high transition probabilities.
If you're looking for a Markov Chain implementation in Python I would point you towards this gist that I wrote up back in the day: https://gist.github.com/Slater-Victoroff/6227656
If you want to get much more advanced than that, you're going to quickly descend into dissertation territory. I hope that helps.
P.S. Nltk includes a huge number of pre-annotated corpuses that might work for your purposes.

A: It appears you are trying to do noun phrase extraction. The TextBlob Python library includes two noun phrase extraction implementations out of the box.
The simplest way to get started is to use the default FastNPExtractor which is based of Shlomi Babluki's algorithm described here.
from text.blob import TextBlob

text = '''
players control a character avatar within a game world in third person or first
person view, exploring the landscape, fighting various monsters, completing quests,
and interacting with non-player characters (NPCs) or other players. Also similar
to other MMORPGs, World of Warcraft requires the player to pay for a
subscription, either by buying prepaid game cards for a selected amount of
playing time, or by using a credit or debit card to pay on a regular basis
'''

blob = TextBlob(text)
print(blob.noun_phrases)  # ['players control', 'character avatar' ...]

Swapping out for the other implementation (an NLTK-based chunker) is quite easy.
from text.np_extractors import ConllExtractor

blob = TextBlob(text, np_extractor=ConllExtractor())

print(blob.noun_phrases)  # ['character avatar', 'game world' ...]

If neither of these suffice, you can create your own noun phrase extractor class. I recommend looking at the TextBlob np_extractor module source for examples. To gain a better understanding of noun phrase chunking, check out the NLTK book, Chapter 7.


text:
Q: LRU c++ program I've been working on a program in one of my college classes. I have been having trouble with the implementation of my LRU code as it is not displaying any errors or anything, but compiles. There are two parts. The main that we input the values into, which we then specify which algorithm we want to use to find page faults. I know the main works, along with the FIFO algorithm, but I'm not getting anything with my LRU code (It compiles and "runs" but displays nothing as if I did not click to use the algorithm). Can anyone help me figure out what is wrong?
main.cpp
    #include <iostream>
#include <string>

//#include "fifo.cpp"
#include "lru.cpp"
//#include "optimal.cpp"

using namespace std;

int main() {

    // List of different variables
    string pagestring;
    int fs,pn[50], n;

    // Prompt for page references
    cout<<"Virtual Memory Simulation\nBy blah\n----------\nEnter the number of pages : " << endl;
        cin >> n;
    cout<<"\n-------------\nPlease enter a list of page numbers separated by commas.\n"<< endl;
        cin>>pagestring;

    // algorithm to use
    char algo;

    while (true) {
        // Prompt algorithm to use
        cout<<"----------\nPlease select an algorithm to use.\n\n1: First-In-First-Out (FIFO)\n2: Least-Recently-Used (LRU)\n3: Optimal\n0: Quit\n"<<endl;
        cin>>algo;

        if (algo == '1') {
            //fifo(pagestring);
        }
        else if (algo == '2'){
            LRU_Execute(pagestring, n);
        }
        else if (algo == '3'){
            cout<<"Optimal Not yet coded"<<endl;
        }
        else if (algo == '0'){
            break;
        }
        else {
            cout<<"Invalid choice. Please try again."<<endl;
        }

    }

    cout<<"Goodbye!!"<<endl;

};

LRU.cpp
#include <iostream>
#include <string>

using namespace std;

class pra
{
int fs,z;
 int  frame[50], frame1[50][2], pn[50], n, cnt, p, x;
public:
 pra();
 void init(string pagestring);
 void getdata(string pagestring, int n);
 void lru(int* pn, int n, string pagestring);

};

pra::pra()
{
 int i;

 for (i = 0; i < fs; i++)
 {
  frame[i] = -1;
 }
 for (i = 0; i < fs; i++)
 {
  frame1[i][0] = -1;
  frame1[i][1] = 0;
 }
 p = 0;
 cnt = 0;
}

void pra::init(string pagestring)
{
 int i;
 for (i = 0; i < fs; i++)
 {
  frame[i] = -1;
 }
 for (i = 0; i < fs; i++)
 {
  frame1[i][0] = -1;
  frame1[i][1] = 0;
 }
 p = 0;
 cnt = 0;
}

void pra::getdata(string pagestring, int n)
{
fs=3;

// index to loop through input string
    int i = 0;

    // current input string character
    char z = pagestring[i];
    int x = 0;

//cout << "\nEnter the page numbers : ";
while (z != '\0'){
        // skip over commas and spaces
        if (!(z == ',')) {
              pn[x] = z;
        x++;

//  cout<<pn[x]<<"-This is pn[x]\n";
}
    z = pagestring[++i];

}
//cout<<pn[x]<<"-This is pn[x] AGAIN\n";
this->lru(pn, n, pagestring);
}

void pra::lru(int* pn, int n, string pagestring)
{
 init(pagestring);
 int ind = 0, fault = 0, pi = 0, j, fn;
 char i, z;
 p = 0;
 cnt = 0;
 int min;
cout<<n<<"---"<<i<<" - "<<j<<" - "<<" - "<<fn<<" - "<<z;
 for (i = 0; i < fs; i++)
 {
  frame1[i][0] = -1;
  frame1[i][1] = 0;
 }
pi = 0;
 for (i = 0; i < n; i++)

 {
  j = 0;
  if (ind > fs - 1)
   ind = 0;
  fault = 1;
  min = 999;

  while (j < fs)
  {
   if (frame1[j][0] = pn[pi])
   {
    fault = 0;
    p++;
    frame1[j][1] = p;

    goto l2;
   }
   if (frame1[j][1] < min)
   {
    min = frame1[j][1];
    fn = j;
   }
   j++;
  }
  j = 0;
  while (j < fs)
  {
   if (frame1[j][0] = -1)
   {
    fault = 1;
    fn = j;
    goto l2;
   }
   j++;
  }
  ind++;
l2:
  if (fault == 1)
  {
   p++;
   frame1[fn][0] = pn[pi];
   frame1[fn][1] = p;
   cnt++;
  }
  cout << "\nElement: " << pn[pi];
  pi++;
  for (z = 0; z < fs; z++)
  {
   cout << "\t" << frame1[z][0];
  }
  if (fault == 1)
   cout << "\t**Page Fault**";
  else
   cout << "\t--No Page Fault--";
 }
 cout << "\nTotal number of page faults: " << cnt;
 cout << "\n";
}

void LRU_Execute(string pagestring, int n)
{
 pra p;
 int  j, fault = 0, i, pi, z, fn, ind = 0, ans, ch;
 p.getdata(pagestring, n);
 //p.lru();
 while (ans == 1);
 //return 1;
}


text:
Q: JAX-RS: Authenticate with multiple principals (more than just username) Using a Jersey service, what would be the most elegant method to authenticate a user with more than just username and password? say, a Business Id, and username as the Principals, and password as the only Credential.
I have a postgres DB with a users table, the same username string can exist for multiple Business entities. (A unique constraint belongs to two columns, Business id and username together).
I Use Basic authentication, having the client send an additional HTTP Header for the Business id. how do I go on from here?
Now, Regarding Authorization, how would I set up Roles and Permissions, if roles are created specifically for each business entity (each business can define it's own roles and connect it to permissions.)? Permissions are static.
does apache shiro (or any other pluggable security extension) offer a solution in this case?
Thanks.

A: You might consider.

*

*Implement auth logic in the good old servlet filter. JAX-RS application is just normal WWW aplication, so Filters fits well as a simple authorization mechanism.

*JAX-RS interceptors (PreProcessInterceptor) where you can implement your auth logic as you need (calling database, etc.) This is "more idiomatic" while working with JAX-RS.

*Use Spring Security. This is a good option if you are ready to learn a little it of Spring Framework. Spring Security provides full featured authentication and access control mechanism, so you can implement whatever you need. Note that the rest of application does not neeed to use Spring.

*You might also use CDI decorators (example) to implement auth logic, but that would be sort of exotic given still low CDI adoption.
Personaly I would go with 1. or 2, for simple cases and 3 for something more advanced.

A: (Old question! a response for new users) As you tagged SHIRO in your question, you can just add your own logic by extanding  org.apache.shiro.realm.jdbc.JdbcRealm  and @Override:  getRoleNamesForUser(...) , getPermissions(..), doGetAuthenticationInfo(..) This is an example:
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
    Set<String> roleNames = new LinkedHashSet<>();

    Collection<UserRole> roles = /* Get roles from your DB, this example use  JPA entity, **but you put here any logic you want**...*/
    for(UserRole userRole:roles){
        roleNames.add(userRole.getRole().getName());
    }
    return roleNames; // return roles so Shiro is 'aware' of roles to add them to current user
}

*note that same logic applies for other methods that you override.
** You don't need 2 http calls to log the user, you can just user Shiro programatic auth.
here is a Complete example with Shiro annotation enabled..and more


text:
Q: Kendo dropdown giving [Object Object] when binding values dynamically from array This is my code:
var arr = [];

 for (var i = 0; i < GanttData.length; i++)
     {  arr.push({"text":GanttData[i].Projectname,"value":GanttData[i].Projectuid});}

var dropdownlistF = $("#drp_resources").data("kendoMultiSelect");
dropdownlistF.setDataSource(arr);

But it's not working. Any help will be blessing.
Thanks

A: It depends on how you defined the widget parameters. According to MultiSelect docs the default text field name it will look for in  the data is ''(dataTextField), so you need to set it:
$("#drp_resources").kendoMultiSelect({
    dataTextField: 'text'
});

Demo:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Untitled</title>

  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.2.510/styles/kendo.common.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.2.510/styles/kendo.rtl.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.2.510/styles/kendo.default.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.2.510/styles/kendo.mobile.all.min.css">

  <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
  <script src="https://kendo.cdn.telerik.com/2022.2.510/js/angular.min.js"></script>
  <script src="https://kendo.cdn.telerik.com/2022.2.510/js/jszip.min.js"></script>
  <script src="https://kendo.cdn.telerik.com/2022.2.510/js/kendo.all.min.js"></script></head>
<body>
  <select id="drp_resources"></select>
  <script>
  var arr = [],
      GanttData = [{
        Projectname: 'test',
        Projectuid: 123
      }];

    $("#drp_resources").kendoMultiSelect({
      dataTextField: 'text'
    });

   for (var i = 0; i < GanttData.length; i++)
       {  arr.push({"text":GanttData[i].Projectname,"value":GanttData[i].Projectuid});}

  var dropdownlistF = $("#drp_resources").data("kendoMultiSelect");
  dropdownlistF.setDataSource(arr);
  </script>
</body>
</html>

Dojo


text:
Q: Using Autohotkey for Emacs I am using emacs in Cygwin and have used Autohotkey to re-map the lefthand 'Alt' key and the lefthand 'Windows' key to be (left)Ctrl and (left)Alt respectively.
This means that an emacs sequence like Ctrl-xCtrl-c is done with my left thumb pressing on the key labelled 'Alt' to produce the Ctrl. Ok.
All seems okay except that I cannot get M-SPC to work, so my question is to ask for help on that.
Here is the Autohotkey script I am using (by the way it is only for theoretical completeness that I re-map the lefthand Ctrl key to be the lefthand Windows button -- I have never actually pressed it when using emacs):
#IfWinActive ahk_class mintty
LWin::LAlt
LAlt::LCtrl
LCtrl::LWin

To be clear, when I say 'all is ok' I mean that within emacs I use the 'describe key sequence' feature (C-h then k) and then try out the key combination I want. For example, all of these show the emacs documentation for the sequence I expected:

*

*Key labelled 'Alt' + g reports emacs documentation for C-g. Good.

*Key labelled 'Alt' + SPACE reports the documentation for C-@, which emacs says is also mapped to C-SPC, so that seems okay. Good.

*Key labelled 'MSWin Symbol' + x reports documentation for M-x. Good.

*Key labelled 'MSWin Symbol' + key labelled 'Alt'+ k reports documentation for C-M-k. Good.

But:

*

*Key labelled 'MSWin Symbol' + SPACE shows me the 'right-click' menu for the cygwin window rather than taking me to the documentation for M-SPC. Bad.

*By the way, I can get to the documentation for M-SPC by instead doing ESC followed by SPACE.

Let me add another point which has come up in the process of reacting to comments on this question:

*

*Key labelled 'MSWin Symbol' + key labelled 'Alt'+ SPACE takes me to the documentation for C-@, so I suspect it is being understood by emacs as C-SPC rather than as C-M-SPC as I thought my Autohotkey script would map it to. Bad.

Any ideas on why Autohotkey won't do the M-SPC as I would expect, or why C-M-SPC is understood by emacs as a C-SPC (I suspect)?
Thanks

A: Here are answers to your problem:
Issues remaping ctrl to alt and alt to ctrl for Emacs
And a discussion of why that happens
Plus to the script that can be found following first link you can add this code to work will all possible keyboard layouts.
#IfWinNotActive, ahk_group HaveEmacsHotkeys
#InputLevel 1
; Aditionally remaps Window keys and AppsKey
*RWin::
    SetKeyDelay, -1
    Send, {Blind}{Alt DownTemp}
    return
*RWin up::
    SetKeyDelay, -1
    Send, {Blind}{Alt Up}
    return

*LWin::
    SetKeyDelay, -1
    Send, {Blind}{Alt DownTemp}
    return
*LWin up::
    SetKeyDelay, -1
    Send, {Blind}{Alt Up}
    return

*AppsKey::
    SetKeyDelay, -1
    Send, {Blind}{Alt DownTemp}
    return
*AppsKey up::
    SetKeyDelay, -1
    Send, {Blind}{Alt Up}
#IfWinActive

A: Alt+Space is a standard Windows shortcut for showing the window menu, which you can also get by left-clicking on the window icon or right-clicking on the titlebar.
You can disable that shortcut on the Keys page of the Cygwin terminal's options (together with the Alt+Enter shortcut for fullscreen, for which Alt+F11 can be used instead).


text:
Q: Is there a keyboard shortcut to select a specific module in the project window? I can't use screen shots (too much proprietary information in those), so I will to explain this UI problem via text.
My IntelliJ project has 3 modules, so the project window shows
A
B
C

My workflow requires me to do:

*

*edit a file X belonging to module A

*trigger an action on module B

In order to do that, I click into the edit window for X (which is open all the time) and make my change. Then I click on the line for module B in the project window (to then invoke a specific context menu action from a 3rd party plugin).
Thing is: I defined a key stroke that invokes that 3rd party plugin action. But in order for the key stroke to work, the B module needs to be "selected" somehow. ( and it is not selected currently, because I have to edit a file that belongs to module A )
In other words: I can do all my work using the keyboard, but I have to reach to the mouse to get the "focus" from the A.X editor window to the B module line in the project view.
Is there a way to get there without using the mouse?

A: You can go to the Project window. The shortcut depends on the OS but you can find it into the keymap menu: "Tool Windows" > Project.
After that just start typing the module name, the focus will move.


text:
Q: xf:submission: Populate Header Value From Current Context I'm wanting to populate the header in a xf:submission with a value from the current context.  Documentation says that an xpath expression can be used but doesn't provide any examples.
I've tried using xsl:value, seen below, but that doesn't populate anything.  Is that the correct syntax to populate xf:value?
<p:for-each href="#attachments" select="//attachment" root="attachments" id="post-document-pages">
    <p:processor name="oxf:xforms-submission">
        <p:input name="submission">
            <xf:submission
                method="post"
                resource="http://localhost:8080/is/document/{@documentId}/page"
                serialization="application/octet-stream">
                <xf:header>
                    <xf:name>Resource-Name</xf:name>
                    <xf:value>
                        <xsl:value-of select="@filename" />
                    </xf:value>
                </xf:header>
            </xf:submission>
        </p:input>
        <p:input name="request"  href="current()" />
        <p:output name="response" ref="post-document-pages" />
    </p:processor>

A: Inside the <xf:header>, simply use:
<xf:value value="[your XForms expression here]"/>


text:
Q: Gradle proxy configuration I need web access from Gradle through a proxy server to use the Gradle/Artifactory integration for Jenkins. To reduce possible causes for issues, I manually add the Artifactory plugin in build.gradle and run it from command line:
apply {
    apply from: "http://gradle.artifactoryonline.com/gradle/plugins/org/jfrog/buildinfo/build-info-extractor-gradle/1.0.1/artifactoryplugin-1.0.1.gradle"
}

Following this description I specified the following in .gradle/gradle.properties in my home directory:
systemProp.http.proxyHost=hostname
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=de\\username
systemProp.http.proxyPassword=xxx

With the above proxy configuration (that is otherwise known to work), it fails:

11:33:17.699 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: java.io.IOException: Server returned HTTP response code: 407 for URL: http://gradle.artifactoryonline.com/gradle/plugins/org/jfrog/buildinfo/build-info-extractor-gradle/1.0.1/artifactoryplugin-1.0.1.gradle

I have two proxy servers to choose from, and one always responds with 407 (Proxy authentication required), the other with 502 (Bad gateway), so obviously, the proxyHost and proxyPort options are used.
As the user name (based on an Active Directory user) contains a backslash, I tried both \\ and \, but neither worked. The user specified is different from the user that is logged in to the machine and Active Directory. This user's credentials aren't valid for the proxy, so I need to be able to specify a different user.
Setting the same options in Jenkins' or Artifactory's GUI worked.

A: This is my gradle.properties, please note those HTTPS portion
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=8118
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=8118

A: In my build.gradle I have the following task, which uses the usual linux proxy settings, HTTP_PROXY and HTTPS_PROXY, from the shell env:
task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            def url = e.value.toURL()
            println " - systemProp.${base}.proxy=${url.host}:${url.port}"
            System.setProperty("${base}.proxyHost", url.host.toString())
            System.setProperty("${base}.proxyPort", url.port.toString())
        }
    }
}

build.dependsOn setHttpProxyFromEnv

A: Based on SourceSimian's response; this worked on Windows domain user accounts. Note that the Username does not have domain included,
task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            def url = e.value.toURL()
            println " - systemProp.${base}.proxy=${url.host}:${url.port}"
            System.setProperty("${base}.proxyHost", url.host.toString())
            System.setProperty("${base}.proxyPort", url.port.toString())
            System.setProperty("${base}.proxyUser", "Username")
            System.setProperty("${base}.proxyPassword", "Password")
        }
    }
}
build.dependsOn setHttpProxyFromEnv

A: For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:
systemProp.http.proxyHost=proxyURL
systemProp.http.proxyPort=proxyPort
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.https.proxyHost=proxyUrl
systemProp.https.proxyPort=proxyPort
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD

Where :
proxyUrl is the url of the proxy server (http://.....)
proxyPort is the port (usually 8080)
USER is my domain user
PASSWORD, my password
In this case, the proxy for http and https is the same

A: Check out at
    c:\Users\your username\.gradle\gradle.properties:
systemProp.http.proxyHost=<proxy host>
systemProp.http.proxyPort=<proxy port>
systemProp.http.proxyUser=<proxy user>
systemProp.http.proxyPassword=<proxy password>
systemProp.http.nonProxyHosts=<csv of exceptions>
systemProp.https.proxyHost=<proxy host>
systemProp.https.proxyPort=<proxy port>
systemProp.https.proxyUser=<proxy user>
systemProp.https.proxyPassword=<proxy password>
systemProp.https.nonProxyHosts=<csv of exceptions seperated by | >

A: Refinement over Daniel's response:
HTTP Only Proxy configuration

gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"

HTTPS Only Proxy configuration

gradlew -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"

Both HTTP and HTTPS Proxy configuration

gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"

Proxy configuration with user and password

gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 -  Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 -Dhttps.proxyUser=user -Dhttps.proxyPassword=pass  -Dhttp.proxyUser=user -Dhttp.proxyPassword=pass -Dhttp.nonProxyHosts=host1.com|host2.com

worked for me (with gradle.properties in either homedir or project dir, build was still failing). Thanks for pointing the issue at gradle that gave this workaround. See reference doc at https://docs.gradle.org/current/userguide/build_environment.html#sec:accessing_the_web_via_a_proxy
Update
You can also put these properties into gradle-wrapper.properties (see: https://stackoverflow.com/a/50492027/474034).

A: Using a very simple "Request a URL" Java program, I was able to replicate the issue.
http.proxyUser and http.proxyPassword seem to be non-standard, albeit popular, options, as they're not described in the Java reference page linked from the Gradle tutorial; even though the Gradle manual mentions them.
It seems Java programs that wish to support proxy authentication need to do this manually (and I was able to do this using the code on the linked page).

I submitted this issue (and a fix) to the Gradle issue tracker. Raised issue GRADLE-1556 was resolved in 1.0-milestone-8 (Feb 2012)

A: Try the following:
gradle -Dhttp.proxyHost=yourProxy -Dhttp.proxyPort=yourPort -Dhttp.proxyUser=usernameProxy -Dhttp.proxyPassword=yourPassoword

A: In case my I try to set up proxy from android studio Appearance & Behaviour => System Settings => HTTP Proxy. But the proxy did not worked out so I click no proxy.

Checking NO PROXY will not remove the proxy setting from the
  gradle.properties(Global). You need to manually remove it.

So I remove all the properties starting with systemProp for example - systemProp.http.nonProxyHosts=*.local, localhost

A: Create a file called gradle.properties inside the project folder where the build.gradle file is present. Add the following entry
     systemProp.http.proxyHost=proxy_url
     systemProp.http.proxyPort=proxy_port
     systemProp.http.proxyUser=USER
     systemProp.http.proxyPassword=PWD
     systemProp.https.proxyHost=proxy_url
     systemProp.https.proxyPort=proxy_port
     systemProp.https.proxyUser=USER
     systemProp.https.proxyPassword=PWD

If you are using DNS for proxy then add it like systemProp.https.proxyHost=www.proxysite.com
For IP just specify the IP with out http:// or https://
 Check gradle official doc for more details and setting up proxy at global level

A: There are 2 ways for using Gradle behind a proxy :
Add arguments in command line
(From Guillaume Berche's post)
Add these arguments in your gradle command :
-Dhttp.proxyHost=your_proxy_http_host -Dhttp.proxyPort=your_proxy_http_port

or these arguments if you are using https :
-Dhttps.proxyHost=your_proxy_https_host -Dhttps.proxyPort=your_proxy_https_port

Add lines in gradle configuration file
in gradle.properties
add the following lines :
systemProp.http.proxyHost=your_proxy_http_host
systemProp.http.proxyPort=your_proxy_http_port
systemProp.https.proxyHost=your_proxy_https_host
systemProp.https.proxyPort=your_proxy_https_port

(for gradle.properties file location, please refer to official documentation https://docs.gradle.org/current/userguide/build_environment.html

EDIT : as said by @Joost :
A small but important detail that I initially overlooked: notice that the actual host name does NOT contain http:// protocol part of the URL...

A: An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.
The following sets the username and password if provided or just adds the host and port if no username and password is set.
task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            //Get proxyHost,port, username, and password from http system properties
            // in the format http://username:password@proxyhost:proxyport
            def (val1,val2) = e.value.tokenize( '@' )
            def (val3,val4) = val1.tokenize( '//' )
            def(userName, password) = val4.tokenize(':')
            def url = e.value.toURL()
            //println " - systemProp.${base}.proxy=${url.host}:${url.port}"
            System.setProperty("${base}.proxyHost", url.host.toString())
            System.setProperty("${base}.proxyPort", url.port.toString())
            System.setProperty("${base}.proxyUser", userName.toString())
            System.setProperty("${base}.proxyPassword", password.toString())
        }
    }
}

A: Edit your ~/.gradle/gradle.properties file, then add the following:
org.gradle.jvmargs=-DsocksProxyHost\=127.0.0.1 -DsocksProxyPort\=1080 -DhttpProxyHost\=127.0.0.1 -DhttpProxyPort\=1081 -DhttpsProxyHost\=127.0.0.1 -DhttpsProxyPort\=1081

*

*DsocksProxyHost is the socks5 proxy host

*DhttpProxyHost is the http proxy host

*DhttpsProxyHost is the https proxy host

It worked for me.

A: If this issue with HTTP error 407 happened to selected packages only then the problem is not in the proxy setting and internet connection. You even may expose your PC to the internet through NAT and still will face this problem. Typically at the same time you can download desired packages in browser.
The only solution I find: delete the .gradle folder in your profile (not in the project). After that sync the project, it will take a long time but restore everything.

A: If you are using flutter, add the following line in android/gradle.properties
systemProp.http.nonProxyHosts=*.local, localhost

A: In the kotlin .kts setting files the properties should be defined like this:
extra["systemProp.http.proxyHost"]="127.0.0.1"
extra["systemProp.http.proxyPort"]="12345"

A: I met the same issue after I installed an older version of SDK and set JAVA_HOME in .zshrc, none of the solutions above help me but finally RESTARTED COMPUTER(Mac) then the error gone.


text:
Q: Googlebot cannot access my WordPress robots.txt I have some troubles with Google indexing on my WordPress site.
When I added my site to Google webmaster the .htaccess was the following
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Now, I tried to add these lines to .htaccess file, but Google still does not index my site.
# BOT SETTINGS
SetEnvIfNoCase User-Agent .*google.* search_robot
SetEnvIfNoCase User-Agent .*yahoo.* search_robot
SetEnvIfNoCase User-Agent .*bot.* search_robot
SetEnvIfNoCase User-Agent .*ask.* search_robot

Order Deny,Allow
#Deny from All
Allow from env=search_robot

Where am I doing wrong?

A: Create robots.txt file and upload your wordpress root folder with following code.
User-agent: google
Disallow:

User-agent: yahoo
Disallow:

User-agent: bot
Disallow:

User-agent: ask
Disallow:

User-agent: *
Disallow: /

And try to remove #BOT SETTING in your .htaccess.


text:
Q: How to fix AIS COG Values I am currently working with AIS dataset containing fields MMSI, Timestamp, LAT, LON, SOG, COG, etc. Here, COG is course over ground, and supported COG value ranges from 0 to 360 degrees. But the dataset contains negative values in some rows. I like to know is there any formula or rule to convert it into 0-360. Since I am working with python, if someone knows how to do it in Python would be appreciated but any formula could work. For convenience, I have attached a screenshot of a sample dataset.

A: To convert an angle to between 0 and 360, find the modulus of dividing by 360:
df["COG_0_to_360"] = df["COG"]%360

examples:
-10%360 == 350
10%360 == 10

A: Here is my final code:
def COG_0_To_360(cog):
    cog = np.fmod(cog, 360.0)
    cog = np.where(cog < 0.0, cog + 360.0, cog)
    return np.abs(cog)

df['COG'] = COG_0_To_360(df['COG'])

Example:
values = [-170, -10, -390, -355, 250, -440]
print(COG_0_To_360(values))

[190  350  330  5  250  280]


text:
Q: gentoo zlib removed = portage corrupted Hello I'm using gentoo not for a long time and have made such mistake:
I've removed zlib package from system.
Now i've got my portage system corrupted:
# emerge --sync
Traceback (most recent call last):
  File "/usr/bin/emerge", line 36, in <module>
    from _emerge.main import emerge_main
  File "/usr/lib64/portage/pym/_emerge/main.py", line 41, in <module>
    from _emerge.actions import action_config, action_sync, action_metadata, \
  File "/usr/lib64/portage/pym/_emerge/actions.py", line 44, in <module>
    from _emerge.depgraph import backtrack_depgraph, depgraph, resume_depgraph
  File "/usr/lib64/portage/pym/_emerge/depgraph.py", line 40, in <module>
    from _emerge.FakeVartree import FakeVartree
  File "/usr/lib64/portage/pym/_emerge/FakeVartree.py", line 11, in <module>
    from portage.dbapi.vartree import vartree
  File "/usr/lib64/portage/pym/portage/dbapi/vartree.py", line 56, in <module>
    import re, shutil, stat, errno, copy, subprocess
  File "/usr/lib64/python2.6/subprocess.py", line 430, in <module>
    import pickle
  File "/usr/lib64/python2.6/pickle.py", line 1258, in <module>
    import binascii as _binascii
ImportError: libz.so.1: cannot open shared object file: No such file or directory

How can I reinstall zlib package and repair system?
updated
Problem solved.
I've copied object file /lib/libz.so.1 from other machine and then I can run emerge and install zlib package in normal way.
Thanks to PowerSp00n

A: Theoretically you can download the stage3 file used for installation and restore the missing files. When emerge is working again reinstall zlib with emerge -av1 zlib.

A: Pre-built binary packages are available on http://tinderbox.dev.gentoo.org/ — check it out next time you run into a problem like this.

A: Also when you remove packages, I suggest using emerge -pv --depclean pkgname because it won't let you unmerge a package if things depend on it.


text:
Q: Is there simple way to transfer string values from one colomn to numerical values in another colomn? I'm new to python and have task to solve. I got large a .csv file and I was wondering is there simple way to transfer string values from one column to numerical values in another colomn.
For example, in one column I have a bunch of different factory names and in the new colum should be numerical value for every factory:

Factories
NumValues

FactoryA
1

FactoryB
2

FactoryA
1

FactoryC
3

I know that i could do this with dictionaries, but since there is quite a lot of different names(factories) i was wondering if there is already some library to make this process easier and faster?
I hope I explained my problem well.

A: you can use ngroup() . Basically, group by factories and give an id for every factory. Does this give the output you want?
df['NumValues']=df.groupby('Factories').ngroup() + 1


text:
Q: Make field names dynamic I have two fields on Opportunity called FY1 and FY2. Now, my requirement is that the name of the fields need to be dynamic and change every Financial Year e.g first it would be FY18 and FY19, then next year it would be FY19 and FY20.
What I was thinking is that I will create an object related to the Opportunity and populate them every financial year. Is there any other better way to do this?

A: If you need to store and report on historical values, a related object is the way to go.
You end up with field-soup if you create new fields on the main object each year. It's a common mistake people make.


text:
Q: Create buckets of an excel column I have column in excel like
A
1000
2000
3000
.
.
.
200000

I have to create another field such that it buckets A into say 4 buckets/groups as bucket1, bucket2, bucket3, bucket4. Bucket1 contains smaller values, bucket2 contains higher values, buckets3 contains further higher values and so on.
A             B
    1000         bucket2
    200000       bucket4
    3000         bucket2
    .            .
    .            .
    30000        bucket3
    2000         bucket2
    10           bucket1
How do i do this in excel?

A: UNTESTED. Please try in say L1 0, M1 .25, M2 .5, M3 .75 M4 1 and in L2:
=PERCENTILE(A:A,M1)

copied down to L4.
In B1 copied down to suit:
=VLOOKUP(A1,L$1:M$4,2)


text:
Q: Как обработать несколько массивов и присвоить им новое значение Подскажите синтаксис
function modify(&$type_arr, &$local_arr, &$locType, &$park_arr, &$arr_com, $vars) {
    foreach ($vars as &$v) {
        $v = asort($v);
    }
}

modify($vars);

$vars = [$type_arr, $local_arr, $locType, $park_arr, $arr_com];

A: function methodSort(&$var)
{
    foreach ($var as &$v) {
        asort($v);
    }
}

$type_arr = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"];
$type_arr2 = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"];

$vars = [$type_arr, $type_arr2];
methodSort($vars);

var_dump($vars);


text:
Q: Use custom users table for eJabberd Updated Answer
So I have a mobile app with registration and login working (with other features of course, but they are not important in this context). Now I want to add chat features to this application. I installed eJabberd, imported SQL script and enabled SQL. The resultant here is two users table, one that the app uses for registration and login, and another is one created by importing ejabberd script which ejabberdctrl registers its users by default.
Then I set up external authentication, which is using app users table (not one created by ejabberd).
Now my question is, with this setup that bypasses ejabberd users table, will the ejabberd server still work? I'm trying to think for example how will ejabberd organize account rosters when it does not know about app users table and its table is empty?
In other words, how can I tell ejabberd to use my custom app table for all users operations instead of its default table? I want to avoid having to insert data in two tables.
Old question (to preserve answers context)
I have a working ejabberd installation authenticating login with custom script. It works fine. But now am facing an issue, that's more of foreseen problem than actually encountered.
As of now I have users duplicated in ejabberd user table and custom user table. This means I will need to post data to my registration API as well ss ejabberd API. Is there a way to tell ejabberd to use certain table as users table in config? Or will it be safe if I just ignore users table and not register and user with ejabberd altogether? Will the rest of ejabberd work?

A: Regardless of what tables exist (or not) and what content they have, ejabberd will use only the one you define in auth_method, as mentioned in the Authentication documentation:
auth_method: internal

ejabberd will use the 'passwd' table in the Mnesia internal database.
auth_method: sql

ejabberd will use the 'users' table in the SQL database that you configured.
auth_method: external

ejabberd will use the extauth script.
auth_method: [sql, external]

ejabberd will first attempt to use sql. If that fails, it will use external.
I don't know the details here, and found no documentation, fortunately you don't need to do this.

In other words, how can I tell ejabberd to use my custom app table for all users operations instead of its default table?

Now the answer is simple:
auth_method: external

A:
I have a working ejabberd installation authenticating login with custom script.

What authentication method are you using, from the ones documented in https://docs.ejabberd.im/admin/configuration/authentication/ ?
Are you using "external"?

As of now I have users duplicated in ejabberd user table and custom user table.

How can that be? If you are using "external" authentication script, the account credentials (username+password) are not stored in ejabberd.
What is "ejabberd user table"? What is "custom user table"?
There is something misterious in your setup, that make impossible to help you.


text:
Q: How do you submit a form from Django server side? I have a form with some paypal fields and other fields specific to my application. I would like to submit the form to my server, have it process some of the fields and then forward it onto the paypal handler url for payment. If I use the following in my server code:
if request.method == 'POST':

    // Process some form elements

    // Forward on to paypal
    return HttpResponseRedirect("https://www.paypal.com/cgi-bin/webscr")

The problem is that the original form does not get posted with the redirect. How can I make this into an HTTP post with the original form so that they are redirected to Paypal and able to login and complete payment?

A: you can use http.client to make POST requests. Below is a link to the documentation and examples.
http://docs.python.org/3.1/library/http.client.html

A: I think that also accepts GET requests, meaning that you can pass that form data in the url. So you should be able to do along these lines...
if request.method == 'POST':

    // Process some form elements
    // Forward on to paypal
    return HttpResponseRedirect("https://www.paypal.com/cgi-bin/webscr?%s" % "&".join(["%s=%s" % (key,value) for key,value in request.POST.iteritems()]))


text:
Q: regarding text.common_contexts() of nltk what is the prime purpose of the using  text.common_contexts() in nltk.Guys I have searched and gone through as best as I could do. but sorry to say I didn't understand a bit.please help me by giving an example.Thank you.

A:
Example to understand:

Let's first define our input text, I will just Copy/Paste the first paragraph of Game of Thrones Wikipedia page:
input_text = "Game of Thrones is an American fantasy drama television series \
created by David Benioff and D. B. Weiss for HBO. It is an adaptation of A Song \
of Ice and Fire, George R. R. Martin's series of fantasy novels, the first of \
which is A Game of Thrones. The show was filmed in Belfast and elsewhere in the \
United Kingdom, Canada, Croatia, Iceland, Malta, Morocco, Spain, and the \
United States.[1] The series premiered on HBO in the United States on April \
17, 2011, and concluded on May 19, 2019, with 73 episodes broadcast over \
eight seasons. Set on the fictional continents of Westeros and Essos, Game of \
Thrones has several plots and a large ensemble cast, and follows several story \
arcs. One arc is about the Iron Throne of the Seven Kingdoms, and follows a web \
of alliances and conflicts among the noble dynasties either vying to claim the \
throne or fighting for independence from it. Another focuses on the last \
descendant of the realm's deposed ruling dynasty, who has been exiled and is \
plotting a return to the throne, while another story arc follows the Night's \
Watch, a brotherhood defending the realm against the fierce peoples and \
legendary creatures of the North."

To be able to apply nltk functions we need to convert our text of type 'str' to 'nltk.text.Text'.
import nltk

text = nltk.Text( input_text.split() )

text.similar()

The similar() method takes an input_word and returns other words who appear in a similar range of contexts in the text.
For example let's see what are the words used in similar context to the word 'game' in our text:
text.similar('game') #output: song web

text.common_contexts()

The common_contexts() method allows you to examine the contexts that are shared by two or more words. Let's see in which context the words 'game' and 'web' were used in the text:
text.common_contexts(['game', 'web']) #outputs a_of

This means that in the text we'll find 'a game of' and 'a song of'.

These methods are especially interesting when your text is quite large (book, magazine...)

A: Observe the below example. You will understand:

>>> text1.concordance("tiger")

of miles you wade knee - deep among Tiger - lilies -- what is the
one charm wa but nurse the cruellest fangs : the tiger of
Bengal crouches in spiced groves  e would be more hideous than a
caged tiger , then . I could not endure the sigh

>>> text1.concordance("bird")

o the winds when that storm - tossed bird is on the wing . The three
correspon    , Ahab seemed not to mark this wild bird ; nor ,
indeed , would any one else   nd incommoding Tashtego there ; this
bird now chanced to intercept its broad f his hammer frozen there
; and so the bird of heaven , with archangelic shrieks

text1.common_contexts(["tiger","bird"])

the_of


text:
Q: Free file locked by new Bitmap(filePath) I have the Image of a PictureBox pointing to a certain file "A". At execution time I want to change the Image of the PictureBox to a different one "B" but I get the following error:

"A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll
  Additional information: The process cannot access the file "A" because it is being used by another process."

I'm setting the Image as follows:
pbAvatar.Image = new Bitmap(filePath);

How can I unlock the first file?

A: You can't dispose / close a stream while a bitmap object is still using it.  (Whether the bitmap object will need access to it again is only deterministic if you know what type of file you are working with and exactly what operations you will be performing. -- for example for SOME .gif format images, the stream is closed before the constructor returns.)
Clone creates an "exact copy" of the bitmap (per documentation; ILSpy shows it calling native methods, so it's too much to track down right now) likely, it copies that Stream data as well -- or else it wouldn't be an exact copy.
Your best bet is creating a pixel-perfect replica of the image -- though YMMV (with certain types of images there may be more than one frame, or you may have to copy palette data as well.)  But for most images, this works:
static Bitmap LoadImage(Stream stream)
{
    Bitmap retval = null;

    using (Bitmap b = new Bitmap(stream))
    {
        retval = new Bitmap(b.Width, b.Height, b.PixelFormat);
        using (Graphics g = Graphics.FromImage(retval))
        {
            g.DrawImage(b, Point.Empty);
            g.Flush();
        }
    }

    return retval;
}

And then you can invoke it like such:
using (Stream s = ...)
{
    Bitmap x = LoadImage(s);
}

A: Here is my approach to opening an image without locking the file...
public static Image FromFile(string path)
{
    var bytes = File.ReadAllBytes(path);
    var ms = new MemoryStream(bytes);
    var img = Image.FromStream(ms);
    return img;
}

UPDATE: I did some perf tests to see which method was the fastest. I compared it to @net_progs "copy from bitmap" answer (which seems to be the closest to correct, though does have some issues). I loaded the image 10000 times for each method and calculated the average time per image. Here are the results:
Loading from bytes: ~0.26 ms per image.
Copying from bitmap: ~0.50 ms per image.

The results seem to make sense since you have to create the image twice using the copy from bitmap method.
UPDATE:
if you need a BitMap you can do:
return (Bitmap)Image.FromStream(ms);

A: As far as I know, this is 100% safe, since the resulting image is 100% created in memory, without any linked resources, and with no open streams left behind in memory. It acts like any other Bitmap that's created from a constructor that doesn't specify any input sources, and unlike some of the other answers here, it preserves the original pixel format, meaning it can be used on indexed formats.
Based on this answer, but with extra fixes and without external library import.
///
/// Clones an image object to free it from any backing resources.
/// Code taken from http://stackoverflow.com/a/3661892/ with some extra fixes.
///
/// <param name="sourceImage">The image to clone</param>
/// <returns>The cloned image</returns>
public static Bitmap CloneImage(Bitmap sourceImage)
{
    Rectangle rect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
    Bitmap targetImage = new Bitmap(rect.Width, rect.Height, sourceImage.PixelFormat);
    targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
    BitmapData sourceData = sourceImage.LockBits(rect, ImageLockMode.ReadOnly, sourceImage.PixelFormat);
    BitmapData targetData = targetImage.LockBits(rect, ImageLockMode.WriteOnly, targetImage.PixelFormat);
    Int32 actualDataWidth = ((Image.GetPixelFormatSize(sourceImage.PixelFormat) * rect.Width) + 7) / 8;
    Int32 h = sourceImage.Height;
    Int32 origStride = sourceData.Stride;
    Boolean isFlipped = origStride < 0;
    origStride = Math.Abs(origStride); // Fix for negative stride in BMP format.
    Int32 targetStride = targetData.Stride;
    Byte[] imageData = new Byte[actualDataWidth];
    IntPtr sourcePos = sourceData.Scan0;
    IntPtr destPos = targetData.Scan0;
    // Copy line by line, skipping by stride but copying actual data width
    for (Int32 y = 0; y < h; y++)
    {
        Marshal.Copy(sourcePos, imageData, 0, actualDataWidth);
        Marshal.Copy(imageData, 0, destPos, actualDataWidth);
        sourcePos = new IntPtr(sourcePos.ToInt64() + origStride);
        destPos = new IntPtr(destPos.ToInt64() + targetStride);
    }
    targetImage.UnlockBits(targetData);
    sourceImage.UnlockBits(sourceData);
    // Fix for negative stride on BMP format.
    if (isFlipped)
        targetImage.RotateFlip(RotateFlipType.Rotate180FlipX);
    // For indexed images, restore the palette. This is not linking to a referenced
    // object in the original image; the getter of Palette creates a new object when called.
    if ((sourceImage.PixelFormat & PixelFormat.Indexed) != 0)
        targetImage.Palette = sourceImage.Palette;
    // Restore DPI settings
    targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
    return targetImage;
}

To call, simply use:
/// Loads an image without locking the underlying file.
/// <param name="path">Path of the image to load</param>
/// <returns>The image</returns>
public static Bitmap LoadImageSafe(String path)
{
    using (Bitmap sourceImage = new Bitmap(path))
    {
        return CloneImage(sourceImage);
    }
}

Or, from bytes:
/// Loads an image from bytes without leaving open a MemoryStream.
/// <param name="fileData">Byte array containing the image to load.</param>
/// <returns>The image</returns>
public static Bitmap LoadImageSafe(Byte[] fileData)
{
    using (MemoryStream stream = new MemoryStream(fileData))
    using (Bitmap sourceImage = new Bitmap(stream))    {
    {
        return CloneImage(sourceImage);
    }
}

A: This is a common locking question widely discussed over the web.
The suggested trick with stream will not work, actually it works initially, but causes problems later. For example, it will load the image and the file will remain unlocked, but if you try to save the loaded image via Save() method, it will throw a generic GDI+ exception.
Next, the way with per pixel replication doesn't seem to be solid, at least it is noisy.
What I found working is described here: http://www.eggheadcafe.com/microsoft/Csharp/35017279/imagefromfile--locks-file.aspx
This is how the image should be loaded:
Image img;
using (var bmpTemp = new Bitmap("image_file_path"))
{
    img = new Bitmap(bmpTemp);
}

I was looking for a solution to this problem and this method works fine for me so far, so I decided to describe it, since I found that many people advise the incorrect stream approach here and over the web.

A: Here's the technique I'm currently using, and seems to work best. It has the advantage of producing a Bitmap object with the same pixel format (24-bit or 32-bit) and resolution (72 dpi, 96 dpi, whatever) as the source file.
  // ImageConverter object used to convert JPEG byte arrays into Image objects. This is static
  //  and only gets instantiated once.
  private static readonly ImageConverter _imageConverter = new ImageConverter();

This can be used as often as needed, as follows:
     Bitmap newBitmap = (Bitmap)_imageConverter.ConvertFrom(File.ReadAllBytes(fileName));

Edit:
Here's an update of the above technique: https://stackoverflow.com/a/16576471/253938

A: Using a filestream will unlock the file once it has been read from and disposed:
using (var fs = new System.IO.FileStream("c:\\path to file.bmp", System.IO.FileMode.Open))
{
    var bmp = new Bitmap(fs);
    pct.Image = (Bitmap) bmp.Clone();
}

Edit: Updated to allow the original bitmap to be disposed, and allow the FileStream to be closed.
THIS ANSWER IS NOT SAFE - See comments, and see discussion in net_prog's answer. The Edit to use Clone does not make it any safer - Clone clones all fields, including the filestream reference, which in certain circumstances will cause a problem.

A: (The accepted answer is wrong. When you try to LockBits(...) on the cloned bitmap eventually you will encounter GDI+ errors.)

I see only 3 ways to get out of this:

*

*copy your file to a temporary file and open that the easy way new Bitmap(temp_filename)

*open your file, read image, create a pixel-size-pixelformat copy (don't Clone()) and dispose the first bitmap

*(accept the locked-file-feature)

A: I suggest to use PixelMap which is available on NuGet
Very easy to use and much faster than standard Bitmap from .NET
            PixelMap pixelMap = new PixelMap(path);
            pictureBox1.Image = pixelMap.GetBitmap();

A: Read it into the stream, create bitmap, close the stream.


text:
Q: How to return error in basic authentication with Okhttp Kotlin? Currently with my code if the user takes an error when trying to enter the authentication attempt occurs again. I don't want this action, when an error occurs I want to display a Toast and handle this error. How do I change?
`fun login(intent: Intent, intentPai: Intent) { //FAZ O LOGIN
    Log.d(configsAndModels!!.myTag, "Login Iniciado")
    configsAndModels!!.myOkHttpClient1 = OkHttpClient.Builder()
        .addInterceptor(AppHeadersInterceptor(configsAndModels!!.appID, deviceID, "1.0"))
        .authenticator(BasicAuthDialogAuthenticator(configsAndModels!!.bapStore)) //Salva as Credenciais de acesso
        .cookieJar(WebkitCookieJar())
        .build()
    val request = Request.Builder()
        .get()
        .url("${configsAndModels!!.serviceURL}/${configsAndModels!!.connectionID}/")
        .addHeader("Authorization", Credentials.basic(configsAndModels!!.usuario.toString(), configsAndModels!!.senha.toString()))
        .build()

    configsAndModels!!.myOkHttpClient1!!.newCall(request).enqueue(object : Callback{
        override fun onFailure(call: Call, e: IOException) {
            Log.d(configsAndModels!!.myTag, "onFailure called during authentication " + e.message)

        }

        @Throws(IOException::class)

        override fun onResponse(call: Call, response: Response) {
            if (response.isSuccessful) {
                buttonEntrar!!.loadingSuccessful()
                Log.d(configsAndModels!!.myTag, "Autenticado com Sucesso ")
                configsAndModels!!.setupOfflineOData(intent, intentPai) //SALVA OS DADOS NA MEMORIA

            } else {
                Log.d(configsAndModels!!.myTag, "Falha na autenticação ")
                runOnUiThread {
                    buttonEntrar!!.loadingFailed()
                }
            }
        }
    }
    )

}

`


text:
Q: Scroll to down in textarea with jQuery
Greetings

    Hello

Test

  <textarea id="one" class="inner">
    Goodbye
</textarea>

$("#one").append("your text to append");
$("#one").append("your text to append");
$("#one").append("your text to append");
$("#one").append("your text to append");

LIVE: http://jsfiddle.net/tGFmq/
how can i make automatically scroll to down in this textarea?

A: Add this bit to your code (preferably at the end of whatever inserts you have):
    var psconsole = $('#one');
    if(psconsole.length)
       psconsole.scrollTop(psconsole[0].scrollHeight - psconsole.height());

A: I realised my problem was that I had the code in the incorrect place. -> Placed under the element and got the problem to solve (rookie mistake....) -- Just a reminder to all.

A: See this Live Demo: here
To calculate the bottom scrollTop, you can simply subtract the height from the scrollHeight:
var oneDiv = $("#one");
bottom = oneDiv.prop('scrollHeight') - oneDiv.height()

Then you can set its scrollTop to bottom, or use amazing jQuery's animate() for cool animation.
Live Demo: here


text:
Q: Spyder won't launch (except once) using Anaconda on Windows 10 Spyder 5.1.5 does not launch from Anaconda 4.1.2 using Windows 10 — except once, directly after install — throwing these errors from the Anaconda Prompt:
link image0 hasn't been detected!
Traceback (most recent call last):
  File "C:\Users\admin\anaconda3\Scripts\spyder-script.py", line 10, in <module>
    sys.exit(main())
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\app\start.py", line 237, in main
    mainwindow.main(options, args)
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\app\mainwindow.py", line 1992, in main
    mainwindow = create_window(MainWindow, app, splash, options, args)
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\app\utils.py", line 281, in create_window
    main.setup()
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\app\mainwindow.py", line 884, in setup
    plugin_instance = PLUGIN_REGISTRY.register_plugin(
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\api\plugin_registration\registry.py", line 278, in register_plugin
    instance = self._instantiate_spyder4_plugin(
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\api\plugin_registration\registry.py", line 191, in _instantiate_spyder4_plugin
    plugin_instance.register_plugin()
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\plugins\ipythonconsole\plugin.py", line 754, in register_plugin
    self._remove_old_stderr_files()
  File "C:\Users\admin\anaconda3\lib\site-packages\spyder\plugins\ipythonconsole\plugin.py", line 1956, in _remove_old_stderr_files
    for fname in os.listdir(tmpdir):
PermissionError: [WinError 5] Access is denied: 'C:\\Users\\admin\\AppData\\Local\\Temp\\spyder'
[14044:5688:0318/111357.900:ERROR:broker_win.cc(59)] Error reading broker pipe: The pipe has been ended. (0x6D)

Here's what happens after freshly installing Anaconda 4.1.2:

*

*Open Anaconda Navigator for the first time

*Launch Spyder for the first time

*Splash screen for Spyder shows initialization and loading, then closes

*Spyder opens

After closing Spyder and Navigator, I do the steps again:

*

*Open Navigator

*Launch Spyder

*Command window opens with Active code page: 1252

*Splash screen for Spyder shows initialization and loading, then closes along with command window

*Application launch error window opens, showing the errors I posted above

*Spyder does not open

I've tried running Navigator as administrator and Spyder does open, but the Active code page: 1252 command window persists. I fear this simply kicks the issue down the road and doesn't resolve my problem. Also, it's my understanding that Anaconda shouldn't need to be run as administrator to work.
I've tried the following to resolve the problem:

*

*Reinstalling Anaconda multiple times:

*

*Normally and as adminstrator

*Add Anaconda to my path unchecked and checked

*Updating via conda update conda and conda update spyder

*Reinstalling Spyder via https://stackoverflow.com/a/69713849/18502309

*Changing Spyder to an earlier version (e.g., 4.2.5)

*Restarting my computer throughout

Does anyone know how I can get Spyder running? Thanks!

A: Using an installation run as administrator and with the option Anaconda added to path checked, I solved this by double-clicking on the folder AppData\Local\Spyder (which had the administrator logo) and allowing access as administrator.

A: You have installed it as an administrator, but when you're running it the second time and thereafter, the "Anaconda prompt" available from the Start menu is not running as administrator.  Right click on it and choose "Run as Administrator" before trying to run Spyder.


text:
Q: Get the number of milliseconds since some date How to get the number of milliseconds from October 15th 2011 1:52:34 P.M.
I can get the number of milliseconds from the current time.
Date date = new Date();
        long currentTime = date.getTime();
        System.out.println("Current time in long: " + currentTime);

A: long now = System.currentTimeMillis(); // Simpler way to get current time
Date date = new SimpleDateFormat("dd yyyy h:mm:ss a").parse("15 2011 1:52:34 PM");
long timeElapsed = now - date.getTime(); // Here's your number of ms

A: Use the Calendar API. Then set the month, date and the time you want (October 15, 2011).
To get you started look into this:
Calendar c = Calendar.getInstance();

Hope this helps!

A: Link
import java.util.Calendar;
import java.util.Date;

public class TimeMilisecond {
  public static void main(String[] argv) {

      long lDateTime = new Date().getTime();
      System.out.println("Date() - Time in milliseconds: " + lDateTime);

      Calendar lCDateTime = Calendar.getInstance();
      System.out.println("Calender - Time in milliseconds :" + lCDateTime.getTimeInMillis());

  }

}

A: You could use SimpleDateFormat to parse an arbitrariy date and get the difference in ms.

A: Use java.util.Calendar and fill it with your date information. Then use java.util.Calendar.getTimeInMillis() to get the number of milliseconds since epoch.