INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
uploaded file differ with the original
I'm trying to upload a file with node using this simple code:
UpdateController.prototype.uploadUpdateFile = function(req, res)
{
var w = fs.createWriteStream(settings.uploadFolder + settings.updateFile);
req.pipe(w);
w.on('finish', function()
{
res.send(JSON.stringify({
status:0,
filename:settings.uploadFolder + settings.updateFile
}));
}, function()
{
res.send(JSON.stringify({
status:1,
message:"error during file upload, operation failed"
}));
});
}
The file is correctly uploaded but it changes between the original because header (------WebKitForm ... /octet-stream....) and footer (..------WebKitFormBoundary9gOZjMubs9GivcUQ--..) are added to the content.
How to get only the file content ? | You would have to look at the headers of the client request to understand how the client decided to send you the file (how the file was encoded)
You will probably end up using busboy or another package that depends on it : <
such a package will "decode" the data sent by the browser. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "node.js, http"
} |
How to enable Recursive (OpenType) font code ligature in Visual Studio Code?
_More specifically_
How to enable code Discretionary Ligatures "dlig" feature of Recursive font ?
Usual fontLigatures `settings.json` configuration doesn't work.
"editor.fontFamily": "Recursive Sans Linear"
"editor.fontLigatures": true // Do not work :-/ | To enable code ligatures edit VSCode `settings.json` with desired OpenType features :
// Code ligatures ON
"editor.fontLigatures": "'dlig'"
// BONUS: other feature set (see below)
"editor.fontLigatures": "'ss01', 'ss02', 'ss03', 'ss04', 'ss05', 'ss06', 'zero', 'onum'"
!Recursive ligature features
Sources :
Stephen Nixon's article on recursive.design
GitHub VSCode related issue
See also : Microsoft OpenType spec | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "fonts, visual studio code, opentype"
} |
Why this user hasn't got the association bonus on Super User
This user has more than 200 rep. On Stack overflow but why he hasn't got the +100 association bonus on Super User?
!User image
Link to user: < | It is because he joined the Super User community, before question votes became +10, so when he joined Super User, he only had 146 reputation.
Now he has 291 reputation, since up-vote reputation from questions became double than before, here is the post announcing question reputation doubled:
Upvotes on questions will now be worth the same as upvotes on answers | stackexchange-meta | {
"answer_score": 2,
"question_score": 1,
"tags": "discussion, reputation, association bonus"
} |
How can I access SymEngine for use with SymPy?
I'm working on some code and I've noticed that compared to Mathematica, SymPy's simplify command is dreadfully slow. What Mathematica can compute in a split second, SymPy takes forever to compute.
I've read recently online that SymEngine is being (or has been?) implemented into SymPy to make it faster, and that the goal is (was?) to access SymEngine from Python. Is there any way I can somehow make SymPy on my computer use SymEngine? | SymEngine is still under heavy development, but I have sucessfully used some of the functionality they have already implemented. Expect no miracles though, as there are still many parts missing.
Easiest way to use symengine is to download from github and follow their instructions: symengine If you have ubuntu it's really easy, if not you have to install from source (also easy). I suggest systemwide install, it's certainly easier.
Once installed you need to install the python wrapper: symengine.py Same project, same team, works very well together.
Now you are all set to start experimenting with symengine. To use it you need to `import symengine`, and likely also `import sympy` as you are likely to use functions not implemented in symengine (yet). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "python, sympy, symengine"
} |
How to separate elements?
from matplotlib import style
print(plt.style.available)
**Output:**
['seaborn-dark', 'seaborn-darkgrid', 'seaborn-ticks', 'fivethirtyeight', 'seaborn-whitegrid', 'classic', '_classic_test', 'fast', 'seaborn-talk', 'seaborn-dark-palette', 'seaborn-bright', 'seaborn-pastel', 'grayscale', 'seaborn-notebook', 'ggplot', 'seaborn-colorblind', 'seaborn-muted', 'seaborn', 'Solarize_Light2', 'seaborn-paper', 'bmh', 'tableau-colorblind10', 'seaborn-white', 'dark_background', 'seaborn-poster', 'seaborn-deep']
I want to separate every element with ',' so that I like to get like this :
seaborn-dark
seaborn-darkgrid
seaborn-ticks
..
..
..
seaborn-poster
seaborn-deep
What method do I use for that? | You can simply use the .join() command for that.
" ".join(style.available)
which will output a string with the desired format you need.
Another way to print each one in a separate line without using a for loop is simply like this.
print(*style.available) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "python, methods"
} |
How to update docker-machine on Linux?
I installed docker-machine on my Ubuntu 18.04 with the instruction provided in Install Docker Machine. Now how do I update it to a more recent version? | As I found out, it is enough to just rerun the commands for installation with changed version in the link
For example, this command installs version 0.14.0:
curl -L -s`-`uname -m` >/tmp/docker-machine && \
sudo install /tmp/docker-machine /usr/local/bin/docker-machine
If you want to update it to 0.16.0, you just run:
curl -L -s`-`uname -m` >/tmp/docker-machine && \
sudo install /tmp/docker-machine /usr/local/bin/docker-machine | stackexchange-unix | {
"answer_score": 1,
"question_score": 0,
"tags": "software installation, docker"
} |
Clean Architecture: Where to implement pagination logic?
There is a REST API where search keyword entered by the user is used to query and get results. Sometimes, too many results are returned. I don't want to put a maximum result limit on the server side so I want to handle it on the application. In the application, I try to follow Clean Architecture. I have a fragment, a presenter, a usecase and an API client. User enters a keyword, presses search button, the keyword passed to related usecase function through presenter. Usecase gets results from API client and pass results to presenter through listener. Presenter notifies fragment so that results are displayed.
I want to show max of ten pages of results. Where should I put this control? Usecase or presenter? | If you will strictly make it ten pages ALWAYS, put it on your **usecase** because here, application business rules resides. So you don't need to pass it if your just always going to pass ten.
But, I suggest to make it as a **parameter** on the **presenter** , to make it flexible because maybe you will have a scenario in which you want to adjust the max pages on a specific `activity/fragment`. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "android, mvp, clean architecture"
} |
Refreshing data from server using NSTimer
i want to refresh the data from the server ,but that refreshing time-> i want to get that from the user and pass to the timer ,how can i do this i know to give the value like,
self.timerCounter =[NSTimer scheduledTimerWithTimeInterval:300.0
target:self selector:@selector(getGraphData) userInfo:nil repeats:YES];
i also tried using protocols and delegates like ,
self.timerCounter =[NSTimer scheduledTimerWithTimeInterval:strTime
target:self selector:@selector(getGraphData) userInfo:nil repeats:YES];
but i got error like
> Sending NSString _strong to parameter of incompatible type NSTimerInterval
now ,i want to get that from the user in the textfield ,please help me to do this | I think there is the problem in converting `strTime` to NSTimeInterval.
self.timerCounter =[NSTimer scheduledTimerWithTimeInterval:[strTime doubleValue] target:self selector:@selector(getGraphData) userInfo:nil repeats:YES];
Try this, This should work if there is conversion problem.. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ios, objective c, xcode6, nstimer"
} |
jQuery hide/remove DIV content after 5 seconds
How to automatically hide or remove DIV's content. I have container where I put some messages.
<div id="msg-container"></div>
I'd like to show new message only for few seconds, it can be 5, 10 whatever, but then I want it empty, add new message, show it and than hide. Of course I know the "trick" with setTimeout:
setTimeout(function(){
$('#divID').remove();
}, 5000);
but in this option I have to pass this script with every message and it's not what I am looking for. I have also tried setInterval, but as the name says it's interval, so the message can be visible for 5 seconds or can be even invisible if it hits the end of the interval time.
Is there any way to write simple script that will clean my DIV exactly after 5 seconds after it was filled with content? | Suppose you have a message container.
<div id="message-container">
</div>
Just create something like a message manager to handle this kind of feature.
var MessageManager = {
show: function(content) {
$('#message-container').html(content);
setTimeout(function(){
$('#message-container').html('');
}, 5000);
}
};
MessageManager.show('<h1>Testing</h1>');
Every time you want to show something, just call MessageManager.show() with the content you want to show. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, html"
} |
Loading html file to webview on android from assets folder using Android Studio
I'm using Android Studio/Gradle.
app\src\main\android_asset folder has the file called chart.html..
I'm trying to load this file to my webview like this:
WebView view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/chart.html");
setContentView(view);
But I always get the error: could not be loaded because ERR_FILE_NOT_FOUND.
What am I missing here? | The directory name should be **assets** not **android_assets**
Do like this: !enter image description here
As shown in the above pics just right click on your **app->New->Folder->Assets Folder**
Now put your **.html** file here in **assets** folder.
That's it. Done.
Remaining is same in code what you did.
WebView view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/hello.html");
setContentView(view); | stackexchange-stackoverflow | {
"answer_score": 61,
"question_score": 27,
"tags": "java, android, webview, android studio, gradle"
} |
Unit Test exception block of simple python function
I am trying to test the exception block of a simple python function as follows
function_list.py
def option_check():
"""
Function to pick and return an option
"""
try:
# DELETE_FILES_ON_SUCCESS is a config value from constants class. Valid values True/False (boolean)
flag = Constants.DELETE_FILES_ON_SUCCESS
if flag:
return "remove_source_file"
else:
return "keep_source_file"
except Exception as error:
error_message = F"task option_check failed with below error {str(error)}"
raise Exception(f"Error occured: {error}") from error
How do I force and exception to unit test the exception block? Please note that what I have here in exception block is a simplified version of what I actually have. What I am looking for is a way to force an exception using unit test to test the exception scenarios. Python version is 3.6 | You could patch the `Constants` class and delete the attribute you access from the mock.
from unittest import mock
# replace __main__ with the package Constants is from
with mock.patch("__main__.Constants") as mock_constants:
del mock_constants.DELETE_FILES_ON_SUCCESS
option_check()
When `option_check()` tries to access `Constants.DELETE_FILES_ON_SUCCESS`, it will raise an `AttributeError`, allowing you to reach the `except` block. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, unit testing, exception, mocking, assert"
} |
Getting the value from option
Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
* * *
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
* * *
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help.. | ### PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
### Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, jquery, ajax"
} |
Mura CMS - Access Local Index items programmatically
I have created a local index for the purpose of user being able to upload images for an image gallery. I just want to be able to access the images from within that local index, but can't work out how to access the contents of the local index.
I have been able to get the index with: $.getBean("feedManager").read('F78748AB-BADD-5E7F-86890BE17C0E11E8').
With this, I can see the appropriate properties for the local index, however I can't see, nor find a way to access the content items within that feed. In particular, I just want to be able to get to the related image for each item.
I am able to view the items via the RSS feed.
Many Thanks in advance for any pointers.
Jason | feed = $.getBean("feedManager").read('F78748AB-BADD-5E7F-86890BE17C0E11E8')
Your code returns you the feedBean for your local index. The next step is to ask the feedBean for the content. The content can be returned in two formats: a Query object or an Iterator.
Query:
feed.getQuery();
Iterator:
feed.getIterator();
If you ask for the query format you can loop over it using the 'cfloop'-tag with the 'query'-attribute.
If you ask for the iterator this documentation will help you looping over an iterator in Mura (the documentation if for a content iterator, but the concept is the same): < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "coldfusion, mura"
} |
IntelliJ IDEA doesn't recognise angular 4 html tags
The plugin "AngularJS" is, as far as I know, for Angular < 2 and doesn't support Angular 4.
I have an entire project which builds with `ng build` and so on, however IDEA doesn't support the HTML tags such as "fxLayout"
It produces the message: "Attribute fxLayout is not allowed here"
How do I configure IntelliJ IDEA to allow Angular4 html tags? | At first AngularJS plugin should be installed via **Settings | Plugins | Install JetBrains plugin.**
Then it should work automatically as long as you have angular.js in your web module.
**AngularJS plugin requires JavaScript support that is not available in Community version** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "javascript, html, angular, intellij idea"
} |
Priority in task manager - HDD write priority too or only CPU priority?
In Windows (8.1) I can set the Priority of a Program in the Task Manager (Details).
Does this affect CPU Priority only or HDD (write) priority too?
E.G.: HDD is at 100% load due to VMWare. A program with normal priority needs to write but gets delayed. Does the program get higher write priority for the HDD if the priority in the task manager is set to High or Realtime? | The Taskmanager only adjust the CPU priority. To set the IO Priority you can use the program ProcessHacker
$ and $f(x+ \delta x)$ the same after Taylor series expansion?
According to 15.2.1 from < the Taylor series of u(x) can be written as
$ and $f(x_i+\delta_x)$ the same? | Both of them are the same. The second Taylor expansion that you have written is the Taylor expansion of $f(x)$ about the point $x=a$.
So in the second Taylor expansion, put $x-a=\Delta x$. See what happens.
Hope this helps you. | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "taylor expansion"
} |
What are the api to delete the folder and replace in java?
i want to know any apis that can copy and replace folders along with its contents.I know about apache commons, but that copies into the destination folder, it doesnt delete the destination folders extra contents | can be done with standard java < this solution is available from 1.7 onwards | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, nio, apache commons"
} |
Issue with CSS priority and !important
Chrome is taking the CSS padding from .link_block ul li, even though li.page_icon appears afterwards and I've included an !important declaration.
I know there are tons of different ways to apply the padding I want, but if anyone could help explain why the link_block class CSS is taking precedent here even though the page_icon class seems more specific and has the !important declaration.
HTML:
<li class="page_icon">Create New Resume</li>
CSS:
.link_block ul li {
color: #000;
text-decoration:none;
padding: 0px 0px 10px 0px;
font-family:Verdana, Geneva, sans-serif;
}
li.page_icon {
display:block;
width: 100%;
min-height: 60px;
background-image:url(../../images/page_icon.png);
background-position:top left;
background-repeat:no-repeat;
padding: 0px 0px 0px 50px; !important
margin: 0px 0px 0px 0px;
} | First, !important should be before the semicolon, like this:
padding: 0px 0px 0px 50px !important;
Second, you really shouldn't using important's in your CSS. You could solve the problem by giving your lower rule equal specificity as the other rule, and thus the lower rule will be the one that gets applied.
ul li.page_icon {
display:block;
width: 100%;
min-height: 60px;
background-image:url(../../images/page_icon.png);
background-position:top left;
background-repeat:no-repeat;
padding: 0px 0px 0px 50px; !important
margin: 0px 0px 0px 0px;
}
Here's a good link on specificity | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "css"
} |
How can I write a vtkTextActor3D to a file?
I have a set of tubes representing boreholes in a vtp-file (written by vtkXMLPolyDataWriter). Now for clarity I would like to add text labels to identify the boreholes when displaying them in paraview.
My idea was to create labels with vtkTextActor3D, to convert these actors to polydata, and then output these labels, split into polygons, to a vtp-file with the polydatawriter.
How can I do this? In paraview I was able to create a 3D Text source and save it to a vtp-file. However, I can't figure out how to do this in python.
Thanks! | I think to do it the way you described you should actually use vtkVectorText instead of vtkTextActor3D, because accroding to the documentation for vtkTextActor3D, it works like this: _The input text is rendered into a buffer, which in turn is used as a texture applied onto a quad (a vtkImageActor is used under the hood)._ So you actually don't get any geometry for individual characters of your text, instead you would have to save the texture and display that in paraview. Meanwhile, vtkVectorText _should_ (I've never used it personally...) produce an actual geometry for your characters so you can save them as any other polydata. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, vtk, paraview"
} |
.NET 2.0 : File.AppendAllText(...) - Thread safe implementation
As an exercise in idle curiosity more than anything else, consider the following simple logging class:
internal static class Logging
{
private static object threadlock;
static Logging()
{
threadlock = new object();
}
internal static void WriteLog(string message)
{
try
{
lock (threadlock)
{
File.AppendAllText(@"C:\logfile.log", message);
}
}
catch
{
...handle logging errors...
}
}
}
Is the `lock` needed around `File.AppendAllText(...)` or is the method inherently thread-safe by its own implementation ?
Searching for information on this yields a lot of contradictory information, some say yes, some say no. MSDN says nothing. | `File.AppendAllText` is going to acquire an exclusive write-lock on the log file, which would cause any concurrent thread attempting to access the file to throw an exception. So yes, you need a static lock object to prevent multiple threads from trying to write to the log file at the same time and raising an `IOException`.
If this is going to be an issue, I'd really suggest logging to a database table which will do a better job of handling concurrent log writers.
Alternatively, you can use `TextWriterTraceListener` which is thread-safe (well, it's going to do the locking for you; I'd rather write as little of my own multithreaded code as possible). | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 16,
"tags": "c#, file io, .net 2.0, thread safety"
} |
Python - Getting around Beautifulsoup's "object has no attribute" error in empty page
To extract the texts that I need, I am able to scrape most webpages using Beautifulsoup's **find_next_sibling** in my conditional execution.
if len(str(h4.find_next_sibling)) < 90:
...
else:
...
For one particular page, however, the webpage is empty so Python reports the error:
> AttributeError: 'NoneType' object has no attribute 'find_next_sibling'
Since the empty page(s) seem to be produced by error in the list of pages I plan to scrape and I need Python to continue scraping without stopping at every similar instance, one possibility is to write a if condition to only run the code above when there is actually find_next_sibling in the page. Is it possible to do it? Any thoughts are appreciated! | Huge thanks to the commenters, this issue is successfully solved using **try: except** :
try:
if len(str(h4.find_next_sibling)) < 90:
coverage = h4.find_next_sibling(text=True)
else:
if len(str(h4.find_next_sibling)[1]) < 90:
coverage = h4.find_next_siblings(text=True)[2]
else:
coverage = h4.find_next_siblings(text=True)[1]
except:
coverage = "Empty page" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, web scraping, beautifulsoup"
} |
Is there a way to detect what device a user is using?
Say I wanted to provide a string to the user, "You are using a..." followed by their device.
For example a Google Nexus 7, Dell Chromebook 13, Samsung Galaxy J3, Apple Macbook Pro... whatever their device is. Specifically the model of their device.
I've seen Spotify do this, for example. Is this possible using JS?
I'm aware that user agent sniffing exists, but it's not as detailed as I'd like it to be. | if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..
}
or you can use whith jQuery this:
var customizeForDevice = function(){
var ua = navigator.userAgent;
var checker = {
iphone: ua.match(/(iPhone|iPod|iPad)/),
blackberry: ua.match(/BlackBerry/),
android: ua.match(/Android/)
};
if (checker.android){
$('.android-only').show();
}
else if (checker.iphone){
$('.idevice-only').show();
}
else if (checker.blackberry){
$('.berry-only').show();
}
else {
$('.unknown-device').show();
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, user agent"
} |
how to Conditionally add values to a matrix without using a for loop?
I have written a for loop code and I want to write in more succinct way without using a `for` loop, but instead use matrix conditional. I am teaching myself matlab and I would appreciate any feedback.
I want to create a new matrix, the first column is `y`, and the second column is filled with zero except for the `y`'s whose indices are contained in the indices matrix. And in the latter case, add 1 instead of 0.
Thanks.
y=[1;2;3;4;5;6;7];
indices=[1;3;5];
[m,n]=size(y);
tem=zeros(m,1);
data=[y,tem];
[r,c]=size(indices);
for i=1:r
a=indices(i);
data(a,2 )=1;
end
Output:
data =
1 1
2 0
3 1
4 0
5 1
6 0
7 0 | A shorter alternative:
data = [y(:), full(sparse(indices, 1, 1, numel(y), 1))];
The resulting matrix `data` is composed of two column vectors: `y(:)` and a `sparse` array, with "1"s at the positions corresponding to `indices`.
Using proper initialization and sparse matrices can be really useful in MATLAB. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "matlab"
} |
Django - how to pass more than one primary key to the view
I need to write a view to delete multiple objects in one go. I have modified the HTML template, put checkboxes to select which objects (users) to delete and a button to delete them, but of course you need a view to perform the task.
When you have one item to select at a time, you pass its primary key to the view through the url, how can I extend this to pass more than one primary key? | What you can do is to send the data in a JSON format, which can easily be decoded by Django
On the frontend, you'd have a JavaScript for a button like so,
function delete_object(pks) {
var args = {type: "POST", url: "/delete/", data: {'pks': pks}};
$.ajax(args);
return false;
}
this function would take selected the primary keys from (which is passed in as `pks`) and POST it to the Django url `^delete/$`. A Django view function can then handle the incoming data like so,
def delete(request):
object_pks = request.POST['pks']
Docs.objects.filter(pk__in=object_pks).delete() | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "django, django templates"
} |
Strange behavior of log on after restart application pool
I am building a simple asp.net mvc3 application using Form authentication. After publishing it to IIS 7.5, I find that even after I restart the application pool for my web site(stop it and then start). A logined user doesn't need to re-login. That's not what I expect and I don't remember I had configured the cookie to be persistent.
I use the simple asp.net mvc3 web application template and haven't done much thing to config authentication. Below is some codes related to authentication:
in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
in LogOn action:
FormsAuthentication.SetAuthCookie(userName, false); | I think I have got your answer, cookie is set at client side and resetting server IIS will not destroy the cookie as it is not available on server. You can set cookie expiration time and it will get destroy at client side.I hope this clears the situation. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, asp.net mvc"
} |
Hook-length formula (equivalent)
I would like to know if anyone knows where I can find a proof for the equivalent hook-length formula
$$f^{\lambda}=\frac{n! \cdot \prod_{i<j}(l_i-l_j)}{l_1! \cdot l_2! \cdot ... \cdot l_k!}$$
where if $\lambda=(\lambda_1 \geq \lambda_2\geq ...\geq \lambda_k \geq 0)$ is a partition, then $l_i=\lambda_i-i + k$ for all $i$.
I have seen the formula in the book Young Tableaux of William Fulton. | _A Course in Combinatorics_ by Van Lint and Wilson has a proof (Theorem 15.10).
_Enumerative Combinatorics Vol. 2_ by Richard Stanley has a proof (see Lemma 7.21.1, equation 7.101)
_A Course in Enumeration_ by Martin Aigner has a proof (around page 388)
_Symmetric Functions and Hall Polynomials_ by Ian Macdonald I believe has a proof, but I can't check right now.
(5.17.1) in _Introduction to Representation Theory_ by Pavel Etingof, Oleg Golberg, Sebastian Hensel, Tiankai Liu, Alex Schwendner, Dmitry Vaintrob, and Elena Yudovina with historical interludes by Slava Gerovitch | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "abstract algebra, representation theory, symmetric groups, young tableaux"
} |
Run AZCopy via Powershell and Monitor Progress
Is it possible to run AZCopy.exe via powershell and be able to view or output the real-time copy progress somewhere visible? When running it through a standard command line it will display the copy progress and speed in the console window, but when running it in powershell this doesn't display. Otherwise the utility runs fine and returns the final output upon completion. If this isn't possible, do you have any other tips on how to automate azcopy via powershell and interact with the output or results programatically. Thanks in advance. | Do you run AzCopy in a PowerShell ISE window?
If you run it in PowerShell Window, it will have progress. (I test with AzCopy 6.1 on PowerShell 5.1)
If you run AzCopy in PowerShell ISE, it will not have progress. But can show the transfer summary when transfer finished. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "powershell, azcopy"
} |
How do I copy workspace URL in slack application for windows?
How do I copy workspace URL in slack application for windows?
I tried to read manual and google about how to find slack worspace URL in windows client application, but the only link I have found is < and it doesn't provide information about how do I copy the workspace URL to migrate to another machine.
I think it would be very awkward to make screenshot and then use OCR to copy the text of the Slack Workspace URL link to another machine. Especially if the workspace URL is very long and if I need to migrate many workspaces to different machine.
I am definitely missing something, there should be a way to do this simply.
Also I am not administrator of these workspaces, so I can't use option to change workspace url to copy the link. | Ok, looks like the trick is not to try copy the link, but start copying the workspace name, in such way it is possible to copy the URL as well.
">someText</a>
<a onclick="someFunction(2)">someText</a>
<a onclick="someFunction(3)">someText</a>
</div>
I've tried
$("#AnchorHolder").append("<a>" + someText + "</a>").click(function (e) {
someFunction(someIntVariable);
});
but instead connects all of the anchors to the IntVariables current value, whereas I wanted the previous ones.
How can I accomplish this? | Well, I would suggest you to try `data` attributes. As far I know they are made for that porpuse. See:
$("#AnchorHolder").append("<a href='#' data-myvar='" + someIntVariable + "'>" + someText + "</a>");
// Keep the event binding out of any loop, considering the code above will be called more than once...
$("#AnchorHolder").on('click', 'a', function (e) {
alert($(this).data("myvar"));
});
Fiddle | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery"
} |
How to Pass Decimal Value as Argument Correctly
I have this:
double myDecimal = static_cast<double>(atoi(arg_vec[1]));
cout << myDecimal << endl;
But why when I pass the argument like this:
./MyCode 0.003
It prints `0` instead of `0.003`. | `atoi()` converts to integer. You want `atof()`.
Or you could use strtod(). | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "c++, decimal, argument passing"
} |
Dual-booted computer switches OS when asleep
I have a computer set up to dual boot Windows 10 and Linux Mint. When I leave the computer sitting and it goes to sleep under Windows, I find that it will wake back up suddenly booted in the linux partition.
Why is this happening and how can I fix it?
Update: Two new interesting things:
1. It has not done in a couple of days, maybe something is keeping it awake.
2. I noticed that when I then shut down linux and go back to boot up windows, it is not coming back from hibernation, rather, it is loading as if I completly shut down windows. | Quick fix #1: Set Windows as your default boot option
Quick fix #2: Turn off hibernation
When Windows hibernates, it saves the current system state in a file called `hiberfile.sys` and completely shuts down. When you then boot your computer, it will restore the system state from this file.
BUT since you have Linux installed, the boot loader (`grub`, most likely) have no idea of this fact, and will start the default OS. If you change the default to Windows, the Windows boot loader should check for that file and resume the computer as you would expect. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "windows, multi boot, linux mint, sleep, hibernate"
} |
BinaryReader read 4 bytes and don't get expected result
I use BinaryReader to read a file and i've problem i can't solve. (c#)
I need to read 4 bytes. When i look at these bytes with my hex viewer it's `00 00 00 13`. So i tried `Int32 fLength = dbr.ReadInt32();` The result is 318767104 instead of 19 (what i expected and need). When i use `byte[] fLength = dbr.ReadBytes(4);` i can see that i've read the correct bytes [0] [0] [0] [19].
(i've the same problem with the folowing bytes)
How can i read these 4 bytes and get 19 as result.
Thanks in advance !
Robertico | It's a little endian vs big endian problem: 318767104 = 0x13000000
From the documentation:
> BinaryReader stores this data type in little endian format.
Jon Skeet's miscutil has a reader that allows you to choose big or little endian. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "c#, binary, byte"
} |
Filter the elements of one list with an other using Immutabel.js / functional JS
I have an array that contains **all** items and an other array that contains **selected** items. Then I want to create a third array **available** that consists of **all** except the elements contained in **selected**.
E.g
all = [1,2,3]
selected = [3]
available = [1,2]
How do I filter all and selected to create available? | If you're already using `immutable.js`, the operation you're looking for is the `Set` class's `.subtract()` method.
[in functional programming, the term "filter" normally means the operation of returning a new list from those elements on a source list that match a given predicate] | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, functional programming, immutable.js"
} |
invalid syntax when copying weight in pytorch
I tried this:
model2.down1.maxpool_conv.1.double_conv.0.weight.copy_(state_dict['layer1.0.conv1.weight'])
But I got below error message:
model2.down1.maxpool_conv.1.double_conv.0.weight.copy_(state_dict['layer1.0.conv1.weight'])
^
SyntaxError: invalid syntax
But my model output show its has " _ **down1.maxpool_conv.1.double_conv.0.weight**_ "
 you will not have access to them through dot notation (and this is why you get an invalid syntax error, rather than something like Attribute not found error).
