INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Convert string to Json Array
I have a Dictionary like that:
Dictionary<string, string> // key value pair
and the example values are:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("key1","value1");
parameters.Add("products","[{"name":"Widget A","qty":3},{"name":"Widget B","qty":1}]");
how Can I serialize that as :
vars={"key1":"value1",products":[{"name":"Widget A","qty":3},{"name":"Widget B","qty":1}]}
When I try to serialize :
vars={"key1":"value1",products":**"**[{"name":"Widget A","qty":3},{"name":"Widget B","qty":1}]**"**}
its append double quotes. Using JSON.Net
I'm using third party API and it accepts HashTable for parameters.
thanks | Define Dictionary object as
`Dictionary<string, object>`
instead of
`Dictionary<string, string>`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "json, jsonserializer"
} |
python gettin a value from a file
I am a new python learner and I want to write a program which reads a text file, and save value of a line contains "width" and print it. The file looks like:
width: 10128
nlines: 7101
I am trying something like:
filename = "text.txtr"
# open the file for reading
filehandle = open(filename, 'r')
while True:
# read a single line
line = filehandle.readline()
if " width " in line:
num = str(num) # type:
print (num)
# close the pointer to that file
filehandle.close() | Your approach to opening the file is not good, try using with statement whenever opening a file. Afterwards you can iterate over each line from the file and check if it contains width, and if it does you need to extract the number, which can be done using regex. See the code below.
import re
filename = "text.txtr"
with open(filename, 'r') as filehandle:
# read a single line
for line in filehandle:
if "width" in line:
num = re.search(r'(\d+)\D+$', line).group(1)
num = str(num) # type:
print (num)
Please see Matt's comment below for another solution to get the number. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "python"
} |
passing pointer to std::function<void()>
what is the best practice to avoid UB when passing a pointer to `std::function<void()>` in `[]` ?
will the `cls_ptr` always be valid in the `second_on_finish` if the object isnt deleted?
this is the current code:
void Foo()
{
SomeClass* cls_ptr = GetPointerToClass();
std::function<void()> first_on_finish = [cls_ptr]() {
if (some_argument == true)
{
std::function<void()> second_on_finish = [cls_ptr]() {
//cls_ptr is always valid here?
};
run_in_a_few_seconds(second_on_finish);
}
};
run_in_a_few_seconds(first_on_finish);
} | > will the cls_ptr always be valid in the second_on_finish if the object isnt deleted
If you mean that `cls_ptr`wasn't destroyed by that time - the answer is **yes**. Pointer is captured by value (not the object it points to) so untill object is destroyed at that address - you can deference it. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c++"
} |
How do you use environment variables in Tup run statements?
I'm trying to run a file given an environment variable to generate some environment-specific rules.
However, Tup doesn't allow for environment variables to be used in Tupfiles directly (you can send them through to child processes using the `export` keyword but you can't use them in `run` statements).
How can I use an environment variable in a `run` statement? | You can achieve this by using the `export` keyword to pass the environment variable through to a child process (bash, in this case), and then using the child process' ability to access environment variables to then run whatever script you want.
To do this, create a helper script:
#!/bin/bash
# bootstrap-script.sh
"${!1}/$2"
which takes the first argument passed to it, _resolves it_ as a variable name, and then performs a replacement (where as the second argument is a direct replacement), and then run it from your Tupfile by using:
# Tupfile
export SCRIPT_DIR
run ./bootstrap-script.sh SCRIPT_DIR my_script.py
The above passes through `SCRIPT_DIR` to the previously mentioned bootstrap script, along with a target script or program to run (in order to generate rules using Tup's `run` keyword). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "tup"
} |
UIkit Dynamics in swift
Trying to convert some objective c code to swift and struggling to achieve results.
animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
_gravity = [[UIGravityBehavior alloc] initWithItems:@[square]];
at to moment I have got
animator.referenceView = self.view
Doesn't work though. Can someone guide me in the right direction. Thanks in advance
Full Code
let square = UIView()
square.frame = CGRectMake(100, 100, 100, 100)
square.backgroundColor = UIColor.redColor()
self.view.addSubview(square)
var animator = UIDynamicAnimator()
var gravity = UIGravityBehavior()
animator.referenceView = self.view
animator.addBehavior(gravity) | holex was on to it, but the key is that you have to store a reference to the animator, here's a working example:
class ViewController: UIViewController {
var animator:UIDynamicAnimator?
override func viewDidLoad() {
super.viewDidLoad()
let square = UIView()
square.frame = CGRectMake(100, 100, 100, 100)
square.backgroundColor = UIColor.redColor()
self.view.addSubview(square)
self.animator = UIDynamicAnimator(referenceView:self.view)
var gravity = UIGravityBehavior(items: [square])
animator!.addBehavior(gravity)
}
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "ios, swift"
} |
xe:viewJsonService only returns 10 rows
I'm using the viewJsonService to retrieve rows from a Notes view, but only ever get the first 10 rows returned. I haven't specified a value for "searchMaxDocs", but even if I put in a value greater than 10, I still only get the first 10 rows of the view returned.
<xe:restService id="restServiceEvents" pathInfo="getEvents">
<xe:this.service>
<xe:viewJsonService defaultColumns="true"
viewName="vwEvents" var="eventRow">
</xe:viewJsonService>
</xe:this.service>
</xe:restService>
Is this limit defined somewhere else? How can I retrieve all rows from the view? | Set property `count` to `"100000"`. It will deliver all documents, at least first 100000.
<xe:viewJsonService defaultColumns="true"
viewName="vwEvents" var="eventRow" count="100000">
</xe:viewJsonService> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "xpages, xpages extlib"
} |
adding to to a C# .NET Dictionary efficiently
I am generating zillions of < string, double > pairs and storing each one in a .NET Dictionary if the string key is not already in use.
Efficiency-wise, is it better to do this ?
try { Dict.Add(key, val); } catch (ArgumentException) {} //blind attempt
or this ?
if (!Dict.ContainsKey(key)) { Dict.Add(key, val); } //smart attempt
The blind attempt triggers exceptions on dup keys; the smart attempt taps the Dictionary index twice - once to check, then again to add. (In my particular case there are dup keys around 10% of the time.)
Does anyone know offhand if one method should be preferred over the other? | Exceptions in general are costly:
> When a member throws an exception, its performance can be orders of magnitude slower.
That said, as Andrew Barber pointed out, this depends on what "zillions" is and how often you expect collisions to occur.
While you'd have to measure your performance to know for sure, I'd personally likely go for the check over waiting for an exception especially if you're not actually _doing_ anything to handle the exception and are just planning to swallow it. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "c#, .net"
} |
Regular expression on tagged words
Given a string representing a sentence like this followed by tagging the string using OpenNLP.
`String sentence = "His plays remain highly popular, and are constantly studied.";`
I get this below. My question is how do I know apply a regular expression to it to filter out tags? What is throwing me off is the word prepended to each hyphen. If it were just tags I can do something like `(VBP|VBN)+` for example, the words in front would vary.
`His_PRP$ plays_NNS remain_VBP highly_RB popular,_JJ and_CC are_VBP constantly_RB studied._VBN`
For example, how would I write a regular expression to keep all `NN` and `CC`? So given the tagged string as shown above how do I get `plays_NNS and_CC`? | I think you can use regular expressions and extract the desired substrings which matches your pattern and concatenate to get required resultant string.
String text = "His_PRP$ plays_NNS remain_VBP highly_RB popular,_JJ and_CC are_VBP constantly_RB studied._VBN";
String pattern = "([^\\s]+_(NNS|CC))";
String resultText = "";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(text);
while (m.find( ))
{
resultText = resultText + m.group(0) + " ";
}
System.out.println("RESULT: " + resultText);
/*
#### OUTPUT #####
RESULT: plays_NNS and_CC
*/ | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, regex, nlp, opennlp"
} |
Regex select text inside quotation marks into groups
I have a lot of lines in this format. I need to capture the quoted text blocks (including quotes), but the last block may be `null` (without quotes).
"1" "Melbourne is the capital of Australia." "0" "Canberra is the capital of Australia."
"2" "New York is the capital of Florida." "0" "Tallahassee is the capital of Florida."
"3" "Paris is the capital of France." "1" null
Expected replacement after match:
{"id":\1,"statement":\2,"correct":\3,"additional":\4}, | Since you know there are exactly 4 terms:
.*?(".*?").*?(".*?").*?(".*?").*?(null|(".*?").*
See demo
It's important to use _reluctant_ quantifiers, which capture as little as possible. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, json, regex, format"
} |
Dynamic use of Workspace Mechanic in Eclipse
Can Workspace Mechanic be configured to load certain rules only if a given plugin or feature is installed?
For example, we have both Java and C++ developers. As it stands today, you get the option to follow both Java AND C++ guidelines in the workspace popup. Can Workspace Mechanic check if JDT and/or CDT are installed? | I do not think Workspace Mechnanic supports this out of the box. However, as it provides extension points, you may be able to build your own plugin to reach your goal. I did it once, but had to use a fragment to access internal capabilities not to reinvent the wheel. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "eclipse plugin, eclipse rcp"
} |
find special order n length combinations of two n length arrays
Given two N length arrays, find the N length combinations of those arrays giving precedence to the elements of the B array.
For example, given the input of arrays `A: [1,2,3]` and `B: [4,5,6]` `Fun(A,B)` could yield:
` [4, 5, 6] -> contains 3 from the B array [4, 5, 3] -> contains 2 from the B array [4, 2, 6] -> contains 2 from the B array [1, 5, 6] -> contains 2 from the B array [4, 2, 3] -> contains 1 from the B array [1, 5, 3] -> contains 1 from the B array [1, 2, 6] -> contains 1 from the B array `
What is most important, is that the most elements in the B array appear first when yielding combinations.
P.S. I would prefer a linear runtime solution of K where K is the number of combinations that can be created (`2^N`). | There are `2 ** N` combinations (or `2 ** N - 1` of you ignore a combination having all elements from `A`), so just listing them has a run time far from linear of `N`.
To generate them notice that each combination corresponds to an `N`-bit number, with `0` meaning "take an element from `A`", and `1` meaning "take an element from `B`". So, generate all `N`-bit numbers, and sort them according to the popcount.
It is possible to generate them directly in a correct order, with the exponential space complexity penalty. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "algorithm"
} |
Ethernet a protocol or cable?
Is ethernet a protocol or cable? How it is different from Cat-5 cables? I'm very confused when I hear the term 'ethernet' for a protocol and cables. | A collection of protocols, detailing the physical and logical data transmission. There are details on wikipedia: <
The cable is described as an "Ethernet" cable because it can carry Ethernet traffic, but it isn't specifically just for Ethernet. Category 5 cable is a specific set of standards for unshielded twisted pair cable; see < | stackexchange-superuser | {
"answer_score": 7,
"question_score": 2,
"tags": "networking, network protocols"
} |
How do I remove people's intestines?
I'm trying to remove someone's intestines, but I can't figure out how. I can cut the small intestine on the left and the large on the right, but pulling on the large intestine doesn't do anything, and I can't grab the small intestine. I've tried cutting everywhere, but I don't see any new spots to cut and that makes him die fast.
?
I was reading about std.flush() in python. And I found this example a lot.
import sys,time
for i in range(10):
print i,
#sys.stdout.flush()
time.sleep(1)
It is often said that it makes a difference with/without the "sys.stdout.flush()". However, when I called this script from command prompt, it didn't make a difference in my case. Both printed numbers to the screen in real time. I used python 2.7.5 in windows.
Why is that happening?
p.s. In another example which printed the output through subprocess.PIPE instead of to the screen directly, I did observe a difference of the buffering.
What am I missing? | Using `flush` will generally _guarantee_ that flushing is done but assuming the reverse relationship is a logical fallacy, akin to:
1. Dogs are animals.
2. This is an animal.
3. Therefore this is a dog.
In other words, _not_ using `flush` does not guarantee flushing will not happen.
Interestingly enough, using Python 2.7.8 under Cygwin in Win81, I see the opposite behaviour - everything is batched up until the end. It may be different with Windows-native Python, it may also be different from within IDLE. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, flush, buffering"
} |
How to make network request only after the user stops typing
I know this question has been asked many times over but I can't get any of the solutions to work.
I am implementing a `TextWatcher` and I want to make a network request but only when the user has finished typing. Here is my code.
val StartFragment.textWatcher: TextWatcher
get() = object : TextWatcher {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
searchPlaces(s)
}
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
}
How do I wait to find out if the user is not typing anymore before performing `searchPlaces(s)`. | I have been able to solve the problem by setting up a `Timer` in the `ViewModel` thanks to user2340612's comment.
// In the ViewModel
private var timer = Timer()
private val delay: Long = 500L
fun searchPlaces(placeName: String) {
searchWord.value = placeName
timer.cancel()
timer = Timer()
timer.schedule(object: TimerTask() {
override fun run() {
viewModelScope.launch {
repository.searchPlaces(placeName)
}
}
}, delay)
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "kotlin"
} |
new MongoDB\BSON\Regex search on text with apostrophe or parentheses
I'm trying to search my mongo collection field to match on strings, some of which have an apostrophe or parentheses like the title:
There's No Way out of Here
All my searches on strings without these characters work. How do I specify my code to match?
My code:
$cursor = $collection->find(
['$and' => [
[ 'recording.title' => new MongoDB\BSON\Regex($title, 'i') ],
[ 'artist.name' => new MongoDB\BSON\Regex($artist, 'ig') ]
]
],
['projection' => [
'recording' => 1,
'release' => 1,
'artist' => 1,
'release-group' => 1
],
['limit' => 1 ]]
);
Any assistance with this would be MUCH appreciated! | Try using to escape these characters like
`$title = "There\'s No Way out of Here";`
You can write `PHP` code to escape all special characters in your query string. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, mongodb"
} |
Change Category Page Display
I have several category pages (e.g. example.com/?cat=3) that display only the post titles. I would like to make them display the post as well. What is the easiest way to do this? | Category pages or archives? If you're a little more specific you will probably get multiple ideas, but in general, if you've got a loop you can use one of the two following functions:
* `<?php the_excerpt(); ?>` will show the custom or default excerpt for the post
* `<?php the_content('Read More »'); ?>` will show the full post with a "Read More" link employed if you've used `<!-- more-->` in your post to show only part of the post on aggregate templates
If you are looking for simple functions for your templates to display content, you should probably read up on the WordPress codex. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
Parsing Mixed Binary Data in C++
I have a blob of data I am parsing. It has mixed data types, some doubles followed by some floats. This is how I have gone about parsing out the doubles into a vector. I just want some feedback on if there is a better way to do this. I feel like there may be a way to do this more concisely.
BlobData::MyDoubles is a vector<double>;
BlobData::MyDoubles MyClass::GetDataPointsFromBlob(const text* blob, const int numDoubles)
{
BlobData::MyDoubles::value_type* doubles = new BlobData::MyDoubles::value_type[numDoubles];
memcpy(doubles, blob, numDoubles*sizeof(BlobData::MyDoubles::value_type));
BlobData::MyDoubles returnVal = BlobData::MyDoubles(doubles,doubles+numDoubles);
delete [] doubles;
return returnVal;
} | You don't need an extra allocation as vector will copy the content no matter what. To convert data from a pointer to void/char/whatever_blob use `reinterpret_cast` that is exactly what it was made for. And you can construct vector with a pair with iterators (pointers are iterators).
vector<double> GetDataPoints(const char* blob, const int numDoubles) {
const double* dbegin = reinterpret_cast<const double*>(blob);
return { dbegin, dbegin + numDoubles };
}
Also note that in the end we don't have any `sizeof(double)` because of pointer arithmetic in C++
P.S. Unlike your code (which has no exception safety) this one has strong exception safety. And for the size type is better to use dedicated `size_t`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "c++, binary data"
} |
Unregister a XLL in Excel (VBA)
I am just discovering the world of programming XLLs for Excel using XLW under Visual C++ 2010 and everything has been smooth so far using the template provided with the XLW package, I have a few questions:
1. I found out that I can register an XLL by double-clicking it. What other ways are there, especially from VBA or the Excel menu?
2. How can I unregister an XLL, both via the Excel GUI and VBA? I assume this has to be done each time I rebuild the Xll under Visual Studio.
3. Does Excel 2010 64-bit require XLLs compiled and linked for 64-bit?
Thanks, Steve | I usually use below as I have to loan/unload xla multiple times during excel session. Let me know if it works for you:
AddIns.Add Filename:= "C:\test\1.XLL"
AddIns("Pricer Add-In").Installed = False
AddIns.Add Filename:= "C:\test\Arbitrage.XLL"
AddIns("Pricer Add-In").Installed = True
you have to make sure that filepath and name of the addin match. To check the name of the addin, go to Tools -> Addin.
you can also use "Record Macro" feature and start recording and disable/enable the addin/xll from Tools -> Addin. Good luck | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 9,
"tags": "excel, vba, xll"
} |
How to verify the stats of a fifo using sox?
I record a wav file using the arecord and I will redirect that to a fifo using
`arecord -d 1 -c 2 -r 48000 -f S32_LE > myfifo`
but how can I get the stats of this using sox?
`sox myfifo -n stat`
gives
`sox FAIL formats: can't open input file myfifo: WAVE: RIFF header not found`
See this Question on how I am doing that.
What options I need to give to sox to ignore the header. I wanna provide the header details as command line if possible. | sox should be informed that the file is a raw type. use `sox -t raw`
Now let's solve the issue.
Create a fifo using mkfifo and then arecord something into it
mkfifo temp.wav
arecord -c 2 -r 48000 -b 32 > temp.wav
Now apply the sox on it.
sox -t raw -r 48000 -b 32 -c 2 -e signed-integer temp.wav -n stat trim 0 1
as it is raw you need to specify the rate, bit depth, channels, and encoding format.
Now it will work without giving any error.
Cheers. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, linux, python multithreading, sox"
} |
Best way to check for inner exception?
I know sometimes innerException is null
So the following might fail:
repEvent.InnerException = ex.InnerException.Message;
Is there a quick ternary way to check if innerException is null or not? | Is this what you are looking for?
String innerMessage = (ex.InnerException != null)
? ex.InnerException.Message
: ""; | stackexchange-stackoverflow | {
"answer_score": 67,
"question_score": 68,
"tags": "c#, .net, exception"
} |
AJAX doesn't work in browser when wanting to retrieve data from URL
I've been experiencing this weird problem when I want to retrieve data from an URL.
$.ajax({
url: 'URLHERE',
dataType: 'html',
success: function(data) { //function 2
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function() //function 3
{
var name = $(this).attr('name');
var x = $(this).attr('x');
alert(name);
alert(x);
}); //function 3 end } //function 2 end }); //ajax end
This does work in Dreamweaver, but not in browser. I've been reading that it could be because AJAX doesn't work on cross domain on browsers. Is this true? Also read that I could change dataType to 'jsonp' - but this doesn't even work in dreamweaver.
Any ideas what could be wrong? Or should I use a whole other thing than AJAX for this problem?
This is a mobile app in PhoneGap, so I am also using jquery. | Here is what i think is possible, as you use PhoneGap. You can test it with IE (not other browsers)
var xhr = new XMLHttpRequest();
xhr.open("GET", "url", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var text = xhr.responseText;
alert(text);
}
}
xhr.send();
Hope this works, it does for me at least. after this you can parse to xml.... and continue your work as you intended. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery, ajax, browser"
} |
change div css style if browser safari
I have the following div:
<div id="views" style="margin-top:34px; margin-left:35px;">
// code...
</div>
this works perfect for me in all explorers but in safari in order to work perfect I need to set margin-top: -40 px; Any idea which is the easiest way to do this? I mean to make is select browser and if safari to apply margin-top: -40 px; | 1. Take out your inline styles.
2. Detect the browser by JavaScript, add a class of `.safari` to the `body` tag if Safari is detected, then have your general and Safari specific styles like this:
CSS:
#views {
margin-top:34px;
margin-left:35px;
}
.safari #views {
margin-top:-40px;
margin-left:35px;
}
Safari styles will be applied to Safari due to higher CSS specificity. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "css, html, safari"
} |
Get height of DIV and its content with JQuery
I have a div which contains several elements:
<div class="menuItem designMenu" id="dMenu">
<ul class="menuList menu">
<li class="menuHeader">Design</li>
<li class="projectHeader">Mother</li>
<li class="projectBody">Some text here</li>
<li class="more">More</li>
</ul>
</div>
I need to get the height of the dMenu items that I can animate it upwards, including all the content inside. My Javascript currently:
var designHeight = $("#dMenu").height();
Returns nothing.
I've tried `offsetHeight`, `scrollHeight`, and everything else Google turns up. I'm running the jQuery at the end of the body, inside a document ready function.
The reason to get the height to animate, instead of doing it manually, is that a: I'd like to learn how and b: I don't yet know how many items will be in the div. | Are the `li`s within the `ul` floated? If so, and the parent does not have `overflow: hidden` the parent collapses and therefor has no height. Try (if possible) adding `overflow: hidden` to the parent element, or hard code a height in your CSS. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, height"
} |
how to upload multiple images in to a server?
I tried to upload the image in to the server using Flex.The coding is compiled and run sucessfully but the images are upload at a time. i want to upload images seperately and also put progres bar to upload each image uploaded. can any one help me? | You can achive this with the FileReferenceList, you can find all the info and example code here:
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "actionscript 3, apache flex, flex4.5"
} |
Python pandas.DataFrame: Make whole row NaN according to condition
I want to make the whole row NaN according to a condition, based on a column. For example, if `B > 5`, I want to make the whole row NaN.
Unprocessed data frame looks like this:
A B
0 1 4
1 3 5
2 4 6
3 8 7
Make whole row NaN, if `B > 5`:
A B
0 1.0 4.0
1 3.0 5.0
2 NaN NaN
3 NaN NaN
Thank you. | You can also use `df.loc[df.B > 5, :] = np.nan`
* * *
Example
In [14]: df
Out[14]:
A B
0 1 4
1 3 5
2 4 6
3 8 7
In [15]: df.loc[df.B > 5, :] = np.nan
In [16]: df
Out[16]:
A B
0 1.0 4.0
1 3.0 5.0
2 NaN NaN
3 NaN NaN
in human language `df.loc[df.B > 5, :] = np.nan` can be translated to:
> assign `np.nan` to any column (`:`) of the dataframe ( `df` ) where the condition `df.B > 5` is valid. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "python, pandas, dataframe"
} |
How do game engines manage to 'detect' the opengl supported in a computer
I am learning OpenGL 3.3 and OpenGL 2.1. I want to make a game engine with both. So far I can do advanced stuff with both of them. I noticed that graphics engines like Irrlicht support OpenGL 1.x to 4.x. When i run an Irrlicht program in my computer that supports OpenGL 3.3, it runs perfectly. And when i run it in a computer with OpenGL 2.1, it still runs perfectly.
How does it _know_ that my computer supports OpenGL 3.3, and adapt itself to it. Is it through trial and error? or how are they able to do this. That is a feature i want to incorporate in my game engine. | What works for me is simple:
// create OpenGL context first, gl** functions dont work without it
fOpenGL_Vendor := String(glGetString(GL_VENDOR));
fOpenGL_Renderer := String(glGetString(GL_RENDERER));
fOpenGL_Version := String(glGetString(GL_VERSION)); // <-- this
Last line returns OpenGL version reported by GPU driver, in a `x.x.x` format. You can trim last `.x` from it to get common 2-digit version format.
* * *
For example this is breakdown from my game:
Count Version
2175 4.5
684 3.3
435 4.0
331 4.4
262 4.3
248 3.1
216 4.2
97 3.0
75 4.1
73 2.1 | stackexchange-gamedev | {
"answer_score": 2,
"question_score": 0,
"tags": "opengl"
} |
SQL Comparing values in two rows
I have the following data of sales for various categories of items:
category year salesVolume
1 2002 45
1 2003 47
2 2002 789
2 2003 908
3 2002 333
3 2003 123
41 2002 111
41 2003 90
Now I want to compare sales volume in the year 2002 to the year 2003, category wise, and write results as:
category salesIncreasing?
1 TRUE
2 TRUE
3 FALSE
41 FALSE
Is it possible to do it in SQL. If so please let me know. Actually I am using Impala SQL. Thanks. | SELECT
a.category,
CASE WHEN a.salesVolumes < b.salesVolumes THEN 'TRUE' ELSE 'FALSE' END AS salesIncreasing
FROM MyTable a
INNER JOIN MyTable b ON a.category = b.category
WHERE a.year = 2002
AND b.year = 2003
The idea is to have a single table as a result that let you compare and project the sales into a new data. In order to do this, you join the table with itself, and you use two restrictions in the WHERE clause. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 9,
"tags": "sql"
} |
BASH script to change names on files with same name but differing cases
I'm trying to write a bash script that will recursively search a directory, find files with the same names but different cases, and rename them.
For example a directory containing file.txt and File.txt, file.txt would remain and File.txt would be File.0 (Or any number as long as both copies are preserved.)
Here is the code I have, though I see the problem. The line to scan for duplicate names is changing the case in the paths to the files, making them invalid. I can't think of a way to detect duplicates without also removing the case in the paths.
#!/bin/bash
#Scan for duplicates
find $1 -name "*"| tr 'A-Z' 'a-z' | sort | uniq -d > ~/case.tmp
#Count changes
i=0
#Make changes
for line in `cat ~/case.tmp`
do mv $line $line.$i
let i++
done
#Print Results
echo "$i file(s) renamed".
Thanks for the help. | Did you try something like
find $1 | sort -f | uniq -i -d -D
Explanation:
* `sort -f`: ignore case
* `uniq -i -d -D`: ignore case (-i), print duplicate lines (-d), print all duplicate lines (-D)
From there it should be easy to realize what you want to do. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "bash, case, rename, case sensitive"
} |
Quick Edit not allowing me to change Content Type of a file within Document Set
I'm working on developing a new document library for our Team and am very interested in using Document Sets. I setup a simple Document Set with a few different content types, as well as shared columns. Things have been working as expected so far, however, I've noticed that when trying to use "Edit in grid view" I'm not able to change the content type associated with a given file. Is there a reason for this?
I am able to update the content type through the info panel, and can update other cells in grid view, just not the content type.
Thanks in advance for the help!
 don't have the flexibility to switch fields dynamically based on the selected content type.
