text
stringlengths 175
47.7k
| meta
dict |
---|---|
Q:
How would you do multiple operations on a java 8 stream?
You have a list of a pojo you want to convert to a JSONObject for instance. You have a list of pojo. But in order to convert to a JSONObject you need to use the JSONObject put method.
JSONObject personJson = new JSONObject();
for(Person person : personList){
personJson.put("firstName", person.firstName);
personJson.put("lastName", person.lastname);
...
}
If it were just one operation I wanted to do, then I could do
personList.stream.map(personJson.put("firstName", person.firstName));
A:
JSONArray array=new JSONArray();
personList.stream().forEach(element ->
{
JSONObject personJson = new JSONObject();
personJson.put("firstName", element.firstName);
personJson.put("lastName", element.lastname);
array.add(personJson);
});
A:
The solutions mentioned here are working but they are mutating objects outside the streams context, which should be avoided.
So instead of using .forEach() which is a terminating operation returning void. The correct approach would be to use .map() which, like the name says, maps one value to another. In your case the first operation you want to do is to map a Person to a JSONObject. The second operation is a reducer function where you want to reduce all JSONObjects to one JSONArray object.
public JSONArray mapListToJsonArray(List<Person> persons) {
List<JSONObject> jsonObjects = persons
.stream()
.map(person -> {
JSONObject json = new JSONObject();
json.put("firstName", person.getFirstName());
json.put("lastName", person.getLastName());
return json;
})
.collect(Collectors.toList());
return new JSONArray(jsonObjects);
}
Unfortunately the json.org implementation of JSONArray does not have a way to easily merge two arrays. So I instead of reducing to a JSONArray, I first collected all JSONObjects as a List and created a JSONArray from that.
The solution looks even nicer if you replace the lambda expression with a method reference.
public JSONArray mapListToJsonArray(List<Person> persons) {
List<JSONObject> jsonObjects = persons
.stream()
.map(this::mapPersonToJsonObject)
.collect(Collectors.toList());
return new JSONArray(jsonObjects);
}
public JSONObject mapPersonToJsonObject(Person person) {
JSONObject json = new JSONObject();
json.put("firstName", person.getFirstName());
json.put("lastName", person.getLastName());
return json;
}
A:
personList.forEach(person ->
{
personJson.put("firstName",person.firstName);
personJson.put("lastName", person.lastName);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Initialization Pattern?
Say I have class A:
public class A
{
private B _b;
public class A(B b)
{
Assert.That(b != null);
_b = b;
}
}
And object b needs some complex initialization, like:
b.Prop1 = ...
b.Prop2 = ...
b.Prop3 = ...
int answerToSomeComplexFormula = PerformComplexFormula();
b.Prop4 = answerToSomeCopmlexFormula
etc...
I do not want to perform this initialization in the constructor. Is there a name for some pattern that describes returning an object that has complex initialization? Something like:
public class BInitializer
{
public B Create()
{
B b = new B();
// set up properties
return b;
}
}
BInitializer initializer = new BInitializer();
B b = initializer.Create();
A a = new A(b)
Thanks!
A:
Your solution with BInitializer is very good and it is called Factory Method design pattern.
Here you can find some common creational design patterns: https://sourcemaking.com/design_patterns/creational_patterns
| {
"pile_set_name": "StackExchange"
} |
Q:
How should I get rid of TFS Branches properly?
I am wondering how I should properly get rid of branches that no longer have any purpose. Right now even if i delete them and commit they are still listed as branches in the properties windows for a particular branching root (directory). If I select merge I don't get an option to merge to the deleted branch which obviously is as expected but therefore I am puzzled about the branch still showing up in the properties window.
Any explanation on this behavior would be greatly appreciated.
A:
I had a situation where a branch had been deleted and there was no purpose for it to stick around. I couldn't get tf destroy to work until I found out the deletion number of the directory like Damien mentioned. I couldn't get that ID with tf properties since there was no local copy and no server copy based on the error messages.
I was able to get the full TFS path by using:
tf dir $/MyPathTo/TheParent/Directory /deleted
Then I found the postfixed ";Ident" to the directory and could issue:
tf destroy $/MyPathTo/TheParent/Directory/TheDirectoryToGetRidOff;Ident
Damien your answer helped me out - thanks. I thought I'd include the syntax that got me through it to go along with your post.
A:
The deleted branch is only marked as deleted at a moment in time and it's possible to still get to the code if you sync to a changeset or time before that delete operation.
If you do not want to have the file in the branch in the database at all you can use the tf destroy command line:
http://msdn.microsoft.com/en-us/library/bb386005.aspx
As your branch is already deleted you'll need to use tf dir /deleted to find the deletion number of that branch in order to destroy the files.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fix Permission denied (publickey,password) in gitlab Ci/CD?
I have below simple script in .gitlab-cl.yml file:
build_deploy_stage:
stage: build
environment: Staging
only:
- master
script:
- mkdir -p ~/.ssh
- echo "$PRIVATE_KEY" >> ~/.ssh/id_dsa
- cat ~/.ssh/id_dsa
- chmod 600 ~/.ssh/id_dsa
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
- cat ~/.ssh/config
- scp myfile.js [email protected]:~
But I get this error when job is run, executing the last line (scp command):
Warning: Permanently added 'example.com' (ECDSA) to the list of known hosts.
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
I spent whole day but could not fix it. I verified that $PRIVATE_KEY exists. I generated key pair while logged into example.com copying the generated private to PRIVATE_KEY variable on gitlab.
How to fix this problem?
Note that it is dsa key.
A:
Check your permission for ~/.ssh (700) and all the files in them (600)
Your config file, for instance, might have default permissions that are too large.
If you can, activate a debug session in the sshd of the remote server: you will see if an dsa key is accepted (for recent version of sshd, that might be restricted). rsa would be better.
As seen here, OpenSSH 7.0 and higher no longer accept DSA keys by default.
The OP ace confirms in the comments:
I fixed the problem when I regenerated tsa key pairs instead of dsa keys
| {
"pile_set_name": "StackExchange"
} |
Q:
Framework7 dynamic AJAX loaded pages not working
I am building a framework7 app and since lots of editing has been done to one page, the AJAX loaded in pages have stopped working. I have a feeling this is to do with the structure as I ran into this problem once before, but I need someone with more experience or a better brain to help me solve this.
The problem is with the links at the end of the code that link to the chat.html page. They just do not work.
Thanks
A:
After trial and error I found that enabling inline pages fixed my problem even though the pages I am loading in are not inline.
var mainView = myApp.addView('.view-main', {
domCache: true //enable inline pages
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Display solution/file path in the Visual Studio IDE
I frequently work with multiple instances of Visual Studio, often working on different branches of the same solution.
Visual C++ 6.0 used to display the full path of the current source file in its title bar, but Visual Studio 2005 doesn't appear to do this. This makes it slightly more awkward than it should be to work out which branch of the solution I'm currently looking at (the quickest way I know of is to hover over a tab so you get the source file's path as a tooltip).
Is there a way to get the full solution or file path into the title bar, or at least somewhere that's always visible, so I can quickly tell which branch is loaded into each instance?
A:
This is a extension available in the online gallery specifically tailored for this job. Checkout Labs > Visual Studio Extension: Customize Visual Studio Window Title.
A:
There is not a native way to do it, but you can achieve it with a macro. The details are described here in full: How To Show Full File Path (or Anything Else) in VS 2005 Title Bar
You just have to add a little Visual Basic macro to the EvironmentEvents macro section and restart Visual Studio.
Note: The path will not show up when you first load Visual Studio, but it will whenever you change which file you are viewing. There is probably a way to fix this, but it doesn't seem like a big deal.
A:
Check out the latest release of VSCommands 2010 Lite. It introduced a feature called Friendly Solution Name where you can set it to display the solution file path (or any part of it) in Visual Studio's main window title.
More details: http://vscommands.com/releasenotes/3.6.8.0 and http://vscommands.com/releasenotes/3.6.9.0
| {
"pile_set_name": "StackExchange"
} |
Q:
Usage of "call" when arranging a phone call
Imagine I'm one the phone with somebody and want to postpone the call. I know i can say
I'll call you tomorrow
or
Call me tomorrow
But what if I don't want to specify who is calling who? Can I use "call" too? Like
Let's call tomorrow
What would be the common term to express something like this?
A:
You can say "Let's have a call tomorrow" or "Let's call each other tomorrow".
Note that "have a call" has a slight sense of this being a business call. If you want to be less formal, you might use "let's talk tomorrow" instead.
A:
Why would you EVER want to not specify who is making the call? If you don't specify, then in all likelihood, you are going to wait for them to call and they are going to wait for you to call, meaning the call will never happen. I suggest, instead, ask this;
We should talk about this tomorrow, what would be a good time for me to call?
| {
"pile_set_name": "StackExchange"
} |
Q:
Can i get the generic type of an object?
this is my method: GetListItemsPainted<T>(List<T> list)
and i don't know what type is that list of,
how can i create new list that would have the passed list type?
something like this:
List<list.GetType()> newList = new List<list.GetType()>();
how can i cast my list to the real type so i would have all his properties etc.?
thanks
A:
You can create a list using T:
List<T> newList = new List<T>();
If you must get the type, you can use typeof. This is similar to what you asked for, but has other uses, you don't need it to make generics work:
Type myType = typeof(T);
A:
You do not have to create a new List, you already have one.
If you require a specific type, then constrain your generic type parameters with a where constraint
If you intend to react to a wide variety of arbitrary types, which is a bad design decision in my opinion, then you will need to use a conditional with .Cast<T>()
something like:
Type myListType = list.GetType().GetGenericArguments()[0];
// or Type myListType = typeof(T); as stated by Kobi
if(myListType == typeof(SomeArbitraryType))
{
var typedList = list.Cast<SomeArbitraryType>();
// do something interesting with your new typed list.
}
But again, I would consider using a constraint.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parallellizable Algorithms to traverse a 2D matrix being aware of both col/row-wise neighborhood
I have a fairly large N*N integer matrix Matrix2D (assume sufficient memory),
1, within each row/column, I need to record the col/row index of an element if it's value is different than it's right/lower neighbour.
2, I want to find an optimal algorithms that is parallellizable, ideally by OMP.
So, finally I will have some data structures like,
std::vector<std::vector<int>> RowWiseDiscontinuity(N);// N= #of rows
std::vector<std::vector<int>> ColWiseDiscontinuity(N);// N= #of cols
where inner std::vector<int> records the row/col indices.
I put my serial version here but find it difficult to be OMP parallelized... Someone could provide some idea how to implement the traversing over this 2D matrix with omp?
code snippet,
std::vector<std::vector<int>> RowWiseDiscontinuity(N);// N= #of rows
std::vector<std::vector<int>> ColWiseDiscontinuity(N);// N= #of cols
std::vector<int> TempX1;
std::vector<int> TempX2;
for (int y=0; y<N; ++y)
{
TempX1.clear();
for (int x =0; x<N; ++x)
{
int value = Matrix2D(x,y);
TempX1.push_back(value);
}
auto iter1 = TempX1.begin();
auto iter2 = TempX2.begin();
if (y>0)
for (int x =0; x<N; ++x)
{
if (*iter1 !=*(iter1+1))
{
RowWiseDiscontinuity[y].push_back(x); //Critical for OMP
}
++iter1;
++iter2;
if (*iter1 != *iter2)
{
ColWiseDiscontinuity[x].push_back(y); //Critical for OMP
}
}
TempX2.swap(TempX1); // proceed to next row, remember previous
}
A:
I would create another array that holds the nearest neighbor both column and row-wise. This would have to be done as a first pass, obviously. I recommend creating a 2d array of pairs (pair) that holds the indices you want. Instead of two vectors, I would do a vector of pairs. Pairs are parallellizable and easily sorted.
vector<vector<pair<int, int>>> elements(N);
| {
"pile_set_name": "StackExchange"
} |
Q:
How should I proceed after hours of not finding balance in this design?
Problem / Question:
I designed a logo for a little project I just began contributing on, but there's a problem:
The F was unbalanced, meaning there was no way I could use this logo on rectangular button or shape. Ultimately the balance makes it a poorly designed logo.
I've been working for hours to balance this thing, but I simply cannot figure out how to create an "F" that is balanced with the "I" & "X" using the style shown here (this is horrid):
Is there any way that I can achieve symmetric balance with the letter F in this style?
How should I proceed after hours of not finding balance in this design?
Result after building upon advice here:
Note: I'm still not liking the balance / shape that I've achieved. I'll keep trying.
Thanks to everyone who helped here, and feel free to chime in in the future with advice that might help others with this kind of problem.
This is posted as an answer, but just to make sure everyone sees it:
I think the lesson I learned from this may benefit others in the future:
When it just isn't working, try re-thinking your design.
Sometimes it's good to just play it simple. Although the simplest solutions can often be the hardest to reach:
While this isn't related to the question directly, it's indirectly important: I kept working a design that didn't seem to want to be what I needed.
In the end the answer was to revisit my objective and ask: Am I trying to create something because I like the style, or because it's the right style for the job at hand?
The answer was obvious in this case.
A:
Can you use one of the front slash line from the x letter and work something out with that? It could give the logo a nice flow. My suggestion is a 5 minute work with bad proportions, but it might give you an idea of something....
A:
I think the lesson I learned from this may benefit others in the future:
When it just isn't working, try re-thinking your design.
Sometimes it's good to just play it simple. Although the simplest solutions can often be the hardest to reach:
While this isn't related to the question directly, it's indirectly important: I kept working a design that didn't seem to want to be what I needed.
In the end the answer was to revisit my objective and ask: Am I trying to create something because I like the style, or because it's the right style for the job at hand?
The answer was obvious in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
php Invalid argument supplied for foreach();
Есть скрипт, который пингует все IP адреса в столбце "ip_address". Нужно чтобы после пинга записывались результат в столбец "status". Т.е. если компьютер находится онлайн, в столбец "status" писать значение 1, а если оффлайн - 0. Пример базы:
Вот мой скрипт:
<?php
$link = mysqli_connect("192.168.10.56", "test", "test", "test");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Работает: Подключение с базой данных имеется!" . PHP_EOL;
echo "Информация о хосте: " . mysqli_get_host_info($link) . PHP_EOL;
foreach($devices as $value){
exec("ping -c 1 " . $value->ip_address, $output, $result);
if ($result == 0) {
$insert_sql = mysqli_query($link, "UPDATE 'test' SET 'status'='1' WHERE ip_addres = '".$value->ip_address."'");
}else{
$insert_sql = mysqli_query($link, "UPDATE 'test' SET 'status'='0' WHERE ip_addres = '".$value->ip_address."'");
}
}
mysqli_close($link);
?>
Меня удивляет то, что, когда я запускаю скрипт в самом сервере, он не показывает никаких ошибок, но и не пишет в столбец. Но когда запускаю его на виртуальном сервере, то вот что:
A:
Вообще-то правильно он все пишет.
Invalid argument supplied for foreach() - он ссылается на строку foreach($devices as $value). Судя по коду, переменная $devices нигде не создается, вот он ее и не видит.
Предположим, что $devices это массив с IP адресами.
В таком случае Ваш код будет выглядить вот так:
// берем из таблицы список ip адресов (тут можно и WHERE добавить)
$result = mysqli_query($link, "SELECT ip_address FROM devices");
if ($result) { // если список есть
$ok = $bad = Array(); // в этих массивах будем хранить списки адресов после проверки
while ($row = mysql_fetch_assoc($result)) { // прокручиваемся через него по одному
exec("ping -c 1 " . $row["ip_address"], $output, $result); // пингуем адрес
if ($result == 0) { // в зависимости от результатов пинга заносим адрес в массив
$ok[] = $row["ip_address"];
} else {
$bad[] = $row["ip_address"];
}
}
// если есть OK адреса - обновлем все сразу одним запросом
if (Count($ok)) {
mysqli_query($link, "UPDATE test SET `status`=1 WHERE `ip_address` IN ('".implode("', '", $ok)."')");
}
// если есть BAD адреса - обновлем все сразу одним запросом
if (Count($bad)) {
mysqli_query($link, "UPDATE test SET `status`=0 WHERE `ip_address` IN ('".implode("', '", $bad)."')");
}
}
А если Вас удивляет то, что ошибки показываются на одном сервере и не показываются на другом, так это вполне могут быть просто настройки. Отключено показывание сообщений об ошибках.
Поставьте вот это
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', '1');
в первых строчках кода. И тогда ошибки будут отображаться везде.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to achieve the desired output in SQL Server 2008?
tbl_Fuel #Temp1
CommodityID Commodity Fuel_Sector Fuel_Rate Fuel_Min Fuel_EffectiveDate
----------------------------------------------------------------------------------------------------
1 General Cargo OTHERS 38.00 0.00 01/Apr/2019
1 General Cargo GULF+M.EAST 27.00 0.00 01/Apr/2019
1 General Cargo C/D 16.00 0.00 01/Apr/2019
2 Perishable - General OTHERS 7.00 0.00 15/Jun/2015
2 Perishable - General GULF+M.EAST 7.00 0.00 15/Jun/2015
2 Perishable - General C/D 7.00 0.00 15/Jun/2015
tbl_War #Temp2
CommodityID Commodity War_Sector War_Rate War_Min War_EffectiveDate
--------------------------------------------------------------------------------------------
1 General Cargo OTHERS 7.00 0.00 01/Apr/2019
1 General Cargo GULF+M.EAST 5.00 0.00 01/Apr/2019
1 General Cargo C\D 5.00 0.00 01/Apr/2019
1 General Cargo BGW 5.00 0.00 01/Apr/2019
3 Cut Flowers OTHERS 2.00 0.00 15/Jun/2015
3 Cut Flowers GULF+M.EAST 2.00 0.00 15/Jun/2015
tbl_XRay #Temp3
CommodityID Commodity XRay_Sector XRay_Rate XRay_Min XRay_EffectiveDate
--------------------------------------------------------------------------------------------
1 General Cargo ALL 2.00 225.00 16/Nov/2019
9 Pharma & Chemicals ALL 2.00 225.00 01/Jun/2011
Desired output:
CommodityID Commodity | Fuel_Sector | Fuel_Rate | Fuel_Min | Fuel_EffectiveDate |War_Sector | War_Rate | War_Min | War_EffectiveDate | XRay_Sector | XRay_Rate | XRay_Min | XRay_EffectiveDate
1 General Cargo | OTHERS | 38.00 | 0.00 | 01/Apr/2019 | OTHERS | 7.00 | 0.00 | 01/Apr/2019 | ALL | 2.00 | 225.00 | 16/Nov/2019
1 General Cargo | GULF+M.EAST | 27.00 | 0.00 | 01/Apr/2019 | GULF+M.EAST| 5.00 | 0.00 | 01/Apr/2019 | | | |
1 General Cargo | C/D | 16.00 | 0.00 | 01/Apr/2019 | C\D | 5.00 | 0.00 | 01/Apr/2019 | | | |
1 General Cargo | NULL | NULL | NULL | NULL | BGW | 5.00 | 0.00 | 01/Apr/2019 | | | |
2 Perishable - General | OTHERS | 7.00 | 0.00 | 15/Jun/2015 | | | | | | | |
2 Perishable - General | GULF+M.EAST | 7.00 | 0.00 | 15/Jun/2015 | | | | | | | |
2 Perishable - General | C/D | 7.00 | 0.00 | 15/Jun/2015 | | | | | | | |
3 Cut Flowers | | | | |OTHERS | 2.00 | 0.00 | 15/Jun/2015 | | | |
3 Cut Flowers | | | | |GULF+M.EAST | 2.00 | 0.00 | 15/Jun/2015 | | | |
9 Pharma & Chemicals | | | | | | | | | ALL | 2.00 | 225.00 | 01/Jun/2011
After so many Condn.. I get the data in three different temp tables... War, Fuel, XRay... I want to show the data commodity wise, if available....
I tried this query:
SELECT *
INTO #Temp4
FROM
(SELECT DISTINCT AirLine, CommodityId FROM #Temp1
UNION ALL
SELECT DISTINCT AirLine, CommodityId FROM #Temp2
UNION ALL
SELECT DISTINCT AirLine, CommodityId FROM #Temp3) a
SELECT *
FROM #Temp4
SELECT *
FROM #Temp4 a1
LEFT OUTER JOIN #Temp1 a2 ON a1.AirLine = a2.AirLine
AND a1.CommodityId = a2.CommodityId
LEFT OUTER JOIN #Temp2 a3 ON a1.AirLine = a3.AirLine
AND a1.CommodityId = a3.CommodityId
LEFT OUTER JOIN #Temp3 a4 ON a1.AirLine = a4.AirLine
AND a1.CommodityId = a4.CommodityId
This query first DISTINCT data hold in another temp table, then I'm doing a few Left Joins with all temp tables, but it's not returning the correct output.
A:
You can use full join, but to avoid a Cartesian product for each commodityID, you need a sequence number:
select coalesce(f.commodityID, w.commodityID, x.commodityID) as commodityID,
coalesce(f.commodity, w.commodity, x.commodity) as commodity,
f.fuel_sector, f.fule_rate, . . .
-- other columns from "tbl_fuel"
w.war_sector, . . .
x.xray_sector, . . .
from (select f.*,
row_number() over (partition by commodityID order by commodityID) as seqnum
from tbl_fuel f
) f full join
(select w.*,
row_number() over (partition by commodityID order by commodityID) as seqnum
from tbl_war w
) w
on w.commodityID = f.commodityID and
w.seqnum = f.seqnum full join
(select x.*,
row_number() over (partition by commodityID order by commodityID) as seqnum
from tbl_xray x
) x
on x.commodityID = coalesce(f.commodityID, w.commodityID) and
x.seqnum = coalesce(f.seqnum, w.seqnum);
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Template: typename and function to map to int
I'm writing a C++ template that needs two params: typename T, and an arbitrary function that maps T to an unsigned int.
How can I declare and use a template that can do that? I'd like to keep it simple, so that any dumb function can be used.
UPDATE:
Here is an example of what I'd like to do:
template<typename T, function f> // f has signature: unsigned int f(T);
class SortedContainer {
...
}
And, in this file:
unsigned int weight(Package p) { return p.w; }
SortedContainer<Package, &weight> sc;
UPDATE upon writing code
Based on the answers, I tried writing code, but it won't compile. Or rather, the template will compile, but not the test which invokes it.
The template code looks like this:
template<typename T, typename f>
class C {
...f(T)...
...
The invocation code looks like:
struct S {
int operator()(const int n) {
return n; // Dummy test code
}
};
...C<int, S>&...
The error message is:
error: no matching function for call to 'S::S(const int&)'
note: candidates are:
note: S::S()
It seems like it's trying to use S's constructor for some reason, as opposed to using the operator() which I want it to do.
The purpose of the f parameter is that the SortedContainer needs to be able to position T by an integer value. T is not necessarily an integer or even Comparable, so the caller, when instantiating a SortedContainer, needs to pass not only type T, but a function f to transform T to an integer.
A:
IMO, you don't require a separate template argument for Function F.
template<typename T> // F not required!
class SortedContainer {
...
};
Choose a good name and use that function by overloading it for various cases. e.g. to_uint()
Since you want to map (i.e. relate) a type to an unsigned int (uint), use following function in global scope:
template<typename T>
uint to_uint (const T& t) {
return t.to_uint(); // Must have `uint to_uint() const` member, else error
}
// Overloads of `to_uint()` for PODs (if needed)
template<typename T> // For all kinds of pointers
uint to_uint (const T* const pT) {
if(pT == nullptr)
<error handling>;
return to_uint(*pT);
}
Scenario: For Sorted_Container<X>, whenever to_uint(x) is invoked, then:
If X is a class, then it must have uint to_uint() const method
Else if X is a POD, then you may have to overload to_uint() for that type
Else, the compiler will generate an error
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make Symfony Form to use addSomething() / removeSomething() methods of the underlying object?
Suppose I have User object, which has $emails field. User object also has addEmail() and removeEmail() methods.
In my form type (UserType) I use CollectionType for $emails field.
After submitting a form, I want methods User::addEmail() and User::removeEmail() to be called instead of User::setEmails().
Is it possible?
A:
Yes it is possible, you just have to add the option 'by_reference' => false when building the form field.
| {
"pile_set_name": "StackExchange"
} |
Q:
Upper and lower sums - Spivak
I am using the 2nd edition of the book page 218 in Calculus by Michael Spivak in the chapter of the Riemann Integral.
$$\sup \{ L(f,P) \} \leq \inf \{ U(f,P) \} $$
It is clear that both of thes numbers are between
$$L(f,P') \leq \sup \{ L(f,P) \} \leq U(f,P')$$
$$L(f,P') \leq \inf \{ U(f,P)\} \leq U(f,P'),$$
for all partitions $P'$
I really do not understand why $L(f,P') \leq \inf \{ U(f,P)\} \leq U(f,P'),$ is true. How does he justify the fact that $U(f,P) \leq U(f,P')$? He didn't state $P' \subset P$, he is claiming that this inequality is true for any partitions $P$ and $P'$. In the previous page he uses $P_1, P_2,P$ so I do not understand where $P'$ suddenly comes from
A:
Do you understand why $L(f,P') \leq \sup \{ L(f,P) \} \leq U(f,P')$ is true?
Is the same reasoning for $L(f,P') \leq \inf \{ U(f,P)\} \leq U(f,P')$.
The first inequality $L(f,P') \leq \inf \{ U(f,P)\}$ is true because $L(f,P') \leq U(f,P)$ for all partitions $P$ ( If $Q$ is the common refinement of $P$ and $P'$ then $L(f,P') \leq L(f,Q)\leq U(f,Q)\leq U(f,P)$).
For the other inequality note that the infimum is taken over all partitions of your interval (let's denote it as $[a,b]$) therefore $\inf \{ U(f,P)\}=\inf \{ U(f,P):P \text{ partition of }[a,b]\}$ and this is less or equal of $U(f,P')$ since $P'$ is a partition of $[a,b]$.
| {
"pile_set_name": "StackExchange"
} |
Q:
IDocument cannot be resolved to a type
I'm very new to eclipse plugin devalopment and i want to get content from editor using eclipse plugin so i found this answer.
But problem is: I get the compile error IDocument cannot be resolved to a type. No quick fix imports available. My Eclipse version is 3.8.2.
How can I fix this problem?
The code I used (from the linked answer) is this:
public String getCurrentEditorContent() {
final IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
if (activeEditor == null)
return null;
final IDocument doc = (IDocument) activeEditor.getAdapter(IDocument.class);
if (doc == null) return null;
return doc.get();
}
I can't find org.eclipse.jface.text among my dependencies. Here is a snapshot:
A:
IDocument is in the org.eclipse.text plugin so you must add this to your plugin's dependencies list.
Note: You can also add the org.eclipse.jface.text plugin to the dependencies list as that will include the org.eclipse.text plugin.
| {
"pile_set_name": "StackExchange"
} |
Q:
Struggling with CORS error using Spring,Angularjs and Ionic frame work
Controller.java
In Controller class,I have defined url and while accessing from browser its working fine.
But when accessing the same url request from Ionic program, getting CORS error.Due to this error i have added necessary content in doFilter method too.But still left helpless.
@RestController
@RequestMapping("/service")
public class Controller implements Filter {
@RequestMapping(value = "/name", method = RequestMethod.POST,
headers = "content-type=application/x-www-form-urlencoded",produces="application/json")
public String reg(@ModelAttribute Farmer farmer) {
System.out.println("Getting request from Mobile client...!!" + farmer);//farmer.firstName is null
String result = "Hello..!";
System.out.println("Request processed");
return result;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) resp;
System.out.println("External request start..!!");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT,GET,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, resp);
System.out.println("External request end..!!");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
Farmer.java
public class Farmer {
private String firstName;
private String lastName;
//getters and setters
}
I have edited my question.Please do check it.
Thank you.
A:
After going with lot of trials and referring examples.Finally fixed this issue.So just thought of adding here.If in case anyone might need it.
This fixes just by adding
@CrossOrigin,@RestController,consumes="application/json" in your
controller method.
@CrossOrigin
@RestController
@RequestMapping("/service")
public class Controller implements Filter {
@RequestMapping(value = "/name", method = RequestMethod.POST,
headers = "content-type=application/x-www-form-urlencoded",consumes="application/json")
public String reg(@ModelAttribute Farmer farmer) {
System.out.println("Getting request from Mobile client...!!" + farmer);//farmer.firstName is null
String result = "Hello..!";
System.out.println("Request processed");
return result;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) resp;
System.out.println("External request start..!!");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT,GET,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, resp);
System.out.println("External request end..!!");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
Thank you
| {
"pile_set_name": "StackExchange"
} |
Q:
Array assignment produces NullPointerException
I am experiencing problems when assigning a value to an array, which is previously declared like so:
Enemy[] enemies = new Enemy[100];
I also have another variable defining the number of enemies spawned:
int numEnemies = 0;
Later, I (attempt to) dynamically assign members of this array to Enemy objects when the screen is touched:
public void spawnEnemy() {
Enemy enemy = new Enemy(...);
... initialise enemy ...
enemies[numEnemies++] = enemy; // this line causes NPE
}
I have this stack trace:
01-24 02:00:28.509: E/AndroidRuntime(1394): FATAL EXCEPTION: UpdateThread
01-24 02:00:28.509: E/AndroidRuntime(1394): Process: com.example.menutest, PID: 1394
01-24 02:00:28.509: E/AndroidRuntime(1394): java.lang.NullPointerException
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.GameScene.spawnEnemy(GameScene.java:333)
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.GameScene.initJoints(GameScene.java:325)
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.GameScene.loadLevel(GameScene.java:189)
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.GameScene.createScene(GameScene.java:80)
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.BaseScene.<init>(BaseScene.java:24)
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.GameScene.<init>(GameScene.java:32)
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.SceneManager$1.onTimePassed(SceneManager.java:118)
01-24 02:00:28.509: E/AndroidRuntime(1394): at org.andengine.engine.handler.timer.TimerHandler.onUpdate(TimerHandler.java:94)
01-24 02:00:28.509: E/AndroidRuntime(1394): at org.andengine.engine.handler.UpdateHandlerList.onUpdate(UpdateHandlerList.java:47)
01-24 02:00:28.509: E/AndroidRuntime(1394): at org.andengine.engine.Engine.onUpdateUpdateHandlers(Engine.java:618)
01-24 02:00:28.509: E/AndroidRuntime(1394): at org.andengine.engine.Engine.onUpdate(Engine.java:605)
01-24 02:00:28.509: E/AndroidRuntime(1394): at org.andengine.engine.Engine.onTickUpdate(Engine.java:568)
01-24 02:00:28.509: E/AndroidRuntime(1394): at org.andengine.engine.Engine$UpdateThread.run(Engine.java:858)
EDIT:
My app is written in AndEngine, so the CreateScene() method is called from a SceneManager which I am certain works perfectly.
public class GameScene extends BaseScene {
Enemy enemies[] = new Enemy[100];
int numEnemies = 0;
public void createScene() {
ResourcesManager.getInstance().setGameScene(this);
this.setOnSceneTouchListener((IOnSceneTouchListener) ResourcesManager.mBaseGameActivity);
createBackground();
createHUD();
createPhysicsWorld();
// the above set up scene for later use
loadLevel(1);
}
public void loadLevel(int levelID) {
initJoints();
}
private void initJoints() {
mPlanet = new Planet(400, 225, ResourcesManager.getInstance().planet, mVertexBufferObjectManager, 500);
mPlanet.mBody = PhysicsFactory.createBoxBody(mPhysicsWorld, mPlanet, BodyType.StaticBody, FIXTURE_DEF);
mPlanet.mBody.setUserData(mPlanet);
this.attachChild(mPlanet);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPlanet, mPlanet.mBody, true, true));
float x1 = 200;
float y1 = 112;
mSatellite = SatelliteFactory.createSatellite(SatelliteType.BASIC, x1, y1, mVertexBufferObjectManager, mPlanet);
this.attachChild(mSatellite);
spawnEnemy(); // causes exception
}
private void spawnEnemy() {
float y = getRandomY();
float maxHealth = 100;
Enemy enemy = new Enemy(0, y, ResourcesManager.getInstance().satellite_no_image, ResourcesManager.mVertexBufferObjectManager, maxHealth);
enemy.mBody = PhysicsFactory.createBoxBody(mPhysicsWorld, enemy, BodyType.DynamicBody, FIXTURE_DEF);
this.attachChild(enemy);
enemy.mBody.setLinearVelocity(new Vector2((mPlanet.getX() - enemy.mBody.getPosition().x) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
(mPlanet.getY() - enemy.mBody.getPosition().y) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT));
enemy.mBody.setLinearVelocity(new Vector2(mPlanet.getX(), mPlanet.getY() - y));
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(enemy, enemy.mBody, true, true));
enemies[numEnemies++] = enemy; // NPE
}
}
A:
I'll explain what happens:
How do I call an instance method before calling the instance constructor?
class B {
B() {
m();
}
void m() {
System.out.println("B.m()");
}
}
class X extends B {
int x = 8;
void m() {
System.out.println("X.m() x="+x);
}
}
public class A {
public static void main(String[] p) {
X x = new X();
x.m();
}
}
Let's run it:
$ javac A.java
$ java A
X.m() x=0
X.m() x=8
This kind of misbehavior is not possible in C++ where B.m() rather than X.m() would be called from within the base class constructor.
The constructor B() is called automatically before executing any code from the constructor X(), and so the method X.m() is called before any code within the constructor X() receives control.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do people think in a language?
I was discussing some things with a psychology major, and he insisted that people always use a language to think. This is quite opposed to my own experience.
I agree that I am capable of formulating my own thoughts in a kind of internal monologue, which is certainly in a language. But this is just one kind of my thought process. Sometimes my thoughts seem to be less language-bound. And what I think is the most important, it happens to me sometimes that I am speaking and suddenly notice that the word I am going to say is in a different language (almost always it happens just before I say it, but after the sentence has been formed and said up to the word). I don't mean the cases where I have learned a concept in another language and I am grasping for the correct word in the language I am currently speaking, I mean perfectly everyday words, like saying "I saw the book " and realizing that the word which I am going to say next is "gestern" instead of "yesterday". But at the time I realize this, I have already spoken the preceding part of the sentence. In very rare cases, I only notice it after I have said it, and hear my own wrong sentence.
I interpret such occasions as follows: I must have thought of the time reference without using a word in a language, after that constructed a sentence without consciously choosing words (else I would have noticed that "gestern" is wrong), and only made use of my vocabulary after that, practically at the point of commanding the mouth to form the words.
But he claimed that this isn't true, and that humans always use a language for thinking, not just for communicating. He couldn't point me to sources, or even tell me about an author researching such problems. He just claimed that he knows it for a fact, and must have learned it in a lecture. Do you know of research in that area? And what is its conclusion?
Skivvz's comment about off-topic makes me think that maybe I didn't state my question clear enough.
The claim I am disputing is: People always use a language in their internal thought processes. I provided an example which I interpret as anecdotal evidence against the claim. I also explained my interpretation. I am not asking how good my interpretation of this example is (this is probably the content suited to a psychology forum). But if you know of research which proves or disproves the claim, I'd like to hear about it.
A:
No. Human thought precedes language.
The anecdotal evidence for this should suffice, but you cannot be trusted (as you already have language skills).
Short Answer: Prelingual infants think.
In 2004 researchers Hespos and Spelke explored Korean language concepts with a group of five-month-old (human) infants from English-speaking homes...
The example they used to explore this
question was differences between how
different languages describe space.
For example, the distinction between a
tight fit versus a loose fit is marked
in Korean but not in English. A cap on
a pen would be a tight fit
relationship, while a pen on a table
would be a loose fit relationship.
English does not mark this distinction
in the same way, instead emphasizing
the “containment” versus “support”
relationship, for example: the coffee
is in the mug or the mug is on the
table. - source
...the infants showed an understanding of events that represented a change in "fit"...
Because this capacity is observed well
before the acquisition of a natural
language in infants whose ambient
language does not mark the
distinction, this capacity does not
depend on language experience.
Instead, the capacity seems to be
linked to mechanisms for representing
objects and their motions that are
shared by other animals and therefore
evolved before the human language
faculty. - source
In other words...
Learning a particular language may
lead us to favor some of these
concepts over others, but the concepts
already existed before we put them
into words. - source
More: Why would you think language is required ?
On one hand we can claim that we can
even think in pictures or on the other
hand one has to think to learn a
language. In terms of neurosciences it
has been proved that thinking without
language is possible. However the
philosophical references often deny
that one can think without language.
- source
These philosophical discussions have been going on for sometime...
When people have begun to reflect on
language, its relation to thinking
becomes a central concern. Several
cultures have independently viewed the
main function of language as the
expression of thought. Ancient Indian
grammarians speak of the soul
apprehending things with the intellect
and inspiring the mind with a desire
to speak, and in the Greek
intellectual tradition Aristotle
declared, “Speech is the
representation of the experiences of
the mind” (On Interpretation). Such an
attitude passed into Latin theory and
thence into medieval doctrine.
Medieval grammarians envisaged three
stages in the speaking process: things
in the world exhibit properties; these
properties are understood by the minds
of humans; and, in the manner in which
they have been understood, so they are
communicated to others by the
resources of language. Rationalist
writers on language in the 17th
century gave essentially a similar
account: speaking is expressing
thoughts by signs invented for the
purpose, and words of different
classes (the different parts of
speech) came into being to correspond
to the different aspects of thinking.
- source
Wilhelm von Humboldt: Credited as an originator of the linguistic relativity hypothesis (aka: the Sapir–Whorf hypothesis).
Benjamin Lee Whorf: Widely known for his ideas about linguistic relativity, the hypothesis that language influences thought.
Noam Chomsky: Well known in the academic and scientific community as one of the fathers of modern linguistics.
On the one hand, most people, after
hearing evidence that language is an
innate faculty of humans, would not be
surprised to learn that it comes from
the same source that every other
complex innate aspect of the human
brain and body comes from — namely,
natural selection. But two very
prominent people deny this conclusion,
and they aren't just any old prominent
people, but Stephen Jay Gould,
probably the most famous person who
has written on evolution, and Noam
Chomsky, the most famous person who
has written on language. They've
suggested that language appeared as a
by- product of the laws of growth and
form of the human brain, or perhaps as
an accidental by-product of selection
for something else, and they deny that
language is an adaptation. I disagree
with both of them. - Pinker, Language Is a Human Instinct
Steven Pinker: Argues that language is an "instinct" or biological adaptation shaped by natural selection.
...These scholars, ranging from
Aristotle to Freud, took these
specific instances to be exceptional,
marginal eruptions of meaning, curious
and suggestive. But none of them
focused on the general mental capacity
of blending or, as far as we can tell,
even recognize that there is such a
mental capacity. Attentive to the
specific attraction - the painting
,the poem, the dream , the scientific
insight - they did not look for what
all these bits and pieces have in
common. The spectacular trees masked
the forest.
- Turner-Fauconnier, The
Way We Think
More...
Does language shape what we think ?
How does our Language shape the way we think ?
Background: Why is language important ?
Before Homo sapiens came on the scene 150 kya innovation and change amongst the genus of the family Hominidae was pretty dull. Homo habilis showed up 2.4 mya and stayed around for a million years. They had one, and only one, great idea: Stone tools. Next up was Homo erectus (1.5 – 0.2 mya). Erectus was a slow starter but about 400,000 years ago they hit pay-dirt: Controlled use of Fire. Great. For 2.2 million years of effort we have some sharp rocks and a barbeque.
Then things get really interesting.....
Any innovation must take place within
a species, since there is no place
else it can do so. Natural selection
is, moreover, not a creative force. It
merely works on variations that come
into existence spontaneously—it cannot
call innovations into existence just
because they might be advantageous.
Any new structure or aptitude has to
be in place before it can be exploited
by its possessors, and it may take
some time for those possessors to
discover all the uses of such
novelties. Such seems to have been the
case for Homo sapiens in that the
earliest well-documented members of
our species appear to have behaved in
broadly the same manner as
Neanderthals for many tens of
thousands of years. It is highly
unlikely that another species
anatomically indistinguishable from
Homo sapiens but behaviorally similar
to Neanderthals was supplanted
worldwide in an extremely short span
of time. Therefore, it seems
appropriate to conclude that a latent
capacity for symbolic reasoning was
present when anatomically modern Homo
sapiens emerged and that our forebears
discovered their radically new
behavioral abilities somewhat later in
time.
A cultural “release mechanism” of some
sort was necessarily involved in this
discovery, and the favoured candidate
for this role is language, the
existence of which cannot be inferred
with any degree of confidence from the
records left behind by any other
species but our own. Language is the
ultimate symbolic activity, involving
the creation and manipulation of
mental symbols and permitting the
posing of questions such as “What if?”
Not all components of human thought
are symbolic (the human brain has a
very long accretionary, evolutionary
history that still governs the way
thoughts and feelings are processed),
but it is certainly the addition of
symbolic manipulations to intuitive
processes that makes possible what is
recognized as the human mind.
The origins of this mind are obscure
indeed, especially as scientists are
still ignorant of how a mass of
electrochemical signals in the brain
gives rise to what we experience as
consciousness. But the invention of
language would plausibly have released
the earliest of the cultural and
technological innovations that
symbolic thought makes possible—in the
process unleashing a cascade of
discoveries that is still ongoing. One
of the most striking features of the
archaeological record that accompanies
the arrival of behaviorally modern
Homo sapiens is a distinct alteration
in the tempo of innovation and change.
Significant cultural and technological
novelties had previously been rare,
with long periods of apparent
stability intervening between
relatively sudden episodes of
innovation. But once behaviorally
modern Homo sapiens arrived on the
scene, different local technological
traditions—and, by extension, other
forms of cultural diversity—began to
proliferate regularly, setting a pace
that is still gathering today.
- source
The Bottom Line
When you look into the eyes of the one you love and think of what they mean to you...
What language do you think in ?
Love is a smoke made with the fume of sighs, Being purged, a fire sparkling in lovers’ eyes, Being vexed, a sea nourished with lovers’ tears. What is it else? A madness most discreet, A choking gall and a preserving sweet. - Bill
What language was he thinking in ?
A:
Your question reminded me TED talk:
http://www.ted.com/talks/temple_grandin_the_world_needs_all_kinds_of_minds.html
in which Temple Grandin explains how her autistic mind works. She says that unlike majority of people she thinks in pictures, not in language.
| {
"pile_set_name": "StackExchange"
} |
Q:
How should I store a collection of objects and provide specific methods to query them?
I need some advise on the best way to achive the following:
Store a collection of a specific type of objects in order
Custom methods to search the collection
Other custom methods for returning objects from the collection based on some rules
Need instance variables to keep track of things in the collection
Originally I was thinking about sub classing the NSMutableArray class and adding the extra methods and variables that I want that are specific to the objects that I'm going to be storing in the array, but the Apple docs said this was a no no!
I know that you can use Categories but they don't support adding instance variables which I need to keep track of elements in the collection.
Also I don't want these extra methods being adding to all NSMutableArray objects just my custom one.
What is the best way to do this, the idea is to have a nice wrapper around NSMutableArray to query my custom objects and manipulate them.
A:
Create a class (inheriting from NSObject) that contains a NSMutableArray. Write your own custom add: and remove... methods to add and remove objects from the array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving list entry in multiple lists
I have 6 different but similar lists created on the same SharePoint 2010 site to collect information with my team. I would like to create a workflow that automatically duplicates list items as they are being created in one of the 6 individual lists into one master list on the same site. I've tried setting up a workflow to copy from the original list to the master list, but have not had success. Any help would be appreciated.
A:
the copy item requires to have both lists with the SAME field names and same amount of fields, if they are different you won't be able to copy the item.
if the field amount and names are different you should create a new item in the workflow and get the current item information
or, make all your lists and master list look the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I determine if page is being viewed through lightbox?
I have several sites I'm working on that are loading sub-pages via lightbox. The actual content is being found by Google, but the pages are hideous as they aren't meant to load all the headers and whatnot - this is content intended for lightbox delivery (ajax, fancybox).
In PHP, or javascript if necessary, how might I determine if the content is being viewed in a lightbox or not? Would be nice to throw up a "view the original page" link or something.
A:
lightbox like every other similar lib use AJAX for pulling content ... am not sure sure if you can detect if it is a standard jquery or moottools or lightbox because they all you the same technology
What you can do is detect if your page is been called via AJAX
function isAjax() {
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest");
}
if(isAjax())
{
die("Don't Use AJAX");
}
else
{
echo "WELCOME" ;
}
A:
Lightboxes often use iframes to display external pages. If this is the case (you can inspect the Lightbox using Firebug to check this), you can use window.top on JavaScript to check this.
if (window.top.location != window.location) {
//this page is inside a frame or iframe
}
| {
"pile_set_name": "StackExchange"
} |
Q:
como sumar 2 propiedades de 2 objetos diferentes en js (nodejs)
Tengo estos 3 objetos
const leagues = [
{ id: 1, country: 'England', name: 'Premier League' },
{ id: 2, country: 'Germany', name: 'Bundesliga' },
{ id: 3, country: 'Netherlands', name: 'Eredivisie' },
{ id: 4, country: 'Spain', name: 'La Liga' },
{ id: 5, country: 'Italy', name: 'Serie A' },
{ id: 6, country: 'Portugal', name: 'Liga NOS' },
{ id: 7, country: 'France', name: 'Lige 1' }
]
const teamsByLeague = [
{ teamId: 12, leagueId: 5 },
{ teamId: 6, leagueId: 3 },
{ teamId: 2, leagueId: 5 },
{ teamId: 3, leagueId: 4 },
{ teamId: 4, leagueId: 2 },
{ teamId: 8, leagueId: 1 },
{ teamId: 10, leagueId: 6 },
{ teamId: 5, leagueId: 1 },
{ teamId: 7, leagueId: 5 },
{ teamId: 9, leagueId: 1 },
{ teamId: 11, leagueId: 2 },
{ teamId: 1, leagueId: 4 },
{ teamId: 13, leagueId: 7 }
]
const winsByTeams = [
{ teamId: 10, wins: 2 },
{ teamId: 6, wins: 4 },
{ teamId: 5, wins: 5 },
{ teamId: 1, wins: 13 },
{ teamId: 7, wins: 3 },
{ teamId: 4, wins: 5 },
{ teamId: 8, wins: 3 },
{ teamId: 2, wins: 7 },
{ teamId: 9, wins: 1 },
{ teamId: 3, wins: 5 },
{ teamId: 11, wins: 1 },
{ teamId: 12, wins: 2 },
{ teamId: 13, wins: 1 }
]
y tengo que saber el total de wins por league, osea sumar los wins del objeto 3 que están relacionados al objeto 1 a través del objeto 2.
He ocupado funciones como .find
(wins: (winsByTeams.find(win => win.teamId === team.id)).wins)
Para encontrar las id que sean igual, pero me pregunto si hay alguna funcion especial para sumar los wins del 3 objeto sin transformarlos en arreglo a través de .map
( const ligasOrdenadas = leagues.map((leagues) => ({
name: leagues.name,
winsTotal: (winsByTeams.find(win => win.teamId === leagues.id)).wins
}));)
A:
Como siempre, todo es aplicar divide y vencerás:
Dada una liga, filtras los IDs de los equipos que pertenecen a dicha liga:
const teamIds = teamsByLeague
.filter(team => team.leagueId ===leagueId) //nos quedamos los equipos de la liga
.map(team => team.teamId); // y cogemos sus IDs
Una vez que tenemos los equipos, sumamos sus victorias:
return winsByTeams
.reduce((acc,tw) => teamIds.includes(tw.teamId) ? acc + tw.wins: acc, 0);
Que también se podría escribir como:
return winsByTeams
.filter(tw => teamIds.includes(tw.teamId))
.reduce((acumulador,team) => acumulador + team.wins, 0);
Y todo junto queda así:
function getWinsByLeague(leagueId) {
const teamIds = teamsByLeague
.filter(team => team.leagueId ===leagueId) //nos quedamos los equipos de la liga
.map(team => team.teamId); // y cogemos sus IDs
console.log('Equipos de la liga',leagueId,':',teamIds.toString());
// sumamos las victorias de los equipos si su ID está en la lista obtenida
return winsByTeams
.filter(tw => teamIds.includes(tw.teamId))
.reduce((acumulador,team) => acumulador + team.wins, 0);
}
const leagues = [
{ id: 1, country: 'England', name: 'Premier League' },
{ id: 2, country: 'Germany', name: 'Bundesliga' },
{ id: 3, country: 'Netherlands', name: 'Eredivisie' },
{ id: 4, country: 'Spain', name: 'La Liga' },
{ id: 5, country: 'Italy', name: 'Serie A' },
{ id: 6, country: 'Portugal', name: 'Liga NOS' },
{ id: 7, country: 'France', name: 'Lige 1' }
]
const teamsByLeague = [
{ teamId: 12, leagueId: 5 },
{ teamId: 6, leagueId: 3 },
{ teamId: 2, leagueId: 5 },
{ teamId: 3, leagueId: 4 },
{ teamId: 4, leagueId: 2 },
{ teamId: 8, leagueId: 1 },
{ teamId: 10, leagueId: 6 },
{ teamId: 5, leagueId: 1 },
{ teamId: 7, leagueId: 5 },
{ teamId: 9, leagueId: 1 },
{ teamId: 11, leagueId: 2 },
{ teamId: 1, leagueId: 4 },
{ teamId: 13, leagueId: 7 }
]
const winsByTeams = [
{ teamId: 10, wins: 2 },
{ teamId: 6, wins: 4 },
{ teamId: 5, wins: 5 },
{ teamId: 1, wins: 13 },
{ teamId: 7, wins: 3 },
{ teamId: 4, wins: 5 },
{ teamId: 8, wins: 3 },
{ teamId: 2, wins: 7 },
{ teamId: 9, wins: 1 },
{ teamId: 3, wins: 5 },
{ teamId: 11, wins: 1 },
{ teamId: 12, wins: 2 },
{ teamId: 13, wins: 1 }
]
leagues.forEach(l => console.log('La liga',l.name,'tiene',getWinsByLeague(l.id),'victorias'));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the CategoryId using the name in Magento 1.9?
Looking to find the category ID using the Name attribute programmatically. My script returns a 1 when it should be a 19. Here is my code:
$collection = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('is_active', 1)
->addAttributeToFilter('parent_id', $currentCategoryId)
->addAttributeToFilter('name', $categoryName);
which should return the category right? Then the script utilizes $catid = $collection->getFirstItem()->getId(); to get the ID, however it is returning the wrong ID. Any ideas?
A:
$category = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('name', 'Men')
->getFirstItem() // The parent category
->getChildrenCategories()
->addFieldToFilter('name', 'Clothing')
->getFirstItem(); // The child category
$categoryId = $category->getId();
A:
Please try using the following.
$_category = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('name', $categoryName)
->getFirstItem();
$categoryId = $_category->getId();
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading data from a text file into a 2D array and getting out of bounds exception
I've been having trouble with reading data in from a text file to a 2D array. I am not too sure what the issue with the out of bounds exception is because I thought I initialized it correctly but I am not sure.
Here is my code.
String [][] f_team = new String [20][6]; //20 and 6
int cnt = 0;
int cnt2 = 0;
String line = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadData();
}
public void loadData()
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("team.txt")));
while(cnt<=20) {
line = br.readLine();
f_team[cnt][cnt2] = line;
cnt2 = cnt2 + 1;
if (cnt2 == 5) {
cnt = cnt + 1;
cnt2 = 0;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my logcat for the error:
05-16 17:33:29.119 26312-26312/com.jmac.jmac.footy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jmac.jmac.footy, PID: 26312
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jmac.jmac.footy/com.jmac.jmac.footy.Pitch}: java.lang.ArrayIndexOutOfBoundsException: length=20; index=20
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=20; index=20
at com.jmac.jmac.footy.Pitch.loadData(Pitch.java:82)
at com.jmac.jmac.footy.Pitch.onCreate(Pitch.java:74)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
A:
If your array has size 20, you can only access index [0;19]
you are accessing index 20 in your while clause
while(cnt<=20)
you have to put:
while(cnt<20)
see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Inner class with main method doesn't compile
abstract class Manager {
static void test() {
System.out.println(12);
}
class Manager1 {
public static void main(String args[]) {
System.out.println(Manager.test());
}
}
}
It's producing a compile time error. Can an abstract class have a static method with void type?
A:
Non-static inner classes cannot have static methods - only top-level and static classes can (as per JLS §8.1.3).
Furthermore:
System.out.println(Manager.test());
Manager.test() is void: you can't print that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Storekit: How to check if the product is purchased or not?
I think everyone knows that Apple In-App Purchases are a little bit difficult thing to implement. (Especially for Swift newbies).
Anyway, I tried to learn working with it. Maybe it's better to say that I followed the tutorial Kilo Loco made on YouTube.
Here
I did everything what he did and it's working but it's obvious that I don't understand everything yet.
My question is.. how to check if the customer already purchased it or not?
Maybe there's some kind of status?
Then I would just write something like that:
if(status=="purchased")
{
// I would do something what premium user can do.
}
I know it's not really clear but I guess who have more experience in it can help me to understand more. (or maybe I should go watch tutorial once again and once again)
THANK YOUU!
A:
You can check this tutorial, the section about Purchased Items.
In short, you should save locally if the Item has been already purchased, maybe in UserDefaults
A more secure alternative is to validate the receipt of the purchase, as shown in the Apple Documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
htaccess 301 redirect entire site but with exceptions
I am trying to create an htaccess file to redirect my entire site except with some exceptions, but I can't get it working. I need to redirect the entire thing, provide a specific redirect, and exclude two pages. Below is my non-working sample. Thanks!
RewriteCond %{REQUEST_URI} !^/events/index.html
RewriteCond %{REQUEST_URI} !^/calendar/index.html
Redirect 301 /info/faq.html http://mynewsite.com/my-page
Redirect 301 / http://mynewsite.com
A:
You're attempting to mix mod_rewrite with mod_alias, but the RewriteCond statements cannot condition the Redirect statements, as they don't come from the same module.
I believe you want something more like this, if I've correctly understood what you were trying to accomplish:
RewriteEngine On
RewriteCond %{REQUEST_URI} !=/events/index.html
RewriteCond %{REQUEST_URI} !=/calendar/index.html
RewriteCond %{REQUEST_URI} !=/info/faq.html
RewriteRule ^.*$ http://mynewsite.com/$0 [R=301,L]
Redirect 301 /info/faq.html http://mynewsite.com/my-page
A:
I had a similar issue. Trying to redirect an entire domain with the exception of its robots.txt file. Tim's answer didn't work for me, but this did
RewriteEngine On
RewriteRule robots.txt - [L]
RewriteRule ^.*$ http://www.newsite.com/$0 [R=301,L]
| {
"pile_set_name": "StackExchange"
} |
Q:
OleDbCommand: SQL syntax error
I am having trouble with a ALTER TABLE command that I am trying to use on a MS Access database in a C# project. I am trying to rename a column and change the type at the same time.
Here is my command:
string sqlCommand = "ALTER TABLE " + tableName + " CHANGE [" + oldColName + "] ["
+ newColName + "] " + colType;
What is wrong in this command and what do I need to do to make this it work?
*Edits:
-The type and the names of the table, new column and old column are not the problem!
-The exception that is catched is :
Syntax error in ALTER TABLE statement.
-The final string looks like this:
ALTER TABLE [Big List] CHANGE [num] [test] CHARACTER
-Connection provider:
Microsoft.ACE.OLEDB.12.0
A:
I don't think you can rename a column with SQL and access.
The best way to achieve this is to create a new column with the new name, update the new column and drop the old one.
ALTER TABLE [Big List] ADD COLUMN [num] YOURTYPE;
UPDATE [Big List] SET [num] = [test];
ALTER TABLE [Big List] DROP COLUMN [test];
| {
"pile_set_name": "StackExchange"
} |
Q:
Maximize and Minimize $\vec C$ s.t. $|\vec A + \vec B + \vec C| \le 2400$
Given three vectors: $|\vec A| = 2850$ and forms a $150^\circ$ angle with the positive $x$-axis, $|\vec B| = 650$ and forms a $60^\circ$ angle with the positive $x$-axis, $\vec C$ which has a positive $x$-component and zero $y$-component. I need to find the minimum and maximum values of $|\vec C|$ such that $|\vec A + \vec B + \vec C| \le 2400$.
I initially thought about using law of cosines,
\begin{align*}
|\vec A + \vec B|^2 &= |\vec A|^2 + |\vec B|^2 - 2|\vec A||\vec B|\cos 90^\circ \\
|\vec A + \vec B|^2 &= 2850^2 + 650^2 - 0 \\
|\vec A + \vec B| &\approx 2923.183 \\
\end{align*}
And I could repeat this using $|\vec A + \vec B|$ and $|\vec C|$, to see what value of $|\vec C|$ gives me $2400$, but I don't see how this gives me the minimum and maximum possible values.
What approach should I be taking to find the min and max values?
A:
All three vectors are essentially given, so maybe we can simply write them all in components, add them together, and solve the given inequality for the unknown component of $\vec C$?
Here's what I mean. From its description,
$$\vec A = \left\langle 2850\cos(150^{\circ}),2850\sin(150^{\circ}) \right\rangle = \left\langle -1425\sqrt{3},1425 \right\rangle.$$
Similarly, you can find vector $\vec B$. And $\vec C=\langle x,0 \rangle$ with the unknown component $x$. Add them together to form $\vec A+\vec B+\vec C$, and then set up the inequality $\left|\vec A+\vec B+\vec C\right|\le2400$ to solve for the unknown $x$. By the way, to avoid the square root in the norm of a vector formula, you should square both sides to be solving $\left|\vec A+\vec B+\vec C\right|^2\le5760000$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple Event Machine causing one to report undefined method `stop' for nil:NilClass
I have two classes in two separate modules (I know that is not a good use for now :/)
I have something like this:
module MQ
class Client
def self.start(opts = {})
new(opts).start
end
def initialize(queue, message)
@template_message = message
@queue = queue
end
def start
EventMachine.run do
#some code to send message via AMQP
Signal.trap("INT") { connection.close { EventMachine.stop { exit } }}
Signal.trap("TERM") { connection.close {EventMachine.stop { exit(0) } }}
Signal.trap("INFO") { puts "Current active statements: #{statements.keys.inspect}" }
end
end
def stop
EventMachine.stop
end
end
end
And next I have defined Server class:
module Esper
class Server
def self.start(opts = {})
new(opts).start
end
def initialize(options)
end
def start
EventMachine.run do
#some code here to receive messages
Signal.trap("INT") { connection.close { EventMachine.stop { exit } }}
Signal.trap("TERM") { connection.close {EventMachine.stop { exit(0) } }}
Signal.trap("INFO") { puts "Current active statements: #{statements.keys.inspect}" }
end
end
def stop
EventMachine.stop
end
end
end
Now I have in rspec (and here is the error reporting):
context "matched messages" do
before :each do
@template_message = { }
@server = Esper::Server.new
@client = MQ::Client.new("queue_name", @template_message)
end
describe "transfer" do
it "should receive statements" do
Thread.new do
@server.start
end
Thread.new do
@client.start
end
puts "Sleep for 6 seconds"
sleep(6.0)
#some check here
@server.stop
@client.stop # and here it reports when I am trying to access nil class in class client in method stop.
end
end
It is reporting in Client class in method stop when trying to call EventMahine.stop
It is saying:
undefined method `stop' for nil:NilClass
Can someone point me where am I wrong and if you have any suggestion how to fix it?
A:
I have had this problem because I was trying to incorporate esper and ampq.
The problem which is showing I overcome by using somewhat different approach. I still don't know why it was giving the nil pointer exception.
My solution was to use a deamon-kit gem for rails. I have created a deamon using this kit.
The deamon is a separate application inside my original application. That way I can test the ampq in it's separate folders and when I want to test the whole application, I can run the deamon from within original application, send data to the deamon and then check returned values in the original application.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change content of dynamically on click of link from menu through Ajax
I'm using JSF2 with Primefaces running on Tomcat 7. I have created a layout in baseLayout.xhtml as below: -
<h:body>
<p:layout fullPage="true">
<p:layoutUnit position="north" size="50" id="top">
<h:form>
<ui:include src="/template/header.xhtml" />
</h:form>
</p:layoutUnit>
<p:layoutUnit position="south" size="20">
<h:form>
<ui:include src="/template/footer.xhtml" />
</h:form>
</p:layoutUnit>
<p:layoutUnit position="west" size="400">
<h:form>
<ui:include src="/template/menu.xhtml" />
</h:form>
</p:layoutUnit>
<p:layoutUnit position="center" size="400">
<h:panelGroup id="centerContentPanel">
<ui:include src="#{navigationBean.pageName}.xhtml" />
</h:panelGroup>
</p:layoutUnit>
</p:layout>
</h:body>
I want to dynamically change the source of centerContentPanel without refreshing the whole page and just the centerContentPanel i.e for on click of link present in the menu.xhtml as below: -
<h:form id="form2">
<f:ajax render=":centerContentPanel" execute="@this">
<h:commandLink value="page1" action="#{navigationBean.doNav}" >
<f:param name="test" value="/pages/page1" />
</h:commandLink>
<h:commandLink value="page2" action="#{navigationBean.doNav}" >
<f:param name="test" value="/pages/page2" />
</h:commandLink>
</f:ajax>
</h:form>
. I tried doing that, but instead it refreshes the whole page without changing the URL, and when I refresh it again, the new page is included. I don't know what is happening. My NavigationBean as below:-
public class NavigationBean {
private String pageName="/template/body";
public NavigationBean() {
}
public String doNav() {
System.out.println("Hello");
String str = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("test");
this.pageName = str;
return pageName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
}
A:
change doNav() into void , no need to return value... (cause it will cause your commandLink to reload page...) you already updating the pageName that is in use in <ui:include src="#{navigationBean.pageName}.xhtml" />
doNav should look like this:
public void doNav() {
System.out.println("Hello");
String str = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("test");
this.pageName = str;
}
the returning value from your action="..." causes the refreshes the whole page without changing the URL
| {
"pile_set_name": "StackExchange"
} |
Q:
Proper use of async, await and task.delay for a game loop
I'm currently in the process of making a game loop in a console application. I'm trying to make the game loop wait at the end of its loop for (1000*10000/fps) - ElapsedTicks to put a cap on game loop speed. For reference 1 millisecond is 10,000 ticks.
If the ElapsedTicks < FrameTimeTicks I execute await Task.Delay(FrameTimeTicks - ElapsedTicks) but this ends my console application.
The code responsible is the await Task.Delay so I assume I'm not using it properly.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApp1
{
class Program
{
static byte fps = 30;
public static byte Fps { get { return fps; } set { fps = value; } }
//user specified fps
static long frameTimeTicks = (1000 * 10000) / Fps;
static long FrameTimeTicks { get { return frameTimeTicks; } }
//amount of ticks desired in one frame
static bool draw = true;
public static bool Draw { get { return draw; } set { draw = value; } }
static long elapsedTicks;
static long ElapsedTicks { get { return elapsedTicks; } set { elapsedTicks = value; } }
//ticks elapsed in one game loop
static void Main(string[] args)
{
GameLoop();
}
static void UpdateGame()
{
int a = 0;
a++;
}
static void Render()
{
Console.WriteLine("@");
}
public static async void GameLoop()
{
Stopwatch gameLoopTicks = Stopwatch.StartNew();
while (true)
{
gameLoopTicks.Restart();
if (Console.KeyAvailable == true)
{
char KeyPressed = Console.ReadKey().KeyChar;
}
UpdateGame();
if (Draw == true)
{
Render();
}
ElapsedTicks = gameLoopTicks.ElapsedTicks;
if (ElapsedTicks > FrameTimeTicks)
{
Draw = false;
}
else
{
Draw = true;
await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
}
}
}
}
}
I Have also tried this variation but to the same result, my console application ends.
public static async void GameLoop()
{
Stopwatch gameLoopTicks = Stopwatch.StartNew();
async Task PauseGameLoop()
{
//Console.ReadKey(); execution ends here!
await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
GameLoop();
}
while (true)
{
gameLoopTicks.Restart();
if (Console.KeyAvailable == true)
{
char KeyPressed = Console.ReadKey().KeyChar;
}
UpdateGame();
if (Draw == true)
{
Render();
}
ElapsedTicks = gameLoopTicks.ElapsedTicks;
if (ElapsedTicks > FrameTimeTicks)
{
Draw = false;
}
else
{
Draw = true;
await PauseGameLoop();
}
}
Task.Delay MSDN, await MSDN. Am I tackling this problem the wrong way ? This post is why I chose this method. Thanks for the help!
A:
How do keep the program from exiting when there's an active async function running?
You GameLoop is async but your Main function is not. By default, starting a Task starts it on pooled thread. The minimal changes to avoid exiting Main are to return a Task and wait on it in Main:
static void Main() {
GameLoop().Wait();
}
public static async Task GameLoop() {
.. same as before ..
}
A bigger issue will be that the resolution of the timer in Task.Delay is (system-dependent) probably only around 15ms, so you're not going to get very stable framerates. In fact, the resolution of sleeping a thread in general is going to be too low.
How to get consistent sleep times if Task.Delay isn't high-resolution enough?
For most consistent results, You'll want to look into implementing a fixed-timestep game loop where you just render as fast as possible (or perhaps spinwait any extra time away) or use VSync to naturally limit your loop speed.
The Go-to article on how to implement a fixed-timestep game loop has been Fix your Timestep, and there have been plenty of previous fixed-timestep questions asked here.
We take a page from the standard fixed-timestep pattern and wrap a main loop around a time-delta generating function. When that delta goes above our desired frameTime we call Update(). The rest of the loop consists of either a Thread.Sleep(1) if your platform has a high-resolution sleep timer or an empty loop while you're waiting for enough time to pass, to get a spinwait. In theory, you could use unsafe / unmanaged code to call the equivalent of _mm_pause to reduce your power consumption in the spinwait, but that's outside the scope of this answer.
using System;
class Program {
public Program(double fps) {
DesiredFPS = fps;
frameTime = TimeSpan.FromSeconds(1.0 / fps);
}
double DesiredFPS;
TimeSpan frameTime;
// counts how many times we've looped while waiting
int spinCounter = 0;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
// this is the function we run at the desired FPS
void Update() {
Console.WriteLine("{0} {1}", spinCounter, sw.Elapsed);
spinCounter = 0;
}
void MainLoop() {
sw.Start();
var last = sw.Elapsed;
var update_time = new TimeSpan(0);
while (true) {
var delta = sw.Elapsed - last;
last += delta;
update_time += delta;
while (update_time > frameTime) {
update_time -= frameTime;
Update();
}
spinCounter++;
// On some systems, this returns in 1 millisecond
// on others, it may return in much higher.
// If so, you should just comment this out, and let the main loop
// spin to wait out the timer.
System.Threading.Thread.Sleep(1);
}
}
static void Main() { new Program(30.0).MainLoop(); }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
The approach to avoid including js file twice
this is a simple html file:
<!DOCTYPE html>
<html>
<head>
<title>Test Uploading Func.</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.js"> </script>
<link type="text/css" href="jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="jquery-ui-1.8.21.custom.min.js"></script>
<!--Include js file-->
<script type="text/javascript" src="upload.js" ></script>
</head>
<body>
<button id="Upload" value="upload">upload</button>
<script type="text/javascript" src="upload.js" ></script>
</body>
And this is the js file I want to include:
$( '#Upload' ).bind('click', function(){
alert(">");
});
If I just include the js file in the beginning, the selector # can't know the id Upload so that I have to include it again
at the end of the file... I do know it's not correct. But I don't know how to resolve it? Don't we just include all the js file within the tag head?
What's the appropriate coding style I show have?
Thanks.
UPDATE question!!!
If I have a lot of scenario like this, should I add "$(document).ready()" to all the functions? A little weird...
Still another approach? Or web developers always do so.
And where should I include my js file? In the begin or the end?
If I include them all in the end, this kind of problem won't appear.
Then why lots of people include the js file just in the start?
A:
Wait for the DOM to be ready before selecting elements:
$(document).ready(function () {
$( '#Upload' ).bind('click', function(){
alert(">");
});
});
Update:
You should always use $(document).ready(...) if you are manipulating elements that you expect to be on the page when your code runs. This is especially important if your code is in the <head></head> of the document.
You are not required to use $(document).ready(...) if your code is inside the </body> tag, but be aware that there are differences between the two.
| {
"pile_set_name": "StackExchange"
} |
Q:
How did Indy know to not look at the Ark?
My grasp of Scripture is poor, but the only thing I can recall in the Bible along these lines is Uzzah being struck down because he TOUCHED the Ark. How did Indy know that they should close their eyes and escape being fried by the Ark?
A:
Cross-referenced from that initial link is 1 Samuel 6:19.
But God struck down some of the men of Beth Shemesh, putting seventy of them to death because they had looked into the ark of the LORD. ..
See also 1 Samuel 6:19 in the King James Bible.
And he smote the men of Bethshemesh, because they had looked into the ark of the LORD, even he smote of the people fifty thousand and threescore and ten men: and the people lamented, because the LORD had smitten many of the people with a great slaughter.
Those versions are pretty much in agreement, though the number jumped from 70 to over 50 thousand.
A:
It wasn't so much the Ark he wasn't looking at, but the everything. The Ark, the angels, and the whole thing.
I remember seeing a special on TV, a "Making of" type show, and they had a shot of Spielberg working with Harrison Ford and Karen Allen and he said something to the effect of, "And, according to the Gospel of Lucas, Indy and Marion are spared because of their goodness." I thought that was interesting because his comment, as the director, indicated that in his mind it wasn't so much whether they looked at the Ark and angels (were they ark-angels?), but that the angels actually distinguished between good people and bad people.
A:
This is a common idea in Judaism. To paraphrase:
It is impossible for a human to behold God, because He is too mind-boggling for a mortal to comprehend. If you see God, you die.
This is what my Hebrew instructor taught me.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this English doing in the middle of my Japanese?
Note: I understand this question is on the edge of being off topic. I'll accept the community assessement if enough people feel that is the case.
I'm reading 脳{のう}は0.1秒{びょう}で恋{こい}をする by 茂木{もぎ}健一郎{けんいちろう}, and out of the blue, there's an English word right in the middle of a sentence:
The sentence reads 人生{じんせい}は「偶有性{ぐうゆうせい}」(contingency)に満{み}ちています。 I think I basically understand it, in that it says life is full of contingencies.
My question, though, is why is this English word here? The book is written by and for Japanese. The way the word is offered, it looks as though it is a clarification of 偶有性{ぐうゆうせい}, where 偶有{ぐうゆう} means having an accident, and 性{せい} means the suffix ~ness, so I guess it's supposed to approximate the word "contingencies".
I just don't get how this would help a Japanese person reading the book? Does Mogi San expect that a Japanese person who doesn't know 偶有性{ぐうゆうせい} would be helped by knowing that it meant "contingencies"? That doesn't seem very likely to me.
I appreciated it, because it helped me understand what he meant, but I don't think this is for the benefit of Japanese learners.
What is going on here?
A:
Technical subjects usually have a large English-speaking community, and theses and books on that subject are often published in English (or some other international language, but you probably get a wider readership by publishing in English).
It's important to know the English technical terms so you can understand those books and theses, so even when reading a Japanese technical book that introduces its terms in Japanese, it will often include the corresponding English terms in parentheses so that you're not completely confused when you try to read foreign material on the subject.
Whether or not this particular sentence is actually from a technical work or field, and even if you are never likely to need to look it up anywhere else, the inclusion of an English word here reminds the reader of that kind of technical text, which does two things:
emphasizes "this is an important word to this discussion" (so important you'd want to learn it in English too)
creates a feeling of "this is a scientific explanation", and implies the presence of other information published elsewhere on the same subject that corroborates the statement
Looking on Amazon, the cover of this book has a subtitle of 「『赤い糸』の科学」 on it, so it seems to fit the context.
| {
"pile_set_name": "StackExchange"
} |
Q:
position absolute left:50% does not position span in the middle
I have a wrap div and inside I have a <span> position absolute to the wrap as it is an icon from Icomoon and I need to be part of the background. And then, at the same level that the <span>, another div, and inside this I have a <h1>, a <p>, an <input> and a <span>.
I have positioned the <span> absolute to the wrap (which it has position relative), but although I want to put it in the middle, it just needs left:26%, which is not 50% at all! So the problem becomes when I resize the screen, that it doesn't stay in the middle of the wrap.
I was wondering, why can it be caused? I posted another post a while ago because I wanted to include this problem in a JSFiddle but I couldn't work out how to include the fonts files in the JSFiddle so the icons don't appear there.
Does anyone has a slight idea about what can I do to fix it?
.containerOfSites {
display: block;
height: auto;
float: none !important;
margin: 0 auto;
}
.wrapPortalItem {
padding: 0;
}
.insideWrapItem {
text-align: center;
border: 3px solid black;
padding: 15px;
position: relative;
}
.portalItem {
background-color: rgba(255, 255, 255, 0.75);
padding-top: 3%;
padding-bottom: 10%;
font-family: 'Open Sans', sans-serif;
position: relative;
}
.portalItem p {
margin-bottom: 40%;
font-size: 30px;
padding: 5px;
}
.portalItem p>span {
font-weight: 900;
}
.portalItem span.viewMorePs {
text-decoration: none;
font-size: 18px !important;
z-index: 999;
}
.portalItem h1 {
color: #B5D803;
font-weight: 900;
text-transform: uppercase;
text-shadow: 2px 2px 0 #fff;
}
.insideWrapItem span[class^="iconI-"] {
position: absolute;
color: white;
bottom: 12%;
left: 26%; /* <- */
font-size: 14em !important;
}
<div id="portalPage" class="col-md-24">
<div class="containerOfSites col-md-18 col-sm-24">
<div class="wrapPortalItem col-md-8">
<div class="insideWrapItem">
<span class="iconI-iconDA_automotive img-responsive"></span>
<div class="portalItem portA ">
<h1>AUTOMOTIVE</h1>
<p>web sites<br /> for the<br /> <span> automotive<br /> </span> market</p>
<a href="http://motors06.denison-automotive.co.uk/denison/"><span class="viewMorePsGreen">GO</span></a>
</div>
</div>
</div>
<div class="wrapPortalItem col-md-8">
<div class="insideWrapItem">
<span class="iconI-iconDA_web"></span>
<div class="portalItem">
<h1>DESIGN</h1>
<p>web sites<br /> for the small &<br /> large business<br /> for<span> all sectors</span></p>
<a href="http://motors06.denison-automotive.co.uk/denison/denison-2/web-sites/"><span class="viewMorePsGreen">GO</span></a>
</div>
</div>
</div>
<div class="wrapPortalItem col-md-8">
<div class="insideWrapItem">
<span class="iconI-iconDA_yourbrand"></span>
<div class="portalItem">
<h1>BRANDING</h1>
<p><span>branding<br /> </span> and<br /> design</p>
<a href="http://motors06.denison-automotive.co.uk/denison/denison-2/branding/"><span class="viewMorePsGreen">GO</span></a>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
A:
It's difficult to say exactly without seeing some code, but I'd guess your problem is the the left edge of your is sitting at 50% but you want the center of the to sit in the center of it's parent?
Try something like this on the span (in addition to any other styles):
span {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
This should move (trasnlate) the half of it's own width to it's left.
| {
"pile_set_name": "StackExchange"
} |
Q:
Transitions Maps on a Vector Bundle are Linear
Let $E$ be a vector bundle, with $X$ base space and $p:E\to X$ a surjective projection.
Let $x\in X$ be given. Let $U_1, U_2$ be two neighborhoods of $x$ in $X$ which carry local trivializations, that is, $$\varphi_1:p^{-1}(U_1)\cong U_1 \times V_1$$and $$ \varphi_2:p^{-1}(U_2)\cong U_2 \times V_2$$ are two homeomorphisms, where $V_i\in obj(Vect_{\mathbb{C}})$ for $i=1,2$.
Then clearly, $$\left.\varphi_1\right|_{U_1\cap U_2}:p^{-1}(U_1)\cap p^{-1}(U_2)\cong U_1\cap U_2 \times V_1$$ and $$\left.\varphi_2\right|_{U_1\cap U_2}:p^{-1}(U_1)\cap p^{-1}(U_2)\cong U_1\cap U_2 \times V_2$$ are two homeomorphisms and thus $$\left.\varphi_2\right|_{U_1\cap U_2}\circ \left(\left.\varphi_1\right|_{U_1\cap U_2}\right)^{-1}: U_1\cap U_2 \times V_1 \cong U_1\cap U_2 \times V_2 $$ is also a homeomorphism.
If $p_2:U_1\cap U_2\times V_2 \to V_2$ is the projection onto the second component, define the map $t_x:V_1\to V_2$ by $$ V_1\ni v_1 \mapsto p_2(\left.\varphi_2\right|_{U_1\cap U_2}\circ \left(\left.\varphi_1\right|_{U_1\cap U_2}\right)^{-1}((x,v_1))) \in V_2 $$
My question is: how do you see that $t_x$ is a linear homeomorphism and not merely a homeomorphism?
A:
Note that $\varphi_i : p^{-1} (U_i) \to U_i \times V_i$ are not mere homeomorphisms: they are local trivialization. That is, the following diagram commute
$\require{AMScd}$
\begin{CD}
p^{-1}(U_i) @>\varphi_i>> U_i \times V_i\\
@V p V V\ @VV p_i V\\
U_i @>>id> U_i
\end{CD}
and $\phi_i$ is linear when restricted to each fiber. This latter fact implies that the transition map is linear.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I correctly document an extension method in C#?
I am just starting to look at the C# documentation standards. Here's a method that I have:
/// <summary>
/// Reformats a key in x.x format to 0x0x format
/// </summary>
/// <param name="dotFormatRowKey">key in ##.## format</param>
public static string DotFormatToRowKey(this string dotFormatRowKey)
{
if (! Regex.IsMatch(dotFormatRowKey, @"\d+\.\d+"))
throw new ArgumentException("Expected ##.##, was " + dotFormatRowKey);
var splits = dotFormatRowKey.Split('.')
.Select(x => String.Format("{0:d2}", Int32.Parse(x)))
.ToList();
var joined = String.Join(String.Empty, splits.ToArray())
return joined;
}
Can someone give me advice on how I should document the input and return parameters for this method. Also when I do this will the documented comments be available to a person if they use VS2010 intellisense?
A:
As for how you should document the parameters: i think thats pretty subjective but the way you did it now looks ok to me. Altho you could maybe change your return variable joined into something more verbose, like "keyFormattedString" or something.
as for the second part of your question:
Also when I do this will the documented comments be available to a
person if they use VS2010 intellisense?
Quote taken from msdn:
Extension methods are only in scope when you explicitly import the
namespace into your source code with a using directive.
If the method is inside some class in a class library, then they will have to reference that library into their current solution, in order to use/see the method and documented comments. You can basically make a new class library with all your extension methods in it, and then import that DLL to whatever solution you're working on.
Let's say that you have a class library, then you simply add
using ExtensionMethodsLib; // or whatever you'll call it
to your using statements, on whatever page you might need it.
Extension methods (msdn)
| {
"pile_set_name": "StackExchange"
} |
Q:
Define ~ on x by (a1,a2, ...) ~ (b1, b2, ...) if ai = bi for 1 <= i <= k. Find a bijection between X/~ and N x N x .... x N
Here is the full question written out:
My professor defined a bijection f: N x N x ... N -> X/~ as f((a1, ..., ak)) = (a1, ..., ak, 0, 0, ...). I do not understand how she got this bijection.
Here is her full answer if that helps:
A:
I will present an alternative solution to this problem. In the first place, recall that $X / \sim$ is the set of all equivalence classes induced by $\sim$, that is, $X / \sim$ is the collection of all the sets of the form
$$[(a_1,a_2,\dots)] = \{ (b_1,b_2,\dots) \in X :\, a_i = b_i \textrm{ for all } i=1,\dots,k \}$$
where $(a_1,a_2,\dots) \in X$. So, define $f : (X/\sim) \to \mathbb{N}^k$ by the rule
$$f \big( [(a_1,a_2,\dots)] \big) = (a_1,a_2,\dots,a_k).$$
We claim that $f$ is, in fact, a function. To see this, it suffices to prove that
$$\textrm{if $[(a_1,a_2,\dots)] = [(b_1,b_2,\dots)]$ then } f \big( [(a_1,a_2,\dots)] \big) = f \big( [(b_1,b_2,\dots)] \big), \tag{1}$$
but this is easy, since $[(a_1,a_2,\dots)] = [(b_1,b_2,\dots)]$ tell us that $(a_1,a_2,\dots) \sim (b_1,b_2,\dots)$ and then $a_i=b_i$ for $i=1,\dots,k$, that is, $(a_1,a_2,\dots,a_k) = (b_1,b_2,\dots,b_k)$. Hence, $f$ is well-defined.
Now, to prove that $f$ is a bijection, we need to prove that $f$ is injective and that is surjective. To see the injectivity, show that the converse of $(1)$ is also true. The surjectivity is also very easy, given $(c_1,c_2,\dots,c_k) \in \mathbb{N}^k$, the sequence $(c_1,c_2,\dots,c_k,0,0,\dots) \in X$ satisfies that
$$f \big( [(c_1,c_2,\dots,c_k,0,0,\dots)] \big) = (c_1,c_2,\dots,c_k)$$
showing that the image of $f$ is the whole $\mathbb{N}^k$, you agree?
Let me know if you need help showing the injectivity.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do some of my friends have yellow names, and how do I get it?
Some of the friends on my list have yellow names now. I can't seem to find out if it has to do with their status or something new added in the options, but I can't recall having seen this earlier this year.
What do these yellow names represent, and how do I get them?
A:
One of the Lunar New Year rewards introduced in this year's Lunar New Year Steam sale lets you turn your Steam profile golden for a limited time. Users with golden profiles also have their name displayed in gold, and a gold border around their profile avatar.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stormpath Rest api Java
can someone help me write this in the form of an httpRequest in java. I´ve tried many times and failed. I don´t know why but I simply can´t get it right =(
curl -X POST --user $YOUR_API_KEY_ID:$YOUR_API_KEY_SECRET \
-H "Accept: application/json" \
-H "Content-Type: application/json;charset=UTF-8" \
-d '{
"favoriteColor": "red",
"hobby": "Kendo"
}' \
"https://api.stormpath.com/v1/accounts/cJoiwcorTTmkDDBsf02bAb/customData"
(the custom data has to be in json format)
Any help would be greatly appreciated. =)
A:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"https://api.stormpath.com/v1/accounts/cJoiwcorTTmkDDBsf02bAb/customData");
String credentials = apiKey.getId() + ":" + apiKey.getSecret();
postRequest.setHeader("Authorization", "Basic " + Base64.encodeBase64String(credentials.getBytes("UTF-8")));
postRequest.setHeader("Accept", "application/json");
StringEntity input = new StringEntity("{\"favoriteColor\":\"red\",\"hobby\":\"Kendo\"}");
input.setContentType(ContentType.APPLICATION_JSON.toString());
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
System.out.println(response);
| {
"pile_set_name": "StackExchange"
} |
Q:
Display a "No Javascript" div, but not to google / facebook share service
I would like to show a div near the top of a site to suggest to visitors that do not have javascript enabled that they should enable their javascript. I thought I had found a good method by using the noscript tag.
Unfortunately I found that this solution was less than ideal because of services like Google's indexer and Facebook's link sharing functionality. These services scrape the page and read the text in the noscript div as the summary of the page. This happens because these services are not utilising javascript (obviously).
So, my question to the masses is: What techniques do you prefer for avoiding having your "please enable your javascript" messages appearing in Google's results etc.
Ideally, I'm hoping to discover the best practice for solving this issue, but am interested in hearing any techniques you have user successfully, or unsuccessfully in the past.
Thanks!
A:
In a pure HTML scenario (as tagged), consider placing your message at the bottom of the page, and using CSS to position it visibly at the top. This should push your warning far enough down the page as to avoid it showing up in typical search results.
If your HTML is generated by server script, then you may be able to conditionally present the element based on the client UserAgent. A good search engine user agent list would be convenient in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql, how to join this key id?
Forgive me, I am new to mysql
I have this mysql table:
|ID|KeyID1|KeyID2|Param|Value|...
|asdf|1|2| ...
The KeyID1 and KeyID2 values exist another Table like this:
|KeyID|Real Name|
| 1 | Gordon
| 2 | Jason
I want to be able to join the two tables together such that I would have ID|Real Name1|Real Name2|Param|Value
what would i need to do in mysql? Would I need to duplicate another table?
edit: i can change the database design
A:
This is a classic JOIN operation:
SELECT ID, tab1.RealName as RealName1, tab2.RealName as RealName2, Param, Value
FROM mytable JOIN nametable AS tab1 ON (mytable.KeyID1 = tab1.KeyID)
JOIN nametable AS tab2 ON (mytable.KeyID2 = tab2.KeyID) ;
I'm assuming that your first table is called mytable and that the name lookup table is called nametable, and I also removed the spaces from column names.
Whenever you need to replace a foreign unique identifier by values from the corresponding lookup table, it's time for a JOIN on that lookup table. If you do it multiple times from the same table, you can use aliases (AS) to disambiguate which instance you are referring to.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: Creating dummy variables for values of one variable conditional on another variable
ORIGINAL QUESTION
I want to add a series of dummy variables in a data frame for each value of x in that data frame but containing an NA if another variable is NA. For example, suppose I have the below data frame:
x <- seq(1:5)
y <- c(NA, 1, NA, 0, NA)
z <- data.frame(x, y)
I am looking to produce:
var1 such that: z$var1 == 1 if x == 1, else if y == NA, z$var1 == NA, else z$var1 == 0.
var2 such that: z$var2 == 1 if x == 2, else if y == NA, z$var2 == NA, else z$var2 == 0.
var3 etc.
I can't seem to figure out how to vectorize this. I am looking for a solution that can be used for a large count of values of x.
UPDATE
There was some confusion that I wanted to iterate through each index of x. I am not looking for this, but rather for a solution that creates a variable for each unique value of x. When taking the below data as an input:
x <- c(1,1,2,3,9)
y <- c(NA, 1, NA, 0, NA)
z <- data.frame(x, y)
I am looking for z$var1, z$var2, z$var3, z$var9 where z$var1 <- c(1, 1, NA, 0, NA) and z$var2 <- c(NA, 0, 1, 0, NA). The original solution produces z$var1 <- z$var2 <- c(1,1,NA,0,NA).
A:
You can use the ifelse which is vectorized to construct the variables:
cbind(z, setNames(data.frame(sapply(unique(x), function(i) ifelse(x == i, 1, ifelse(is.na(y), NA, 0)))),
paste("var", unique(x), sep = "")))
x y var1 var2 var3 var9
1 1 NA 1 NA NA NA
2 1 1 1 0 0 0
3 2 NA NA 1 NA NA
4 3 0 0 0 1 0
5 9 NA NA NA NA 1
Update:
cbind(z, data.frame(sapply(unique(x), function(i) ifelse(x == i, 1, ifelse(is.na(y), NA, 0)))))
x y X1 X2 X3 X4
1 1 NA 1 NA NA NA
2 1 1 1 0 0 0
3 2 NA NA 1 NA NA
4 3 0 0 0 1 0
5 9 NA NA NA NA 1
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use net user with c#
I am trying to use net user with c#
System.Diagnostics.ProcessStartInfo proccessStartInfo = new System.Diagnostics.ProcessStartInfo("net user " + id + " /domain");
proccessStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process {StartInfo = proccessStartInfo};
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
textBoxOp.Text = result;
When the I execute the code Win32 exception occurs with message The system cannot find the file specified
Details of exceptions are as follows
at
System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo
startInfo) at GetUserFromAD.Form1.GetInformation(String id) in
D:\GetUserFromAD\GetUserFromAD\Form1.cs:line 25 at
GetUserFromAD.Form1.button_Click(Object sender, EventArgs e) in
D:\Ram\MyC#\GetUserFromAD\GetUserFromAD\Form1.cs:line 35 at
System.Windows.Forms.Control.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at
System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ButtonBase.WndProc(Message& m) at
System.Windows.Forms.Button.WndProc(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at GetUserFromAD.Program.Main()
in D:\Ram\MyC#\GetUserFromAD\GetUserFromAD\Program.cs:line 18 at
System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
A:
net is the command. Everything from user onwards are command arguments. As such, you'll need to use the following constructor:
System.Diagnostics.ProcessStartInfo proccessStartInfo = new System.Diagnostics.ProcessStartInfo("net", "user " + id + " /domain");
In addition, in order to capture the standard output you'll need to set the following properties before you call proc.Start()
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
| {
"pile_set_name": "StackExchange"
} |
Q:
Pipeline Release's to environment fail tests
In our release pipeline within TFS (on prem) the Run Functional test task are having redundant logs with "Test run is in 'InProgress' state ".
After several repetition (some times up to the time-out level) of the same message the test is aborted causing the task to be failed. Reattempting would execute test case to success. We do not have this issue on our build server only when we test what we have released to an environment.
We want to know the root cause and resolution for this issue.
We do have a Test Agent installed on the Server so that the test are performed there.
Here is an example of what we sometimes see that is causing the issue.
2019-10-02T15:08:02.6850117Z DistributedTests: build id: 6374
2019-10-02T15:08:02.6850117Z DistributedTests: test configuration mapping:
2019-10-02T15:08:02.9506501Z DistributedTests: Test Run with Id 3439 Queued
2019-10-02T15:08:03.0450717Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:08:13.1288425Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:08:23.1965836Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:08:33.2571132Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:08:43.3372572Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:08:53.4159907Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:09:03.4760176Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:09:13.5396749Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:09:23.5995694Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:09:33.6578911Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:09:43.7221898Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:09:53.8077140Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:10:03.8614622Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:10:13.9438805Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:10:24.0015664Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:10:34.0601261Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:10:44.1201041Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:10:54.1826966Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:11:04.2538091Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:11:14.3385817Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:11:24.3927960Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:11:34.4611704Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:11:44.5277491Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:11:54.5927946Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:12:04.6715006Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:12:14.7412140Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:12:24.8137052Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:12:34.8707487Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:12:44.9422325Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:12:55.0129476Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:13:05.1284906Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:13:15.1900203Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:13:25.2565799Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:13:35.3280345Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:13:45.3982751Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:13:55.4603385Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:14:05.5207280Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:14:15.5857792Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:14:25.6530083Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:14:35.7347753Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:14:45.7941659Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:14:55.8551101Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:15:05.9238471Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:15:15.9829484Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:15:26.0513261Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:15:36.1212279Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:15:46.2300557Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:15:56.2810072Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:16:06.3525471Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:16:16.4174982Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:16:26.4911422Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:16:36.5562109Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:16:46.6349393Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:16:56.6933076Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:17:06.7679881Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:17:16.8282799Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:17:26.8957535Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:17:36.9561716Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:17:47.0226277Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:17:57.0822145Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:18:07.1718473Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:18:17.2482416Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:18:27.3100487Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:18:37.3705919Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:18:47.4270207Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:18:57.4878769Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:19:07.5784610Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:19:17.6583487Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:19:27.7184931Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:19:37.7861986Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:19:47.8453393Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:19:57.9135570Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:20:07.9783979Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:20:18.0400239Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:20:28.1168838Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:20:38.1722693Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:20:48.2345722Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:20:58.2978591Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:21:08.3585618Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:21:18.4180230Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:21:28.4809123Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:21:38.5409894Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:21:48.6067102Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:21:58.6745500Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:22:08.7298142Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:22:18.8020461Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:22:28.8787059Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:22:38.9554949Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:22:49.0238237Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:22:59.0795040Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:23:09.1508546Z DistributedTests: Test run '3439' is in 'InProgress' state.
2019-10-02T15:23:19.2118167Z DistributedTests: Test run '3439' is in 'Aborted' state.
2019-10-02T15:23:29.2214050Z ##[warning]DistributedTests: Test run is aborted. Logging details of the run logs.
2019-10-02T15:23:29.2370197Z ##[warning]DistributedTests: New test run created.
2019-10-02T15:23:29.2370197Z Test Run queued for Project Collection Build Service (EnterpriseA).
2019-10-02T15:23:29.2370197Z
2019-10-02T15:23:29.2370197Z ##[warning]DistributedTests: Test discovery started.
2019-10-02T15:23:29.2370197Z ##[warning]DistributedTests: UnExpected error occured during test execution. Try again.
2019-10-02T15:23:29.2370197Z ##[warning]DistributedTests: Error : Some tests could not run because all test agents of this testrun were unreachable for long time. Ensure that all testagents are able to communicate with the server and retry again.
2019-10-02T15:23:29.2370197Z
2019-10-02T15:23:29.2370197Z ##[warning]DistributedTests: Test run aborted. Test run id: 3439
2019-10-02T15:23:29.2370197Z ##[error]System.Exception: The test run was aborted, failing the task.
2019-10-02T15:23:29.2838927Z ##[error]PowerShell script completed with 1 errors.
A:
This is a known issue for Run Functional test task. A single test run timed out cause that test run aborted, finally fail the task.
We have fixed this issue and it's available in TFS 2018 Update 1 and
VSTS.
We are asking folks to move to the VsTest v2 task that is capable of
parallel execution both in release and build.
For more detail info you could refer below two similar questions:
Run Functional Tests: The test run was aborted, failing the task
Release: Run Functional Tests Task Issue: The test run was aborted,
failing the task - DistributedTests: Test run timed out
According to your tag, seems you are still working on TFS2017. Unfortunately, there isn't any better workaround expect reattempt as you pointed out in question.
Suggest you upgrade to TFS 2018 and use 2.x or higher Visual Studio Test task instead.
Run Functional test task is deprecated in Azure Pipelines and TFS 2018 and later. Use version 2.x or higher of the Visual Studio Test task together with jobs to run unit and functional tests on the universal agent.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Network Transparent Boolean Logic Evaluator
Write an expression evaluator for boolean expressions encoded as JSON. Read on for explanation and rules.
Motivation:
Consider a scenario where two agents (Alice and Bob) are communicating with each other under the following constraints:
All communication must be done as valid JSON strings (no JSONP or extensions), because Bob and Alice love JSON. They have had problems with character encoding in the past, so they have decided to restrict themselves to ASCII.
Alice needs Bob to notify her in case a certain condition is met, but:
Bob doesn't know what the condition is in advance.
Alice can't evaluate the condition herself because it requires information that only Bob has.
The status of the variables can change rapidly enough (and the network is slow enough) that it would be infeasible for Bob to continuously transmit the data to Alice.
Neither knows anything about the implementation of the other agent (for example, they can't make assumptions about the implementation language of the other agent).
Alice and Bob have worked out a protocol to help them complete their task.
Representing Conditional Expressions:
They have agreed to represent Boolean literals by strings, for example "foo" or "!bar", where ! represents the negation of a literal, and valid names contain only letters and numbers (case sensitive, any strictly positive length; "" and "!" are not valid; i.e. a literal is a string whose contents match the regex /^!?[a-zA-Z0-9]+$/).
Expressions are only transmitted in negation normal form. This means that only literals can be negated, not subexpressions.
Expressions are normalized as a conjunction of disjunctions of conjunctions of disjunctions ... etc encoded as nested arrays of strings. This needs a bit more explanation, so...
Expression Syntax:
Consider the following boolean expression:
(¬a ∧ b ∧ (c ∨ ¬d ∨ e ∨ ¬f) ∧ (c ∨ (d ∧ (f ∨ ¬e))))
Notice that the entire expression is contained in parentheses. Also notice that the first level(and all odd levels) contains only conjunctions(∧), the second level(and all even levels) contains only disjunctions(∨). Also notice that no subexpression is negated. Anyway meat and potatoes... This would be represented by Alice in JSON as:
["!a","b",["c","!d","e","!f"],["c",["d",["f","!e"]]]]
Another example:
((a ∨ b ∨ c))
Becomes:
[["a","b","c"]]
In summary: [] are interpreted as parentheses, literals are wrapped in "",! means negation, and , means AND or OR depending on nesting depth.
NB: the empty conjunction (the result of ANDing no variables) is true, and the empty disjunction (the result of ORing no variables) is false. They are both valid boolean expressions.
Bob's data:
Bob's data is emitted by a program on his computer as a simple JSON object as key-value pairs, where the key is the name of the variable, and the value is either true or false. For example:
{"a":false,"b":true,"c":false}
Bob needs our help!
Bob has little programming experience, and he's in over his head. He has handed you the task.
You need to write a program that accepts the JSON text that Alice sent along with the JSON text for Bob's data, and evaluates the expression with those values, returning true or false (the actual strings true and false; Bob and Alice love JSON, remember?)
Bob says less is more, so he wants you to make your source code as short as possible (this is a code-golf)
You are allowed to use an external library to parse the JSON text, but this is the only exception. Only standard library functionality is allowed.
Note that the JSON is accepted and returned as a string. There is no requirement to explicitly parse it though, if you can get it to always work without doing so.
If Alice uses a variable that Bob doesn't know, assume it is false. Bob's data may contain variables that Alice doesn't use.
If Alice's or Bob's JSON Object contains an invalid literal, or the JSON is invalid, or it contains a non ASCII character, then your program must return null
Some test cases(in JSON):
[
{"alice":"[\"\"]","bob":"{}","result":"null"},
{"alice":"[\"!\"]","bob":"{}","result":"null"},
{"alice":"[\"0\"]","bob":"{\"0\":true}","result":"true"},
{"alice":"[]","bob":"{}","result":"true"},
{"alice":"[[]]","bob":"{}","result":"false"},
{"alice":"[\"a>\"]","bob":"{\"a\":true}","result":"null"},
{"alice":"[\"0\"]","bob":"{}","result":"false"},
{"alice":"[\"0\"]","bob":"","result":"null"},
{"alice":"[\"1\"]","bob":"{\"1\":false}","result":"false"},
{"alice":"[\"true\"]","bob":"{\"true\":false}","result":"false"},
{"alice":"[\"foo\",\"bar\",\"baz\"]","bob":"{\"foo\":true,\"bar\":true,\"biz\":true}","result":"false"},
{"alice":"[[[\"a\",[\"!b\",\"c\"],\"!c\"],\"d\"]]","bob":"{\"a\":true,\"b\":false,\"c\":true,\"d\":false}","result":"false"},
{"alice":"[\"!a\",\"b\",[\"c\",\"!d\",\"e\",\"!f\"],[\"c\",[\"d\",[\"f\",\"!e\"]]]]","bob":"{\"a\":false,\"b\":true,\"c\":true,\"e\":true,\"f\":false}","result":"true"}
]
As can be seen from the test cases, input and output are strings that are correctly parseable JSON. The empty string test case for bob was originally in error, the correct value to return is null, but if it saves you characters to return false, then that is also acceptable. I added cases for the empty clauses to make that explicit. I added another 2 test cases in response to a bug I found in someone's implementation
A:
ECMASCript 6 variation, 213 194 190 189 192 166 chars
try{P=_=>JSON.parse(prompt())
B=P()
f=(a,c)=>a[c?'some':'every'](v=>v.big?[B][+/\W|_/.test(s=v.slice(C=v[0]=='!'))-!s][s]^C:f(v,!c))
q=f(P())}catch(_){q=null}alert(q)
Note: takes Bob's input first, and then Alice's input. This saves us four bytes.
Checks for syntactically valid JSON since JSON.parse throws if it isn't.
Since we're already relying on the try-catch for the above, we (ab)use out-of-bounds access to trigger our "failed validation" path when validating the (possibly negated) literals
This is accomplished with the [B][...][s] part (thanks, @l4m2! used to use a slightly more verbose construction)
The -!s is to catch "" and "!" as invalid literals
The C variable holds the "should negate" state, which is accomplished with a "bitwise" XOR (and relies on implicit type coercion)
ES5 solution: https://codegolf.stackexchange.com/revisions/19863/8
A:
Ruby, 335 (327?) characters
begin;a,b=*$<;require'json';b=JSON[b];q if a=~/{|}/||!a[?[]||b.any?{|v,x|v=~/[\W_]/||x!=!!x}
l=0;a.gsub!(/\[|\]/){"[{}]"[($&==?]?2:0)+l=1-l]};a.gsub!(/"(!)?([a-z\d]+)"/i){b[$2]^$1}
0 while [[/\[[#{f=!1},\s]*\]/,f],[/{[#{t=!f},\s]*?}/,t],[/\[[\w,\s]*\]/,t],[/{[\w,\s]*}/,f]].any?{|k,v|a.sub!(k){v}}
rescue a=??;end;puts a=~/\W/?"null":a
I've heard you can't parse HTML with Regex, but I've never been told you cannot parse JSON this way, so I tried.
Alice's input is separated from Bob's input by a newline; also, it's assumed that neither input contains newlines itself. This assumption is for I/O purposes only, and is not used later. If I can make an extra assumption that Alice's input contains no whitespace, we can drop 8 characters by removing all \s's on line #3. If we can only assume it contains no whitespace but spaces, we can still replace \s's with the space characters to save 4 characters.
A:
Python 3 (429)
Longer than the other answers, but arguably the most readable so far... :)
import json,sys,re
r,p,m='^!?[a-zA-Z\d]+$',print,re.match
def g(a,b,s):
if type(a)is str:
if m(r,a):
try:return('not '+str(b[a[1:]]))if a[0]=='!'else str(b[a])
except:return'False'
raise Exception
return'('+((' and 'if s else' or ').join(g(x,b,not s)for x in a))+')'
s,j=sys.argv,json.loads
try:
a,b = j(s[1]),j(s[2]or'{}');
if all(m(r,x)and x[0]!='!'for x in b):p(str(eval(g(a,b,1))).lower())
except:
p('null')
| {
"pile_set_name": "StackExchange"
} |
Q:
How to query a constexpr std::tuple at compile time?
In C++0x, one can create a constexpr std::tuple, e.g. like
#include <tuple>
constexpr int i = 10;
constexpr float f = 2.4f;
constexpr double d = -10.4;
constexpr std::tuple<int, float, double> tup(i, f, d);
One also can query a std::tuple at runtime, e.g. via
int i2 = std::get<0>(tup);
But it is not possible to query it at compile time, e.g.,
constexpr int i2 = std::get<0>(tup);
will throw a compilation error (at least with the latest g++
snapshot 2011-02-19).
Is there any other way to query a constexpr std::tuple at compile time?
And if not, is there a conceptual reason why one is not supposed to query it?
(I am aware of avoiding using std::tuple, e.g., by using boost::mpl
or boost::fusion instead, but somehow it sounds wrong not to use the tuple class
in the new standard...).
By the way, does anybody know why
constexpr std::tuple<int, float, double> tup(i, f, d);
compiles fine, but
constexpr std::tuple<int, float, double> tup(10, 2.4f, -10.4);
not?
Thanks a lot in advance!
- lars
A:
std::get is not marked constexpr, so you cannot use it to retrieve the values from a tuple in a constexpr context, even if that tuple is itself constexpr.
Unfortunately, the implementation of std::tuple is opaque, so you cannot write your own accessors either.
| {
"pile_set_name": "StackExchange"
} |
Q:
Silverlight element binding not working
I have a window that I want to appear to the left of existing content and am using element binding to do so. This works perfectly in WPF but in Silverlight the window simply goes to the far right of the Canvas control its in and I dont know why?
<Grid x:Name="rightPanelGrid" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="10,10,10,0">
<!-- Other xaml -->
<local:mywindow IToolkit:CanvasControl.Right="{Binding ElementName=rightPanelGrid, Path=ActualWidth}"
A:
Silverlight does not support binding to ActualWidth like this :(
For purposes of ElementName binding, ActualWidth does not post updates when it changes (due to its asynchronous and run-time calculated nature). Do not attempt to use ActualWidth as a binding source for an ElementName binding. If you have a scenario that requires updates based on ActualWidth, use a SizeChanged handler.
| {
"pile_set_name": "StackExchange"
} |
Q:
System.Net.Dns.GetHostAddresses("")
I have an application I have been working on and it can be slow to start when my ISP is down because of DNS. My ISP was down for 3 hours yesterday, so I didn't think much about this piece of code I had added, until I found that it is always slow to start. This code is supposed to return your IP address and my reading of the link suggests that should be immediate, but it isn't, at least on my machine.
Oh, and yesterday before the internet went down, I upgraded (oymoron) to XP SP3, and have had other problems.
So my questions / request:
Am I doing this right?
If you run this on your machine does it take 39 seconds to return your IP address? It does on mine.
One other note, I did a packet capture and the first request did NOT go on the wire, but the second did, and was answered quickly. So the question is what happened in XP SP3 that I am missing, besides a brain.
One last note. If I resolve a FQDN all is well.
Public Class Form1
'http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx
'
'excerpt
'The GetHostAddresses method queries a DNS server
'for the IP addresses associated with a host name.
'
'If hostNameOrAddress is an IP address, this address
'is returned without querying the DNS server.
'
'When an empty string is passed as the host name,
'this method returns the IPv4 addresses of the local host
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim stpw As New Stopwatch
stpw.Reset()
stpw.Start()
'originally Dns.GetHostEntry, but slow also
Dim myIPs() As System.Net.IPAddress = System.Net.Dns.GetHostAddresses("")
stpw.Stop()
Debug.WriteLine("'" & stpw.Elapsed.TotalSeconds)
If myIPs.Length > 0 Then Debug.WriteLine("'" & myIPs(0).ToString)
'debug
'39.8990525
'192.168.1.2
stpw.Reset()
stpw.Start()
'originally Dns.GetHostEntry, but slow also
myIPs = System.Net.Dns.GetHostAddresses("www.vbforums.com")
stpw.Stop()
Debug.WriteLine("'" & stpw.Elapsed.TotalSeconds)
If myIPs.Length > 0 Then Debug.WriteLine("'" & myIPs(0).ToString)
'debug
'0.042212
'63.236.73.220
End Sub
End Class
A:
See post #7 here Fix
| {
"pile_set_name": "StackExchange"
} |
Q:
count number of (pid) variables in an array?
I'm trying to count the number of ruby scripts I am running in a batch script.
I can get the script to list the numbers, but how do I count them. Ideally, I would receive an alert when the number of PIDs has decreased.
Thank you!
@Echo off & SetLocal EnableDelayedExpansion
set "RUBY="
for /f "tokens=2" %%A in ('tasklist ^| findstr /i "ruby.exe" 2^>NUL') do
@Set "PID=!PID!,%%A"
if defined PID Echo cmd.exe has PID(s) %PID:~1%
echo ${#PID[@]}
pause
A:
If you just want to know how many instances of a program is running then use the count functionality of the FIND command.
FOR /F "delims=" %%G IN ('tasklist ^|find /I /C "ruby.exe"') do set count=%%G
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference in adding of elements to linked list
This is how i add elements to the head of a linked list
//typedef void* VoidPtr
//typedef node* NodePtr
struct Node
{
NodePtr next
VoidPtr data
};
void LinkedList::Addelement(VoidPtr horoscope)
{
if(head == NULL)
{
head = new Node;
head->data = horoscope;
head->next = NULL;
}
NodePtr temp = new Node;
temp -> data = horoscope;
temp -> next = head;
head = temp;
}
This is how i add elements to the tail of a linked list
void LinkedList::addelementfromback(VoidPtr horoscope)
{
NodePtr temp=head;
if(head == NULL)
{
head = new Node;
head->data = horoscope;
head->next = NULL;
}
while( temp->next != NULL)
{
temp=temp->next
}
NodePtr element=New Node;
element->data=horoscope;
element->next=NULL;
temp->next=element;
}
i dont understand why we use temp=element for adding to the head of a linked list
but for adding to the tail of a linked list we use temp->next=element. I dont understand why we cant use while temp=next for adding element to tail of linked list
A:
In your Addelement method, you need an else clause because if the list is empty (head == NULL), you only need to point the head to the new node. Nothing else, there are no other nodes in the list.
Also, rather than using a void pointer, consider using templates. Templates are great for data structures and algorithms where the data type changes, not the structure or algorithm, such as stacks and linked lists.
I suggest you consider separating the node pointers from the data item as two separate structures. This will help you use common code between single linked lists and doubly linked lists. Also a great help when you don't want to use templates.
struct Node_Link
{
Node_Link * next;
};
struct Node_Integer
: public Node_Link
{
int data;
};
struct Node_Double
: public Node_Link
{
double data;
};
struct Node_String
: public Node_Link
{
std::string data;
};
| {
"pile_set_name": "StackExchange"
} |
Q:
edittext crashing application
i have 1 edittext with number input only.the problem is,suppose user types 1234 no in it and afterwrds if he wants to change it and for that when he wil press del key tat time wen he cmes at 2 and press one more time del key,application crashes.and i tried handling if edittext text length 0 case also but stil not wrkng
here is my code
input.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
final String in= input.getText().toString();//input is edittext
final int j=in.length();
Cursor ansof1=(Cursor) mSpinner.getSelectedItem();//1st spinner tks 1 value
String temp=ansof1.getString(1);
Cursor ansof2=(Cursor)mSpinner2.getSelectedItem();//for 2 spinner
String temp2=ansof2.getString(1);
Cursor cn = myDbHelper.selectcur(temp);
double ans1=cn.getDouble(3);
Cursor cm=myDbHelper.selectcur(temp2);
double ans2=cm.getDouble(3);
no = Integer.parseInt(in);
final double finalans=((ans1/ans2)*no);
NumberFormat formatter = new DecimalFormat("##,##,###");
if(temp.equalsIgnoreCase(temp2))
{
//dlgAlert.setMessage("OOpss..!! Both Currencies Are Same...!!");
text1.setText(no+" "+temp+" "+"="+" "+no+" "+temp2);
//dlgAlert.create().show();
}
else
text1.setText(no+" "+temp+" "+"="+" "+formatter.format(finalans)+" "+temp2);
}
@Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
// TODO Auto-generated method stub
}
});
A:
It's because you try to convert empty string to number. So check for length of string like this,
input.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
if(s.length()==0)
{
return;
}
else
{
// your code here
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Which one is more efficient: boolean or binary integer?
I have to store a binary value in a variable or an array element, to indicate that an option is enabled or disabled.
I believe using "Yes" or "No" is less efficient than 1 or 0 (or empty), but I wonder whether there's any difference between 1/0 and TRUE/FALSE, in terms of performance or memory usage or anything else.
Between
$option = 1; # if the option is enabled
$option = 0; # if the option is disabled OR
$option = ""; # if the option is disabled
and
$option = TRUE; # if the option is enabled
$option = FALSE; # if the option is disabled
which way is recommended? Why?
Thanks.
A:
This answer1 suggests that zero, null and empty are equivalent, and this answer2 suggests that 1 and true are equivalent.
| {
"pile_set_name": "StackExchange"
} |
Q:
IPhone: How to Switch Between Subviews That Were Created in Interface Builder
So I basically have two subviews within my main view. I created each subview by going to the library in IB and dragging a view onto my main nib file and then positioning controls on them.
Now, I'd like to flip between these views via a "flip" button. What I don't understand is how I can programmatically do this.
My question is: do I "Hide" one of the subviews and then unhide it someway programmatically when I do the flip? Do I give each a name via the Interface Builder and do it that way? I don't really need the code to actually do the flip or anything, I just need a conceptual understanding of how I'd refer to views built in IB programmatically and if hiding makes sense in my scenerio...
Any suggestions? thanks
A:
You connect to things in IB by using
IBOutlet UIView *myView;
or
@property (nonatomic, retain) IBOutlet UIView *myView;
in your header file. The IBOutlet keyword tells IB to make that outlet available to connect.
You make the actual connection in the Connection inspector by dragging from the outlet to the view:
making a connection http://cl.ly/eb3b5cd826b20fc9e307/content
(Do this for both your views.)
Note: your views don't have to be inside the window in IB. You can create them outside, and they won't be displayed until you want them to. You might want to put one of them in so it shows up when your app launches.
Then, when you actually want to flip to the other view, assuming you're using iOS 4.0, it's simple (there are methods for 3.x and lower, but this is the easiest):
[UIView transitionFromView:myView1
toView:myView2
duration:0.2
options:UIViewAnimationOptionTransitionFlipFromRight
completion:^{
// something to do when the flip completes
}];
Or, if you want to dynamically determine which view is already visible:
UIView *oldView, *newView;
UIViewAnimationOptions transition;
if (myView1.superview) { // view 1 is already visible
oldView = myView1;
newView = myView2;
transition = UIViewAnimationOptionTransitionFlipFromRight;
} else { // view 2 is visible
oldView = myView2;
newView = myView1;
transition = UIViewAnimationOptionTransitionFlipFromLeft;
}
[UIView transitionFromView:oldView
toView:newView
duration:0.2
options:transition
completion:^{
// something to do when the flip completes
}];
| {
"pile_set_name": "StackExchange"
} |
Q:
Find JSON value for a specific key in Nested JSON with unstructured keys using underscore
I have a Nested JSON object and I want to find the value of the specific key in it. let's say JSON is like this:
var data={
name:"dsd",
work: "abcd",
address:{
street:"wewe 32",
apt: 12,
city: "ca",
geo:{
lat: 23.4332,
lng: 132.232
},
hobbies:["play","sing"]
}
}
Now if I want to find the value of "city", then it should give me "ca", If I want to find the value of "lng" then it should return 132.232. if I want to find the value of "hobbies" it should give me [play, sing]. How can I get this? Solution using underscore or lodash will be appreciated.
A:
You can achieve this by recursively iterating over lodash#some. Check the comments below for guidance.
function getValueByKey(object, key) {
// The resulting value of a matched key
var result;
// Use _.some as an iterator, to stop the iteration
// and recursion once a match is found. Also, name
// the predicate function for recursion.
_.some(object, function matchKey(value, $key) {
if ($key === key) { // is key a match?
result = value; // set the result
return true; // this stops the iteration and recursion
} else if (_.isObject(value)) { // is value an object?
// recursively match the keys all over again
return _.some(value, matchKey);
}
});
// return matched result
return result;
}
var data = {
name: "dsd",
work: "abcd",
address: {
street: "wewe 32",
apt: 12,
city: "ca",
geo: {
lat: 23.4332,
lng: 132.232
},
hobbies: ["play", "sing"]
}
};
function getValueByKey(object, key) {
// The resulting value of a matched key
var result;
// Use _.some as an iterator, to stop the iteration
// and recursion once a match is found. Also, name
// the predicate function for recursion.
_.some(object, function matchKey(value, $key) {
if ($key === key) { // is key a match?
result = value; // set the result
return true; // this stops the iteration and recursion
} else if (_.isObject(value)) { // is value an object?
// recursively match the keys all over again
return _.some(value, matchKey);
}
});
// return matched result
return result;
}
console.log('hobbies:', getValueByKey(data, 'hobbies'));
console.log('geo:', getValueByKey(data, 'geo'));
console.log('lng:', getValueByKey(data, 'lng'));
.as-console-wrapper {
min-height: 100%;
top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Alternative: Here's a non-recursive vanilla javascript solution:
function getValueByKey(object, key) {
// simulate recursion by stacking
var stack = [object];
var current, index, value;
// keep iterating until the stack is empty
while (stack.length) {
// take the head of the stack
current = stack.pop();
// iterate over the current object
for (index in current) {
// get value of the iterated object
value = current[index];
// is it a match?
if (key === index) {
return value; // return the matched value
}
// value must be an object and not a null value
// to be subject for the next stack iteration
else if (value !== null && typeof value === 'object') {
// add this value in the stack
stack.unshift(value);
}
}
}
}
var data = {
name: "dsd",
work: "abcd",
address: {
street: "wewe 32",
apt: 12,
city: "ca",
geo: {
lat: 23.4332,
lng: 132.232
},
hobbies: ["play", "sing"]
}
}
function getValueByKey(object, key) {
// simulate recursion by stacking
var stack = [object];
var current, index, value;
// keep iterating until the stack is empty
while (stack.length) {
// take the head of the stack
current = stack.pop();
// iterate over the current object
for (index in current) {
// get value of the iterated object
value = current[index];
// is it a match?
if (key === index) {
return value; // return the matched value
}
// value must be an object and not a null value
// to be subject for the next stack iteration
else if (value !== null && typeof value === 'object') {
// add this value in the stack
stack.unshift(value);
}
}
}
}
console.log('hobbies:', getValueByKey(data, 'hobbies'));
console.log('geo:', getValueByKey(data, 'geo'));
console.log('lng:', getValueByKey(data, 'lng'));
.as-console-wrapper { min-height: 100%; top: 0; }
| {
"pile_set_name": "StackExchange"
} |
Q:
Как добавить на изображение строчку текста? Python
Есть картинка, требуется на нее добавить строчку текста, которую можно задать. Как это сделать с помощью Python? Требуется создать бота для ВК, на примере вот это бота. https://vk.com/memes_bot
A:
Например, используйте библиотеку PIL.
Самый простой пример рисования:
# pip install Pillow
from PIL import Image, ImageDraw, ImageFont
image = Image.open("images.jpg")
font = ImageFont.truetype("arial.ttf", 25)
drawer = ImageDraw.Draw(image)
drawer.text((50, 100), "Hello World!\nПривет мир!", font=font, fill='black')
image.save('new_img.jpg')
image.show()
Скриншот:
| {
"pile_set_name": "StackExchange"
} |
Q:
I'm Indonesian, can I leave Frankfurt airport without a visa when I'm waiting for a connecting flight to London?
So far I know that Indonesians need a visa to visit Germany (EU) however I will have a UK visa on my passport, and a ticket (connecting flight to London), and my question is pretty obvious:
Are all those documents good enough to pass through immigration? Or do I need to apply for a German visa in the German embassy for a really short visit? or is there some special counter that can do a visa on arrival in the airport? Can anyone give me an answer?
A:
As an Indonesian Citizen transiting Germany when travelling between two non-Schengen countries you do not need a visa, presuming you are passing through one of the following airports :
Cologne/Bonn (CGN), Frankfurt (FRA), Munich (MUC), Hamburg (HAM), or Dusseldorf (DUS).
When traveling through these airports you will be able to "Transit Without Visa" (TWOV), however as you will not have a Visa you will have to remain "airside" and will not be allowed to pass through 'Passport Control' and enter the country.
If you wish to enter Germany, even briefly, you will require a Visa. Visa's are NOT available at the airport, and would need to be arranged in advance.
If you are travelling through Berlin Tegel (TXL) then you MAY also be able TWOV, however it depends on the exact details of your arrival/departure, and you should contact your airline to confirm what is required.
| {
"pile_set_name": "StackExchange"
} |
Q:
The TCP/IP connection to the host localhost, port 1433 has failed error, need assistance
Full error I'm getting:
The TCP/IP connection to the host localhost, port 1433 has failed. Error: "connect timed out. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
I have already checked that TCP/IP is enabled, using port 1433, and TCP dynamic ports is empty. I have disabled windows firewall.
Here is my code:
import java.sql.*;
public class DBConnect {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=TestDB1;instance=SQLSERVER;encrypt=true;TrustServerCertificate=true;";
String user = "sa";
String pass = "";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection myConn = DriverManager.getConnection(dbURL, user, pass);
try {
Statement myStmt = myConn.createStatement();
try {
ResultSet myRs = myStmt.executeQuery("Select * from Login");
while (myRs.next())
{
System.out.println(myRs.getString("Username"));
System.out.println(myRs.getString("Password"));
}
}
catch (Exception e)
{
System.out.println("Error with query");
}
}
catch (Exception e)
{
System.out.println("Error connecting to database");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
A:
Have you enabled 'Named Pipes' and 'TCP/IP'?
Open the 'Sql Server Configuration' application.
In the left pane, go to 'SQL Server Network Configuration' -> 'Protocols for [instance-name]'
Right-click on both 'Named Pipes' and 'TCP/IP' and select 'enable'.
Have you used the correct port?
Double-click on 'TCP/IP'
Select 'IP Addresses' tab
Scroll to IPAII. Your port number is here.
Restart the 'SQL Server ([instance-name])' windows service.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a best practice to fix a bug in an old release version?
I have a GitHub project with few releases:
1.0
1.5
2.0
2.1
I was asked to fix a bug in version 1.5. What is the best practice to do it?
Shall I check out the 1.5, fix the bug and push it as 1.5.1?
Is this a proper way?
A:
Yes, this is exactly what you should be doing. Since you won't be able to change the commit the tag refers to without major ramifications, branching off of the tag is the most logical solution here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert a vertical string in a list?
d = {'Banana' : {'price': 7, 'Color' : "yellow"},
'Apple' : {'price' : 8, 'Color': "green"}, 'Orange' :{'price' : 6, 'Color': "orange"}}
for fruit, props in dict.iteritems():
prices= str(props['price']):
Now I want to have the price of each fruit in a list
print prices
6
7
8
But if I use split(), I get:
print prices.split()
['6']
['7']
['8']
And what I really want is [6,7,8].
Can someone help me?
A:
You can use str.splitlines. From the documentation:
Return a list of the lines in the string, breaking at line boundaries.
You can use it like this:
>>> mystring = """1
2
3"""
>>> mylist = mystring.splitlines()
>>> print(mylist)
['1', '2', '3']
And since you want the lines as integers:
>>> mylist = [int(i) for i in mystring.splitlines()]
>>> print(mylist)
[1, 2, 3]
Keep in mind that you'll get an error if any line is not a integer or float.
EDIT (after the post revision):
It seems like your main problem is the for loop. You are setting prices on each iteration, overwriting the last. You should use something like this:
prices = []
for fruit, props in d.iteritems():
prices.append(props['price'])
Then you have a list, looking like this:
[8, 6, 7]
Notice it has no order. This is because dictionaries are unstructured data types. From the docs:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
If you want, you could sort your prices:
Least to Greatest
>>> sorted(prices)
[6, 7, 8]
Greatest to Least
>>> sorted(prices, reverse=True)
[8, 7, 6]
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a (good) struct from a javascript typed array?
I'm thinking about typed arrays in javascript; in particular, reading binary file headers. Reading the MDN Typed Arrays documentation, they blithely say we can represent the C struct:
struct someStruct {
unsigned long id;
char username[16];
float amountDue;
};
with the javascript:
var buffer = new ArrayBuffer(24);
// ... read the data into the buffer ...
var idView = new Uint32Array(buffer, 0, 1);
var usernameView = new Uint8Array(buffer, 4, 16);
var amountDueView = new Float32Array(buffer, 20, 1);
and then you can say amountDueView[0] but seem oblivious to the fact that treating a scalar as a one-element array is terrible and being able to say something like sizeof(someStruct) is useful as well.
So... is there something better? MDN makes reference to js-ctypes but it's no standard javascript.
Edit: Yes, I know about javascript objects. Modeling the data isn't the problem; reading and writing binary data elegantly is.
A:
For what it's worth, there's jBinary, which lets you do stuff like:
var binary_data = '\x0f\x00\x00\x00Bruce\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xecQXA';
var myTypeset = {
'jBinary.all': 'someStruct',
'jBinary.littleEndian': true,
someStruct: {
id: 'uint32',
username: ['string0', 16],
amountDue: 'float'
}
};
var binary = new jBinary(binary_data, myTypeset);
header = binary.readAll(); // Object {id: 15, username: "Bruce", amountDue: 13.520000457763672}
header.username = "Jim";
binary.writeAll(header);
binary.readAll(); // Object {id: 15, username: "Jim", amountDue: 13.520000457763672}
It's not particularly well-documented (an example like the above would be very welcome) but it's quite good.
The biggest caveat is that it relies on javascript objects having properties remain in the order they're defined, which is practically the case but not part of the javascript spec. I suspect this will never actually change because it would break a kajillion things, but still.
| {
"pile_set_name": "StackExchange"
} |
Q:
Populating textbox ng attributes from within directive
A JSFiddle is here:
http://jsfiddle.net/DfLdF/
The problem description is as follows, I have a controller wrapping a form which contains some logic, and can not be defined within the directive hash as controller:
I need the ability to populate a field from a directive dynamically like so:
App.Directive.SomeAwesomeDirective = ->
restrict: 'C'
link: (scope, element, attrs) ->
someValue = scope.someValue
field = element.find(".some-class")
scope.fieldValue = someValue
field.ngModel = "scope.fieldValue"
field.ngClass = "scope.someAwesomeClass"
monitorFields = (newValue, oldValue) ->
console.log "we are here"
console.debug newValue
console.debug oldValue
scope.addValue(newValue)
scope.$watch "scope.fieldValue", monitorFields, true
I need the following to be fulfilled:
1) When the textfields value is changed, I want scope.fieldValue to be updated.
2) After this happens, I want the addValue method (defined on the wrapping controller), to be called with the new value for validation.
3) The addValue method should set the someAwesomeClass scope variable, and the input fields class should update.
4) The ngClasses to be applied are ng-valid/ng-invalid. Form validation should function correctly in correspondence with these classes
As can be seen in my jsfiddle, none of these things are currently happening, and I am unsure as to why...
Thanks!
A:
You can fix it by defining a directive someClass, which will execute the function on its parent. The form tag gets an extra attribute execute, which holds the function to execute. The someClass directive will search the controller of dir directive (hence require: '^dir') and execute it.
Another solution would have been to drop the dir directive and define the execute attribute on the someClass directive (e.g. when each input field should trigger a different function).
<form class="dir" execute="someFunction">
Directives:
app.directive('dir', function () {
return {
restrict: 'C',
scope: {
execute: '='
},
controller: function ($scope) {
this.execute = $scope.execute;
}
};
});
app.directive('someClass', function () {
return {
restrict: 'C',
require: '^dir',
replace: true,
template: '<INPUT name="foo" id="bar" type="text" ng-model="fieldValue" >',
scope: {
fieldValue: '@'
},
link: function (scope, elm, attrs, ctrl) {
var monitorField = function (newValue, oldValue) {
if (newValue) {
ctrl.execute(newValue);
}
};
scope.$watch("fieldValue", monitorField, true);
}
};
});
See jsFiddle.
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting a "system is computationally singular" error in sleuth
I am analysing 142 samples belonging to 6 batches. Additionally, those samples belong to 72 strains, which means that for most of the strains there are two samples.
I could fit simple models (for strain and batches for instance), but when I get to the "full" model (~batch+strain), I get the following error:
so <- sleuth_fit(so, ~strain+batch, 'full')
Error in solve.default(t(X) %*% X) :
system is computationally singular: reciprocal condition number = 5.2412e-19
I should point out that of the 72 strains, only 15 have samples in distinct batches. This means that most strains (57) have both samples in the same batch.
Is the error due to an unknown bug or rather to the experimental design? Does it mean that the information on batches cannot be used?
Thanks
EDIT I've posted the experimental design in a gist
batch strain replica
batch_1 strain_41 1
batch_4 strain_41 2
batch_1 strain_28 1
batch_4 strain_28 2
batch_1 strain_26 1
[...]
A:
This happen when the variables (strain +batch) create a design matrix like this:
batch strain
1 1 #
1 1 #
1 2
2 2
3 3
4 3
...
16 72
Which means that some of the covariates are not linearly independent (ie batch 1 and strain 1), all the strain 1 is in batch 1.
You can correct for batch effects, but not in this design of the linear model (if you want to take into account the strain). You could do one batch more with those 15 strains that are in a single batch (if they are in different batch between them) that way you would get an independent design.
Many strains in a single batch are in the same batch. You need to increase the number of samples (recommended anyway due to the low number of samples per strain) to avoid this problem.
There are a lot of related question in Bioconductor support forum, from where I expanded an answer.
A:
You should be able to remove any one of the following strains to end up with a rank-sufficient model matrix: 5, 10, 12, 13, 14, 15, 19, 26, 28, 3, 30, 32, 36, 39, 41, 45, 46, 49, 5, 50, 52, 53, 58, 59, 60, 69, 8. As an aside you can figure this sort of thing out as follows (I read your dataframe in a the d object):
> m = model.matrix(~batch+strain, d)
> dim(m) # 142 row, 77 columns, so minimum rank is 77
> qr(m)$rank # 76, so just barely rank insufficient
> #see if we can remove a single column and still get rank 76
> colnames(m)[which(sapply(1:77, function(x) qr(m[,-x])$rank) == 76)]
You obviously don't want to remove the batch columns or the intercept. The normal tricks that you can sometimes use to get around this issue with case-control studies don't appear to help here, which is why I would just drop a strain and call it done. Keep in mind that your power is still likely terrible. I generally recommend at least 6 replicates per group (scale down the number of groups to fit your budget).
EDIT:
Once the desired strain is removed from the model, it can be fit directly into the sleuth_fit function to obtain the full model:
> m = m[, -9] # whatever column to drop to get the appropriate rank
> so <- sleuth_fit(so, m, 'full')
| {
"pile_set_name": "StackExchange"
} |
Q:
How did Murph know what happened to Dr Brand?
At the end of Interstellar, Murph tells Coop to
go find Brand instead of staying to watch her die
and her closing monologue suggests she knows that Brand is
setting up the colony on Edmunds' planet.
How did she know anything about Brand's whereabouts or survival?
A:
When Coop first arrives at the station, he asks about Murph, and the doctor says "She'll be here in a couple weeks." So at some point during those two weeks it's reasonable to speculate Coop had been interviewed/debriefed about his experiences, and Murph had learned what he said before they finally saw each other. If this is the case, she would know that Coop had helped Brand escape falling into Gargantua just before he fell in himself, and that she was headed for Edmunds' planet--as mentioned earlier after the disaster caused by Dr. Mann, they had been planning to do a gravitational slingshot around Gargantua in order to get there:
COOPER The navigation mainframe's destroyed and we don't have enough
life support to make it back to Earth. But we might scrape to Edmunds'
planet.
BRAND What about fuel?
COOPER Not enough. But I've got a plan — let Gargantua suck us right
to her horizon — then a powered slingshot around to launch us at
Edmunds.
So based on this, Murph could infer that Brand was on her way to Edmunds' planet, and perhaps had had enough time to get there (for some discussion of why Brand arriving at Edmunds' planet probably happened at roughly the same time Cooper arrived at the station, see this answer). And Murph's use of the word "maybe" in her comments suggests she was just making some reasoned speculations on what was going on with Brand at that moment, not that she knew for sure:
She's out there ... setting up camp...alone in a strange
galaxy...maybe, right now, she's settling in for the long nap...by the
light of our new sun...in our new home.
| {
"pile_set_name": "StackExchange"
} |
Q:
1 = 0 finding the mistake
I was shown the following calculation. There is clearly something wrong but I can not see the mistake. Could someone point out the wrong step or something?
$$ \int \frac{1}{x} dx = \int 1 \cdot \frac{1}{x} dx$$
Let's say $ u = \frac{1}{x}$ and $ dv = 1\ dx$.
So $ du = -\frac{1}{x^2} \ dx$ and $ v = x$.
Putting that into per partes formula:
$$ \int \frac{1}{x} dx = \int 1 \cdot \frac{1}{x} dx= x \cdot \frac{1}{x} - \int x \cdot (-\frac{1}{x^2})dx = 1 + \int \frac{1}{x} dx$$
So we can substract $\int \frac{1}{x}dx$ from both sides which then gives us
$$0 = 1$$
A:
You are forgetting the constant of integration. When you write $\int\frac1xdx$, that could represent any of a family of functions. So in this case, the left-hand $\int\frac1x dx$ represents an antiderivative of $\frac1x$ which is $1$ larger than the $\int \frac1xdx$ on the right-hand side. This also means that you cannot "subtract $\int\frac1xdx$" as easily as you might think.
The moment you put bounds on your integrals, everything changes. In that case (assuming the bounds are valid), we get
$$
\int_a^b\frac1xdx = 1\Big|_{x = a}^b + \int_a^b\frac1xdx
$$
and we see that the $1|_a^b$ term disappears, and all is well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Speed up array query in Numpy/Python
I have an array of points (called points), consisting of ~30000 x,y, and z values. I also have a separate array of points (called vertices), about ~40000 x,y, and z values. The latter array indexes the lower-front-left corners of some cubes of side length size. I would like to find out which points reside in which cubes, and how many points reside in each cube. I wrote a loop to do this, which works like this:
for i in xrange(len(vertices)):
cube=((vertices[i,0]<= points[:,0]) &
(points[:,0]<(vertices[i,0]+size)) &
(vertices[i,1]<= points[:,1]) &
(points[:,1] < (vertices[i,1]+size)) &
(vertices[i,2]<= points[:,2]) &
(points[:,2] < (vertices[i,2]+size))
)
numpoints[i]=len(points[cube])
(The loop is order the individual cubes, and the "cube" creates a boolean array of indices.) I then store points[cube] somewhere, but this isn't what's slowing me down; it's the creating of "cube=".
I would like to speed this loop up (it takes tens of seconds to complete on a macbook pro). I tried rewriting the "cube=" part in C, as follows:
for i in xrange(len(vertices)):
cube=zeros(pp, dtype=bool)
code="""
for (int j=0; j<pp; ++j){
if (vertices(i,0)<= points(j,0))
if (points(j,0) < (vertices(i,0)+size))
if (vertices(i,1)<= points(j,1))
if (points(j,1) < (vertices(i,1)+size))
if (vertices(i,2)<= points(j,2))
if (points(j,2) < (vertices(i,2)+size))
cube(j)=1;
}
return_val = 1;"""
weave.inline(code,
['vertices', 'points','size','pp','cube', 'i'])
numpoints[i]=len(points[cube])
This sped it up by a bit more than a factor of two. Rewriting both loops in C actually made it only slightly faster than the original numpy-only version, because of the frequent references to the array objects necessary to keep track of which points are in which cubes. I suspect it's possible to do this much more rapidly, and that I'm missing something. Can anyone suggest how to speed this up?? I'm new to numpy/python, and thanks in advance.
A:
You can use scipy.spatial.cKDTree to speedup this kind of calculation.
Here is the code:
import time
import numpy as np
#### create some sample data ####
np.random.seed(1)
V_NUM = 6000
P_NUM = 8000
size = 0.1
vertices = np.random.rand(V_NUM, 3)
points = np.random.rand(P_NUM, 3)
numpoints = np.zeros(V_NUM, np.int32)
#### brute force ####
start = time.clock()
for i in xrange(len(vertices)):
cube=((vertices[i,0]<= points[:,0]) &
(points[:,0]<(vertices[i,0]+size)) &
(vertices[i,1]<= points[:,1]) &
(points[:,1] < (vertices[i,1]+size)) &
(vertices[i,2]<= points[:,2]) &
(points[:,2] < (vertices[i,2]+size))
)
numpoints[i]=len(points[cube])
print time.clock() - start
#### KDTree ####
from scipy.spatial import cKDTree
center_vertices = vertices + [[size/2, size/2, size/2]]
start = time.clock()
tree_points = cKDTree(points)
_, result = tree_points.query(center_vertices, k=100, p = np.inf, distance_upper_bound=size/2)
numpoints2 = np.zeros(V_NUM, np.int32)
for i, neighbors in enumerate(result):
numpoints2[i] = np.sum(neighbors!=P_NUM)
print time.clock() - start
print np.all(numpoints == numpoints2)
Change the cube corner position to center position first.
center_vertices = vertices + [[size/2, size/2, size/2]]
Create a cKDTree from points
tree_points = cKDTree(points)
Do query, k is the the number of nearest neighbors to return, p=np.inf means maximum-coordinate-difference distance, distance_upper_bound is the max distance.
_, result = tree_points.query(center_vertices, k=100, p = np.inf, distance_upper_bound=size/2)
The output is:
2.04113164434
0.11087783696
True
If there are more then 100 points in a cube, you can check this by neighbors[-1] == P_NUM in the for loop, and do a k=1000 query for these vertices.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make my main menu link text dynamic?
How can I make my main menu link text dynamic?
My solution:
I tried to use Felix's answer, below, but it would not work for me. Obviously, the method suggested by Felix has worked for others and it is used in core (user.module, for example). However, I was able to conditionally alter my main menu link text at the theme level. I added this to template.php:
/**
* Conditionally alters preprocess links variables.
*/
function MY_THEME_preprocess_links(&$variables) {
if (MY_FUNCTION()) {
if (isset($variables['links']['menu-562 active-trail']['title'])) {
$variables['links']['menu-562 active-trail']['title'] = 'New blog';
} elseif (isset($variables['links']['menu-562']['title'])) {
$variables['links']['menu-562']['title'] = 'New blog';
}
if (isset($variables['links']['menu-563 active-trail']['title'])) {
$variables['links']['menu-563 active-trail']['title'] = 'New notes';
} elseif (isset($variables['links']['menu-563']['title'])) {
$variables['links']['menu-563']['title'] = 'New notes';
}
}
}
A:
Drupal menu's are cached and this makes it hard to change then on the fly when the page is rendered. It is possible though using the functions aimed at translating menu items: see hook_translated_menu_link_alter.
This hook is called before every menu item is rendered IF it has the property ['options']['alter'] = TRUE.
You can set this property to menu items using hook_menu_link_alter.
Example code would be:
function MY_MODULE_menu_link_alter(&$item) {
// add in an if statement here to just target the links you want to change on the fly
$item['options']['alter'] = TRUE;
}
function MY_MODULE_translated_menu_link_alter(&$item, $map) {
if($item['mlid']==89) {
// this line is actually to change the link however if you inspect the $item
// variable then you will be able to see the other property that you can change.
$item['link_path'] .= 'my-new-path';
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Objective-C strange appearance in debugger after stringByReplacingOccurrencesOfString
I´m on Mac OS X and Xcode 4.5.2
When executing these lines:
NSString *asSrcFileName = @"chromebar.png"
NSString *asSrcExtName = @".png"
NSString *asTempName = [asSrcFileName stringByReplacingOccurrencesOfString:asSrcExtName withString:@""];
I get a strange view of my variables in the debugger. See rectangle:
I expected asTmp to be @"chromebar" after line three.
I´ve been using stringByReplacingOccurrencesOfString pretty often so far and have no idea what´s wrong. Somehow it looks like there is a unicode issue.
Anyone out there to shed some light on me?
A:
Are you inspecting asSrcTempName after the variable has been initialized (the green line showing the current execution point is below the initialization)?
Otherwise it's probably only uninitialized memory and lldb is showing garbage from a previous run.
I could not reproduce your problem in Xcode 4.5.1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the table name is returned by a sql query in application
I have a stored procedure that returns a table. But it can return two kind of tables according to what condition it has like below
...
if @TestCondition > 0
begin
select *
from Test1 NoExpiredTable
end
else
begin
select *
from Test2 ExpiredTable
end
So in the application how can I get the table name ? What I tried is
if (ds.Tables[0].TableName == "NoExpiredTable")
{
}
but ds.Tables[0].TableName gives me "Table".
A:
SQL queries do not return tables. They return result sets. A result set has no name.
A:
The result set has no concept of the table it came from, you can include the table name in the records returned by the procedure . . .
if @TestCondition > 0
begin
select *, 'NoExpiredTable' TableName
from Test1 NoExpiredTable
end
else
begin
select *, 'ExpiredTable' TableName
from Test2 ExpiredTable
end
Then you can access it the same way you'd access any other column.
This won't do anything for you if no rows are returned, you won't know which table was selected from.
Here you can return a single record with the result of the condition (i.e. a single row with a single column, TableName) then the records from the actual table. e.g.
select case when
if @TestCondition > 0
begin
select 'NoExpiredTable' TableName
select *
from Test1 NoExpiredTable
end
else
begin
select 'ExpiredTable' TableName
select *
from Test2 ExpiredTable
end
| {
"pile_set_name": "StackExchange"
} |
Q:
How to execute node js functions one after another which dynamically listed using their names in a string array
I need to achieve following in my Node.js program.
How create a function array from their names provided in strings?
How to execute those functions one after another. Not asynchronously.
How to pass parameters for those functions.
Suggest me a better approach to achieve this or code snippet somewhere already implemented this.
A:
You can do like this;
function foo(v){console.log("foo: ",v)};
function bar(v){console.log("bar: ",v)};
var funs = ["foo", "bar"],
i = 0;
while (i < funs.length) this[funs[i]](i++);
Well of course your functions definitions might reside in a particular scope and you may need to invoke them from within whatnot..! In that case you can of course wrap the above code in a function and bind it to whatever scope your function definitions are made in. Such as
var obj = {
foo: function(v){console.log("foo: ",v)},
bar: function(v){console.log("bar: ",v)}
},
funs = ["foo", "bar"],
runner = function(a){
var i = 0;
while (i < a.length) this[a[i]](i++);
}.bind(obj);
runner(funs);
| {
"pile_set_name": "StackExchange"
} |
Q:
Android : JSON Parser with async task (GET and POST methods)
Just want to check whether this JSON Parser with async task is it correctly done? When I put this code into my Eclipse, this (method.equals("POST") was underline red. And it state that the 'method' cannot be solved. Any suggestion or help in this? Thank you.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String url=null;
List<NameValuePair> nvp=null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
BackGroundTask Task= new BackGroundTask(url, method, params);
try {
return Task.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
}
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
A:
You forgot to declare method property in your BackGroundTask class.
EDIT Like this:
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
this.method = method;
}
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to retrieve the value from a cell of specific row and column python?
2020-04-13
2020-04-14
2020-04-15
2020-04-16
2020-04-17
2020-04-20
2020-04-21
2020-04-22
2020-04-23
2020-04-24
2020-04-27
2020-04-28
2020-04-29
2020-04-30
2020-05-01
2020-05-04
2020-05-05
2020-05-06
2020-05-07
2020-05-08
2020-05-11
2020-05-12
2020-05-13
2020-05-14
2020-05-15
2020-05-18
2020-05-19
2020-05-20
2020-05-21
2020-05-22
I want to retrieve value from 2020-04-20(todays date) column of 3rd row from the above.This is the result of
print(data.columns)
I tried using get_value and .at.It didnt work
print(data.columns)
for i in data.columns:
convert_date=i.date()#converting to date type
if date.today()==convert_date:#comparing todays date
print(date.today())
print(data.at[3,date.today()])#throws KeyError: datetime.date(2020, 4, 20)
A:
You need to convert your index into datetime object. Currently its string. you can change index into datetime :
df.index = pd.to_datetime(df.index)
After that it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как вывести данные нужной даты?
Привет всем. Подскажите, как вывести записи с указанным промежутком времени? Сейчас вообще ничего не работает.
В БД время записи записывается 2015-06-14
<form action='index.php' method='POST' id='myform'>
<header>Найти запись с <input type='date' name='from' value=''/>
по <input type='date' name='to' value='' />
<button class='btn mini green-stripe' name='show' value=''>Готово</button>
</header>
</form>
if (isset($_POST['show'])){
$from = $_POST['from'];
$to = $_POST['to'];
$from1 = date('Y-d-m', strtotime($from));
$to1 = date('Y-d-m', strtotime($to));
$query = ("SELECT * FROM Configuration WHERE `Date` BETWEEN '".$from1."' and '".$to1."' ");
$result = mysql_query($query) or die(mysql_error());
}
+ Как сделать так, чтобы, если во втором поле не была выбрана дата, то искать записи с даты, которая выбрана в 1 поле иначе сообщить об ошибке?
A:
Поле Date в БД имеет формат строка? Если да, то срочно изменяйте на DATE, либо INT и записывайте туде Timestamp, иначе вырастет много проблем.
Как сделать так, чтобы, если во втором поле не была выбрана дата, то искать записи с даты, которая выбрана в 1 поле иначе сообщить об ошибке?
if ($to) {
SQL-запрос с BETWEEN
} else {
SQL-запрос WHERE `Date` > from
}
UPDATE
Поле Date все-таки имеет формат Date, поэтому нужно всего лишь:
"SELECT * FROM Configuration WHERE `Date` BETWEEN CAST('".$from1."' AS DATE) and CAST('".$to1."' AS DATE) "
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting ClassCast Exception on API 19 but working fine on API 21
I have implemented a material design navigation drawer and a custom toolbar. It works perfectly fine on Lollipop device.
But when run on Android 4.4.4, it crashes with error mentioned below :
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
cannot be cast to android.widget.AbsListView$LayoutParams
I have not changed any layout of navigation drawer. Code sample to set up drawer :
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer,
(DrawerLayout) findViewById(R.id.drawer), mToolbar);
LogCat :
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
at android.widget.ListView.setupChild(ListView.java:1826)
at android.widget.ListView.makeAndAddView(ListView.java:1793)
at android.widget.ListView.fillDown(ListView.java:691)
at android.widget.ListView.fillFromTop(ListView.java:752)
at android.widget.ListView.layoutChildren(ListView.java:1630)
at android.widget.AbsListView.onLayout(AbsListView.java:2087)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14857)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2013)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1770)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
Any help is appreciated.
A:
Android has made major changes in AppCompat v21.
So, please refer to this link:
http://android-developers.blogspot.in/2015/04/android-support-library-221.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Hiding a Datatables column on page load then using a checkbox to show or hide it
Sorry if this is a dumb question but here's what i need to do. When the page loads, I have a DT column that needs to be hidden. I have a checkbox on the page will either show or hide the column depending on whether the checkbox is checked. Is there a way to do this with a combination of jquery and the datatables methods? I tried something where I hide the column on page load with jquery but when you toggle the checkbox and reload the page, it doesn't work right (probably due to the table and how it's getting redrawn). Code below.
if (!userAccountsDTO) {
userAccountsDTO = $adminUserAccountsTable.DataTable({
destroy:true,
data:normalizedData,
columns:userAccountsMap,
autoWidth:false,
paging:false,
dom:'lftip',
2 = user name, 0 = invisible child indicator sort
orderFixed: {
post: [[2,'desc'],[0, 'desc']]
},
order:[4,'asc'],
language:{
search:'',
searchPlaceholder:ax.L(5008),
emptyTable: ax.L(905),
zeroRecords: ax.L(905),
info: tableFilters.info,
infoFiltered: tableFilters.infoFiltered,
infoEmpty: tableFilters.info
},
rowCallback:function(row, data, index) {
var $row = $(row);
var uname = data.username.replace(/[@._#]/gi,'-');
var id = data.id;
$row.data('username',uname);
$row.data('id',id);
if (!data.enabled) {
$row.addClass('row-disabled');
}
if (data.current_profile.id != data.default_profile.id) {
$row.addClass('childrow un-'+id);
} else {
$row.addClass('parentrow un-'+id);
}
}
});
ax.Utils.setupTableFiltering($adminUserAccountsTable, userAccountsDTO, MAX_RESULTS, { visibleOnly: true });
var $profileColumnHidden = $adminUserAccountsTable.find('.admin-user-accounts-profile-column').hide();
} else {
userAccountsDTO.clear();
userAccountsDTO.search('');
userAccountsDTO.rows.add(normalizedData);
userAccountsDTO.draw();
}
//Checkbox
$adminUserAccountsShowHideProfiles.change(function(e) {
var $profileChildRows = $adminUserAccountsTable.find('tr.childrow');
var $profileColumn = $adminUserAccountsTable.find('.admin-user-accounts-profile-column');
if ( $(this).is(':checked') ) {
$profileChildRows.show();
$profileColumn.show();
} else {
$profileChildRows.hide();
$profileColumn.hide();
}
});
A:
create a css class for hiding particular column.
table.hide_col tr > td:nth-child(1){
display:none
}
table.hide_col tr > th:nth-child(1){
display:none
}
add/remove class on checkbox click event
$('table').addClass('hide_col')
$('#chkShow').on('click', function(){
$('table').toggleClass('hide_col')
});
http://jsfiddle.net/ercanpeker/0kpmjd1u/
| {
"pile_set_name": "StackExchange"
} |
Q:
Sharepoint search query fields missing in my 2010 sharepoint version
The below query i used to search the content of the MOSS 2007 site and SP 2010 site.
I get the ContentType value in MOSS site.But if i use the same query with ContentType, It will give the malformed error.
SELECT Title, Rank, Size, Description, Write, Path, contentclass,FROM Scope()
WHERE FREETEXT(DefaultProperties, '1') ORDER BY "Rank" DESC
What the exactly the problem?. IS I need to add the ContentType column name in search service application(metadata propertie). or it need to do any configuration.
Also i am using sharepoint search tool there itself for 2010 it's not showing the ContentType Column.
A:
Try using following query
SELECT Title, Rank, Size, Description, Write, Path, contentclass,FROM portal..scope() WHERE FREETEXT(DefaultProperties, '1') ORDER BY "Rank" DESC
I had faced same issue while I consumed Search.asmx and searching for MOSS 2007 site and SP2010. I was getting proper data for MOSS 2007 using only scope() but for SP 2010 I need to put portal..scope().
Also have a look at here
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS Game Center submit float instead of int64_t
I am trying to submit a float of two decimal length to my Game Center leaderboard, however the only format allowed to submit with is int64_t. I am using the default Apple report score method:
- (void)reportScore:(int64_t)score forCategory:(NSString *)category {
GKScore *scoreReporter = [[GKScore alloc] initWithCategory:category];
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler: ^(NSError *error) {
[self callDelegateOnMainThread: @selector(scoreReported:) withArg: NULL error: error];
}];
}
I am trying to use this method to provide the score to the report score method:
- (IBAction)increaseScore {
self.currentScore = self.currentScore + 1;
currentScoreLabel.text = [NSString stringWithFormat: @"%lld", self.currentScore];
NSLog(@"%lld", self.currentScore);
}
Please help, I have been googling like crazy and cannot find the answer to this.
A:
GameCenter only accepts int64_t
The only difference between values that appear like floats or decimal values and those that appear as integers is the position of the decimal mark, while in fact all of them are int64_t.
If your internal representation is a double and you configured game center to show 3 digits after the decimal mark you have to convert it to an integer by multiplying with 10^3 and casting to integer.
int64_t gameCenterScore = (int64_t)(doubleValue * 1000.0f)
A:
You can only submit 64 bit integers as scores to a leaderboard. From the documentation:
To Game Center, a score is just a
64-bit integer value reported by your
application. You are free to decide
what a score means, and how your
application calculates it. When you
are ready to add the leaderboard to
your application, you configure
leaderboards on iTunes Connect to tell
Game Center how a score should be
formatted and displayed to the player.
Further, you provide localized strings
so that the scores can be displayed
correctly in different languages. A
key advantage of configuring
leaderboards in iTunes Connect is that
the Game Center application can show
your game’s scores without you having
to write any code.
That doc page should tell you about formatting your score. It sounds like in order to display float-like scores you will have to tinker with the format settings in iTunes Connect.
Update
Try this for increaseScore:
- (IBAction) increaseScore {
self.currentScore = self.currentScore + 5;
float score = (float)self.currentScore / 100.0f;
currentScoreLabel.text = [NSString stringWithFormat: @"%f", score];
NSLog(@"%lld", self.currentScore);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Error in loadNamespace(name) : there is no package called ‘Rsenal’
I am trying to use this source from github.
devtools::source_url('https://raw.githubusercontent.com/brooksandrew/Rsenal/master/R/bin.R')
I could use this and work with it till few hours back. but now it gives me the following error
Error in loadNamespace(name) : there is no package called ‘Rsenal’
The code is still there in the provided url. I did re run the following two commands but still not working.
install.packages("devtools")
library("devtools")
What should I do to fix this issue?
A:
I believe your issue is arising because you are sourcing functions that live inside a package, that is meant to be distributed as a package.
Instead of using devtools::source_url(), try this:
devtools::install_github('brooksandrew/Rsenal')
library("Rsenal")
Once the package is properly installed, all of the primary functions (such as binCat()) should be available for use.
I believe you ran into this error because some functions within the package probably depend on others that are not found within the two files you manually sourced. So when those lines are executed, R looks for the Rsenal package file and does not find them.
Further troubleshooting would require a reproducible example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Animated ImageIcon as Button
I have an imageIcon as Button, now i would to animate it when you rollover. I tried to use a animated gif (without loop) on setRolloverIcon(Icon). But when i hover again on the button the gif is not playing again. When i use a looped gif then it plays it from a random frame. I tried using paintComponent to draw a Shape or an image as Button, which works fine, but even when i use setPreferredSize() or setSize() or setMaximumSize() the Button uses its default size, as you can see in the picture (middle button). Im using GroupLayout, might this be the problem?
A:
Seems to work just fine for me...
I used the following icons...(png and gif)...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class AnimatedButton {
public static void main(String[] args) {
new AnimatedButton();
}
public AnimatedButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private ImageIcon animatedGif;
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton(new ImageIcon("WildPony.png"));
btn.setRolloverEnabled(true);
animatedGif = new ImageIcon("ajax-loader.gif");
btn.setRolloverIcon(animatedGif);
add(btn);
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
animatedGif.getImage().flush();
}
});
}
}
}
I just realised that you are using a non-looping gif. This means you are going to nee to try and "reset" to start it playing again.
Try using something like icon.getImage().flush();, where icon is your ImageIcon. You're going to have to attach a MouseListener to the button to detect the mouseEnter event and reset the ImageIcon...
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to load AWS credentials from any provider in the chain - error - when trying to load model from S3
I have an MLLib model saved in a folder on S3, say bucket-name/test-model. Now, I have a spark cluster (let's say on a single machine for now). I am running the following commands to load the model:
pyspark --packages com.amazonaws:aws-java-sdk:1.7.4,org.apache.hadoop:hadoop-aws:2.7.3
Then,
sc.setSystemProperty("com.amazonaws.services.s3.enableV4", "true")
hadoopConf = sc._jsc.hadoopConfiguration()
hadoopConf.set("fs.s3a.awsAccessKeyId", AWS_ACCESS_KEY)
hadoopConf.set("fs.s3a.awsSecretAccessKey", AWS_SECRET_KEY)
hadoopConf.set("fs.s3a.endpoint", "s3.us-east-1.amazonaws.com")
hadoopConf.set("com.amazonaws.services.s3a.enableV4", "true")
hadoopConf.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
from pyspark.ml.classification import RandomForestClassifier, RandomForestClassificationModel
m1 = RandomForestClassificationModel.load('s3a://test-bucket/test-model')
and I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/.local/lib/python3.6/site-packages/pyspark/ml/util.py", line 362, in load
return cls.read().load(path)
File "/home/user/.local/lib/python3.6/site-packages/pyspark/ml/util.py", line 300, in load
java_obj = self._jread.load(path)
File "/home/user/.local/lib/python3.6/site-packages/pyspark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in __call__
File "/home/user/.local/lib/python3.6/site-packages/pyspark/sql/utils.py", line 63, in deco
return f(*a, **kw)
File "/home/user/.local/lib/python3.6/site-packages/pyspark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o35.load.
: com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3521)
at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297)
at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:258)
at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:229)
at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:315)
at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:204)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:253)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:251)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:251)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:49)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:253)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:251)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:251)
at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1343)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.RDD.take(RDD.scala:1337)
at org.apache.spark.rdd.RDD$$anonfun$first$1.apply(RDD.scala:1378)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.RDD.first(RDD.scala:1377)
at org.apache.spark.ml.util.DefaultParamsReader$.loadMetadata(ReadWrite.scala:615)
at org.apache.spark.ml.tree.EnsembleModelReadWrite$.loadImpl(treeModels.scala:427)
at org.apache.spark.ml.classification.RandomForestClassificationModel$RandomForestClassificationModelReader.load(RandomForestClassifier.scala:316)
at org.apache.spark.ml.classification.RandomForestClassificationModel$RandomForestClassificationModelReader.load(RandomForestClassifier.scala:306)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:238)
at java.lang.Thread.run(Thread.java:748)
Honestly, these lines of code are taken from the web and I have no idea about storing and loading MLLib models on to S3. Any help here will be appreciated and also the next step for me is to do the same on a cluster of machines. So any heads up will also be appreciated.
A:
You are using the wrong property names for the s3a connector.
see https://hadoop.apache.org/docs/current3/hadoop-aws/tools/hadoop-aws/#Authentication_properties
| {
"pile_set_name": "StackExchange"
} |
Q:
Add nanoseconds from Win32 epoch to Go time
I'm trying to process some WMI counters using Go (as part of learning Go) and am trying to figure out how to generate the necessary time object.
The base is the Win32 epoch (1601-01-01) and a sample timestamp is 13224382394716547600ns (or rather, 132243823947165476 100ns units).
Here's what I've tried:
test 1 (add nanoseconds)
win_epoch := time.Date(1601,1,1, 0, 0, 0, 0, time.UTC)
current_ts_1 := win_epoch.Add(13224382394716547600*time.Nanosecond)
test 2 (add days)
win_epoch := time.Date(1601,1,1, 0, 0, 0, 0, time.UTC)
current_ts_2 := win_epoch.AddDate(0,0,(132243823947165476/10000000 / 3600 / 24))
current_ts_1 in test 1 fails with an overflow error.
current_ts_2 in test 2 only gives me resolution at the date level.
Ideally I'd be able to get the millisecond resolution on this. Does there exist a way to not overflow the Duration being passed to .Add() and still get this resolution?
A:
This conversion requires dealing with some huge numbers. Your example time
13,224,382,394,716,547,600 is too big to fit into an int64 (max 9,223,372,036,854,775,807) but does fit into a unit64.
You cannot use time.Duration when dealing with this because that is a int64 nanosecond count; as the docs say "The representation limits the largest representable duration to approximately 290 years". This is why your first attempt fails.
However there is another way of creating a time that will work better here func Unix(sec int64, nsec int64) Time. This takes data in the unix format and this is the time since January 1, 1970 UTC (or 11644473600000000000 represented as ns since the windows epoch).
Using this information it's possible to perform the conversion:
func main() {
const unixTimeBaseAsWin = 11644473600000000000 // The unix base time (January 1, 1970 UTC) as ns since Win32 epoch (1601-01-01)
const nsToSecFactor = 1000000000
timeToConvert := uint64(13224382394716547600)
unixsec := int64(timeToConvert - unixTimeBaseAsWin ) / nsToSecFactor
unixns := int64(timeToConvert % nsToSecFactor)
time := time.Unix(unixsec, unixns)
fmt.Println(time.Local())
}
Note: I have checked this with a few figures but would suggest further testing before you rely upon it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add cluster to an existing table in oracle
Is it possible to add cluster to an existing table? For example...
I have a table:
CREATE TABLE table_name(
t_id number PRIMARY KEY,
t_name varchar2(50));
Cluster:
CREATE CLUSTER my_cluster
(c_id NUMBER) SIZE 100;
Is there a command like: ALTER TABLE t_name ADD CLUSTER my_cluster(t_id); or something like that?
Because I want table to look something like this:
CREATE TABLE table_name(
t_id number PRIMARY KEY,
t_name varchar2(50))
CLUSTER my_cluster(t_id);
And dropping all connected tables isn't really what I want to do.
Thanks
A:
You really need to understand what a cluster really is. From the docs:
"Clusters are groups of one or more tables physically stored
together because they share common columns and are often used
together. Because related rows are physically stored together, disk
access time improves." (emphasis mine)
The point being, the tables in a cluster are co-located. This is a physical arrangement. So, for the database to cluster existing tables we must drop and re-create them.
It is possible to minimise the downtime by building the clustered table under a different name. You will need to keep the data in synch with the live table until you are ready to swap. You will need to restrict access to the database while you do this, to prevent data loss. Then you rename the old table, rename the clustered table with the proper name, run the necessary grants and recompile invalid procedures, synonyms, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the cheapest way to discover all dealerships?
I found the map beneath in this Reddit post (that lists the dealerships too), and I know that it's outmoded, as v1.34.0.5 added states. Dealers are listed on this forum too.
I started playing ATS yesterday, and have merely the one default tractor unit.
Can I drive to dealers in merely the lone tractor unit (without a semi-trailer)?
If I must drive to dealers in the whole semi-trailer truck, how?
A:
The ATS Wikia Dealers page seems to be more updated than the Reddit post. It even includes Oregon.
What I did was follow the Wikia page to find the cities where dealers are located, and just take jobs that would take me to those cities. You can drive to dealers with just the truck without a hitched trailer. Once I completed my job in the city with an undiscovered dealer, I would drive around with just the truck.
You can also stop by the dealer before you complete the job (i.e. with the trailer attached). Just make sure you leave enough time to finish your delivery.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Returning posgreSQL database records with user input
I am faced with a blocker in my Node/express application.
I want to return data from a postgresSQL database table, but doing that with the query parameter passed by a user...
Assume the following:
db is a postgresSQL database pool connection.
Trips table is already created and populated with trips having their destination value as "Nigeria".
Below is my model and controller code.
model.js
const getTrips = async ( column, value )=> {
const query = 'SELECT * FROM trips WHERE $1 = $2';
const { rows } = await db.query ( query, [value] );
return rows;
}
controller.js
const getTrips = async ( req, res) => {
const { destination } = req.query;
const result = await Trips.getTrips( 'destination' destination );
console.log( result.length )
}
Issue am faced with
Url = http://.../?destination="Nigeria"
When I pass the destination query parameter from the user directly , like this Trips.getTrips('destination', destination ), an empty array is returned.
However if the string equivalent of the query parameter value is passed, like this Trips.getTrips('destination', 'Nigeria'), an array with the Trips matching Nigeria as destination is returned.
Checks have done
console.log(typeof destination) // returns string.
console.log (destination) // returns "Nigeria"
Question
Why is passing the parameter directly not returning the appropriate records and passing its string equivalent returns appropriate records?
A:
Try taking away the quotes in your URL query (Url = http://.../?destination=Nigeria). It seems like you're querying for "Nigeria" literally (quotes included). Does this help?
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is my synchronous code using setTimeout behaving asynchronous in JavaScript?
I'm trying to loop 10x over a test (waiting for the condition to be true), but somehow it's not working.
Here is what I have:
// my counter
$.testHelper.countDown = function(test, iteration) {
var ticker = iteration || 0;
if (ticker > 10) {
return false;
}
window.setTimeout(function() {
if (test === true) {
console.log("SENDING");
return true;
}
ticker += 1;
$.testHelper.countDown(test, ticker);
}, 1000);
};
// my test
$.testHelper.testForElement = function(element) {
var result;
console.log($i.find(element).length > 0); // true
result = $.testHelper.countDown(
$i.find(element).length > 0
);
console.log(result); // undefined
return result;
};
My problem is that although my condition equates to true before I'm calling countdown, the answer from countDown is undefined. So my logs come in like this:
// true - before firing my countDown method
// undefined - should not log
// SENDING - response from countDown (= true)
Question:
From the code displayed, is there a reason, why my undefined is logged before countDown is through and returns true?
Thanks!
A:
Erm, because setTimeout is always asynchronous? That's kind of the whole point.
Here's a possibility for you:
function when(condition,then) {
// condition must be a callback that returns `true` when the condition is met
if( condition()) then();
else setTimeout(function() {when(condition,then);},1000);
}
This will poll once every second until the condition is met, and then do whatever is given in the then callback.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to measure and quantify concentration or focus?
How can we measure and quantify concentration or focus? For example, if I were to say:
"If you do Activity X while using Y, you will be more concentrated
than if you were using Z"
How can I quantify that? And what tests should I do to actually prove that statement? Examples are appreciated.
Background
I am trying to build some different technology products and I want them to help the user stay more focused than they would using a competitor product of the same kind. The only research I've done so far was to build some interfaces and ask the user how they feel.
A:
Short answer
Attention can be quantified with a sustained attention to response task.
Background
I think with focus or concentration you mean sustained attention to a certain task. A sustained attention to response task (SART) (Silverstein & Palumbo, 1998) could be helpful to you (here is a free PsychoPy script). SART seems to be a reliable measure for attention (Smilek et al., 2010).
Basically SART consists of a set of stimuli (e.g., simple shapes) and the subject is asked to repeatedly give a response (e.g. a button press) when a certain event occurs (e.g. a shape changes color). Reductions in correct rates, increased lapse rates, and/or decreased reaction times all may signal reduced attention to the task.
Admittedly I am not too familiar with these tests, but I do have a lot of experience with people loosing attention during tedious psychophysical tasks :) I hope the links and references provided here may be of further help.
References
- Silverstein & Palumbo, Computers in Human Behavior (1998); 14(3): 463-75
- Smilek et al., Neuropsychologia (2010); 48(9): 2564-70
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I convert timestamp into date?
I wanna covert timestamp in format "%Y-%m-%d %H:%M:%S" into date format "%Y-%m-%d".
My data:
Timestamp Open High Low Close Volume_(BTC) Volume_(Currency) Weighted_Price
142 2017-09-25 00:00:00+00:00 4102.00 4102.99 4098.13 4102.99 3.583970 14704.368394 4102.815806
143 2017-10-02 00:00:00+00:00 3920.66 3923.00 3920.65 3923.00 11.622131 45578.428351 3921.692822
144 2017-10-09 00:00:00+00:00 4391.41 4391.41 4377.95 4377.95 3.356237 14696.859302 4378.970080
145 2017-10-16 00:00:00+00:00 4761.67 4770.99 4761.53 4770.99 4.068390 19394.983344 4767.237680
146 2017-10-23 00:00:00+00:00 5752.20 5756.37 5745.61 5754.30 4.496116 25857.849205 5751.152455
I've tried:
datetime.datetime.utcfromtimestamp(data['Timestamp']).strftime('%Y-%m-%d')
...which returns:
TypeError: cannot convert the series to
Help would be appreciated. Thanks.
A:
if it is a datetime object you can simply add .date()
date = '2017-09-25 00:00:00+00:00'
date = pd.to_datetime(date).date()
print(date)
2017-09-25
Since this does not automatically work for Series you can do something like:
date = ['2017-09-25 00:00:00+00:00', '2017-09-25 00:00:00+00:00']
date= pd.Series(date)
date = pd.to_datetime(date)
for i in range(len(date)):
date[i] = date[i].date()
print(date)
0 2017-09-25
1 2017-09-25
Or you can use (better answer):
date.dt.date
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues with Dividing by Negative Fractions
I am working on a coding assignment where I am supposed to write the methods to simplify, find gcf, add, subtract, multiply and divide two fractions. I have written all of the methods, but I am having trouble in the divide method because whenever I attempt to divide by a negative fraction (such as the -6/17), it prints 0/1 as the result. Here is my Fraction class with all methods, but the only ones I added are the ones listed above. The rest were provided by my instructor. Here's the class:
class Fraction {
private int numerator = 0; // numerator (and keeps sign)
private int denominator = 1; // always stores positive value
public Fraction() {
}
public Fraction(int n, int d) {
if (set(n, d) == false)
set(0, 1);
}
public boolean set(int n, int d) {
if (d > 0) {
numerator = n;
denominator = d;
return true;
} else
return false;
}
public String toString() {
return (numerator + "/" + denominator);
}
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
public double decimal() {
return (double) numerator / denominator;
}
public Fraction simplify(){
int gcd = GetGcd(this);
int simpNum = this.numerator;
int simpDen = this.denominator;
simpNum /= gcd;
simpDen /= gcd;
Fraction f = new Fraction (simpNum, simpDen);
return f;
}
public int GetGcd (Fraction f){
int testNum = f.numerator;
int testDen = f.denominator;
if (testNum < 0)
testNum = 0 - testNum;
else if (testDen < 0)
testDen = 0 - testDen;
if (testNum == 0){
return testDen;
}
while (testNum != testDen){
if (testNum > testDen)
testNum -= testDen;
else
testDen -= testNum;
}
return testNum;
}
public Fraction add (Fraction f){
int cd = this.denominator * f.denominator;
int den1 = this.denominator;
int den2 = f.denominator;
int num1 = this.numerator * (cd / den1);
int num2 = f.numerator * (cd / den2);
int num3 = num1 + num2;
Fraction f2 = new Fraction (num3, cd);
f2 = f2.simplify();
return f2;
}
public Fraction subtract (Fraction f){
int cd = this.denominator * f.denominator;
int den1 = this.denominator;
int den2 = f.denominator;
int num1 = this.numerator * (cd / den1);
int num2 = f.numerator * (cd / den2);
int num3 = num1 - num2;
Fraction f2 = new Fraction (num3, cd);
f2 = f2.simplify();
return f2;
}
public Fraction multiply (Fraction f){
int den1 = this.denominator;
int den2 = f.denominator;
int num1 = this.numerator;
int num2 = f.numerator;
int num3 = num1 * num2;
int den3 = den1 * den2;
Fraction f2 = new Fraction (num3, den3);
f2 = f2.simplify();
return f2;
}
public Fraction divide (Fraction f){
int den1 = this.denominator;
int den2 = f.denominator;
int num1 = this.numerator;
int num2 = f.numerator;
int num3 = num1 * den2;
int den3 = den1 * num2;
Fraction f2 = new Fraction (num3, den3);
f2 = f2.simplify();
return f2;
}
}
And I was given a test code by my instructor that has test fractions. Here it is:
public class FractionTester {
public static void main (String[] args) {
System.out.println("\n\nFraction tests:\n");
Fraction f1 = new Fraction(4, 6);
Fraction f2 = new Fraction(75, 175);
Fraction f3 = new Fraction(-6, 17);
System.out.println(f1 + " simplified = " + f1.simplify());
System.out.println(f2 + " simplified = " + f2.simplify());
System.out.println(f3 + " simplified = " + f3.simplify());
// show that f1, f2, f3 haven't changed
System.out.println("f1 = " + f1);
System.out.println("f2 = " + f2);
System.out.println("f3 = " + f3);
// arithmetic
System.out.println(f1 + " + " + f2 + " = " + f1.add(f2));
System.out.println(f1 + " - " + f2 + " = " + f1.subtract(f2));
System.out.println(f1 + " * " + f2 + " = " + f1.multiply(f2));
System.out.println(f1 + " / " + f2 + " = " + f1.divide(f2));
System.out.println();
System.out.println(f2 + " + " + f3 + " = " + f2.add(f3));
System.out.println(f2 + " - " + f3 + " = " + f2.subtract(f3));
System.out.println(f2 + " * " + f3 + " = " + f2.multiply(f3));
System.out.println(f2 + " / " + f3 + " = " + f2.divide(f3));
System.out.println();
// test 'division by zero' handling
Fraction zero = new Fraction();
System.out.println(f2 + " / " + zero + " = " + f2.divide(zero));
}
}
The results should show up like this:
4/6 simplified = 2/3
75/175 simplified = 3/7
-6/17 simplified = -6/17
f1 = 4/6
f2 = 75/175
f3 = -6/17
4/6 + 75/175 = 23/21
4/6 - 75/175 = 5/21
4/6 * 75/175 = 2/7
4/6 / 75/175 = 14/9
75/175 + -6/17 = 9/119
75/175 - -6/17 = 93/119
75/175 * -6/17 = -18/119
75/175 / -6/17 = -17/14 (THIS SHOWS UP AS 0/1 INSTEAD...)
75/175 / 0/1 = 0/1
I know it's something in the Divide method because when I changed -6/17 to just 6/17 in the last one, it worked and printed 17/14 when simplified. I just have no idea what in the Divide method is not working with negative fractions. Is there maybe something I can add in there to help with this issue? Thanks in advance.
A:
In divide(),
public Fraction divide (Fraction f){
int den1 = this.denominator;
int den2 = f.denominator;
int num1 = this.numerator;
int num2 = f.numerator;
int num3 = num1 * den2;
int den3 = den1 * num2;
Fraction f2 = new Fraction (num3, den3);
...
Assume this is positive while f is negative. According to your assumption,
den1 > 0
den2 > 0
num1 > 0
num2 < 0
num3 = num1 * den2 > 0
den3 = den1 * num2 < 0
However, when new Fraction(num3, den3) which calls set(),
public boolean set(int n, int d) {
if (d > 0) {
numerator = n;
denominator = d;
return true;
} else
return false;
}
When the denominator is less than 0, you returned false which forbids the value from set into the class.
You could inverse signs for both numerator and denominator instead of simply returning false.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using local imports in Pytest
I have never really fully understood how packages are handled in Python and I'm having a problem with that right now. But googling doesn't seem to help as I find the topic really confusing.
I have a project with this structure:
project_name/
src/
main.py
utils/
string_utils.py
tests/
test_string_utils.py
I am using Pytest for running unit testing and currently inside the "test_string_utils.py" file I have the following:
from ..src.utils.string_utils import StringUtilsClass
But I go to the folder "project_name" and try to run tests with any of this command I get errors:
$ pytest tests/
ValueError: attempted relative import beyond top-level package
I know about the -m argument for python, but it seems that running "pytest -m" has a completely different behavior.
How can I solve this? Am I using the wrong folder architecture? I don't think what I'm building should be a pip package (which would simplify imports)
A:
did you try : from src.utils.string_utils import StringUtilsClass without .. before src?
or from string_utils import StringUtilsClass
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I change color of a particular word document using apache poi?
Current output:
Needed output:
above are the snapshots of the .docx and below is the code sample code, I want to change the color of a after it is replaced by @. r.setColor("DC143C") doesn't work:
for (XWPFParagraph p : docx.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String origText = r.getText(0);
if (origText != null && origText.contains("a")) {
origText = origText.replace("a", "@");
r.setText(origText, 0);
}
}
}
}
A:
If the need is to change the color of just one character then this character must be in its own run. This is because only runs can be styled.
If you have a document containing text already then you must run through all already existing runs and possible split those runs into multiple ones. As the result each string part which shall be styled separately must be in its own run, also if it is only one character.
Example:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import java.awt.Desktop;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public class WordReadAndWrite {
public static void main(String[] args) throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx"));
for (XWPFParagraph p : doc.getParagraphs()) { //go through all paragraphs
int runNumber = 0;
while (runNumber < p.getRuns().size()) { //go through all runs, we cannot use for each since we will possibly insert new runs
XWPFRun r = p.getRuns().get(runNumber);
String runText = r.getText(0);
if (runText != null && runText.contains("a")) { //if we have a run with an "a" in it, then
char[] runChars = runText.toCharArray();
StringBuffer sb = new StringBuffer();
for (int charNumber = 0; charNumber < runChars.length; charNumber++) { //go through all characters in that run
if (runChars[charNumber] == 'a') { //if the charcter is an 'a' then
r.setText(sb.toString(), 0); //set all characters, which are current buffered, as the text of the actual run
r = p.insertNewRun(++runNumber); //insert new run for the '@' as the replacement for the 'a'
r.setText("@", 0);
r.setColor("DC143C");
r = p.insertNewRun(++runNumber); //insert new run for the next characters
sb = new StringBuffer(); //empty buffer
} else {
sb.append(runChars[charNumber]); //buffer all characters which are not 'a's
}
}
r.setText(sb.toString(), 0); //set all characters, which are current buffered, as the text of the actual run
}
runNumber++;
}
}
doc.write(new FileOutputStream("result.docx"));
doc.close();
System.out.println("Done");
Desktop.getDesktop().open(new File("result.docx"));
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Error when returning character array from function, C++
I'm writing a sketch for the Arduino board and am using the following C++ code to do so. I'm trying to convert decimal numbers to binary by passing a decimal through the dec2bin function which is to return a character array that I will then print out. However, I'm getting the error:
"Incompatible types of assignment of 'char' to 'char [0]'"
at the function call to dec2bin and I'm receiving another error at the return inside of the dec2bin function that says:
"Invalid conversion from 'char*' to 'char' [-fpermissive]"
If anyone could please assist me with this it would be greatly appreciated. I need to use a character array here and not a string! Thank you!
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0){
char BinaryNum [0];
int Decimal = Serial.parseInt();
BinaryNum = dec2bin(Decimal);
Serial.println (BinaryNum);
}
}
char dec2bin (int Decimal){
int Remainder; // Remainder of Decimal%2
char Binary [0]; // Character array returned by dec2bin
int x = 0;
while (Decimal != 0 ){
Remainder = Decimal%2;
Decimal = Decimal/2;
Binary[x] = Remainder;
Serial.println(Binary[x]);
x+=1;
}
return Binary;
}
A:
Danger Danger, you're returning a pointer to a local variable, Binary, that is on the stack, once the function returns it is out of scope and no longer valid. This will cause weirdness, it will work some times and then it will stop working, don't do it!
See Can a local variable's memory be accessed outside its scope?
You need to pass in the storage.
eg.
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0){
char BinaryNum[33]; // allows for 32 bits plus null terminator
int Decimal = Serial.parseInt();
dec2bin(Decimal, BinaryNum);
Serial.println (BinaryNum);
}
}
void dec2bin (int Decimal, char* Binary){
int Remainder; // Remainder of Decimal%2
int x = 0;
while (Decimal != 0 ){
Remainder = Decimal%2;
Decimal = Decimal/2;
Binary[x] = Remainder;
x+=1;
}
Binary[x] = '\0';
}
On a "real" computer with an operating system there are many more memory management options than on a little arduino. You could allocation from the heap and use something fancy like an auto_ptr to manage it (see What is a smart pointer and when should I use one?).
This just isn't possible on something as small as an arduino. You could however allocate it as a static. This isn't appropriate for a fancy computer because it is not re-entrant and thus not thread safe. Static allocation is done at program linking or startup and persistent across calls.
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0){
int Decimal = Serial.parseInt();
char* BinaryNum = dec2bin(Decimal);
Serial.println (BinaryNum);
}
}
void dec2bin (int Decimal) {
static Binary[33]; // allows for 32 bits plus null terminator
int Remainder; // Remainder of Decimal%2
int x = 0;
while (Decimal != 0 ){
Remainder = Decimal%2;
Decimal = Decimal/2;
Binary[x] = Remainder;
x+=1;
}
Binary[x] = '\0';
return Binary;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Making custom non-trivial loss function in pytorch
I'm just started with pytorch and trying to understand how to deal with custom loss functions, especially with some non trivial ones.
Problem 1. I'd like to stimulate my nn to maximize true positive rate and at the same time minimize
false discovery rate. For example increase total score on +2 for true positive, and decrease on -5 for false positive.
def tp_fp_loss(yhat, y):
total_score = 0
for i in range(y.size()):
if is_tp(yhat[i],y[i]):
total_score += 2
if is_fp(yhat[i],y[i]):
total_score -= 5
return -total_score
Problem 2. In case when y is a list of positive and negative rewards (y = [10,-5, -40, 23, 11, -7]),
stimulate nn to maximize sum of rewards.
def max_reward_loss(yhat,y):
r = torch.autograd.Variable(torch.Tensor(y[yhat >= .5]), requires_grad=True).sum()
return -r
Maybe I'm not completely understand some autograd mechanics, functions which I implemented correctly calculate loss but
learning with them doesnt work :( What I'm doing wrong? Can anybody help me with some working solution of any of that problems?
A:
Your loss function is not differentiable - you cannot compute its gradient (go ahead and try).
You should look as something like infogain loss
A:
@Shai already summed it up: Your loss function is not differentiable.
One way to think about it is that your loss function should be plottable, and the "downhill" slope should "roll" toward the desired model output. In order to plot your loss function, fix y_true=1 then plot [loss(y_pred) for y_pred in np.linspace(0, 1, 101)] where loss is your loss function, and make sure your plotted loss function has the slope as desired. In your case, it sounds like you want to weight the the loss more strongly when it is on the wrong side of the threshold. As long as you can plot it, and the slope is always downhill toward your target value (no flat spots or uphill slopes on the way from a valid prediction to the target value), your model should learn from it.
Also note that if you're just trying to take into account some business objective which prioritizes precision over recall, you could accomplish this by training to convergence with cross entropy or some well-known loss function, and then by tuning your model threshold based on your use case. A higher threshold would normally prioritize precision, and a lower threshold would normally prioritize recall. After you've trained, you can then evaluate your model at a variety of thresholds and choose the most appropriate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Connotation of "appease"
Is "Bob did what he could in his capability to appease them" a positive or negative comment about Bob?
A:
The term appease itself is fairly neutral:
appease - verb
pacify or placate (someone) by acceding to their demands.
assuage or satisfy (a demand or a feeling).
It's not defined as being disparaging, and you can use it fairly neutrally.
I appeased my growling stomach by eating a sandwich.
We appeased the opposing parties, by throwing some concessions in.
However, it does have some negative connotations, going back to pre-World War II, where Britain's policy toward Hitler under Neville Chamberlain was one of appeasement.
This has been heavily criticised as allowing Hitler to gain momentum and power, and World War II happening.
See the Wikipedia article on Appeasement for more details.
See also this question:
What is the polite word describing a person who unreasonably says and does things to make a person happy?
A:
Appeasement as a national policy got negative connotation during WWII:
"The term is most often applied to the foreign policy of the British Prime Minister Neville Chamberlain towards Nazi Germany between 1937 and 1939. His policies of avoiding war with Germany have been the subject of intense debate for seventy years among academics, politicians and diplomats. The historians' assessments have ranged from condemnation for allowing Adolf Hitler's Germany to grow too strong, to the judgment that he had no alternative and acted in Britain's best interests. At the time, these concessions were widely seen as positive, and the Munich Pact concluded on 30 September 1938 among Germany, Britain, France, and Italy prompted Chamberlain to announce that he had secured "peace for our time." (http://en.wikipedia.org/wiki/Appeasement)
Regarding actions of a single human, I'd say the connotations are fairly neutral.
A:
Bob did what he could to appease them.
I would consider them to be the insulted party here. Appease is being used in the sense of soothing or pacifying. Adults don't need to be soothed or pacified.
| {
"pile_set_name": "StackExchange"
} |
Q:
Let $(G,\cdot)$ be a set with an associative operation. Show that the following two Axioms are equivalent
Let $(G,\cdot)$ be a set with an associative operation. Show that the following two Axioms are equivalent:
(a) : there exists a left-hand neutral element $e'$, so that $\forall a \in G: e'a=a$
(b): There exists a neutral element $e$, so that $\forall a\in G:ea=ae=a$
My attempt:
$(a)\Longrightarrow (b) :$
Let $e'$ be the left-hand inverse on $(G,\cdot)$.
Now let's take $a,b \in G$:
$$ab=a(e'b)=(ae')b=ab.$$
So in order for the associativity on $(G,\cdot)$ to hold, $e'$ has to be right-hand neutral as well.
$(b) \Longrightarrow (a):$
Is obvious ?
Is this correct? I mean, its quit obvious, thats why I suspect myself jumping to conclusions..
A:
The two statements are not equivalent. Although (b) implies (a), it is not the case that (a) implies (b).
To verify this, let $G=\{e,a\}$, and define the operation as follows: $ea=a$, $aa=a$, $ae=e$, $ee=e$. That is, the result of multiplying $x$ by $y$ is always $y$.
This is easily seen to be associative, since $x(yz) = yz = z$ and $(xy)z=z$.
It is also clear that both $e$ and $a$ are left inverses, since $ee=e$, $ea=a$ (and also $ae=e$ and $aa=a$). However, neither $e$ nor $a$ are two-sided inverses.
The flaw in your attempt, as has been pointed out, is that associativity does not imply cancellativity. You cannot go from $xy=xz$ to $y=z$, or from $xy=zy$ to $x=z$, from just knowing the operation is associative. But that is what you are attempting to do when claiming that $(ae’)b = ab$ requires $ae’=a$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Isometry on a round n-Sphere preserves geodesic
Q) If $(M,g)$ is a Riemannian manifold, $p \in M$ and $f \, : \, M \, \rightarrow \, M$ an isometry such that $\mathrm{D}_{p}f \cdot v = v$ for some $v \in T_{p}M$ then, for the geodesic $\gamma \, : \, [a,b] \, \rightarrow \, M$ with $\gamma(0) =p$ and $\gamma'(0)=v$, then prove that we have $f \circ \gamma = \gamma$
My work so far: Once I have proven that $f \circ \gamma$ is a geodesic, then by uniqueness of geodesic it automatically proves that its equal to $\gamma$. I have shown that $f \circ \gamma$ is locally length minimizing because $\gamma$ is a geodesic and they have the same integrated length due to isometry (chosen over any small interval). So the I have proven the last part of the question, but need to see that $f \circ \gamma$ would indeed be a geodesic initialized at $p$
My question is this: how do I show that $f \circ \gamma$ has constant speed and initialzed at the same $p$ that $\gamma$ is?
A:
First note that $D_pf$ is a linear mapping from $T_pM$ to $T_{f(p)}M$. Since $v\in T_pM$ and $D_pf$ maps $v$ to $v$, $(D_pf)v=v\in T_pM\cap T_{f(p)}M$, which implies $f(p)=p$. This proves $f\circ\gamma(0)=f(\gamma(0))=f(p)=p$.
Second, the initial velocity of $f\circ\gamma$ is $(f\circ\gamma)'(0)=(D_{\gamma(0)}f)\gamma'(0)=(D_pf)v=v$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I get different results with same random seed, same computer, same program
I am running a simulation with a lot of modules.
I use random a number of times.
I read input files.
I use rounding.
Of course, I am setting a random.seed(1) in the very first line of my program, immediately after importing random.
Even though, shouldn't I get exactly the same result running the same program same parameters in the same computer with the same input files?
A:
Inject the source for random numbers as a service into the modules using it. You can then easily replace it with a deterministic version that gives a predefined sequence of numbers. This is for example a prerequisite for proper unit testing and it also applies to things like the time, too.
Concerning your case, you could e.g. inject an instance of random.Random instead of using a global (the one provided by the random module). This generator could then be seeded appropriately (constructor argument) to provide reproducible sequences.
Bad code:
def simulation():
sum = 0
for i in range(10):
sum += random.random()
return sum / 10
# Think about how to test that code without
# monkey-patching random.random.
Good code:
def simulation(rn_provider):
sum = 0
for i in range(10):
sum += rn_provider()
return sum / 10
rng1 = random.Random(0)
sum1 = simulation(rng1.random)
rng2 = random.Random(0)
sum2 = simulation(rng2.random)
print(sum1 == sum2)
The code here uses a simple function parameter. For classes, you could also use "dependency injection".
BTW: Remember hearing that globals are bad? Here's your example why. ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
On Lao triphthongs / tones / orthography
Information on the Lao language is a bit patchy, especially when you start getting a little deeper and find gaps, inconsistencies, and contradictions in and between sources on the Internet.
Lao vowel sounds are spelled using one or more vowel characters and a couple of characters which are also used for consonants or semivowels. There is a distinction between long vowels and short vowels which plays an important part in determining the tone of a syllable.
Various articles give lists of vowels and diphthongs and tables relating them to their spellings, their length, and their tone. But some words cannot be analysed using just the information in these sources:
ເຂົ້າໜຽວ "sticky rice" /khao niao/
The second syllable appears to contain a triphthong, "ຽວ". Each of the letters "ຽ" and "ວ" can be used either alone or in combination with other letters, but none of the sources I can find mention them in combination with each other.
As vowels "ຽ" usually represents /iːə/ and "ວ" usually represents /uːə/.
As a consonant or semivowel "ວ" usually represents [ʋ] or [w] (depending on dialect).
So what is this "iao" sound in the "niao" of the second syllable? Or should I regard it as two syllables?
How can I reconcile this with Wikipedia's assertion that "Diphthongs are all centering diphthongs with falling sonority"?
Where does the "ao" come from in this combination, is it the same sound that is usually spelled "ເ-ົາ" as seen in the first syllable of the word?
A:
"ໜຽວ" is 1 syllable, "ຽ" /iːə/ is a typical Lao diphthong with falling sonority, and "ວ" is a consonant /w/, so this is a CVC-type syllable, /n/-/iːə/-/w/, /niːəw/. Note, that /w/ is allowed as the coda in Lao syllables (See A Grammar of Lao, p. 35, section "3.3 Final consonants." Lower on that page there is a list of Lao vowel phonemes and there are no triphthongs there).
Also, /iːə/ is written as "ຽ" only before final consonants, in open syllables /iːə/ is written as ເ◌ຍ, that is another proof that ວ" is onsonant /w/ here. (See this paper, pp. 10-11)
In the first word, the "ເ-ົາ" stands for a combination of a vowel + consonant, /aw/, so the two words have just one thing in common, they both end in /w/. However this /w/ is realised phonetically and acoustically in the coda, it is still the same phoneme as /w/ as the initial consonant. Transliterating this /aw/ as "ao" is just a convention.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why didn't battleship Bismarck have more support?
The primary objective of battleship Bismarck was to sink transporters coming from the U.S. and sailing to Europe transporting goods (oil, food). It encountered HMS Hood and sank it.
German cruiser Prinz Eugen was sailing along with the Bismarck all the time apart from the time the Royal Navy engaged heavy forces to sink it.
Why didn't the Bismarck have decent battleships, carriers and other fleet types sailing with it all the time? It was certain to German admirals that after the sinking of HMS Hood the Brits would employ forces in order to destroy the Bismarck.
Why didn't Otto Ernst Lindemann (naval captain, only commander of the Bismarck) ask for reinforcements after the HMS Hood event?
A:
The Germans wanted to send more, but there were none available. Most were unsuitable to escort Bismarck. Those which were suitable were damaged.
A good warship for commerce raiding is fast, both to catch enemy ships and run from warships, fuel efficient to keep at sea for as long as possible, and carries heavy armament to rapidly sink enemy ships from long range. Bismarck could make 30 knots and cruise for 10,000 miles, there were few heavy ships in the Germany Navy which could keep up.
Her sister, Tirpitz, was still working up. The battleships Scharnhorst and Gneisenau were both under repair in Brest on the wrong side of the North Sea. The old pre-Dreadnaught Deutschland battleships were far too slow.
Germany had build a small fleet of brand new Admiral Hipper heavy cruisers. Blücher had been sunk, Admiral Hipper was being overhauled in Kiel, Seydlitz was never completed, and Lützow had been sold to the Soviets. Prinz Eugen which was damaged but hastily repaired and ready.
This left the older and slightly slower Deutschland class "pocket battleships" designed as commerce raiders. Of the pocket battleships, Admiral Graf Spee had been famously scuttled in her own commerce raid. Lützow nee Deutschland had recently finished repairs from a British torpedo attack and was waiting to go on its own raid with Admiral Sheer. Admiral Scheer had just returned from a five month long shipping raid in the Atlantic and was undergoing repairs in Kiel.
The rest of the Germany Navy was light cruisers, destroyers and smaller ships. While they had the speed, they did not have the endurance. They also didn't have the firepower. The heavy 203mm and 380mm guns of the Prinz Eugen and Bismarck will be in range long before the 150mm guns of a German light cruiser. Since you're not planning on fighting a fleet of warships there's no need for a screen of light ships. They're just a liability.
As for carriers, Germany never had one.
Bismarck was used as a commerce raider because she could destroy most British ships before they could even get in range and run from the rest. Prinz Eugen was the only available consort. But they were caught by equally fast and powerful units of the British Navy sent to find them, the Hood and the Prince of Wales, and forced to fight.
Sending more warships risks the commander thinking they should be fighting enemy warships. This was not their mission, though the German commanders often did not agree. The diminutive German Navy had no hope of defeating the Royal Navy in a fair fight on the high seas, but it didn't stop officers from thinking they could, especially with a ship as new and powerful as the Bismarck. Captain Lindeman, commanding Bismarck, was eager for a fight to use his powerful new ship. But Admiral Lütjens strictly held them to their mission.
Then there is the problem of supply, in particular food and fuel. A successful commerce raider will be out as sea for as long as possible. Even if they fail to sink a single ship, their existence can tie up enemy naval assets hugely out of proportion.
A commerce raider can resupply from friendly overseas ports, and from friendly supply units, but mainly from scavenging from the commerce they raid. The more fuel hungry warships you have in your fleet, and their very large and hungry crews to feed, the more thinly you need to spread your supplies.
The Bismarck's mission was to raid commerce, not engage enemy warships. A good commerce raider will hide or run, only as a last resort should it fight. Why? It jeopardizes its mission of raiding commerce. Fighting a warship risks damage, damage that could force it to return to port early (thus aborting its primary mission), or make it vulnerable. The Bismarck's victory against the Hood caused both these consequences. The Admiral Graf Spee had a similar fate after its victory in the Battle of the River Plate.
Even with no damage, engaging a warship means firing a lot of precious main battery armament. Fuel can be taken from enemy ships, but ammunition cannot be replaced without returning to port or a risky at-sea resupply mission. Resupply at sea leaves you stopped and vulnerable with more ships for the enemy to track. Returning to port both cuts short its primary mission, and it leaves it open to bombing and blockade by the much more powerful British Navy, as happened to its sister Tirpitz.
If you sink a Royal Navy warship you risk the wrath of the Royal Navy, far more powerful and numerous than the German Navy. It makes it difficult to raid commerce when you're dodging an ocean full of British warships. It happened in WWI after a German victory by von Spee's powerful commerce raiding squadron at the Battle of Coronel, they were destroyed a month later by an even more powerful British task force sent to hunt them down at the Battle of the Falkland Islands.
Sinking the Hood, pride of the Royal Navy, and in such a spectacular fashion, signaled the death of the Bismarck, failure of her mission, and the loss of an irreplaceable German battleship.
See Also
Operation Rheinübung - First and Last Voyage of the Bismarck by Drachinifel
A:
As identified in the first paragraph of the question, the purpose of Operation Rheinübung was a continuation of the commerce raids on allied shipping in the Atlantic. The Scharnhorst and Gneisenau had previously performed a similar exercise with great success.
Commerce raiding was a common tactic used against a superior (or simply numerically larger) naval force. It allowed the smaller force to do disproportionate damage against the enemy shipping while avoiding the risk of putting all of their warships at risk at once. By keeping their own ships dispersed, the Germans would force the British to spread their own forces to find and attack them. In that situation, there was the possibility that the German battleship would be able to out-fight the force it encountered (or simply out-run, as was the case when the Scharnhorst and Gneisenau encountered a couple of British battleships).
Had the Germans committed a larger flotilla (or even fleet) to the operation, it would have allowed the British to concentrate their forces too. In a fleet action the Germans would have, almost certainly, been outnumbered and outgunned. In which, case they would have been at risk of losing a considerable part of their surface fleet in a single action.
A:
As far as "battleships" go, the Germans only had the Bismarck. The Tirpitz had just completed construction and wasn't quite "ready" for major duty, and the battle-cruisers Scharnhorst and Gneisenau were undergoing repairs.
A more interesting question is why didn't Germany send out cruisers and destroyers with the Bismarck to protect it from "cheap shots." Apparently, no one felt that they were needed. The Bismarck originally had a cruiser escort, the Prinz Eugen, that did a great job of shielding the Bismarck against the opening fire of the Hood. But Bismarck's Admiral Luetgens apparently didn't feel the need for such an escort, and detached the Prinz Eugen for "independent" duty. The idea was that the Prinz Eugen could do more damage by itself than by accompanying a Bismarck that was damaged, and needed to head to port for repairs.
With benefit of hindsight, the Prinz Eugen's anti-aircraft fire might have helped save the Bismarck from air attack by the bombers of Britain's Ark Royal. But that's with hindsight, because no one thought in those terms at the time.
| {
"pile_set_name": "StackExchange"
} |