You should instead take the `param` reference that you already have in your loop and do the copy
for name, param in model2.named_parameters():
if name == 'down1.maxpool_conv.1.double_conv.0.weight':
param.copy_(state_dict['layer1.0.conv1.weight']) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, tensorflow, keras, deep learning, pytorch"
} |
find string in loaded text
i have this problem;
i load in the IDLE a .txt with a bunch of different words, so in my code i want to assert that certain string included in the function i am defining is in this .txt file, but i keep getting AssertionError
for example, in my shell, for test if a word i know is in the file i put
--> 'AA' in WORDLIST
False
_when the result i'm looking for it's 'True', because in the .txt i know there is an AA word writte it there thanks for help_ | I think I know what is causing your problem: a mistaken use of `assert`.
Do not use `assert` for comparisons. I'm guessing you're doing something like this:
assert 'word' in text_opened_file
The result of this is `None` because `assert` raises an exception if the condition is `False`, but does not return `True` if the condition is `True`. Use `if` and `==` to return `True` or `False` from your comparisons.
Here you can find a debate about effective use of `assert`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "python, python 2.7, load, assert, assertions"
} |
Render a continually changing numpy array to screen at 30Hz with opencv
The following code is not rendering:
import cv2
import numpy as np
from time import sleep
hz = 30
bitmap = np.zeros((512,512,3),np.uint8)
for i in range(512):
sleep(1/hz)
bitmap[i,i,:] = 128
cv2.imshow("Color Image", bitmap)
cv2.waitKey(0)
cv2.destroyAllWindows()
What am I missing? | The waitKey should be inside the loop. The input to the waitKey is the number of milliseconds the frame should be rendered. When its 0, the frame is rendered indefinitely. Try this.
import cv2
import numpy as np
from time import sleep
hz = 30
bitmap = np.zeros((512,512,3),np.uint8)
for i in range(512):
sleep(1/hz)
bitmap[i,i,:] = 128
cv2.imshow("Color Image", bitmap)
cv2.waitKey(3)
cv2.destroyAllWindows() | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, opencv, animation, numpy ndarray"
} |
How to retrieve a specific data from Firebase
I am designing a website where when the user comes and enters his email id, a corresponding value gets printed on the website. I have the below data on my real-time firebase database. How do I write a javascript function in my JS file so that when a user enters his/her email-id, the value of the total gets printed on the website?
{
var email=document.getElementById("email").value;
firebase.database().ref('0/'+email).once('value').then(function(snapshort){
var total=snapshort.val().total;
document.getElementById("total").innerHTML=total;
})} | I think you're trying to perform a query based on the `email` property of the node.
In that case, it'd be:
firebase.database().ref()
.orderByChild("email")
.equalTo(email)
.once('value').then((results) => {
results.forEach((snapshot) => {
let total = snapshot.val().total;
document.getElementById("total").innerHTML=total;
});
});
I recommend reading the Firebase Realtime Database documentation end-to-end, as it should answer many of the questions you may have about the API. A few hours spent there now, will save you many hours down the line. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, firebase, firebase realtime database"
} |
Passing variables through multiple partials (rails 4)
I am trying to pass instance variables through multiple partials and having trouble. `undefined local variable or method "product"`
Application.html.erb"
<%= render 'shared/footer', :product => @product %>
_footer.html.erb
<%= render 'shared/my_form', :product => product %>
_my_form.html.erb
<%= form_for( product ) %>
UPDATE:
I'm starting to think it might be that the instance variable @product is just not being set/passed for the redirect. Could the following be causing the issue? Opened different issue here:
Instance variable not set with redirect | You have to use this syntax:
**Application.html.erb"**
<%= render partial: 'shared/footer', locals: {:product => @product} %>
**_footer.html.erb**
<%= render partial: 'shared/my_form', locals: {:product => product} %>
**_my_form.html.erb**
<%= form_for( product ) %>
Notice the use of `partial:` and `locals:` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 4, partials"
} |
url rewrite not working for a subfolder
I'm trying to change some urls with url rewrite (apache), but nothing works and I just don't understand why. This is my .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !^ [NC]
RewriteCond %{HTTP_REFERER} !^ [NC]
RewriteCond %{HTTP_REFERER} !^ [NC]
RewriteRule ^.*$ [R,L]
ErrorDocument 404 /404.php
RewriteRule ^home$ /t01/index.php [L]
RewriteRule ^chi-siamo$ /t01/chisiamo.php [L]
RewriteRule ^faq$ /t01/faq.php [L]
RewriteRule ^login$ /t01/login_splash.php [L]
RewriteRule ^logout$ /t01/logout.php [L]
There is t01/ in front of the files because I'm trying to see if it works in a subfolder. | I solved everything by putting my files in the main directory and by cleaing my rules(no more t01/ ). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "apache, url rewriting"
} |
Lucene.Net TermQuery wildcard search
I have a lucene index I am trying to do a wildcard search. In index i have a character like `'234Test2343'` I am trying to do the search like %Test%..
My lucene syntax looks like
string catalogNumber="test";
Term searchTerm = new Term("FIELD", "*"+catalogNumber+"*");
Query query = new TermQuery(searchTerm);
I don't get the results back. Any thoughts?
Thanks | You can use a WildCardQuery. A TermQuery looks for the literal asterisk, rather than a wild card. Please note that a WildCardQuery's performance is usually very slow, probably more so when using two wild cards as you do. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 5,
"tags": "c#, .net, lucene, lucene.net"
} |
Lookup User field limit
Is there any limit of lookup user field in ShP list(Sharepoint Online)? I've created just a simple list with over 18 single user select fields and everything seems to works fine, but I've seen somewhere that the lookup limit is 12. Could someone explain how it works? | From <
> This applies to SharePoint online too. Lists created before this timeline in SharePoint online will share the List View Lookup Threshold set to Default =8. Lists created after this timeline in SharePoint online, will have List View Lookup Threshold set to Default =12.
>
> With on-premises SharePoint, these throttles and limits can be changed on the Resource Throttling page in Central Administration. But on SharePoint online, increasing the List View Threshold is not permitted.
>
> Hope this could help.
>
> Regards,
>
> Mona Li
>
> Community Support Team _ Mona Li
Please note that the max of 12 lookup fields is PER View , the max for a list is 96 lookup fields | stackexchange-sharepoint | {
"answer_score": 1,
"question_score": 1,
"tags": "sharepoint online, lookup column"
} |
How can I convert HTML to XPS?
How can I convert HTML to XPS?
* * *
Need a way or a library. But not the finished software product. | Print page from browser to **Microsoft XPS Document Writer** (Virual Printer). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, image, xps"
} |
Basic Grepping/Sedding a part of output
I need to remove the "+0x10" part, but the numbers could change (more digits) so I can't really always remove 5 chars from the back.
something -- printf@plt+0x10
The pattern is always "plt+" and then a hex number. I want it to look like this:
something -- printf@plt
Just without the "+0x10". I'm a bash beginner so please just bear with me. | You can use:
s='something -- printf@plt+0x10'
sed 's/^\(.*\)+0x[0-9]*$/\1/' <<< "$s"
something -- printf@plt | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "bash, sed, scripting, grep"
} |
Autotools new cpu support
What would be right way to add arm64 bit support for an autools based package.
I am trying to cross compile libdbuscpp for arm64 bit architecture.
I see there is a file called `config.sub` that lists all supported cpu. `autoreconf -vfi` is again not updating the cpu sets.
Should I maually edit this file ? | Recent versions of libtool and automake have `config.sub` files that have aarch64 support. You should consider updating GNU Build System tools. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "embedded linux, autotools, autoconf"
} |
How to enable breadcrumbs both Classic and Modern experience
Hi is there any way to enable/put breadcrumbs to SharePoint online site both classic and modern experience? | For classic experience you can create a custom master page and place your breadcrumbs and select it as the master for your site.
For modern experience we don't have the option of master page Or the script editor webpart. So only way is to go for SPFx.
You can find an example here but not sure how useful it would be
<
Thanks.
Regards, Sukumar MS | stackexchange-sharepoint | {
"answer_score": 0,
"question_score": 1,
"tags": "sharepoint online"
} |
Auto insert text at a newline in vim
I am editing a LaTeX file with vim. When I am in the `\begin{itemize}` environment, is there any way to tell vim to autoinsert `\item` whenever I open a new line? | function CR()
if searchpair('\\begin{itemize}', '', '\\end{itemize}', '')
return "\r\\item"
endif
return "\r"
endfunction
inoremap <expr><buffer> <CR> CR()
Put this into your `.vim/ftplugins/tex.vim` file (or any `.vim` inside `.vim/ftplugins/tex` directory). | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "vim, latex"
} |
colour chooser in java gui using buttons
I'm supposed to create a Java GUI with 255 buttons for each RGB color. I have the buttons done with a for loop
for (int i = 0; i <255; i++)
{
JButton btnG = new JButton();
btnG.setBackground(new Color(0, 255, 0 ));
theGreenButton.add(btnG);
btnG.addActionListener(this);
}
but now I'm stuck with getting the shades right. The first buttons should be black and the last one should be bright green, and for now they're all the same color unfortunately. I searched Google and couldn't find anything; any suggestions? | You need to use your i defined in the for loop as Color value in the Button.
for (int i = 0; i <255; i++) {
JButton btnG = new JButton();
btnG.setBackground(new Color(0, i, 0 ));
}
EDIT: for your additional requirements:
in the actionPerformed Method (depending on Buttons color)
int newRed = btnR.getBackground().getRed();
updateRed(newRed);
private void updateRed(int r){
int g = bottomPanel.getBackground().getGreen();
int b = bottomPanel.getBackground().getBlue();
updateColor(r, g, b);
}
private void updateColor(int r, int g, int b){
bottomPanel.setBackground(new Color(r, g, b));
}
now you need to adept the updateRed method to updateBlue and updateGreen and select te correct color according to your Button. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, user interface, colors"
} |
What is the maximum value of $k$ so that $x^2+4(\sin^{2}{x}\tan^{2}{x}+\cos^{2}{x}\cot^{2}{x}+k^2-x\sec{x}\csc{x})=0$ has real roots.
> What is the largest value of $k$ such that the equation $$x^2+4(\sin^{2}{x}\tan^{2}{x}+\cos^{2}{x}\cot^{2}{x}+k^2-x\sec{x}\csc{x})=0$$ has real roots?
I tried to find out the roots in terms of $k$. But I couldn't.
How do we approach this problem without finding the roots actually? | $$x^2- (4\sec{x}\csc{x})x +4(\sin^{2}{x}\tan^{2}{x}+\cos^{2}{x}\cot^{2}{x}+k^2)=0$$ Look for the discriminant, for real roots $D\ge 0 $ $$16\sec^2 x\csc^2 x-16(\sin^2 x\tan^2 x+\cos^2 x\cot^2 x+k^2)\ge 0$$ $$\frac{1}{\sin^2 x\cos^2 x}-\frac{\sin^4 x}{\cos^2 x}-\frac{\cos^4 x}{\sin^2 x}-k^2\ge 0$$ $$\frac{1-\sin^6 x-\cos^6 x}{\sin^2 x\cos^2 x}\ge k^2$$ $$\frac{\sin^2 x+\cos^2 x-\sin^6 x-\cos^6 x}{\sin^2 x\cos^2 x}\ge k^2 $$ $$\frac{\sin^2 x(1-\sin^4 x)+\cos^2 x(1-\cos^4 x)}{\sin^2 x\cos^2 x}\ge k^2$$ $$\frac{\sin^2 x(1-\sin^2 x)(1+\sin^2 x)+\cos^2 x(1-\cos^2 x)(1+\cos^2 x)}{\sin^2 x\cos^2 x}\ge k^2$$ $$\frac{\sin^2 x\cos^2 x(1+\sin^2 x +1+\cos^2 x)}{\sin^2 x\cos^2 x}\ge k^2$$ $3\ge k^2$ $\implies -\sqrt3\le k\le \sqrt3\;$ So maximum value of $k$ is $\sqrt3$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "trigonometry, polynomials"
} |
Nginx, installing fastcgi_purge_cache on centos 7?
I'm trying to setup my sites to run with fastcgi_cache and found it a bit problematic that it doesnt really refresh content when something new is added to my site/webshop.
So i stumbled upon the plugin nginx_helper, and it seemed to be everything i needed - but it requires the fastcgi_purge_cache module to be installed. I have now tried a couple of times on refresh AWS servers (obviously nginx and stuff installed aswell) - but i seem unable to get it to work.
Setup:
* AWS server
* Nginx / php-fpm / php 7
* Wordpress
* CentOS 7
I'm very new at server stuff, and i tried a couple of diffrent guides - but nothing seemed to workout in the end.
Im trying to install < , but im not quite sure how to do it correctly | I maintain a Copr repo with nginx rebuilt to include this specific module. You can enable it on CentOS 7 by installing the appropriate yum repo
[error-nginx]
name=Copr repo for nginx owned by error
baseurl=
type=rpm-md
skip_if_unavailable=True
gpgcheck=1
gpgkey=
repo_gpgcheck=0
enabled=1
enabled_metadata=1
... or on Fedora with `dnf copr enable error/nginx`. | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "nginx, centos, php fpm"
} |
How to gracefully initialize a series of objects in TypeScript?
I need to _temporarily_ create an object in format like `one.two.three.four` in my code.
But the way I known to initialize them is annoying. Is there anyway I can gracefully initialize them with _few lines of code_?
What I am doing now is ugly:
let one: any;
one = {};
one.two = {};
one.two.three = {};
console.log(one.two.three); | As Chris suggested, we can simply do it by:
let one: any = {two: {three: {four:false}}} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "typescript"
} |
Encryption: What is a tag?
I am reading through node-forge documentation and I keep seeing a reference to a 'tag' variable. What is the tag and what is it meant for? | In the examples given, they're using AES in Galois/Counter Mode (GCM). GCM provides both confidentiality (similar to CTR mode), and also message integrity (similar to if you were using an HMAC in addition to AES).
The tag is the authentication tag. It's computed from each block of ciphertext, and is used to verify no one has tampered with your data.
You can see these lines here:
var pass = decipher.finish();
// pass is false if there was a failure (eg: authentication tag didn't match)
if (pass) {
// outputs decrypted hex
console.log(decipher.output.toHex());
}
Where the check is made to see if the authentication tag validated correctly. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, security, encryption"
} |
Rules for Integral Test for Convergence/Divergence
Suppose we're considering the series: $$\sum_{n=2}^\infty\frac{n+\sin n}{1+n^2}$$
For some reason, it seems I can't use the integral test for this problem despite the fact that it fulfills the criteria of being positive, continuous and decreasing. What exactly would the reason be? | You "shouldn't" use the integral test because the integral $\int \frac{x + \sin x}{x^2+1}\, dx$ is difficult.
You "can't" use the integral test because the integrand, $\frac{x + \sin x}{x^2+1}$, is not monotone as $x\to \infty$.
The derivative of $\frac{x + \sin x}{x^2+1}$ is $\frac{1+\cos x -2x\sin x + x^2(\cos x -1)}{(1+x^2)^2}$ which has the same sign as the numerator $$ 1+\cos x -2x\sin x + x^2(\cos x -1) $$ When $\cos x$ is $1$ this expresion is $2$ and the integrand is _increasing_. So the integral test does not apply. Fortunately the limit comparison test easily gives confirmation of divergence.
* * *
The limit comparison test seems appropriate: $\frac{n+\sin n}{1+n^2}\sim \frac{1}{n}$. $$ \lim_{n\to\infty} \frac{\frac{n+\sin n}{1+n^2}}{\frac{1}{n}} =\lim_{n\to\infty}\frac{n^2+n\sin n}{1+n^2} =\lim_{n\to\infty}\frac{1+\sin n/n}{1/n^2+1} =1 $$ and since $\sum\frac{1}{n}$ diverges, so does $\sum\frac{n+\sin n}{1+n^2}$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "sequences and series, convergence divergence, power series"
} |
Default Windows Roboto Alternative
Somewhat similar to this question, I'm looking for an alternative to Roboto. My office is pretty locked down. I can't install any new fonts either on my machine or firmwide, but I love the look of Roboto. I'm looking for a similar font that's included in the default Windows 7 fonts (defaults here) and to the extent there's a different/better fit in default Windows 10 (defaults here). Any thoughts/suggestions would be greatly appreciated. | A great tool to use is similar fonts from identifont. They analyze several different features of the each font and deliver a quantitative, ranked list of similar fonts.
You can see the list of the 30 most similar fonts for Roboto and Roboto 2014 on the left in each of these respective lists. Cross checking these against the list of available fonts in Windows 7 and Windows 10, it looks like **Arial** is the closest match. You could also use the fonts by appearance tool, which will help identify fonts with similar features (of course, not limited to those available in Windows by default). | stackexchange-graphicdesign | {
"answer_score": 0,
"question_score": -2,
"tags": "fonts, font recommendation, windows, windows 10, windows 7"
} |
React ref undefined
so I'm having a little trouble using ref's with React.
All I'm trying to do is print the text content of an element using ref's like this:
export default class SomeClass extends Component {
constructor(props) {
super(props);
this.intro = React.createRef();
console.log(this.intro.textContent);
}
render() {
return (
<div ref={this.intro}>Hi</div>
)
}
}
However, this always prints null or undefined instead of "Hi" which is what I want. | You should use `current` with `ref`, like `this.ref.current.textContent`
Check the stackblitz demo Here
export default class App extends Component {
constructor(props) {
super(props);
this.intro = React.createRef();
}
componentDidMount(){
console.log( this.intro.current.textContent);
}
render() {
return (
<div ref={this.intro}>Hi</div>
)
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "reactjs, ref"
} |
In shopping cart frameworks, what is the "model" field?
I've started to study OpenCart.
When I edit a product, there is a field for `model`, which must not be blank. I know lots of other e-commerce programs that also have a `model` attribute.
Can somebody tell me what this `model` field is used for? | Usually the field "product model" is the product number the shop owner uses to identify the exact product. Normally, in the shop systems I know, it does not need to be unique nor is it a required field (as the shop identifies a product by its ID not its model number) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, opencart"
} |
Iterate on available control and check if this are enabled
I want iterate on GroupBox controls and check if the `CheckBox` are Checked or not. Actually I'm stuck on this:
For Each c In User.GroupBox3.Controls
If c.GetType.Name = "CheckBox" Then
If c.Checked = True ..?
End If
Next
How you can see I can't access to `.Checked` property, someone know how can I figure out? | Its about `Types`. `CheckBox` is a Type, which inherits from `Control` which is another Type. Since a `ControlsCollection` holds the items as `Control`, you have to cast to the specific Type in order to access the more specific properties and methods:
### Long Form:
For Each c As Control In TabPage1.Controls
' check if it is the Type we are looking for
If TypeOf c Is CheckBox Then
' convert to desired type, do something
CType(c, CheckBox).Checked = True
End If
Next
`CType` converts/casts from `Control` to `CheckBox`.
### Short Form:
For Each c As CheckBox In TabPage1.Controls.OfType(Of CheckBox)()
c.Checked = True
Next
This version filters to a given Type so the cast isnt needed. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "vb.net"
} |
Setting cursor for the gap in between controls
I have statically added few .cur files to the executable. I can get them well;
wc.hCursor=LoadCursor(hInstance,MAKEINTRESOURCE(151)); //before registering window class
HCURSOR cursn=LoadCursor(hInstance,MAKEINTRESOURCE(151));
HCURSOR cibeam=LoadCursor(hInstance,MAKEINTRESOURCE(152));
Then I use this method I've found after some search;
SetClassLongPtr(GetDlgItem(hwnd,4),GCLP_HCURSOR,LONG_PTR(cursn)); //on a button
SetClassLongPtr(GetDlgItem(hwnd,21),GCLP_HCURSOR,LONG_PTR(cibeam)); //on an edit box
Now the custom cursors are working fine. But there's an issue. When the cursor is pointing the gap between controls, it turns to the default IDC_ARROW as shown here. How can I make these gaps use `cursn`? | I figured out that "the gaps" between controls are called `nonclient area` and setting cursor like this;
case WM_SETCURSOR:
{
if(LOWORD(lParam)!=HTCLIENT) //the opposite of the example documented on MSDN
{
SetCursor(cursn);
return 1;
}
break;
}
It may be nonstandard and disapproved but it still looks nicer. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, winapi, mouse cursor"
} |
Add / Remove the word 'The' to specific countries
I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays:
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("eire","hispaniola");
and thats it.
Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that. Thank you. | This builds on @sgehrig's answer, but note the change in your exceptions:
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("the eire","the hispaniola");
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The ' . $country;
} else if (in_array($countryKey, $exceptions)) {
$country = substr($country, 4);
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php"
} |
Permalink coming from the Front Matter
I'm working in Jekyll, and I want to customize the permalink of my posts, so I add this line in `config.yml`:
permalink: /:category/:title/
The `category` is the category of the post and `title` is its name as `.md` file. But suppose I want to get info from the from matter of the post: imagine the front matter of `file.md` is
---
title: my_title
lang: en
---
Now I want to get this title (`my_title`, not `file`) and this lang, so that I gent `.../en/my_title.md`. So in `config.yml` I should have
permalink: /page.lang/page.title/
Obviously that does not work because I'm mixing different languages. How should I do? | You cannot use variables in the front matter.
But you can put your post in an `en/` folder and have a default permalink for posts like `:path/:title`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby, config, jekyll, permalinks"
} |
What is the meaning of "argv['A']" in c?
I have found the following code, and I do not understand what it is or how it works. I have only seen `argv[n]` (argv with an integer index) in C before, never with a character literal like `argv['A']`.
if(argc != 100) return 0;
if(strcmp(argv['A'],"\x00")) return 0;
if(strcmp(argv['B'],"\x20\x0a\x0d")) return 0;
printf("Stage 1 clear!\n");
What does this do? Could you explain why it works? | Technically, this is valid in C for accessing an element of the argv (`argv[65]`).
**Edit** : as John Ballinger noted in the comments, this is only if your C implementation maps character literals to their ASCII values, which is not required by the standard. However, most C implementations do, so I would assume the author of the code was using this assumption.
This is because in C, all character literals can act as numeric literals.
Granted, if you are expecting 65+ elements in your argv, something is probably wrong. And even so, using `'A'` and `'B'` for the indices 65 and 66 wouldn't make sense unless you had some specific association of your argv with letters.
**TL;DR** it is an index, but the code is incredibly abnormal and probably intentionally obfuscated | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "c"
} |
TrueType Font Parsing in C
I want to read a ttf and draw a text with that font on a buffer. Even though there are libraries such as freetype, gd to do this task, I want to write my own code. Can you advice me on how to accomplish this task? | Unless you're one of the world's top experts on fonts, typography, and writing systems, the answer is simple: **DON'T**. TrueType/OpenType has a lot of tables you need to support for correct rendering, and even when using FreeType (which is an extremely low-level library), most people get it wrong.
If you need to do low-level, deterministic-across-platforms font handling, then at the very least, you should be using FreeType and libotf. This will provide you with access to the glyphs and outlines which you can then render however you like. In most cases though using your GUI system's text rendering routines will be a lot easier and less error-prone.
Finally, if you insist on ignoring my advice, a good RTFS on FreeType and Microsoft's online resources explaining the tables in TrueType/OpenType fonts are probably the best place to get started. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 14,
"tags": "c, parsing, truetype"
} |
Иконка в Qt c++
Хотел бы в свою программу добавить иконку, чтоб потом нажимая на нее открывалась руководство.После того как скачал, надо иконку button'а изменить, я правильно понял?
Привел как пример иконку в windows:
. При этом, если Вы задаете `icon`, то надпись на самой кнопке будет игнорироваться. | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, qt, icon"
} |
Apache 2.0 vs Apache 2.2 and PHP - what difference do I need to know about?
We have a production server that is running Apache 2.0 and our admins are trying to move us to a development server that is running Apache 2.2.
We need to know what kind of impact, if any, this may have for PHP development.
I know we _should_ be matching our production environment as closely as possible, but I need to give some explanation to our admins as opposed to a directive.
Thoughts? | Please read the announcement or the CHANGELOG, and determine whether either is useful when communicating with your INTJ-type admins.
As far as PHP development goes, you may re-use the version of PHP currently in use on your production server, if you are concerned about application portability. Although, while you're at it, you may want to upgrade PHP to the latest stable release of the major version you are using in production, if only for security purposes. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 2,
"tags": "php, apache 2.2"
} |
Laravel subdomain config
Our staging environment on a project uses the same domain AKA staging.mydomain.com. How do I get the Laravel database config to point to a different DB as the config switch is based on the hostname which is the same for staging. and www.? | You can update the `detectEnvironment` method to use a closure function and run your login in there to determine if your application is local or not.
update **bootstrap/start.php** like this:
$env = $app->detectEnvironment(function() {
return preg_match('/staging/', $_SERVER['HTTP_HOST']) ? 'staging' : 'production';
});
Now when you are visiting your laravel project from < URL, it will detect it as `staging` environment.
Now, you can place the database config specific to `staging` env in here:
**app/config/staging/database.php**
This should do the trick. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "laravel, laravel 4, configuration"
} |
How are EXE, DLL, SYS, etc. filetypes called together?
I'm wondering what's the proper name for all files with executable content? In .NET world, it's called an assembly. Any generic term in Windows world? | _Portable Executable_ encompasses them all; < (Of which .net executables are an extended form) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "windows, terminology, executable"
} |
Anyway to mass delete Custom Metadata Type records?
I currently have 100+ records I need to delete under my custom metadata type, and I am not keen on having to do it one by one (I will need to reset the records every now and then as our requirements keep updating). I tried to do this via Apex but according to the documentation:
> Apex code can create, read, and update ( **but not delete** ) custom metadata records... | As Custom Metadata Records are metadata you can use Force.com Migration Tool and deploy the destructive changes
content of `destructiveChanges.xml`
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="
<types>
<members>CustomMetadataType.CustomMetadataTypeRecord</members>
<name>CustomMetadata</name>
</types>
</Package> | stackexchange-salesforce | {
"answer_score": 8,
"question_score": 2,
"tags": "metadata api, custom metadata, bulk delete"
} |
Getting bizarre error message from Mail
I have Mail set up to handle two different accounts: [my name]_iCloud, and [my name]_Gmail.
Today, when I try to send a message from the iCloud account, I get this message:
Can't Connect to the account "[my name]_iCloud". Enter the password for user "".
The message is exactly as I typed -- it does not provide the user name (which would've been [my name]@icloud.com). Just two quotation marks next to each other. Entering the iCloud password does nothing. It refuses to send any mail.
The iCloud account will **RECEIVE** messages. The Gmail account will both send and receive messages as usual.
Tried deleting the iCloud entries in keychain. Did not work.
Any suggestions on how to fix this? | For the record, the problem appears to have been resolved. Steps I took to fix:
(1) Delete everything from key chain (2) Remove gmail account from Mail. (3) Restore gmail to Mail.
Everything works again. For now. | stackexchange-apple | {
"answer_score": 0,
"question_score": 1,
"tags": "mail.app"
} |
Emacs ESS SAS: Automatic windows splitting to display program, log, and listing
I would like to set up Emacs /ESS so that upon pressing F3 to run a program (on server), it would split my windows into 3 sections. Ideally, it would have one larger window on one side for the SAS program and two half-height windows on the other side containing the LOG and LST files.
I have been using C-x 2 and C-x 3 to split my Emacs windows manually, then cycling through the buffers in each window to get the result I described. This works, but it would be great to have this be automated in some way.
Is this possible, and if so, how can I do it? | You first need to define a command (with `defun`) to do what you need (you'll be using `(split-window-below)` and `(split-window-right)` instead of `C-x 2` and `C-x 3`). Then you bind F3 with that command with:
`(global-set-key (kbd "<f3>") 'your-command-name)` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "emacs, sas, ess"
} |
CodeIgniter incorrect output num_rows == 1
What's wrong with this code why it returns num_rows == 0.
function validate()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('userpassword', md5($this->input->post('password')));
$query = $this->db->get('tbluser');
if($query->num_rows == 1)
{
return true;
}
}
here is my database screenshot
**. It should `be $query->num_rows()`
if($query->num_rows() == 1)
{
return true;
}
The reason it's returning 0 is because `$query->num_rows` does not exist( _that results to false or 0_ ). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php, mysql, codeigniter"
} |
Find all the Partitions of $X$. For each partition, show the corresponding equivalence relation as a subset $X \times X$
So $X = \\{a,b,c\\}$. So I know there are 5 partitions. They are:
$\\{\\{a\\},\\{b\\} ,\\{c\\} \\}$, $\\{\\{a,b\\},\\{c\\} \\}$, $\\{\\{a,c\\},\\{b\\} \\}$, $\\{\\{b,c\\},\\{a\\} \\}$ and $\\{\\{a,b,c\\}\\}$.
I don't really understand how to do the second part. I would know how to find the corresponding equivalence relation for $X$, but I'm not getting it for $X \times X$. Would this just be elements in the partitions grouped as ordered pairs? | In the equivalence relation corresponding to a partition, two things are equivalent if they belong to the same cell (part, class, coset, whatever your book calls it, OK?) of the partition.
Look at the partition $\\{\\{a,c\\},\\{b\\}\\}$. Everything is equivalent to itself (of course), also $a$ and $c$ are equivalent to each other because then are both elements of $\\{a,c\\}$ which is one of the cells of the partition. So the equivalence relation, as a set of pairs, is $$\\{(a,a),(c,c),(a,c),(c,a),(b,b)\\}$$ or maybe $$\\{\langle a,a\rangle,\langle c,c\rangle,\langle a,c\rangle,\langle c,a\rangle,\langle b,b\rangle\\}$$ depending on what kind of brackets your book uses for ordered pairs. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "elementary set theory"
} |
Searchview in LinearLayout using android.support.v7.widget.SearchView
I need a SearchView inside a LinearLayout and I have to support API level 7 and higher. Is it possible to use the support-v7 libraries for this? All the questions in here are about using the support-v7 searchview widget in the actionbar. Does anyone know how to use it in the layout? Thanks. | <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
xmlns:app="
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.SearchView
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:queryHint="@string/search_hint"
app:iconifiedByDefault="false" />
</LinearLayout> | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 4,
"tags": "android, android support library, searchview"
} |
Seaborn clustermap with two row_colors
Quick question, I have a clustermap with variable 'age_range' in row_colors and I would like to add the variable 'education' as a row_color as well. I have the following working code:
agerange = df_cor_small.pop("agerange")
lut = dict(zip(agerange.unique(), "rbg"))
row_colors = agerange.map(lut)
ax = sns.clustermap(df_cor_small, cmap='YlGnBu', row_colors=row_colors, figsize=(15,100), cbar_pos=(1.05, .2, .03, .4))
outputting this figure: 
Any suggestions how I could implement this? | You can provide the colors as a data.frame, I think you are providing a list right now. In the example below, I assign black to the 8 colors, 7x20 and 10 to the rows. Did not cluster the rows to show that the assignment is correct:
import seaborn as sns; sns.set(color_codes=True)
import string
iris = sns.load_dataset("iris")
species = iris.pop("species")
lut = dict(zip(species.unique(), "rbg"))
samples = np.repeat(list(string.ascii_letters[0:8]),20)[:150]
sample_cols = dict(zip(set(samples), sns.color_palette("cubehelix", 8)))
row_colors = pd.DataFrame({'species':species.map(lut),
'sample':[sample_cols[i] for i in samples]})
g = sns.clustermap(iris, row_colors=row_colors,row_cluster=False)
` is an optional part of C11 (more formally called a "conditional feature". Implementations are permitted to not implement the "Bounds-checking interfaces" standardized in Annex K.
Some other conditional features of C11 include:
* atomics
* complex types
* threads
* variable length arrays (the interesting this about this is that VLAs were not optional in C99) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, visual studio, visual c++, strcpy, tr24731"
} |
Invalid Form Key. Please refresh the page while creating new users in Magento 2.3
> Whenever adding new users or editing, updating the products in frontend shows the error Invalid Form Key. Please refresh the page.
***I increased the value of input_max_var but still it showing the error often. Is I need to increase the values for max_input_time and max_execution_time too? Between the site is slow. Will the slow loading cause such issues? ***
_It also displaying the alert messages lately after saving the product or creating users._
_What is the solution?_
_Kindly help me._ | I solved this issue by adding reference container content in the layout.xml file. | stackexchange-magento | {
"answer_score": 1,
"question_score": 0,
"tags": "magento2.3, error, form key, create account"
} |
Create Arrow Button in Qt Designer?
In Qt Designer I can only drag the ToolButton from Widget box. The generated code will look like this.
self.toolButton = QtWidgets.QToolButton(Frame)
self.toolButton.setGeometry(QtCore.QRect(350, 480, 26, 22))
self.toolButton.setObjectName("toolButton")
The button will look like this: 
My question is, how can I make the arrow button directly in QtDesigner without changing any code ? | Its in the settings for the tool button on the right hand side
_ , in a broad sense?
Continuing that thought in context, is there an expression in Spanish that means the same as "apropos of nothing"? | The translation of "apropos of nothing" will vary according to context, for example:
* She kept smiling apropos of nothing. (Source) (Continuaba/continuó sonriendo **sin motivo** ).
* Suddenly, apropos of nothing, he said, `You're such an optimist.' (Source) (De repente, **de la nada** , dijo: Eres todo un optimista.)
* Apropos of nothing, what do you think about her? ( **(No tiene) Nada que ver, pero** ¿qué piensas de ella?) | stackexchange-spanish | {
"answer_score": 6,
"question_score": 4,
"tags": "traducción, uso de palabras, expresiones, palabras raras"
} |
Javascript. Check if there is no tab in focus
Now i'm using visibilitychange event to see which browser tab is active. I use active tab to watch some events on server side, and I don't want to run this watcher in all open tabs.
But now I want to run this watcher even if no tab is in focus, but still, in just one tab.
How to check if no tab is in focus and ensure that some script is running in only one background tab? | You have to solve the issue of communicating between tabs. There are several options:
1. Cookies
2. Local storage
3. Server side syncing (WebSockets, Ajax pooling, etc)
Each tab will have to update its state in the shared data centre (one of the above).
Once that is done, you should use a master selecting algorithm to decide which one of the tab should communicate with the server. In your case, this could be as simple as the first opened tab.
There are some quirks when using local storage such as two different sub-domains can't access the same local storage. Cookies are another way around where you can define parent domain as well. I would say the third option is the best in terms of debugging and adding more complex selection logic. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, tabs"
} |
SharePoint - Organizing Permissions
I have been tasked with redoing our departments SharePoint Site. The main thing I am tackling, which is new to me, is re-organizing the permissions. People would request access and they would be added. I want to create groups and assign everyone to the specific groups. Would this be a reasonable solution at least from an organizational standpoint? Let's say there are 25 people with Read only rights. I want to create a group LibraryX - Read and move the readers there. Is there a better way to organize the permissions? | That is the preferred approach yes. You can group people by general access this way and it works pretty well.
The other option is to create groups based on roles and then you assign permissions to sites and document library permissions based on what the roles should have. Sometimes it's easier to grant permissions to the "Day Shift Users" or "Senior Management" versus Members. | stackexchange-sharepoint | {
"answer_score": 0,
"question_score": 0,
"tags": "permissions"
} |
CVSurf (OpenCV) feature in iOS
I've an issue with OpenCV and iOS. I tried to implement SURF in my Xcode project but when I try to execute it, this error message appears:
> OpenCV Error: The function/feature is not implemented (OpenCV was built without SURF support) in cvExtractSURF, file /Users/alexandershishkov/opencv2.4.3rc/opencv/modules/legacy/src/features2d.cpp, line 77 libc++abi.dylib: terminate called throwing an exception
I had compiled OpenCV from the official repository on Github and with this tutorial: <
Maybe you have an idea... I'm lost.
Thank you. | You need to read my self-answered question here:
openCV 2.4.3 iOS framework compiler trouble recognising some c++ headers
The bit that is catching you out is probably that SURF has been moved to non-free (as it has licensing issues). So you need to:
#include <opencv2/nonfree/nonfree.hpp>
#include <opencv2/legacy/compat.hpp>
and possibly
cv::initModule_nonfree();
if you are working with older the C interface
There are alternatives to SURF if you wish to stick with the open-licensed standard openCV library... | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "objective c, opencv, objective c++, surf"
} |
What is the correct way to represent template classes with UML?
On a UML diagram, what is the correct way to represent a template class? | Normal rectangle with a dotted rectangle in the top right corner, to represent the template parameter. Something like this:
.......
___________: T :
| :.....:
| |
| ClassName |
| |
|______________| | stackexchange-stackoverflow | {
"answer_score": 90,
"question_score": 52,
"tags": "templates, uml, diagram"
} |
How can I start a MMC Agent?
I have a stand alone **Mule Community Edition** instance running an app, which I'd like to view in the Mule Management Console.
I've downloaded the MMC Trial and successfully connected to the trial's Enterprise Mule instance. When trying to add a new server on MMC, connecting to my Community Edition instance, it displays an error with Connection Refused.
Some Googling shows that it I should start the _MMC Agent_ on that server.
How can I do that? | To be able to connect to MMC, you need a agent running along your esb server, which is the one that sends data to MMC and receives commands such as stop/restart/etc. ESB EE runtime comes in 2 flavors: with or without the MMC agent included. In the case is not included, you can add it later as an addon. But you can't add it to a Community Edition (CE). You need the EE version, that is why the mmc trial version comes with the ee runtime trial version. So, in the case you want to test your application running along with the MMC, you have to deploy it in the Mule EE instance (you can deploy the application from MMC). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "mule"
} |
fwrite return int(0) on web server but not on Wamp
I am unable to find any issue with this code on my shared hosting. It is returning `(int)0`, but on my wamp server it is returning the correct bytes. The IP address is taken from gametracker public servers.
**Code**
$socket = fsockopen( 'udp://51.75.36.115', '25565' );
$packet = pack("c3N", 0xFE, 0xFD, 0x09, 2);
$fwrite = fwrite($socket, $packet, strlen($packet));
var_dump( $fwrite);
**Response**
int(0)
I have checked all the php configurations and all modules. I am not getting anything in the error logs. | Turns out it was server restrictions, you cannot do this on shared hosting, you need a cloud or dedicated server. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, linux, wamp, fwrite"
} |
Java array of lists working when type of list is different
I have the following code working and I'm not sure why it doesn't throw an exception:
List[] x=new ArrayList[2];
x[0]=new ArrayList<Integer>();
x[1]=new ArrayList<String>();
x[0].add("test");
x[1].add(5);
System.out.println(x[0]);
System.out.println(x[1]);
This prints:
[test]
[5]
`x[0]` is array of integer and it add String without any issue. `x[1]` is array of String and it add integer without any issue.
How does that work? | You have declared an array of raw typed lists. Generic values do not exist at runtime, after you have compiled your code. So basically your lists are of type `List<Object>`.
* `"test"` is a `String`, which is basically an `Object`
* `5` gets autoboxed to an `Integer` which is also an `Object`
So your compiler will not throw any error. If you are using an IDE it might be warn you:
> Unchecked call to 'add(E)' as a member of raw type `java.util.List'
(From IntelliJ) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "java, arrays, arraylist"
} |
perl + one line change string only if match two words in line
I have the following line in file
<getTheIP ConnectType='INFO' Host='machine_num_1' VirtualIp='12.34.3.9'/>
I need to change the IP 12.34.3.9 to other IP for example 3.4.5.6 but only if I have in line the first word match **ConnectType** and the second word match **machine_num_1**
Please advice how I can do that with perl one line commnand ( I need to run this perl line command from bash script) | >cat test.txt
<getTheIP ConnectType='INFO' Host='machine_num_1' VirtualIp='12.34.3.9'/>
<getTheIP ConnectFour='INFO' Host='machine_num_41' VirtualIp='12.34.3.9'/>
<getTheIP ConnectThree='INFO' Host='machine_num_31' VirtualIp='12.34.3.9'/>
<getTheIP ConnectType='INFO' Host='machine_num_21' VirtualIp='12.34.3.9'/>
>perl -lpe "if (/ConnectType/ && /'machine_num_1'/) {s/(\d{1,3}\.){3}\d{1,3}/3.4.5.6/};" test.txt
<getTheIP ConnectType='INFO' Host='machine_num_1' VirtualIp='3.4.5.6'/>
<getTheIP ConnectFour='INFO' Host='machine_num_41' VirtualIp='12.34.3.9'/>
<getTheIP ConnectThree='INFO' Host='machine_num_31' VirtualIp='12.34.3.9'/>
<getTheIP ConnectType='INFO' Host='machine_num_21' VirtualIp='12.34.3.9'/> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "perl"
} |
html table header locked to the top of the page even when scrolling down
I've used both `to_html()` and `style.render()` of Pandas DataFrame to generate html page from CSV data. It's cool!
But when I scroll the page down I lose sight of the column names, that's the problem.
Is there some way of hanging it up on the top of the page? | Is this what you need?
#NAME HERE{
position: fixed;
{
You can also do the width ect with this code...
#NAME HERE{
position: fixed;
bottom:0px;
right: 0;
width: 0px;
height: 0px;
}
Also, if you want the width to span across the page just change the 0px to 100% Also depending on what you want, change " fixed " to " absolute " | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "python, html, python 2.7, pandas, dataframe"
} |
How to disable 'experimental' warning?
I love chained relational feature (e.g. `0 < a < b` that replaces `0 < a && a < b`) ... but the feature is experimental currently. How to disable/ignore 'experimental' warning? | Pass `--enable-experimental` to `valac`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "vala"
} |
Sympy suddently does not work together with TFQ
I work with tensorflow-quantum and use `sympy` for parameter updating.
Suddenly, without (manually) updating or changing anything this error comes up:
File "/home/eli/anaconda3/lib/python3.8/site-packages/tensorflow_quantum/core/serialize/serializer.py", line 93, in _symbol_extractor
if isinstance(expr, sympy.mul.Mul):
AttributeError: module 'sympy' has no attribute 'mul'
Has anyone had this before? Do you have any suggestions for what I can try to fix this?
I am working on Ubuntu 20.04.2 LTS TFQ version 0.4.0 Sympy version 1.8
the error occurs when I build my PQC layer:
model = tf.keras.Sequential([tf.keras.layers.Input(shape=(), dtype=tf.string),
tfq.layers.PQC(circuit, [cirq.Z(q) for q in builder.get_valid_outputs()]),
], name = model_type)
and it worked like this a long time. | Just to add a little more context to your answer: TensorFlow-Quantum 0.4.0 has an explicit version dependency on `sympy==1.5.0` in the `setup.py` module here, which should have been installed when you first installed TFQ. It's possible that other python pip packages may have overriden or upgraded the sympy version since then. Using something like `pip list | grep sympy` will show which version of sympy you have installed in case you see breakages like this going forward with sympy (or other packages + dependencies) .
Also one final note: TensorFlow Quantum 0.5.0 has been released and does also depend on sympy==1.5.0 which you can see here . | stackexchange-quantumcomputing | {
"answer_score": 5,
"question_score": 3,
"tags": "programming, quantum enhanced machine learning, tfq"
} |
Difference between archiving and compression
What is the difference between Archiving and compression in Linux?
We have different commands for both which we can combine too.. but what exactly are they? | Archiving means that you take 10 files and combine them into one file, with no difference in size. If you start with 10 100KB files and archive them, the resulting single file is 1000KB. On the other hand, if you compress those 10 files, you might find that the resulting files range from only a few kilobytes to close to the original size of 100KB, depending upon the original file type. (source) | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 14,
"tags": "linux, compression, archiving"
} |
Using Linq to return each item only once
Here's what I'm trying to do. Have a use right a sequence of numbers delimited by spaces. After I save those numbers, I want to return a string of all the numbers only once, even if a number has appeared n number of times in the sequence.
string[] tempNumbers = textValue.Split(' ');
IEnumerable<string> distinctNumbers = tempNumbers.Where(value => value.Distinct());
I'm getting this error:
Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<char>' to 'bool' c:\users\sergio\documents\visual studio 2010\Projects\LinqPlayground\LinqPlayground\SetSemanticsExample.cs 67 75 LinqPlayground | The extension method **`IEnumerable.Distinct`** is not a predicate function. It operates on an `IEnumerable<T>` and returns a new `IEnumerable<T>` where each element appears only once.
To fix your code just do this instead:
IEnumerable<string> distinctNumbers = tempNumbers.Distinct();
* * *
> I want to return a string of all the numbers only once
If you want the result as a single space-separated string then in addition to the above you will also need to call `string.Join`:
string result = string.Join(" ", distinctNumbers.ToArray());
txtResult.Text = result; | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "c#, .net, linq, distinct"
} |
MinGW gcj compiler not found by MinGW shell
I tried to compile a simple Java class with gcj, but I'm getting this error: "sh: gcj: command not found". I installed it according to those tutorials: < <
To fix this problem I added all relevant MinGW paths to the user PATH variable: C:\MinGW\bin;C:\MinGW\MSYS\1.0\local\bin;C:\MinGW\MSYS\1.0\bin
This also didn't fix the problem. What might have gone wrong here? Thanks for any help.
The installation file is "mingw-get-inst-20120426.exe", I'm using Windows 7 64 Bit. | You can't get GCJ through official mingw website since they dont develop it anymore. But there a download here: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, compiler construction, mingw"
} |
NRPE: Unable to read output
I try to monitor MySQL database:
> [[email protected] ~]# su nagios -c /usr/lib/nagios/plugins/check_mysql Uptime: 18014 Threads: 1 Questions: 6 Slow queries: 0 Opens: 12 Flush tables: 1 Open tables: 6 Queries per second avg: 0.000
but I've got unexpected error:
> [[email protected] ~]$ /usr/lib/nagios/plugins/check_nrpe -H monitored.com -c check_mysql NRPE: Unable to read output
What's wrong? | From Nagios NRPE Documentation:
> **The check_nrpe plugin returns "NRPE: Unable to read output"**
>
> This error indicates that the command that was run by the NRPE daemon did not return any character output. This could be an indication of the following problems:
>
> – An incorrectly defined command line in the command definition. Verify that the command definition in your NRPE configuration file is correct.
>
> – The plugin that is specified in the command line is malfunctioning. Run the command line manually to make sure the plugin returns some kind of text output.
More details here < | stackexchange-serverfault | {
"answer_score": 2,
"question_score": 4,
"tags": "linux, nagios, nrpe"
} |
SQL select, sum and group
I'm struggling with an Access database: I have a large database with the headers TAG, ZST, KL and R1H00 to R1H23 (24 of them, each one stands for one hour of a day) and I need to get a specific dataset out of it:
SELECT TAG, ZST, (R1H00 + R1H01 + R1H02 + R1H03 + R1H04 + R1H05 + R1H06 + R1H07 + R1H08 + R1H09 + R1H10 + R1H11 + R1H12 + R1H13 + R1H14 + R1H15 + R1H16 + R1H17 + R1H18 + R1H19 + R1H20 + R1H21 + R1H22 + R1H23) AS TOTAL
FROM Klassendaten
WHERE KL = "SWISS7_PW"
So far so good, but the result contains many items with the same ID (ZST). I need to sum all entries with the same ZST, but I couldn't manage to do it so far. (I tried to use the GROUP BY statement, but that only results in errors)
Any experienced SQL people here that could help me with this? | use group by
SELECT TAG, ZST, sum(R1H00 + R1H01 + R1H02 + R1H03 + R1H04 + R1H05 + R1H06 + R1H07 + R1H08 + R1H09 + R1H10 + R1H11 + R1H12 + R1H13 + R1H14 + R1H15 + R1H16 + R1H17 + R1H18 + R1H19 + R1H20 + R1H21 + R1H22 + R1H23) AS TOTAL
FROM Klassendaten
WHERE KL = "SWISS7_PW"
GROUP BY TAG, ZST; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql"
} |
Delphi: generic and type constraints
Is it possible to constrain the type of generic to, say, two different classes?
Like so:
TSomeClass<T: FirstClass; T: SecondClass> = class
// ...
end;
(Sorry about the lack of formatting - the SO tool bar has disappeared from my browser). I know the above won't compile, its only written so to give you guys an idea. I tried
TSomeClass<T: FirstClass, SecondClass> = class
// ...
end;
but then I wasn't allowed to write
procedure TSomeClass.SomeMethod<T> (Param1: string);
Is this even possible? | No, it's not possible. How should the compiler be able to statically verify that your method calls are valid?
Note, that
TSomeClass <T : FirstClass, SecondClass>
is not a valid type constraint. You cannot combine multiple class constraints. You can combine a class constraint with some interface constraints though. But even then
TSomeClass <T : TSomeClass, ISomeInterface>
means, that the generic type has to descend from `TSomeClass` **and** implement `ISomeInterface`.
So the only thing you can do is to extract the stuff that is common between `FirstClass` and `SecondClass`, put it in an interface and use an interface constraint:
TSomeClass <T : IOnePointFive>
Perhaps you can give some more details about what you want to achieve. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 1,
"tags": "delphi, generics, class, constraints"
} |
Can we use include (”TheWalkin.php”) two times in a PHP page “makeit.PHP”?
I it possible to include two times a page called walkin in a page makeit.php | Yes.
But the code will be executed twice.
If you only want it to be included once, use the aptly named include_once.
Problems may occur if you define functions or classes or connections twice. Why do you want to include twice? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Duplicating extenal items into an array
If i was loading external content, such as images or what not will the array load the items twice for example:
load = array(){
load images( "local/folder/www.example.com/" );
items("car.jpeg","bike.jpeg","bike.jpeg");
}
The above is in theory, if you notice twice i have the "bike.jpeg" image in the array; its key value would be either `items[1]` or `items [2]`.
so with the above idea in mind would this bike image be loaded twice or just referenced in the array from the first initial load. | Yes the images are going to be cached by Flash. You can check that in Firebug for example where subsequent requests appear as grayed out (pulled from cache). So you can load the same image several times without much hit on your app's performance. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "actionscript 3"
} |
Can I safely roast a chicken for 4 to 5 hours on a low heat?
Hard pressed office worker and cook here. If I go home at lunchtime and put in a medium sized chicken to roast in the oven can I ensure it's ready to eat when the family get in in the evening?
I've found a recipe instructing me to roast at 120C (250F) for 5 hours, uncovered. The recipe mentions ensuring it reaches 85C (185F) internally.
Does that sound reasonable? Any other tips to ensure I don't risk a charred/undercooked bird? | I would suggest not roasting a chicken at such a low heat for so long. Here is a response to a similar question on another cooking forum:
> A few days ago I printed out a recipe from peacefulnightdove "BEST Slow-Roasted Chicken". It sounded wonderful but was to be roasted at 250 F (126 C) degrees for 5 hours. That sounded like a low temperature to me, so I emailed the County Nutritionist and Health Agent where I lived. Here is her reply: Good for you JoAnn to be suspicious! That is definitely outside the USDA guidelines, and yes bacteria may well be growing for quite a while in there. Poultry especially should not be done at less than 325 degrees. You could use the same spices and onions, increase the temp to 325 and decrease the time. Figure about 20 min per pound for the time. The safest way is to use a meat thermometer, final temp in the thigh should be 180 degrees. <
I would also suggest using a crockpot. | stackexchange-cooking | {
"answer_score": 11,
"question_score": 19,
"tags": "chicken, cooking time, roast"
} |
uniq for Enumerator::Lazy
I am processing something with lots of repeated lines:
# => [ [1, "A", 23626], [1, "A", 31314], [2, "B", 2143], [2, "B", 5247] ]
puts xs
# => [ [1, "A"], [2, "B"] ]
puts xs.uniq{ |x| x[0] }.map{ |x| [x[0], x[1]] }
But **xs** is huge. I'm trying to load it lazily, but **Enumerator#Lazy** does not have an **uniq** method.
How do I do achieve this lazily? | module EnumeratorLazyUniq
refine Enumerator::Lazy do
require 'set'
def uniq
set = Set.new
select { |e|
val = block_given? ? yield(e) : e
!set.include?(val).tap { |exists|
set << val unless exists
}
}
end
end
end
using EnumeratorLazyUniq
xs = [ [1, "A", 23626], [1, "A", 31314], [2, "B", 2143], [2, "B", 5247] ].to_enum.lazy
us = xs.uniq{ |x| x[0] }.map{ |x| [x[0], x[1]] }
puts us.to_a.inspect
# => [[1, "A"], [2, "B"]]
# Works with a block
puts us.class
# => Enumerator::Lazy
# Yep, still lazy.
ns = [1, 4, 6, 1, 2].to_enum.lazy
puts ns.uniq.to_a.inspect
# => [1, 4, 6, 2]
# Works without a block
This is straightforward implementation using `Set`; this means any uniq'd values (i.e. things like `[1, "A"]`, but not stream elements themselves such as `[1, "A", 23626]`) will take up memory. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "ruby"
} |
exit time and indicator function
let $D$ open set of $\mathbb{R}^{n}$ and $T_{D}=\inf\\{t\geq 0 : X_{t}\notin D\\} $ be the first exit time from the $D$ and $1_{A}$ is Indicator function of $A \subseteq \partial D$ $$ \text{Calculated and interpreted } E^{x}[1_{A}(X_{T_{D}})] $$
Indeed: $$ E^{x}[1_{A}(X_{T_{D}})]=E^{x}[1_{\\{X_{T_{D}}\in A\\}}]=P^{x}[X_{T_{D}}\in A] $$ Can we say that $P^{x}[X_{T_{D}}\in A]$ is equal the probability of exit D from A
Please respond | Let $\omega \in \Omega$. By definition of the stopping time, $X_{T_D}(\omega)$ tells us at which point the sample path $t \mapsto X_{t}(\omega)$ leaves for the first time the set $D$. Consequently, $1_A(X_{T_D})(\omega)$ equals $1$ if and only if this point is an element of $A$. Therefore $\mathbb{P}^x[X_{T_D} \in A]$ is the probability that the point of exit (from $D$) is contained in $A$, if the process is started at $x \in \mathbb{R}^n$.
**Example** Let $(B_t)_{t \geq 0}$ a one-dimensional Brownian motion, $B_0=0$, and define $$T:= T_{(-a,b)} := \inf\\{t \geq 0; B_t \notin (-a,b)\\}$$ for $a,b>0$. Obviously, $(B_t)_{t \geq 0}$ exits from the interval $(-a,b)$ either in $-a$ or in $b$ and one can show that
$$\mathbb{P}(B_{T_D} \in \\{-a\\}) \stackrel{\text{def}}{=} \mathbb{P}(B_T = -a) = \frac{b}{a+b} \qquad \mathbb{P}(B_{T_D} \in \\{b\\}) \stackrel{\text{def}}{=} \mathbb{P}(B_T = b) = \frac{a}{a+b}$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "probability theory, stochastic processes, stopping times"
} |
Weapon slots and backpack SDU in DLC
I have started playing Ned's Island. Will I unlock all weapon slots and backpack slots without completing original content? | Your probably not going to unlock those if you stick to the zombi Island DLC. According to the borderlands wiki:
Backpack SDU
The Backpack SDUs each offer 3 additional slots of storage capacity. Each one is gained as a reward for completing one of the ten Claptrap Rescue Missions, for an extra thirty spaces of storage that can be earned throughout the game to a total capacity of 42 on the first playthrough.
Weapon Equip Slot SDU
Two Weapon Equip Slot SDUs are available as quest rewards in Playthrough 1. Together these increase the weapon equipping capacity of a character up to four weapons, allowing an improved selection of weapons in the thick of a fire fight. Each weapon equip slot provides self-contained 'storage' of one weapon in addition to the inventory capacity. The two missions that offer these as rewards are: Return To Zed Road Warriors: Bandit Apocalypse
< | stackexchange-gaming | {
"answer_score": 3,
"question_score": 5,
"tags": "borderlands"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.