So, when you change value of the Content Type field via " **Edit in grid view** ", the page will display " **This cell is read-only** " message. 
The problem is that I only found information about creating method extensions for specific datatypes but any about a method extension for a Class.
If this is not possibly, which similar alternatives I have? | The short answer is, you can't.
Extension methods can only apply to object instances, but the `Console` class is static. The only solution is to write your own, completely separate class, say `ConsoleEx`, and implement any methods you want there.
> Extension methods make it possible to write a method that can be called as if it were **an instance method** of the existing type. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": ".net, vb.net, methods, extension methods, static classes"
} |
UISplitView Ipad custom search bar
I wants to add (custom bar) a search bar and 3 buttons on UISplitView bar, It is possible? please direct me in right way. any tutorial or link really appriciated.
Thanks
!enter image description here | Drag a UIToolBar at the top of desired xib and First drag the BarButtonItem then drag the search bar into it..and finally another barbuttonItem to get your desired custom Bar | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "iphone, ipad, uisplitviewcontroller"
} |
Get IP address in a string
I'm looking for some sort of PHP-code to scan my `/var/log/secure` to filter breakin attempts. Below are just some examples of strings that need to be searched and get the IP address ONLY. I'm using `0.0.0.0` as an example of an IP address and not the actual IP.
Failed password for invalid user admin from 0.0.0.0 port 3108
Invalid user ubnt from 0.0.0.0
pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=0.0.0.0 | With the additional information provided by the OP in this comment, I decided to redo my answer. So;
$file=file_get_contents("/var/log/secure");
$lines=explode("\n",$file);
$accepted=array();
$fail=array();
$r="/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/";
foreach($lines as $line){
//try to get the ip
$t=array();
preg_match($r,$line,$t);
$ip=$t[0];
if(strpos($line,"Accepted password")!==FALSE){
//Successfull login
$accepted[]=$ip;
}
else{
//failed login attempt
$fail[]=$ip;
}
}
Now `$accepted` contains all the IP's who logged in successfully, and `$fail` all those who did not.
I hope this helps you. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, regex, search"
} |
Eclipse shortcut to comment out code doesn't work anymore
I used to be able to use ctrl+7 to comment out code, but all the sudden it doesn't work like that anymore. Instead I get a small window popup at the lower right corner, saying only `Toggle Comment Ctrl+7`. If I use the shortcut again it appears to close and then reopen the window. If I press enter nothing happens. If I double click it, it does toggle comment. How can I fix it?
Here's how it looks: . Could you help me to prove it combinatorially? please | To obtain this combinatorially write left hand side as $\sum_k k {n \choose k} {n \choose n-k}$. This sum can be interpreted as the number of ways to choose $n$ children from a group of $n$ boys and $n$ girls ($2n$ children) and then choosing "leader" from, e.g., chosen boys.
On the other way it can be done as follows: choose a "leader" from boys group and then choose $n-1$ children from whole group of $2n-1$. That is $n {2n-1 \choose n-1}$. | stackexchange-math | {
"answer_score": 5,
"question_score": 4,
"tags": "combinatorics, summation, binomial coefficients"
} |
Saving template information in Subclass
I have a parent-class with a function. In this function I want to call a template method but the type of the template depends on the type of sub-class. So I want to save the information about T there. I can't call foo with a template because it's from another part of the Program wich i can't change
class A
{
//this will be called on an instance of B or C, A will never be
//instantiated
void foo()
{
ba<T>();
}
}
class B :public A
{
//T want to save here the Type of T so i won't have to call foo() with
//a template
}
class C :public A
{
//here comes another Type for T
} | What you need is a CRTP pattern, which is very common in C++ template programming.
template<class T>
void ba() {}
template<class Derived>
struct A
{
void foo() {
ba<typename Derived::MyT>();
}
};
struct B
: public A<B>
{
using MyT = int;
};
struct C
: public A<C>
{
using MyT = double;
};
int main() {
B b;
b.foo();
C c;
c.foo();
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, templates, inheritance"
} |
Default controller in Route::group for routing purposes?
I want to show some user data by id. Simple.
`user/{id}` -> get data from a Controller's method.
I have this:
Route::group(['prefix' => 'user/{id}', 'where' => ['id' => '[0-9]+']], function() {
Route::get('delete', 'UserController@delete')->name('admin.access.user.delete-permanently');
Route::get('restore', 'UserController@restore')->name('admin.access.user.restore');
Route::get('mark/{status}', 'UserController@mark')->name('admin.access.user.mark')->where(['status' => '[0,1]']);
Route::get('password/change', 'UserController@changePassword')->name('admin.access.user.change-password');
Route::post('password/change', 'UserController@updatePassword')->name('admin.access.user.change-password');
});
How can I access a method as a default for `user/{id}`? | You can do this in your controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//Fetch and send the user to the "profile" blade file in the folder "resources/views/user"
return view('user.profile', ['user' => User::findOrFail($id)]);
}
public function changePassword($id)
{
$user = User::findOrFail($id);
return $user->update(
'password' => bcrypt(123456)
);
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "laravel, laravel 5, laravel routing"
} |
$\omega$ satisfies $a \omega^3 + b \omega^2 + c \omega + d = 0$, Prove that $ |\omega| \leq \max( \frac{b}{a}, \frac{c}{b}, \frac{d}{c})$
If $\omega$ is a complex number that satisfies $a \omega^3 + b \omega^2 + c \omega + d = 0$, **where $a,b,c,d$ are positive real numbers**, prove that $|\omega| \leq \max( \frac{b}{a}, \frac{c}{b}, \frac{d}{c})$
This just seems so simple and elegant yet I can't wrap my head around. Was trying to tackle from vieta's formula but nothing fruitful yet.
Another idea was to make the polynomial $\omega^3 + \frac{b}{a} \omega^2 + \frac{c}{b} \omega + \frac{d}{c} = 0$, and prove some contradiction if $\omega > \max( \frac{b}{a}, \frac{c}{b}, \frac{d}{c})$. It might be closer to what we want. | Let $r=\max( \frac{b}{a}, \frac{c}{b}, \frac{d}{c})$. To simplify the problem, use the substitution $\omega =rz$, $$ ar^3z^3+br^2z^2+crz+d=0,\\\ az^3+\frac{b}{r} z^2+ \frac{c}{r^2} z+\frac{d}{r^3}=0,\\\ z^3+B z^2+ C z+D=0, D\leq C\le B\le 1. $$ Now, consider $$ f(z)=(1-z)(z^3+B z^2+ C z+D)+z^4=(1-B)z^3+(B-C)z^2+(C-D)z+D. $$ For $|z|=1$, $f(z)\leq |1-B|+|B-C|+|C-D|+D=1$, so $|z^3f(1/z)|\leq 1\times 1=1$.
By maximum modulus principle, $|z^3f(1/z)|\le 1$ for all $|z|\le 1$. That means for $|z|>1$, $|f(z)/z^3|\le 1$, $|f(z)|\le |z|^3$ Therefore, $$ |(1-z)(z^3+B z^2+ C z+D)|=|f(z)-z^4|\ge -|f(z)|+|z|^4\\\ \ge |z|^4-|z^3|=|z|^3(1-|z|)>0 $$ for $|z|>1$, so for $(1-z)(z^3+B z^2+ C z+D)=0$, $|z|\leq 1$. As a result, $$ |\omega|\le |r||z|\le r. $$ For more information, see this document. | stackexchange-math | {
"answer_score": 3,
"question_score": 3,
"tags": "algebra precalculus, polynomials, complex numbers"
} |
Custom clientside regex validation in an html form
I am trying to validate a form input type text. The value should be ending in ".tar.gz" and should have some keywords. Anyways I have the regex ready, but I am stuck on how to validate this without pressing submit. Kind of like how "pattern" attribute works. Any suggestions? this is the row which needs to be validated and the submit button already has a function to disable the button after 1st click. as shown below.
<tr> <td>Suite Name</td> <td><input type='text' name='same' id='sname' title='Default suite name format: autosuite_<signum>_timestamp'/></td> </tr>
<input type='submit' name='launch' id='launch' onclick='setTimeout(disableFunction, 1)' value='Launch'/><br> | You can use the String.search() method like:
var str = document.getElementById("yourinputelementid").value;
var n = str.search("regexpression");
Will return -1 if it doesn't exist or the index of the match if it does exist. If you want to do validation without pressing submit call a method to test string onkeyup event of your input. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, php, jquery, html"
} |
Validate the Authenticity of a User For Site Subscriptions
I have a web application that creates user accounts, but I would also like to have the ability to have users that can sign up for subscriptions without accounts. All they have is a subscription page to modify email settings and enable the newsletter subscription.
My questions is how do I verify that the user is who they say they are without a username/password, and my second is how should they access this page. I dont want just anyone typing in the url with the email and access subscription settings for that user. | For each user entry you create a unique access code that you use in the url in order to validate that this is the user you want. The subscription form will give these options:
* subscribe by filling in your email
* request to change your settings by just putting your email to another field
both action will send an email to you with a special url
* the first to validate that this is made by you so you will enable this user & his email
* the second to send him another special url to make any changes to his settings in the case that this use is active in your database.
For this unique code you can use md5 of his email with a timestamp when he was registered. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, security, authentication, authorization"
} |
Contacts framework does not seem to be available for iPad Swift Playgrounds
I am using the iPad Swift Playgrounds app to learn Swift. I tried to work with the Contacts framework to do things such as add a contact. When I try to import the Contacts framework by using the statement "import Contacts", I am told that the module does not exist. Is there anything I can do to make this framework available?
I searched Google for sample code and the sample code I have found requires this module.
import Contacts
will display:
> No such module 'Contacts' | Unfortunately, not every Apple-provided framework is available in Swift Playgrounds for iPad. Contacts is one of those not included.
To use the framework, you'll need to use Xcode or Swift Playgrounds on a Mac. Although `import Contacts` does work on a Mac, it won't work on an iPad, as it does not include the framework. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, swift"
} |
A labelling of the vertices of the Petersen graph with integers
The vertices of the Petersen graph (or any other simple graph) can be labelled in infinitely many ways with positive integers so that two vertices are joined by an edge if, and only if, the corresponding labels have a common divisor greater than 1. (One such labelling is with the numbers 645, 658, 902, 1085, 1221, 13243, 13949, 14053, 16813, and 17081, whose sum is 79650). Of all such ways of labelling the Petersen graph, what is the minimum the sum of the 10 corresponding integers can be?
!Petersen graph
The reason to single out the Petersen graph over all other graphs of order ten or less is that it is one particularly difficult to label if one is trying to achieve the minimum sum. Is there some systematic why of finding that minimum other than brute force? | The following labelling, whose sum is $37294$, improves Aaron Meyerowitz's by $64$. It was also found by extensive computer search, but with the strategy of assigning and fixing the first five primes (in all possible permutations) to the edges joining the vertices of the exterior and interior pentagons, and then examining the resulting sums of assigning all $10!$ possible permutations of the next ten primes to the remaining $10$ edges.

{
$return_value = {the index array value being passed above};
echo "which portion in the if statement OR was actually passed? and return that value" . $return_value;
}?>`
can we find out exactly which actually value was being passed in the OR if-statement? | In your if-statement, we can not find out which part is true.
Here is something more detail about Short-circuit evaluation | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, if statement, return"
} |
PHP: Find array difference on values
I have two pretty big arrays with email addresses in them.
`$oldmail` and `$newmail`.
Both looks like this:
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
...
I want to find all the email values in `$newmail` that does not exist anywhere in `$oldmail`.
I think this should work:
foreach ($oldmail as $key => $value)
{
foreach ($newmail as $key2 => $value2)
{
if ($value == $value2)
{
//do nothing..
}
else
{
echo $value2;
}
}
}
But it is way to resource heavy with big lists.
Is there another more effecient way I can do this? | PHP code demo
<?php
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");
$result=array_diff($a1,$a2);
print_r($result);
?> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php"
} |
phpThumb plugin and database images' querystrings
i'm new to the phpthumb plugin and searched stackoverflow for similar questions without success
a standard phpthumb request should be like this
<img src="phpthumb/phpThumb.php?src=../RANDOM-IMAGE.gif&w=100&q=100" />
What if my image is coming from a mysql db and its url is a querystring?
<img src=" />')
How can i generate thumbnails with phpthumb plugin with url like these? | I solved this way
$imageTempURL=rawurlencode("
echo('<img src="phpthumb/phpThumb.php?src='.$imageTempURL); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, query string, phpthumb"
} |
How can search in SO with user + tag information?
Let's say I need to search in SO with tag 'sqlite' and user 'prosseek'.
How can I do that in search panel?
I tried 'user:prosseek [tag] sqlite', but I got nothing. | You are close. Since user names aren't unique, you cannot search that way.
Do it like so:
Or, if you are the currently logged user, you can do:
| stackexchange-meta | {
"answer_score": 5,
"question_score": 2,
"tags": "support, search"
} |
Thin client list
Is there a trusted thin client list somewhere?
I searched one for **OSX** and one for **Android** and I found next to nothing. That is: nothing at all for OSX, and only a source-only on github for Android (which I don't know how trustable is anyway).
(I understand "trusted" might mean anything, so let's just keep to " _you_ trust it". That is, list it only if you actually use it at the very least) | Currently, there is one light client that works on a Mac - MultiBit. This client seems to be around for awhile and is open-source, so should be trustworthy.
There a couple wallets working on Android, like Bitcoin Wallet and Bitcoin. Personally, can't say much about trustworthiness of either, asides the fact that some high-reputation people on the forum seem to be promoting it.
Alternatively, you can try using eWallets, as they can be accessed on any device. | stackexchange-bitcoin | {
"answer_score": 4,
"question_score": 4,
"tags": "thin clients"
} |
Octave: How to vectorize a Fourier series function?
Let's say I have a composite signal; with a Fourier analysis I found the coefficients for the cosine (a) and sine (b) terms and I put them in a matrix together with frequencies in Hz. Using a `for` cycle to compute the Fourier series from coefficients and frequencies, I have the expected results.
%Startcode
t = linspace(1,5,100)';
a0 = 0;
a = [1;3;0;0];
b = [0;0;4;2];
w = [1;10;20;30];
C = [a,b,w];
k = length(w);
fs = a0 .* ones(length(t),1);
for j=1:k
fs = fs + C(j,1)*cos(2*pi*C(j,3)*t) + C(j,2)*sin(2*pi*C(j,3)*t);
end
plot(t,fs);
%Endcode
However, I would like to vectorize the code in order to eliminate the `for` cycle. Any suggestions?
UDATE: The code should me modified thus:
t = linspace(1,5,200)';
Because with only 100 intervals aliasing occurs. | You can obtain the result which is within cosines and sines with normal matrix multiplication after transposing `t`. Multiplying it with columns of `C` can be done with implicit expansion (`.*`) and then just `sum` along the rows.
fs = a0 + sum( C(:,1).*cos(2*pi*C(:,3)*t.') + C(:,2).*sin(2*pi*C(:,3)*t.') ); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "vectorization, octave"
} |
Assign the value of a function to a variable
I am trying to assign the result of a MySQL query to a variable so I can send it to a post request.
Here is my code:
// mysqlCRUD.js
buscarUsuario: function(usuario, cb) {
console.log(usuario);
con.query('SELECT * FROM usuarios WHERE nick = ?', usuario, function(err, results) {
return cb(null, results.length);
});
},
//index.js
router.post('/comprobarUsuario', function(req, res, next) {
resultado = mysqlCRUD.buscarUsuario(req.body.nick, function(err, data){
return data;
});
res.send(resultado);
});
The post request comes from a jquery:
$.post('/comprobarUsuario', { nick: nick}, function(data) {
console.log("Respuesta Usuario: " + data);
});
But I don't know why the result never reaches the post request. Could anybody please help me. | From the documentation <
**The body parameter can be a Buffer object, a String, an object, or an Array.**
router.post('/comprobarUsuario', function(req, res, next) {
mysqlCRUD.buscarUsuario(req.body.nick, function(err, data){
return res.send(data.toString());
});
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, mysql, node.js, express"
} |
How to understand this probability density function with continuous random variable
Could anyone help me? I don't want the solution. Instead I'm just looking to understand what this means:
x
2
Is this the Binomial Coefficient? How is this related with PDF?
, but never a blog that deals solely, mostly, or even regularly with GURPS. Are there any (good) ones out there?
Thanks! | This site T Bones Games Diner has a lot of GURPS related articles but as I don't play GURPS I can't comment on it's quality. :) | stackexchange-rpg | {
"answer_score": 10,
"question_score": 21,
"tags": "gurps"
} |
redistribute someone
In the movie _Love Actually_ , the prime minister asks his secretary to redistribute an employee, I think, because he was falling in love with that particular employee, Natalie.
> Redistribute Natalie.
I can guess from the context that he wants her away to stop himself from thinking of her all the time, but I can't be sure because I couldn't find an authentic reference in dictionaries. However, I found a similar question online though the answers were contradictory and the context was not exactly what I described.
Does he mean _give her a difficult task to do (to get her busier)_ , _reassign her_ , _relocate her somewhere (so he can't see her at all)_ or maybe _fire her_? | I found very few examples online where **redistribute** was followed by a person.
> The plans include a complex formula to **redistribute** asylum-seekers around the EU from countries facing a huge influx, as Greece did last year. Economist May 5, 2016
I can understand that in this example it means relocate.
In thefreedictionary.com **reassign** was given as a synonym to redistribute. _Give her a difficult task to do or fire her_ sound the least possible meanings. | stackexchange-ell | {
"answer_score": 2,
"question_score": 2,
"tags": "meaning"
} |
Change Layout Structure in IGraph Plot based on Community
I created an igraph with a community membership identified:
fc <- fastgreedy.community(graph)
colors <- rainbow(max(membership(fc)))
This provided me the clusters that each of the nodes belong to.
Now when I plot this:
plot(graph,vertex.color=colors[membership(fc)],
layout=layout.kamada.kawai)
it doesn't provide a layout where it exclusively separates each group of nodes based on the membership. Does anyone know a different layout that can provide this? All this is doing is taking the layout: kamada.kawai and coloring in the memberships rather than restructuring the layout so that it is organized by membership.
Hope this question makes sense. Thanks! | You have to calculate the Kamada-Kawai layout with an artificial weight vector that assigns a high weight to edges within clusters and a low weight to edges that cross cluster boundaries:
> graph <- grg.game(100, 0.2) # example graph
> cl <- fastgreedy.community(graph)
> weights <- ifelse(crossing(cl, graph), 1, 100)
> layout <- layout_with_kk(graph, weights=weights)
> plot(graph, layout=layout)
The trick here is the `ifelse(crossing(cl, graph), 1, 100)` part -- `crossing(cl, graph)` takes a clustering and the graph that the clustering belongs to, and returns a Boolean vector that defines for each edge whether the edge is crossing cluster boundaries or not. The `ifelse()` call then simply replaces `TRUE` (i.e. edge crossing boundaries) in this vector with 1 and `FALSE` (i.e. edge stays within the cluster) with 0. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "r, layout, cluster analysis, igraph"
} |
Handling GotFocus when using BringIntoView in WPF
I am scrolling to different items in a control, and using .BringIntoView(Rect) rather than .Focus(), so I can buffer the size around the control, so when I focus on something, its not just at the very top or bottom of the main control.
When calling Focus, one can catch GotFocus() to then fire an event when the control has received focus. But this does not fire when using BringIntoView().
I would like to know when a control received focus so I can highlight it to the user so they know where their content went. Is there any way to when control.BringIntoView has completed so I can then do something to notify the user? | That is because BringIntoView does not activate focus on the control.
Simply call the Focus method on your control reference as well as calling BringIntoView.
Hope that helps. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "wpf, focus"
} |
How can I see what the format of my textfile is?
I have a textfile and I want to know whether it is Ascii or UTF-8 or something else. How can I see this? Any tool or website that I can use? | $ file unicode.txt
unicode.txt: UTF-8 Unicode text
I expect the `file` utility is available for Windows as part of CygWin
I'm surprised it isn't included in UnxUtils or GNU CoreUtils for Windows
As Ignacio Vazquez-Abrams suggests, for many files, software tools can only make a guess based on sampling and probabilites. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "windows xp, file format, textfiles"
} |
Unity Движение объекта в противоположную сторону от точки касания на экран
Как в Unity сделать так, чтобы при нажатии на экран, все объекты которые находятся рядом разбегались в разные стороны? | Я так понимаю, вопрос в том, как сделать само движение. Только-что протестировал, всё работает как надо. Сделать проверку, рядом ли с мышью находятся объекты можешь через Physics2D.OverlapCircle. Если тебе какие-то моменты в коде не понятны - не стесняйся задавать вопросы, постараюсь ответить.
using UnityEngine;
public class Cube : MonoBehaviour
{
private Vector2 _direction;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Vector2 diff = transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
_direction = diff.normalized;
}
transform.Translate(_direction * Time.deltaTime);
}
} | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "unity3d, motion"
} |
Changing vertex array object
Lets see this code:
glGenVertexArrays(1, &name);
glBindVertexArray(name);
glBindBuffer(GL_ARRAY_BUFFER, someBuffer1);
glVertexAttribPointer(...);
(...)
glBindBuffer(GL_ARRAY_BUFFER, someBuffer2);
glVertexAttribPointer(...);
(...)
glBindVertexArray(0);
What happens if I decide to do something like this:
glBindVertexArray(name);
glBindBuffer(GL_ARRAY_BUFFER, someBuffer3);
glVertexAttribPointer(...);
(...)
glBindBuffer(GL_ARRAY_BUFFER, someBuffer4);
glVertexAttribPointer(...);
(...)
glBindVertexArray(0);
? Can I change vertex declaration layout this way? Are there ways to do it? | Yes. That's precisely why a simple solution to avoiding VAO's altogether is generating and binding a single one at program start. However, that mitigates any performance benefits you may gain -- switching VAOs is (or should be) faster than redefining the vertex layout. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "opengl"
} |
Is $x_k=\sin(k)$ eventually/periodic?
A sequence is eventually periodic if we can drop a finite number of terms from the beginning and make it periodic.
$$x_k=\sin(k)$$
I think this is periodic since the function is periodic and it seems to converge to 0 by iterations. The thing that confused me is that there are infinite numbers in the domain in the period of $\sin(k)$ since it's continuous. So I can't really assume that if a function is periodic -> sequence is periodic? | If you have $\sin(k+n)=\sin k$, then1 either $n$ or $2k+n$ is an integer multiple of $\pi$. Can this happen for integers $k,n\ge1$? (Knowing that $\pi$ is irrational2 might be useful.)
You should arrive to the conclusion that the sequence is not periodic.
1We know that $\sin x=\sin y$ holds if and only if $x=y+2z\pi$ or $x=\pi-y+2z\pi$ for some $z\in\mathbb Z$.
2 Wikipedia: Proof that $\pi$ is irrational | stackexchange-math | {
"answer_score": 7,
"question_score": 2,
"tags": "sequences and series, analysis, periodic functions, trigonometry"
} |
GoDaddy include_path and auto_prepend_file
I'm working in a GoDaddy shared hosting environment (Linux, PHP 7.1). I want to automatically prepend a file, globally, but I can't seem to get it working with an .htaccess or php.ini file.
I've tried variations on the following to no avail:
## php.ini
include_path = ".:/home/username/public_html"
auto_prepend_file = "./includes/autoload.php"
## .htaccess
php_value include_path ".:/home/username/public_html"
php_value auto_prepend_file "./includes/autoload.php"
What am I doing wrong? | I was able to get this working by using a .user.ini file:
> Since PHP 5.3.0, PHP includes support for configuration INI files on a per-directory basis.
I also found this documentation from GoDaddy useful. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, apache, .htaccess, include path"
} |
Как растянуть aside по высоте родительского блока без js и flex?
Есть примерно такой html:
<div id="wrapper">
<section></section>
<section></section>
<section></section>
...
<aside></aside>
</div>
Высота блоку #wrapper не задана, поскольку она динамически меняется в зависимости от появления и удаления section. Как на чистом css растянуть aside (зафлоачен справа) по всей высоте #wrapper? Чтобы высота aside, соответственно, тоже динамически изменялась. | Вариант с `position: absolute` :
#wrapper {
position: relative;
}
#wrapper__left {
padding-right: 220px;
}
section {
padding: 10px;
background: green;
}
section + section {
margin-top: .5em;
}
aside {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 200px;
background: yellow;
}
<div id="wrapper">
<div id="wrapper__left">
<section>1</section>
<section>2</section>
<section>3</section>
</div>
<aside></aside>
</div> | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "html, css, height"
} |
How to access a database on mySQL on Windows Server 2012
I have no idea how Windows Server works. All I want to do is gain access to a database in mySQL on Windows Server. Is there a phpmyadmin like there is on Cpanel? I have no idea where to go.
It's a Windows Server 2012 that runs Apache and mySQL on which Wordpress is installed.
Someone please help. | Personally, for accessing mysql databases in a windows app, I use HeidiSQL.. But we don't do recommendations for software on SO, so you're free to choose whatever you want and I'm not going to focus on particular software in this answer
To access the mysql instance you'll need to know the username and password of a user with sufficient privileges to do what you want. If you don't know this username/password, a good place to sart looking is in the config files of any apps (like your apache web apps, wordpress etc) that use the db and see if you can read the password out in plain text there.. With luck the person who set all this up will have left behind the username/password in a config file and yu're away. If your question is about how to break into a database where you don't know the password, make an edit so this is more clear | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "mysql, windows, apache, server"
} |
What factors should I be aware of when storing a kayak?
I've seen various images / comments online of how people decide to store their kayaks.
Some people wall mount them, some have a rack, some stack them with padding, some hang them (horizontally / vertically) from walls, some hang them from ceilings or store them upright with padding.
We would ideally like to wall mount ours but currently do not have the space. They are roughly 9ft x 3ft (2.7m by 0.9m) and there are two of them. Storage for buoyancy aids, seats and paddles is all easily sorted.
Is there any way to store kayaks - inside or outside, in a home or garage - which is preferable to their longevity, or something you should particularly avoid when storing them?
**Edit** We are actually going to now build a custom shed for the kayaks and gear :) | I think this site might have the answer for you.
Main points there are:
* **Protect against Hull Damage & Distortion.** Do not let the kayak to bend, distort, and getting damaged.
* **Protect from Harsh Weather, Sun & Other Elements.** The kayak is usually made out of materials which don't resist the sun infinitely, better to protect them from direct sunlight and of course other elements such as wind and storms.
* **Safety For Your Kayaks & Yourself.** Some obvious things, don't let the kayak fall down on your or other's head when you try to detach or attach to the storage.
See more tips on the linked website for choosing the right space and place it contains valuable data on size, spaces between two kayaks etc...
On "hanging or lying" question it says:
> store the kayak on its side; the strongest part of the boat | stackexchange-outdoors | {
"answer_score": 12,
"question_score": 16,
"tags": "gear, boats, kayaks, storage"
} |
Transformer heating
I have difficulty grasping the concept of transformer heating and the overall effect on voltage, current and magnetic induction. I assume that for a transformer to heat up the current should increase as H = I2RT. So the volatge in the secondary coil should drop.
But from what I came across internet it seems that the volatge drop in the secondary coil is not significant when discussing transformer losses. This made me think that perhaps it is due to the load resistance that the heat is produced and thus it should be the current in the which should decrease and voltage increase.
And for the third scenario, if current is decreased then magnetic induction should decrease ( oppose the cause producing it) and voltage should also decrease.
My question is what actually happens to the voltage, current and magnetic induction when a transformer is heated. | When the primary coil of a transformer is heated by ohmic losses in its wire, its DC resistance goes up and so the current flowing through it goes down. This weakens its magnetic field and causes the current induced in the secondary to decrease. When the secondary gets hot because of ohmic heating, its resistance goes up too and the current flowing through it decreases even more. | stackexchange-physics | {
"answer_score": 0,
"question_score": 0,
"tags": "homework and exercises"
} |
How can I change the resolution of a PDF
I have scanned a document into a PDF at 300dpi. The document file is larger than I would like. Is there a simple way to down-sample the document so that it has a lower resolution? Or do I just need to re-scan the original document? | You can use ImageMagick's scale or resize operators.
> ImageMagick® is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.
For example, from a terminal:
convert input.pdf -resize 50% output.pdf
or
convert input.pdf -scale 50% output.pdf | stackexchange-apple | {
"answer_score": 2,
"question_score": 3,
"tags": "pdf"
} |
How to solve this algebraically
This seems like a really stupid question to ask here...
I'm trying to solve $\sqrt{x^2 - 1} + x > 0$.
When I try this happens:
1. $\sqrt{x^2 - 1} > \- x$
2. $x^2 - 1 > x^2$ (squared both sides)
3. $-1 > 0$
However, on Wolfram Alpha, it says that the answer is $x \ge 1$.
It seems to me that basic rules of algebra are simply breaking down here... what am I doing wrong? | You have a first condition to satisfy, that is $$ x^2-1\ge0 $$ so that the square root exists. Thus, from now on, we assume this condition on $x$ holds.
After this preliminary, let's rewrite the inequation as $$ \sqrt{x^2-1}>-x $$ There are two cases:
1. if $-x<0$, the inequality is clearly satisfied, because $\sqrt{x^2-1}\ge0$ by definition;
2. if $-x\ge0$, we _can_ square both sides, because inequalities between positive numbers is preserved squaring or taking the square root.
In case 2 we get the false inequality $-1>0$, so the second case doesn't provide solutions; hence we remain with only the first case, that is, the system \begin{cases} x^2-1\ge0\\\ -x<0 \end{cases} that is satisfied for $x\ge1$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "inequality, radicals"
} |
Name for SELECT * FROM (VALUES (x,y)) AS TableLiteral(Col1, Col2)
The following is valid SQL syntax:
SELECT *
FROM (VALUES ('p','q'),('x','y')) AS TableLiteral(Col1, Col2)
and returns the table:
| Col1 | Col2
----------------
1 | p | q
2 | x | y
This syntax can further be used in CTEs etc.
Is there a name for this? I've been calling them "TableLiterals" by analogy with string literals and regex literals.
Is there a term that will be widely recognised. | It is called: **Table Value Constructor**
> Specifies a set of row value expressions to be constructed into a table. The Transact-SQL table value constructor allows multiple rows of data to be specified in a single DML statement. **The table value constructor can be specified in the VALUES clause of the INSERT statement, in the USING clause of the MERGE statement, and in the definition of a derived table in the FROM clause.**
>
> VALUES ( ) [ ,...n ]
More info about ANSI standard: F641, Row and table constructors.aspx) and select without from | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 8,
"tags": "sql server, tsql, terminology"
} |
I've inherited a PHP project that has a very consistent file naming pattern that I don't understand
Most of the files in the project are essentially pairs of files named:
1. xxxx
2. xxxx.php
inside the xxxx file is a single php statement requiring the same file name but w/ the php extension, e.g.
`<?php require('xxxx.php'); ?>`
What is the rational / programming practice / style / ... for doing this? It's very consistent so I have to believe it is done for a rational reason. | The point of this scheme is to achieve urls that don't end in `.php`. Like this:
instead of
Another way of achieving the same net effect would be to create folders for each path instead of files and have each folder contain one file called `index.php` (or whatever the default name you've configured is). Yet another way would be to use a rewrite rule configured at the web server level. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "php, coding style"
} |
Pronouncing acronyms
I've noticed that some people in my office spell out "data import tool" as **D**. **I**. **T**., whereas others will say " **dit** " (like "ditty"). Is trying to pronounce an acronym as a word, as opposed to spelling it out, ever correct? | All I could find on pronouncing acronyms and initialisms is this list.
The list distinguishes between acronyms and initialisms. Basically, acronyms are abbreviations that are pronounced as a single word and initialisms are an abbreviations, that are pronounced as a series of letters From this wiki article. | stackexchange-english | {
"answer_score": 6,
"question_score": 5,
"tags": "pronunciation, acronyms"
} |
Empty dataframe in pandas
hi i am new in web scraping this code works perfectly but it is printing on the last row into the csv file.I don't know why I printed values also on console and its printing all the rows
import bs4 as bs
import urllib
import pandas as pd
dfs = pd.read_html(' ,header= 0)
for df in dfs:
df.to_csv('losangeles.csv', sep='\t',encoding='utf-8') | There is problem you overwrite file, always write `df` to same `filename`.
Solution is create unique file names, e.g. add count by `enumerate`:
for i, df in enumerate(dfs):
df.to_csv('losangeles_{}.csv'.format(i), sep='\t',encoding='utf-8') | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "python, pandas, web scraping, beautifulsoup"
} |
Replace string by calling method
I have already got this working, but I know there must be a more succinct way of doing it.
Using onBlur on a text field in the html page, it calls a method which replaces the value of the string if the value is empty or NaN.
JS:
function checkStr(str) {
return str.value = "0";
}
HTML:
onblur="if(this.value=='' || isNaN(this.value)){this.value=checkStr(this.value)};"
So this does work, but seems exhaustive. Using:
function checkStr(str) {
if (str.value == "" || isNaN(str.value)) {
return str.value = "0";
}
}
In the JS file, and:
onblur="checkStr(this.value);"
In the HTML doesn't work.
Any ideas? | Your second method isn't assigning anything to textbox value, so you really need the following , i.e. passing in the textbox into the function
onblur="checkStr(this);"
and then for the function to check and assign the textbox
function checkStr(textbox) {
if (textbox.value == "" || isNaN(textbox.value)) {
textbox.value = "0";
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html"
} |
What is the difference between session_unset() and session_destroy() in PHP?
From the php.net documentation:
> **session_destroy** — Destroys all data registered to a session
>
> **session_unset** — Free all session variables
My three part question is:
The two functions seem very similar.
What is really the difference between the two?
Both seem to delete all variables registered to a session. Does any of them actually destroy the session itself? If not, how do you accomplish this (destroy the session itself).
Is it correct that neither of the two functions deletes the session cookie at the client? | **`session_unset`** just clears the `$_SESSION` variable. It’s equivalent to doing:
$_SESSION = array();
So this does only affect the local `$_SESSION` variable instance but not the session data in the session storage.
In contrast to that, **`session_destroy`** destroys the session data that is stored in the session storage (e.g. the session file in the file system).
Everything else remains unchanged. | stackexchange-stackoverflow | {
"answer_score": 151,
"question_score": 94,
"tags": "php, session, session cookies"
} |
Why 'AttributeError' when I am inheriting the base class already?
Sorry I am new to oop.
class A(object):
def __init__(self, idn, name):
self.idn = idn
self.name = name
class B(object):
def __init__(self, idn, acc_no, criminal_case='No'):
self.idn = idn
self.acc_no = acc_no
self.criminal_case = criminal_case
def get_info(self):
return self.idn
class C(A, B):
pass
c = C(1, 'xyz')
print c.get_info()
print c.criminal_case
Traceback (most recent call last):
File "tp.py", line 25, in
print c.criminal_case
AttributeError: 'C' object has no attribute 'criminal_case' | It's almost impossible to use multiple-inheritance without `super()`,so what you need is to use `super()`.
**super()**
> Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
Your code should be like this:
class A(object):
def __init__(self, idn, name):
super(A, self).__init__(idn, name,'test')
self.idn = idn
self.name = name
And you will get the output:
1
test
In Python 3.x you can just use `super().__init__()`,and it seems that you're using Python 2.x,so you need to use `super(A, self).__init__(idn, name)`.
Hope this helps. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "python, python 2.7, oop, inheritance"
} |
basic html css design of a box with image and title
I am not a very good designer. At least not with html and css. I have been using a very simple code like this:
<fieldset style=\"color: #000000; border: 1px solid #000000; width: 225px; text-align: left; padding: 5px;\">
<legend style=\"color: #999999; font-weight: bold;\">Headline.</legend>
<p>text</p>
</fieldset>
To output information in a php online game i am working on. I need something similar, put a little better looking. Can I get some help. I was thinking something like:
<h2 class="entry-title">Example</h2>
<img= examples.jpg" >
<div class="entry-content">
</div>
But im not sure what css code i can write to make a similar effect to the fieldset/legend that im currently using. I need a box with a title, an image on the left side and tekst on the right side of the image. | You could try use the div block below.
<div class="fieldset">
<h2 class="entry-title">Example</h2>
<img= examples.jpg" >
<div class="entry-content">
</div>
</div>
As styling, first give a border to your fieldset div. Then, you could just position the h2 tag relatively to your fieldset div playing top and left values. and be sure that your body background, filedset div's background and h2 tag's background is the same. Finally float both div entry-content and the image to left.
With a little tweaking you should get a similar looking of tag. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "html, css, fieldset, legend"
} |
Old black and white movie where there was a giant clock on an alien planet that regulated universal time
I saw an old black and white space movie in 1968, where at the end the spacemen had to travel to an alien planet and re-start a giant clock which controlled universal time. | There is a possibility that you saw _The Wizard of Mars_ (1965). It was in color, but you might have seen it on a black and white TV. In the remote future year 1974, a spaceship crashes on Mars and the crew find a Martian city frozen in time and are given the task of restarting a clock to unfreeze the city.
<
<
| stackexchange-scifi | {
"answer_score": 2,
"question_score": 2,
"tags": "story identification"
} |
Manual Fulltext index population time in SQL Server 2012
I would like to know if there is a way to see how much time did it take SQL Server 2012 to index all the data in a table?
In my example I create the table, create the index and set the population to be manual. Then I execute
ALTER FULLTEXT INDEX ON table_name START UPDATE POPULATION;
The query executes immediately but as I know, the population process is actually performed in the background. How can I find out what's the total time it took to index the whole table? | The `sys.fulltext_indexes` system table contains the start/end time of the current or last population (crawl).
SELECT crawl_start_date, crawl_end_date
FROM sys.fulltext_indexes | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "sql, sql server, sql server 2012, full text search, full text indexing"
} |
why we can't assign a string value to 2d char array?
#include<stdio.h>
int main()
{
char a[3][5];
int i;
a[0][5]="hai";
a[1][5]="cool";
a[2][5]="many";
for(i=0;i<3;i++)
printf("%s \n",a[i]);
return 0;
}
Why we cant assign string value like this but it can be assigned using string function? | Another option for read only access (if you don't modify the string literal) is an array of pointers:
char *a[3]; /* Or better yet: const char *a[3]; */
a[0]="hai";
a[1]="cool";
a[2]="many"; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "c, arrays, string, multidimensional array"
} |
How to perform multiplication in django model?
This is my model:
class Purchase(models.Model):
Quantity = models.PositiveIntegerField()
rate = models.DecimalField(max_digits=5,decimal_places=2)
Amount = models.DecimalField(max_digits=5,decimal_places=2)
I want to perform multiplication between Quantity and rate and store the result in Amount...
So I have done something like this:
from django.db.models import F
@receiver(pre_save, sender=Purchase)
def update_amount(sender,instance,*args,**kwargs):
totalamount = Purchase.objects.get(F('rate') * F('Quantity'))
instance.Amount = totalamount
But its giving me this error:
'CombinedExpression' object is not iterable
Do anyone have any idea how to do this??? | But here you already _have_ the instance, so the `totalamount` is simply:
@receiver(pre_save, sender=Purchase)
def update_amount(sender, **instance** , *args, **kwargs):
instance.Amount = **instance.rate * instance.Quantity**
That being said, if the `Amount` is _always_ the `rate` multiplied with the `Quantity`, it is better to define a `@property`, since then you avoid data duplication, like:
class Purchase(models.Model):
Quantity = models.PositiveIntegerField()
rate = models.DecimalField(max_digits=5,decimal_places=2)
def amount(self):
return self.Quantity * self.rate | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "django, django models"
} |
Control the verbosity of Flask's tests
I'm running tests for my Flask app from Bash using `python manage.py test`. In addition to failures and errors, the console prints out
test_name (test_file.TestClass) ... ok
for every single test. That's super annoying when you have a lot of tests. How can I control the verbosity of the printout? | @jonrsharpe was right. I didn't realize that the project was using Flask-Script, which I guess is the reason for the manage.py file. Flask-Script calls unittest with a default verbosity. I reduced the default verbosity and that culled the extra output. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, flask"
} |
Copy a row or column of a matrix and insert it in the next row/column
I was wondering if there is an easy way in MATLAB to do the following operation: I'd like to copy a row or column of a matrix and insert it in the next row/column.
For example: given a 3x3 matrix
1 2 3
4 5 6
7 8 9
I'd like to copy the first row and insert it as a second row:
1 2 3
1 2 3
4 5 6
7 8 9
Can someone advise how I could accomplish this in MATLAB? Thanks! | You can simply repeat the indices of the rows you'd like to repeat
A = A([1 1 2 3],:) | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 8,
"tags": "matlab, matrix, copy"
} |
How to position a "right-aligned" text also in the center without relative position?
This is what I would like to achieve, a formula that is right-aligned, but at the same time positioned at the center of the page, without any relative position but just automatically right and center aligned... is this possible? With relative positions I can, of course, position it wherever I want /(e_1-e_2)\; mod\; q&\\
=((se_1+r)-(se_2+r))/(e_1-e_2)\; mod\; q&\\
=s(e_1-e_2)/(e_1-e_2)\; mod\; q&\\
=s&\\
\end{align*}
\lipsum[2]
\end{document} | stackexchange-tex | {
"answer_score": 3,
"question_score": 1,
"tags": "equations, positioning, alignment"
} |
How to handle PassportJS endpoint errors
If I visit the Facebook callback link at `
with a bogus code: `FacebookTokenError: Invalid verification code format.`
with the same code (replay attack): `FacebookTokenError: This authorization code has been used.`
with an expired code: `FacebookTokenError: This authorization code has expired.`
All of these errors are irrelevant to the client. I would like to simply retry the login process (redirect to Facebook again for authentication).
Express().get('/login', Passport().authenticate('facebook', {
failureRedirect: '/',
}), function(req, res) {
});
However, upon error of those three described above, the server simply throws an error and emits to the client.
Is there an error callback for endpoint errors available? | Here's what I'm using:
// Google OAUTH sendoff
app.get('/auth/google',
passport.authenticate('google')
);
// Google OAUTH return
app.get('/auth/google/return', function(req, res, next) {
passport.authenticate('google', function(err, user, email) {
if (err) { return next(err); }
// OAUTH success, but user isn't authorized
if (!user && email) {
return res.redirect('/myNotAuthorizedUrl');
// OAUTH error
} else if (!user) {
return res.redirect('/login/');
// user disabled or some other check
} else if (user.get('is_blacklisted') !== 1) {
return res.redirect('/youAreEvil');
}
// success and authorized
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/home');
});
})(req, res, next);
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "node.js, express, passport.js"
} |
Working out which folders are svn'd from the command line
I've got a folder that containes a set of folders that are themselves the root of different projects. Some of these projects are versioned under svn, some are not. I'm looking for a one-liner I can type on the command line to give me a list of those projects that arn't versioned… any ideas? | I use 'svn info' to check if a sub directory is under version control. If the tested directory is not a working copy 'svn info' will return with error.
You can redirect output to hide the output of 'svn info'.
I will go on something like the following for iterating directories and if 'svn info' returns with error echo their name.
for D in */; do svn info ${D} &>/dev/null; if [ $? -ne 0 ]; then echo ${D}; fi done
I don't know if you can call it a one-liner but it'll do the work.
Also note that this does not include hidden directories. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 1,
"tags": "svn"
} |
Using the style of the inherited control
My first firemonkey component is inherited from a TSpinBox but I cannot figure out how to get it to use the same style as the base component. At design time in my app I can set the StyleLookup to "spinboxstyle" and get the correct style but if I try to do that in the constructor for the new component it ignores it. What is the correct procedure for this? | The constructor is the correct place.
You have to use FStyleLookup := 'spinboxstyle'; (Note the F)
Not StyleLookup := 'spinboxstyle'; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "delphi, delphi xe2, firemonkey"
} |
set date error on uidatepicker
I've been stumped by the code below. I pass a string date to a UIDatePicker which seems to work on most devices, yet on some, it crashes the app.
here's the code
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"HH:mm"];
NSDate *date = [dateFormat dateFromString:dateStr];
[timePicker setDate:date];
[dateFormat release];
I have a function which passes the "dateStr" variable, as follows, `dateStr = @"0:0";` I cannot see what's wrong - as it works for me! (iphone 3.1.3) but it doesnt work for my tester (ipod touch 3.1.3)
Can anyone see anything wrong with the code?
Thanks v much. any ideas? | Probably locale problem.
Try to set a common locale for the date formatter e.g.
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormat setLocale:usLocale];
[usLocale release]; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "iphone, uidatepicker"
} |
How to take an element inside an url
I have an url rewrited like this : <
I would know if I can take an element inside because `var_dump($_GET['language'])` return nothing.
the original url is < (original). In this case `$_GET['language']` works fine.
I need the element : fr when it's rewrited to identified the good language.
thank you. | * You should get request URI with **`$_SERVER["REQUEST_URI"]`** and parse it.
# Here is simple example which might help you get the idea for achieving your goal:
$temp = explode(".php", $_SERVER["REQUEST_URI"]);
// $temp[1] -> /language/fr
$url = explode("/", substr($temp[1], 1));
// $url[0] -> language , $url[1] -> fr
echo $url[1]; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "php, url rewriting"
} |
There is a way to avoid to download Spa Bundle every request in a PWA
So I've a full CRM aplication made in Vue.js the bundle is about 3mb size, now I'm working in PWA features and I want to know if is possible to avoid user browser to download the app even if the user is online, loading it from cache like the way it works when it is offline. Something like:
1 - User enter in aplication:
2 - Service works check if it has cached and is in the last version.
3 - If aplication is cached and updated it loads the cache storage, else request a new bundle.js | Yes. What you describe is possible.
You're describing what is called a CacheFirst strategy. SW goes to network only when the asset is not found from its caches.
Take a look at the Workbox docs here < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "single page application, service worker, progressive web apps"
} |
Problem on logarithm
$$\mbox{If}\ \log_{2a}\left(a\right) = x,\ \log_{3a}\left(2a\right) = y,\ \log_{4a}\left(3a\right) = z.\quad \mbox{Then, what is the value of}\ xyz-2yz\,?. $$ Not exactly able to solve it any further. | **Hint**. One may write $$ x=\log_{2a}a=\frac{\log(a)}{\log(2a)},\quad y=\log_{3a}(2a)=\frac{\log(2a)}{\log(3a)},\quad z=\log_{4a}(3a)=\frac{\log(3a)}{\log(4a)} $$ giving $$ xyz-2yz=\frac{\log(a)}{\log(2a)}\cdot\frac{\log(2a)}{\log(3a)}\cdot\frac{\log(3a)}{\log(4a)}-2\cdot\frac{\log(2a)}{\log(3a)}\cdot\frac{\log(3a)}{\log(4a)} $$ that is
> $$ xyz-2yz=\frac{\log(a)}{\log(4a)}-\frac{2 \cdot \log(2a)}{\log(4a)}. $$
Can you take it from here? | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "logarithms"
} |
Use TFS 2010 for VS2005 version control w/o TS2005?
My team is moving to TFS 2010, but all of our old projects are from our stand alone VS 2005 and VS 2008. We did not have Team Server. Can put our projects under source control in TFS 2010 without upgrading and migrating them? | If you don't want your VS 2005/2008 projects upgraded (most likely VS 2010 will only touch the solution file), then you can install
this for VS 2005 (allows you to connect to TFS 2010 from VS 2005) <
this for VS 2008 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "version control, visual studio 2005"
} |
undefined is not a function evaluating react create class
I have started learning react-native and When i am following different tutorials on net, some are using Ecma6 and other are without it. Most of the places I have read that we have a choice to use either of the syntax. But when I try to create app without ECMA6 it always gives me this error
undefined is not a function evaluating react create class
This is my code :
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
TextInput,
View,
Image,
ListView
} = React;
var MyApp = React.createClass({
......
});
AppRegistry.registerComponent('MyApp', () => MyApp);
Am I missing something or is it not possible to use code without ECMA6 in new version of react native I am using version 0.27 | importing React from react and other component from react-native fixed the issue
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
View,
Image,
ListView
} from 'react-native'; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android, react native"
} |
How do I get comment form?
In Drupal 7, comment form can be rendered using the following code.
drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));
How can I achieve the same in Drupal 8? | See <
You create a comment entity and then get its form.
<?php
$values = array(
'entity_type' => $commented_entity_type_id,
'entity_id' => $commented_entity_id,
'field_name' => $field_name,
'comment_type' => $comment_type_id,
'pid' => NULL,
);
$comment = \Drupal::entityTypeManager()->getStorage('comment')->create($values);
$form = \Drupal::service('entity.form_builder')->getForm($comment); | stackexchange-drupal | {
"answer_score": 7,
"question_score": 3,
"tags": "forms, comments"
} |
Java Compilation date, like C __DATE__
I need to automate getting the compilation date in a specific format into one Java Source file, like the C compilers **DATE** define, How? | The standard Java compiler has no way of doing this (I don't think C compilers do either - I'm guessing that it is the pre-processor that gives DATE, FILE etc)
You'll have to write a source file with the date as a string into it - look at ant's copy task with a filter
<copy file="pre-src/Version.java" toFile="src/Version.java">
<filterset>
<filter token="DATE" value="${TODAY}"/>
</filterset>
</copy>
then in your source
public class Version {
public static final String date = "@DATE@";
}
To get the date in various formats into the ant property TODAY look at the Tstamp task. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 2,
"tags": "java, compiler construction"
} |
Tem como pegar a porcentagem do desvio padrão (R)?
Por exemplo..
Tenho uma série de valores (preços) relacionados a um produto em várias datas diferentes.
Preciso pegar a porcentagem de alteração desse valor.
Atualmente, os preços estão dando um desvio padrão de 120,00,só que eu queria esse resultado em porcentagem. Tipo, os preços variaram em 20% nesses dias específicos.
Como fazer isso no R? | Se pretende saber o desvio padrão relativo à média, isso é o coeficiente de variação. Para ter em porcentagem basta multiplicar por cem.
Programar o CV em R é um problema muito fácil de resolver.
coefVar <- function(x, na.rm = FALSE){
sd(x, na.rm = na.rm)/mean(x, na.rm = na.rm)
}
set.seed(9580) # Torna os resultados reprodutíveis
x <- runif(100, 0, 20)
coefVar(x)
#[1] 0.621354
coefVar(x)*100 # Em porcentagem
#[1] 62.1354
Tendo em conta o comentário sobre o resultado de um cálculo da função, isto é o que me dá:
y <- c(772.8, 147.28, 993.72)
coefVar(y)*100
#[1] 68.82238
Parece estar certo. | stackexchange-pt_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r"
} |
for attribute - standards wise
How this code should be (asp.net standard)?
<label for="jobno">Job#</label>
<input id="TextBox_JobID" name="jobno" runat="server"/>
<input type="button" value="Show Job" class="fbutt"
id="Button_showJob" onserverclick="Button_showJob_ServerClick"
runat="server" />
</p>
<p>
<asp:Label ID="Label_error" runat="server" class="error"></asp:Label></p>
I think the for attribute is not ok, or not written in correct way? | It should probably read
<label for="TextBox_JobID">Job#</label> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, standards"
} |
What is the maximum size of a Litedb database and how to claim unused space?
The limit size of all database and not only collections, and how claim unused space of delete data?
Update: The question is about LITEDB and no SQLITE, some people don't even ready what is about. | Read the fine manual \- it says theoretically UInt.Max * page size (4096) = 16TB for version 4.x
Apparently, for 5.x, PageSize is 8196. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "c#, database, litedb"
} |
Convergence in Distribution with Piecewise Function
Let $X_i$ be a sequence of independent and identically distributed random variables with $\mathbb{E}(X_i) = \mu$ and var($X_i$) $= 1$ for all $i$. Define $S_n = \frac{1}{n}\sum_{i-1}^n X_i$ and
$$ g(x) = \begin{cases} x & \text{if } x < 1 \\\ 2x-1 & \text{if } x \geq 1 \end{cases} $$
Does $\sqrt{n}(g(S_n)-g(\mu))$ converge to anything when $\mu=1$?
I know that for $\mu \neq 1$, I can apply the delta method and obtain convergence in distribution. When $\mu = 1$ it seems like it converges to a "piecewise" distribution. Is there anything to this? | Let $\\{X_n\\}$ be i.i.d. positive random variables with mean 1 and variance 1. (For example, they can have exponential distribution with parameter 1). By strong law $S_N \to \infty$ almost surely. This implies $g(S_n) \to \infty$ almost surely and $\sqrt {n} (g(S_n)-1) \to \infty$ almost surely. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "probability distributions, probability limit theorems"
} |
@Nullable annotation usage
I saw some method in java declared as:
void foo(@Nullable Object obj)
{ ... }
What's the meaning of `@Nullable` here? Does it mean the input could be `null`?
Without the annotation, the input can still be null, so I guess that's not just it? | It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning. | stackexchange-stackoverflow | {
"answer_score": 441,
"question_score": 424,
"tags": "java, annotations"
} |
Proving $X^4 - 14X^2 + 9$ is irreducible
I have to prove that $X^4 - 14X^2 + 9$ is the minimal polynomial of $\sqrt{2} + \sqrt{5}$ over $\mathbb{Q}$, and to do so I have to prove that it is irreducible over $\mathbb{Q}$. The only tools I have are Einstein's criterion, the mod-$p$ test, and the fact that translations of a polynomial maintain reducibility.
We can't apply Einstein's criterion since the constant term is $9 = 3^2$, and $3$ doesn't divide $14$. Neither the mod-2 nor the mod-7 tests work: in mod-2, $X^4 + 1$ decomposes as $(X^2 + 1)^2$, and in mod-7, $X^4 + 2$ decomposes as $(X^2 + X + 4)(X^2 +6X +4)$.
I could use Perron's irreducibility criterion, however I'm not allowed to use this result. | Let $d = [\mathbb{Q}(\sqrt{2} + \sqrt{5}) : \mathbb{Q}]$.
The fact that $\sqrt{2} + \sqrt{5}$ is a root of $X^4 - 14X^2 + 9$ implies that $d \leq 4$.
But one also has $d=[\mathbb{Q}(\sqrt{2} + \sqrt{5}) : \mathbb{Q}(\sqrt{2})] \times [\mathbb{Q}(\sqrt{2}) : \mathbb{Q}] = 2 \times [\mathbb{Q}(\sqrt{2} + \sqrt{5}) : \mathbb{Q}(\sqrt{2})] $, and because $ [\mathbb{Q}(\sqrt{2} + \sqrt{5}) : \mathbb{Q}(\sqrt{2})] \geq 2$, you get that $d \geq 4$.
So $d=4$, so $X^4 - 14X^2 + 9$ is the minimal polynomial of $\sqrt{2} + \sqrt{5}$. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "polynomials, irreducible polynomials"
} |
Janusgraph how to deal with the global_offline misconfiguration
when i tired to remove an index, I typed wrong **GLOBAL_OFFLINE** setting in **userConfig** in the **ManagementSystem** , which I mistake typed the "index.search.backend" with a directory string ......
when i try to open this janusgraph, the print out as below :
WARN org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration
Local setting index.search.backend=lucene (Type: GLOBAL_OFFLINE) is overridden by globally managed value (/data/lucene). Use the ManagementSystem interface instead of the local configuration to control this setting.
INFO org.janusgraph.diskstorage.Backend - Configuring index [search]
Could not find implementation class: /data/lucene
I wonder whether i could **not drop this table** at the backend and fix this problem ! **many thx !** | I think i have fix this problem !
I just use the **KCVS** backend , and find out the source code of **GraphDatabaseConfiguration** ;
I tried and get the KCVSConfig use the code following :
PropertiesConfiguration configuration = new PropertiesConfiguration(GRAPH_PROPERTIES);
ReadConfiguration localConfig = new CommonsConfiguration(configuration);
BasicConfiguration localBasicConfiguration = new BasicConfiguration(ROOT_NS,localConfig, BasicConfiguration.Restriction.NONE);
KeyColumnValueStoreManager storeManager = Backend.getStorageManager(localBasicConfiguration);
KCVSConfiguration KCVSConfig =Backend.getStandaloneGlobalConfiguration(storeManager,localBasicConfiguration);
Just using the **KCVSConfiguration** to remove all the index configuration ! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "graph databases, tinkerpop3, janusgraph"
} |
Joining Lists of Lists of Strings
I've a list of lists, in which each element is a single character:
ngrams = [['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'],
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']]
From this, I want to generate a new single list with the content `['aa','ab','ac','ba','bb','bc','ca','cb','cc']`. The individual elements of each list are appended to each other but in reverse order of the lists. I've come up with this (where `np = 2`):
for cnt in range(np-2,-1,-1):
thisngrams[-1] = [a+b for (a,b) in zip(thisngrams[-1],thisngrams[cnt])]
My solution needs to handle `np` higher than just 2. I expect this is O(np), which isn't bad. Can someone suggest a more efficient and pythonic way to do what I want (or is this a good pythonic approach)? | You can try this:
ngrams = [['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'],
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']]
new = map(''.join, zip(*ngrams))
Output:
['aa', 'ba', 'ca', 'ab', 'bb', 'cb', 'ac', 'bc', 'cc']
For more than two elements:
n = [["a", "b", "c"], ["a", "c", "d"], ["e", "f", "g"]]
new = map(''.join, zip(* reversed(ngrams)))
#in Python3
#new = list(map(''.join, zip(* reversed(ngrams))))
Output:
['eaa', 'fcb', 'gdc'] | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "python, list"
} |
How do I print a Single item on a Array List
So I want to system print one of the names on my array list I was thinking it's like System.out.print(Names[1]) for the second item on my array list?
System.out.println("How Many Employees On your Payroll");
Employees = reader.nextDouble();
ArrayList Names = new ArrayList();
for (int i=1;i<=Employees;i++)
{
System.out.println("What is the name for Employee #"+i+"");
String userName = userInputScanner.nextLine();
Names.add(userName);
}
System.out.println("Do these Names Seem Correct?: " + Names); | First of all try to obey Java code conventions: <
And to get the second element of the list use
names.get(1);
Where `names` is your list. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "java, arrays, system.out"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.