INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Git, Duvidas quando faço um commit
tenho uma duvida ao utilizar o git, e gostaria da ajuda de voces.
Tenho a seguinte situação:
* Estou desenvolvendo um novo recurso na minha aplicação, mas nao finalizei complementamente. Vamos supor que eu esteja desenvolvendo no pc em casa. Ai eu vou para o trabalho, e resolvo, na hora do almoço, dar continuidade no novo recurso.
Segue minha duvida... A aplicação fica no Github. Eu desenvolvi no pc de casa, e comitei inconpleto para terminar na hora do almoço no trabalho...
Qual a solução para não comitar coisas incompletas no git?
Desde já agradeço!
|
Cria um branch/ramo onde tens essa nova funcionalidade/feature. Quando ela estiver pronta faz merge com o `master`.
git checkout master
# criar novo ramo a partir do master
git checkout -b nova-ideia
E depois no trabalho:
git fetch origin # ou outro nome que deste ao repositório remoto
git checkout nova-ideia (sem o "-b" que é para criar novo)
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 6,
"question_score": 7,
"tags": "git, github"
}
|
Incrementing dates in Excel VBA
this is my current code:
For z = 3 To 52
Cells(z, 1) = Cells((z - 1), 3) + 7
Next z
Where cell z-1 is a date
I want to add 7 days to the previous cell however it's throwing an error, it this the right way to approach this issue or is there a simpler method?
Thank you
|
Try the `DateAdd` function, use inside the loop:
Cells(Z, 1) = DateAdd("ww", 1, Cells((Z - 1), 3))
**Note** : the 1st parameter, is the `Interval`, set it to `"ww"`, which means weeks.
To read more about this function go to MSDN.aspx)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "vba, excel, date"
}
|
Dynamic Desired Capabilities in Appium
We have a lot of real mobile devices to execute functional tests on them. We are facing a lot of difficulties when switching devices. I am looking for a dynamic way of changing Device Capabilities programmatically (Android devices) . Could you help me to figure out this? Any link clue may help.
Regards.
|
As far as I understand, you want your desired capabilities to change every time you connect a new mobile device to your development environment. may be this library can help you. It also support iOS.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, testing, mobile, automation, appium"
}
|
WordPress block how to access and save options values
I have some values stored in WordPress Option table that I usually manage with get_option/add_option/update_option/delete_option in php
is there any way to retrieve them with javascript in Gutenberg block or even to manage them?
|
You could pass the option as a localized javascript variable: <
wp_localize_script('blocks-js', 'locals', array(
'posts_per_page' => get_option('posts_per_page')
));
However, I don't think there is currently a way to set options via Gutenberg. I assume it would be a defined store, but I haven't found anything. The documentation here is kind of lacking.
In the meantime, you could set up a custom REST API endpoint that handles options changes or just a generic ajax call.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, php, wordpress, wordpress gutenberg"
}
|
WebFaultException to pass back an XML message rather than string?
In my RESTful services layer, any exceptions that bubble up to me are caught as Fault Exceptions. Within that FaultException, there's a custom XML message that contains `<errorNumber>`, `<errorCode>` and a `<message>`. I re-package the exception as a WebFaultException so I can set the HttpStatusCode for the response header to 400, 401, 404, etc.
However, I don't want to use `WebFaultException<string>(string message, HttpStatusCode code)`. I want the message to also be an XML message.
Anyone seen how to set the HttpStatusCode of the response message AND set an XML message? I'm using Fiddler to examine my response headers and any messages that come up from the service.
|
What I did to get around this was create a new class `MyException` with simple properties and used `WebFaultException<MyException>` and it works nicely. I found the solution at the following link: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "wcf, exception, faultexception"
}
|
Change PHP grammar
I am wondering if there is a way to change out the grammar of PHP with my own.
For example:
* `print` = `show`
* `class` = `box`
* `function` = `item`
I have read a little about ANTLR but that looks pretty complicated. Wondering if there is a simple way, like a language file?
|
No, there's no simple way. Php keywords are hardcoded in the interpreter and there are no means to change them. So, if you don't like them for some reason, you options are basically:
* edit the lexer file and compile your very own php binary
* use a preprocessor that would convert your keywords into valid php on the fly (like < but it looks rather dead to me)
* use a "better-than-php" language, like Hack
* learn some other programming language
* create your own
or
* just deal with it. Seriously, php is only fun if you enjoy it as is and don't try to make a "better" language out of it.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php"
}
|
Html form label line breaks
i need a twitter bootstrap form with input text boxes on the same line, but its labels must be on the top of input boxes.
So far i have:
<form action="#">
<label for="city">City</label>
<input type="text" id="city"/>
<label for="street">Street</label>
<input type="text" id="street"/>
</form>
<
So i need inputs on the same line and labels must be on the top of each input.
How do i do that?
|
you can put a div around each label and block, and in the css put this div in inline-bloc
like :
<form action="#">
<div class = "css">
<label for="city">City</label>
<input type="text" id="city"/>
</div><div class="css">
<label for="street">Street</label>
<input type="text" id="street"/>
</div>
</form>
and in the CSS:
.css{
display : inline-block;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "html, css, forms, twitter bootstrap"
}
|
Show Online Users in sidePanel using codeigniter and ajax
Side Panel Code:-
<div id="slide_panel">
<div id="showusers"></div>
<div id="holder">
<div id="stick"><span>Chat</span></div>
</div>
</div>
Javascript Of Sidepanel:-
<script type="text/javascript">
$(document).ready(function(){
var stick = $('#stick');
var panel = $('#slide_panel');
var left = $('#stick').offset().left;
var right = $('#stick').offset().right;
$("#stick").on('click',function(){
$("#slide_panel").toggleClass("anim");
});
});
</script>
Here Now When i click on chat button it show the side panel and in that I want display Online users For chat using ajax. I want to display online users list In this DIV:-"`<div id="showusers"></div>`"
|
$("#stick").on('click',function(){
$("#slide_panel").toggleClass("anim");
// simplest
$("#showusers").load('/your/controller/which/returns/userlist/');
/*
.. or ..
$.get('/your_controller/',function(response){
$("#showusers").html(response);
});
*/
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "json, ajax, codeigniter"
}
|
Cardinality of the set of all infinite monotonically decreasing sequences of naturals
> Find the cardinality of the set of all infinite monotonically decreasing sequences of naturals.
I think it's $\aleph_0$. I marked this set in $A$, and said that $\forall n\in\Bbb N \ (n,n,n,...)\in A$, Therefore, $\aleph_0\le|A|$. But I'm not sure how to show that $|A|\le\aleph_o$. Thanks
|
A monotonically non-increasing sequence of natural numbers is eventually constant, so it is completely identified by specifying the finite initial subsequence up to the point at which it becomes constant. There are only countably many finite sequences of natural numbers.
|
stackexchange-math
|
{
"answer_score": 19,
"question_score": 7,
"tags": "discrete mathematics, elementary set theory, cardinals"
}
|
scala array filtering based on information of another array
I have 2 types of array like this: array one,
Array(productId, categoryId)
(2, 423)
(6, 859)
(3, 423)
(5, 859)
and another array Array((productId1, productId2), count)
((2, 6), 1), ((2, 3), 1), ((6, 5), 1), ((6, 3), 1)
I would like to filter the second array based on the first array, firstly I want to check array 2 to see if productId1 and productId2 having the same category, if yes, will keep, otherwise will filter out this element. So the list above will be filtered to remain:
( ((2, 3), 1), ((6, 5), 1) )
Can anybody help me with this? Thank you very much.
|
If you don't mind working with the first array as a map, ie:
scala> val categ_info = cats = Array((2, 423), (6, 859), (3, 423), (5, 859)).toMap
categ_info: Map[Int, Int] = Map(2 -> 423, 6 -> 859, 3 -> 423, 5 -> 859)
then we have (setting up example data as simple `Int`s for convenience):
val data = Array(((2, 6), 1), ((2, 3), 1), ((6, 5), 1), ((6, 3), 1))
data.filter { case ((prod1_id, prod2_id), _) =>
categ_info(prod1_id) == categ_info(prod2_id)
}
producing:
res2: Array[((Int, Int), Int)] = Array(((2, 3), 1), ((6, 5), 1))
as requested.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "scala, scala collections"
}
|
How do I count the number of zeros in sql?
I have a column that has a value that is either 0 or 1. how do i count the numbers of zeros?
SELECT A.id
FROM table1 A
GROUP BY A.id
HAVING SUM(A.zeroorone) >=
ALL (SELECT SUM(AA.zeroorone)
FROM table1 AA
GROUP BY AA.id)
I know this counts the number of ones. I cant seem to get it
|
A CASE statement would do nicely:
SELECT SUM(CASE WHEN zeroorone = 0
THEN 1
ELSE 0 END) AS TOTAL_ZEROS
FROM table1
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 3,
"tags": "mysql, sql, database"
}
|
как при помощи jquery поменять css свойство?
Хочу поменять цвет средствами jqery, почему меняется только на синий а красный не меняется?
<!DCCTYPE html>
<html lang='ru'>
<head>
<title>HasHa4elfi1e oOpaOOTqyjKa cpe~CTBaMl-1 jQuery.</title>
<meta charset='utf-8'>
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(function() {
$("#id_text") .css("cursor", "pointer");
$ ("#id_text") .on("click", function() {
if($("#id_text").css("color") == "blue"){
console.log("123");
$("#id_text").css("color", "red");
}
else
console.log("what ");
$("#id_text").css("color", "blue");
}) ;
}) ;
</script>
</head>
<body>
<p id="id_text">TecT MeHReT ueeT.</p>
</body>
</html>
|
А вы бы посмотрели, что за `css("color")` вам выдается и все исправили бы :)
$(function() {
$("#id_text").css("cursor", "pointer");
$("#id_text").on("click", function() {
if ($("#id_text").css("color") == "blue" || $("#id_text").css("color") == "rgb(0, 0, 255)"){
$("#id_text").css("color", "red");
}
else {
$("#id_text").css("color", "blue");
}
});
});
<script src="
<p id="id_text">TecT MeHReT ueeT.</p>
дело в том, что `color` возвращается не в виде названия цвета, а в виде `rgb` функции
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery"
}
|
Find documents whose analyzed field contains slash and underscore
My documents have an analyzed field `url` with content looking like this
I would like to find all documents whose `filename` starts with an underscore. I've tried multiple approaches (wildcard, pattern, query_string, span queries) but I never got the right result. I expect this is because the the underscore is a term separator. How can I write such a query? Is it possible at all without changing the field to not analyzed (which I cannot do at the moment)?
It's ElasticSearch 1.5, but we'll be migrating to at least 2.4 in foreseeable future.
|
You might be able to write a `script` that would do that, but it would be amazingly slow.
You best bet (even though you say you can't right now) is changing the field from `analyzed` to a multi-field. This way you could have both analyzed and not-analyzed versions to work work.
You could use the Reindex API to migrate all the data from the old version to the new version (assuming you're using ES 2.3 or greater).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "elasticsearch"
}
|
Do we still need to worry about users turning off cookies?
I've noticed that a lot of sites don't bother anymore with work-arounds so users who have turned their cookies off can still get the same experience on the site. Has that problem just gone away in modern web development? Have we gotten to a point where nobody does it, so we don't need to bother?
|
I think I put this in the same category as JavaScript. Most people will have cookies enabled, but there will be a few people who have them turned off. There isn't the scare like there was in the mid 90s about evil corporations tracking you all over the net etc. People have become more accepting about how the web works and what is required to have the convenience of web sites remembering who you are etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 7,
"tags": "cookies, session state"
}
|
Creating a test case in tfs 2015 by rest api version 2.2
I'm trying to create a new test case at the TFS throw Postman by sending a PUT request with an `application/json` but get
> "Message": "The requested resource does not support http method 'PUT'."
I tried to use `X-HTTP-Method-Override` but i get the same response. My api version is 2.2. How can I create a test case using this REST API version
This is the request:
PUT
|
To create a Test Case, use the work item api, not the test case manegement api.
The Shared Step and Test Case are work items and are created using the respective api. After creation you can use the test case management api to put the test cases into suites and plans.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "rest, tfs, testcase, tfs sdk, azure devops rest api"
}
|
How to work with supercapacitors?
I'm thinking of using a supercapacitor to power a device with low power consumption. I have one 1 F capacitor rated at 5.5 V and I plan to charge it using input voltage of 5 V.
What precautions should I take when charging it? I'm afraid that it will overload my power supply if I just connect it directly.
Any other tips would be appreciated too.
|
I have had several students who have used super cap chargers. They provide a lot of nice features like variable current limit on the charging, the particular one that I linked to will also make it so you could use 2 caps with lower voltage on each one and it will make sure you don't over voltage one.
The only down side is the chips for these are VERY small and can be difficult to solder if you aren't very experienced.
|
stackexchange-electronics
|
{
"answer_score": 14,
"question_score": 9,
"tags": "capacitor, supercapacitor"
}
|
Какая нужна директива для использования ToList
Есть фрагмент кода
List<IWebElement> SearchTexts = Browser.FindElement(By.CssSelector("#layout-content div.orchard-layouts-root p")).ToList();
Выпадает такая ошибка
Ошибка CS1061 "IWebElement" не содержит определения для "ToList", и не удалось найти доступный метод расширения "ToList", принимающий тип "IWebElement" в качестве первого аргумента (возможно, пропущена директива using или ссылка на сборку).
Вот используемые директивы:
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq
|
Прошу прощения, не правильно написал, ошибка был
Browser.FindElement
Правильно
Browser.FindElements
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "c#, selenium webdriver"
}
|
Sale of apps on AppExchange
Can the customer buy the apps on App Exchange platform without subscribing to sales force?
|
@Abhi,
The following thread has the necessary answer that would help you understand the differences between Salesforce's ISV and OEM Appexchange Partnership Models.
Salesforce OEM license restrictions for end users
Also, watch this video to understand more about the Partnership models - <
|
stackexchange-salesforce
|
{
"answer_score": -1,
"question_score": 1,
"tags": "appexchange"
}
|
SQL Server Vs MongoDB : Speed test?
MongoDB:
var x = nosql.GetRecords<Event>(p => p._Data == "rawhix", 0, 12222);
// ICursor<T> GetRecords<T>(expression, skip, limit);
SQL:
SqlDataReader dr = SqlHelper.ExecuteReader("Select Top(12222)* From NewsFeed WHERE _Data = 'dddd'");
the MongoDB contains 1000000 record which are the same in the SQL .
the data stored as the following:
Id = 1 , _Data = 1abc
Id = 2 , _Data = 2bc
... etc
`Event` class :
Class Event => int Id => string _Data
when I run the code the result is:
Mongo : 580ms
SQL : 102ms
Should I do anything to fix this !! because the mongo was always faster except this test !?!
|
You need an index. Run this in the mongo console:
db.Events.ensureIndex({_Data:1});
or you can call it through the C# driver:
MongoDatabase db = server.GetDatabase("your_db_name");
MongoCollection<Event> events = hr.GetCollection<Event>("events");
employees.EnsureIndex("_Data");
You wouldn't want to do this on every call though since it is another call to the DB and will have a very tiny performance hit.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "c#, sql server, linq, performance, mongodb"
}
|
Multiple Locale Resolver in Spring.
Is it possible to have multiple locale resolver inside spring ?
I want to have multiple Locale Resolver inside my application like :
1. CookieLocaleResolver for user permanent language.
2. Http request Based LocaleResolver for just seeing a particular page in another language.
|
Don't see problem to write your own `LocaleResolver` and register it as bean with name `DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME`.
The logic of `resolveLocale` implementation may be really based on the `request`, when you can determine to use `CookieLocaleResolver` or provide someother locale from `request` attributes
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "spring, jakarta ee, spring mvc"
}
|
Reshape NumPy на 4 аргумента
Есть такой код
#Тут мы загружаем датасет MNIST
(train_images, train_labels), (_, _) = keras.datasets.mnist.load_data()
#На выходе получаем пары вида "массив изображений цифры 0", 0
#"массив изображений цифры 1", 1 и так далее, вплоть до цифры 9
print(train_images.shape) - выводит (60000, 28, 28)
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
print(train_images.shape) - выводит (60000, 28, 28, 1)
Что означают эти цифры? 28х28 это разрешение самих изображений MNIST, тут всё понятно.
Что такое 60000? Это длина массива-высота матрица-общее количество изображений? И зачем мы перевели эти в другую матрицу, и что означает в ней 1?
Я понимаю что reshape переводит массив в новую форму без изменения его данных, но я не могу представить себе в чем разница между (60000, 28, 28) и (60000, 28, 28, 1) и как это выглядит? И для чего это используется?
|
Разница между `(60000, 28, 28)` и `(60000, 28, 28, 1)` именно в размерности входного тензора / матрицы. Последнее число в размерности четырехмерного тензора обычно отвечает за число цветовых каналов. Т.е. в вашем случае речь идет об изображении в оттенках серого, т.е. с одним цветовым каналом.
> Для чего это используется?
Чаще всего при использовании нейронных сетей мы пользуемся готовой и проверенной архитектурой НС. Чаще всего такие архитектуры ожидают на вход тензор определенной размерности. В вашем случае - `60000` \- число образцов/картинок в обучающем наборе. Каждая из этих картинок имеет размерность `28x28x1` \- т.е. монохромную картинку размером `28x28`/
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, нейронные сети, numpy, keras"
}
|
How do I update input value when page reloads using localstorage?
When a user enters text into the input element, I want to be able to save what they type, so that if they refresh it will still be cached.
const input = document.getElementById('input')
input.onchange = function(){
const key = input.value;
localStorage.setItem('key', key)
input.value = localStorage.getItem("key");
};
|
Simply assign the value to the input element outside of the event handler function:
const input = document.getElementById('input')
input.value = localStorage.getItem("key"); // get and assign the value outside
input.onchange = function(){
const key = input.value;
localStorage.setItem('key', key);
};
**Please Note:** You can also consider using _oninput_ instead of _onchange_.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "javascript, html, local storage"
}
|
How do i programmatically select range of colors
If its possible, i want to select blue colors only and put em into array or something. I am thinking colors from light blue to deep blue.
|
I am assuming you want something like this:
<
This gets you quite a few colors but you might want to look at just creating a color picker or something if you want even more.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "c#, visual studio"
}
|
How can I solve this recurrence relation: $a_n = 3a_{n-1} + \frac{4^n}{4}$?
How can I solve the following recurrence relation?
$$a_n = 3a_{n-1} + \frac{4^n}{4}$$
I know that $a_n^{(h)} = 3a_{n-1}$ and that the characteristic equation is: $$r-3 = 0$$ and thus:
$$a_n^{(h)} = \alpha_1(3)^n$$
I am struggling with the particular solution $a_n^{(p)}$.
|
**Hint.** A particular solution is $a_n^{(p)}=4^n$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "recurrence relations"
}
|
Combining two unsigned bytes to a single integer value using left-shift and bitwise-or
I'm reading 2 bytes which together build up an `unsigned short` value, from 0 to 65536. I want to combine them to a single value, so here what I've done:
int32_t temp;
uint8_t buffer[2];
.............
temp = (buffer[1] << 8) /* [MSByte]*/| (buffer[0]/* [LSByte]*/);
printf (" %d" ,temp) ;
I still get an overflow at 32767. Any idea why?
|
Cast byte to int before shifting, i.e.:
((int32_t)buffer[1] << 8) | buffer[0]
* * *
P.S. 2 bytes can store an unsigned integer value in range of [0, 65535]; the value of 65536 you've mentioned is out of range.
* * *
Complete test program — try different byte values in `buffer`:
#include <stdio.h>
#include <stdint.h>
int main()
{
//uint8_t buffer[2] = {255, 0 }; // prints 255
//uint8_t buffer[2] = {255, 127}; // prints 32767
uint8_t buffer[2] = {255, 255}; // prints 65535
int32_t temp = ((int32_t)buffer[1] << 8) | buffer[0];
printf("%d", temp);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c, integer, bit manipulation"
}
|
Is the SETNX always executed on redis master in the sentinel system?
wanted to ask
1. if the SETNX command (both the NX test and the SET) guaranteed to execute on the redis master in the context of the "Redis Sentinel System" ?
2. if it is guaranteed to to be atomic in the context of the "Redis Sentinel System"?
My understanding after reading the documentation is YES to both, because:
* Ad. 1 only the master can accept writes and since SETNX has a set/write component it has to go to the master (because all writes go through the master).
* Ad. 2 since the SET will be executed on the master it only make sense to check the NX part also on the master (no slaves queried, ever), otherwise it would be unnecessarily time consuming and could undermine atomicity.
Can someone confirm with 100% certainty, maybe point me to some documentation that clears my doubts. Thanks in advance!
|
I can confirm the above with %99.97 (3 sigmas) certainty.
> Ad. 1 only the master can accept writes and since SETNX has a set/write component it has to go to the master (because all writes go through the master).
Correct, excluding the scenario where you deliberately enable writing to replicas and connect to a replica.
> Ad. 2 since the SET will be executed on the master it only make sense to check the NX part also on the master (no slaves queried, ever), otherwise it would be unnecessarily time consuming and could undermine atomicity.
Yep.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "redis, redis sentinel"
}
|
Python: block character will not print
In IDLE, `print(chr(219))` (219's the block character) outputs "Û".
Is there any way to get it to output the block character instead?
This might actually be some sort of computer-wide problem, as I cannot seem to get the block character to print from anywhere, copying it out of charmap and into **any** textbox just results in the Û.
|
Use the correct character set.
3>> print(bytes((219,)).decode('cp437'))
3>> ord(bytes((219,)).decode('cp437'))
9608
3>> hex(9608)
'0x2588'
3>> print('\u2588')
Unicode Character 'FULL BLOCK' (U+2588)
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 7,
"tags": "python, character encoding, ascii, block, non ascii characters"
}
|
Building a querystring based on list column in SharePoint 2010
I am on SPD 2010. I want to set a column value for a custom list based on another column value. Basically, I am trying to build a URL with query-string parameters.
This URL will open a page with a Query String Filter Context Web Part.
Is there a way to dynamically build such a URL?
|
What you are referring to is either calculated or computed fields, depending on which use case you have. Either way its not really javascript related.
You can accomplish your needs by simply editing the XSLT for the view used in your custom list.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, sharepoint, sharepoint 2010"
}
|
Find the number of integer triplets such that $x+y+z=n$ and $x\geq y\geq z > 0$
> Let $n$ be an integer such that $n > 3$ and let $S$ be the set of all ordered triples of strictly positive integers $(x, y, z)$ whose sum is $n$. Show that $S$ has $\frac{1}{2} (n − 1) (n − 2)$ elements.
>
> Distinguishing cases, find the number of integer triples $(x, y, z)$ such that $x + y + z = n$ and $x \geq y \geq z > 0$
I’ve managed to prove the first part, that $S$ has $\frac{1}{2}(n-1)(n-2)$ elements but I am struggling with the latter part.
|
Hints for the second one:
Find the number of integer triples $(x, y, z)$ such that $x + y + z = n$ and $x \geq y \geq z > 0$
let $y = z+k_1$ and $x = y+k_2.$ with $k_1, k_2 \geq 0.$ Then we have $3z +2k_1 +k_2 =n.$ Then let $z_1 = z-1$ then $z_1 \geq 0.$ Finally we have $3z_1 + 2k_1+k_2 = n- 3.$ Note that $z_1, k_1, k_2 \geq 0.$
There are standard tricks to solve such an equation. Either you can use the General Principle of Inclusions & Exclusions or the idea of generating functions.
Basically, Shubham Johri gave you the solution before I wrote these hints.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "number theory"
}
|
Why we need a Thread.sleep with two parameters
Since two parameters of Thread.sleep(long mills, int nanos) are used to define timeout.Why we need the second parameter?Shall we just invoke Thread.sleep(long mills) and increase value of its parameter?If no,what the special point with two parameters?
|
The purpose of the two-argument `Thread.sleep()` is to allow you to specify sleep times in submillisecond intervals on systems that support that kind of resolution.
There would be no way to specify, e.g. a half a millisecond (500,000 nanoseconds) otherwise.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "java"
}
|
Fractional Transaction Count
Based on this question I understand the meaning of the following sorts of errors:
> Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
However I'm seeing:
> Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, **current count = 0.266**
I find a fractional transaction count to be equal parts funny, scary, and odd. I'm sorry I don't have a simple script to share that would reproduce.
Can anyone explain this behavior?
|
Well, I feel silly. I eventually saw this again, but it said "current count = 2.266" I thought that was again strange.
And then I noticed that 266 was the error number. Hmm.
**_Facepalm_**
Turns out I inherited some boiler plate error handling that was appending the error number to the error message without any separation. So what looked for all the world like a wacky ms thing, was in fact a wacky construct. I must have looked at it 100 times without seeing the actual problem.
|
stackexchange-dba
|
{
"answer_score": 4,
"question_score": 4,
"tags": "sql server, sql server 2014"
}
|
MySQL to SQL Server transferring data
I need to convert data that already exists in a MySQL database, to a SQL Server database.
The caveat here is that the old database was poorly designed, but the new one is in a proper 3N form. Does any one have any tips on how to go about doing this? I have SSMS 2005.
1. Can I use this to connect to the MySQL DB and create a DTS? Or do I need to use SSIS?
2. Do I need to script out the MySQL DB and alter every statement to "insert" into the SQL Server DB?
Has anyone gone through this before? Please HELP!!!
|
See this link. The idea is to add your MySQL database as a linked server in SQL Server via the MySQL ODBC driver. Then you can perform any operations you like on the MySQL database via SSMS, including copying data into SQL Server.
Congrats on moving up in the RDBMS world!
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 5,
"tags": "mysql, sql server, ssis, dts"
}
|
Is there a definitive solution for auto_complete in Rails?
I'm using DHH's auto_complete plugin, but am in the process of updating my dependencies on plugins to gems where feasible. Is there a newer, gemified version of this library, or has another solution emerged as the de facto standard?
|
I switched to jQuery autocomplete a long time ago, leaving outdated plugins in favor of unobtrusive custom javascript code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, rubygems"
}
|
How does a 2D game like Zelda handle the character being behind buildings where only part of him is shown?
I'm trying to develop a simple Zelda-style game. I found this very useful topic
How did LoZ: A Link to the Past handle sub-tile collisions?
that I'm using as reference to develop my collision detection mechanism. However, there's something I've failed to understand. When Link is behind buildings, only part of him is shown. Can anyone please help me understanding how this effect can be achieved? Isn't the building part of the background?
|
2D Tiled games usually have more layers which renders in different layers - some renders in the background others above the player.
That part of the roof renders above the player and that's why player can go behind that building.
Here is the image example from my game to explain better: !enter image description here
|
stackexchange-gamedev
|
{
"answer_score": 32,
"question_score": 28,
"tags": "2d"
}
|
Java Web-services. How to create a web service in Java console application?
I have the question... How to create a web service in Java console application **without using the web server**? Could you give me an example or a detailed response ...
|
Easiest way I can think of would be to go RPC style as described in the example below :
<
Though if you prefer jax-rs, the spec documentation would be a good read :
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, web services"
}
|
Keep option selected
I have a selectbox with some values, i inserted those values inside an array.
Now i want to select some specific option, and keep the option selected even when the page reloads.
$logos =array('logo1', 'logo2', 'logo3');
echo '
<td class="jofftd">
<label>Platform</label>
<select name="searchpt">
<option value="0">All</option>
';
foreach ($logos as $value)
{
echo '
<option value="'.$value.'">' .$value . '</option>
';
}
echo '
</select>
</td>';
I would need to do something like this:
foreach ($logos as $value)
{
echo '
<option';
if ($value == $value) echo 'selected="selected"';
echo 'value="'.$value.'">' .$value . '</option>
';
}
But it doesn't work.
Thanks.
|
Assuming you are using a POST method form, the code would look something like this (note: not tested)
foreach ($logos as $value)
{
$selected = ($value == $_POST['searchpt']) ? ' selected' : '';
echo '<option'. $selected . ' value="'.$value.'">' .$value . '</option>';
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, html, forms, foreach"
}
|
Booting into shell instead of graphical interface
I have a laptop with lubuntu. It's great but I wish LXDE was optional instead of autostarting.
So my question is, what can I do to make it boot directly into a text only mode, not loading anything extra until I do something like `start x` ? My goal is to have my system be as lightweight as possible until I need the extra stuff.
|
To disable the login manager permanently on Ubuntu you can do the following:
sudo sh -c "echo 'manual' > /etc/init/lightdm.override"
To start the login manager manually when needed you would do:
sudo service lightdm start
To stop it manually:
sudo service lightdm stop
|
stackexchange-unix
|
{
"answer_score": 5,
"question_score": 2,
"tags": "shell, startup, user interface, lubuntu"
}
|
How can I return two parameters from a javascript function?
I have the following:
function getPk(entity) {
var store = window.localStorage;
switch (entity) {
case "City":
if (store.getItem('AccountID')) {
// Need to return both of the below pieces of information
return store.getItem('AccountID') + "04" + "000";
return "CityTable";
} else {
paramOnFailure("Please reselect");
return false;
}
break;
The problem is I need to be able to call this function and return two strings. Here I show two return statements but I know I cannot do that.
Is there a clean way I can return two strings to the function that calls my getPk(entity) function?
If possible can you give an example also of how I can read what is returned.
|
Return them as either an array, or within an object.
return [store.getItem('AccountID') + "04" + "000", "CityTable"];
or
return { accountID: store.getItem('AccountID') + "04" + "000", table: "CityTable" };
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "javascript"
}
|
Is there a JavaScript/css method of making synced scrolling areas similar to "meld"?
I would like to have a couple of divs that scroll in sync with each other in a manner similar to the diff tool, meld. Note: as this is a static image, when you move the slider, the corresponding slider moves in sync with the other slider. I need to do this both horizontally and vertically.
This is for a highly customized diff tool, some of the diffed lines are very long, and horizontal scrolling needs to happen. This is within a web page, I use jQuery, but any css/JavaScript approach would be appreciated.
|
It should be as easy as binding to the scroll event of each div and set the `.scrollTop` & `.scrollLeft` of the other div equal to scrolled div's `scrollTop` & `scrollLeft`.
See < && <
**Edit:** Here is an example: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, css"
}
|
Modify Div Element with javascript
My script wont run or the document.getElementById("toMove"); doesn't seem to catch the element. Its very basic javascript but I cant understand why its not working.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#toMove
{
background-color:lightblue;
position:absolute;
}
</style>
<script>
var elem = document.getElementById("toMove");
elem.style.margin = "600px";
</script>
</head>
<body>
<div id="toMove" style="margin:200px; font-size:26px;"> Hello World</div>
</body>
Thanks
|
There's a couple of reasons why it's not working
1. You need to close the `<head>` tag properly
2. The point at which your script runs, the element with the id `toMove` does not yet exist in the DOM (Document Object Model)
Solving number 1 should be easy enough, just change `</head` to `</head>`. To solve number 2, you need to ensure that the script fires after the element with id `toMove` exists in the DOM. You can do this by hooking up your script to fire when the window has finished loading. The code below sets up a function to fire when the window has finished loading
window.onload = function(){
var elem = document.getElementById("toMove");
elem.style.margin = "600px";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
Java Generics and reflection!
I have a class that looks like this:
public class UploadBean {
protected UploadBean(Map<String,?> map){
//do nothing.
}
}
To use reflection and create a object by invoking the corresponding constructor, I wrote code as follows:
Class<?> parTypes[] = new Class<?>[1];
parTypes[0] = Map.class;
Constructor ct = format.getMappingBean().getConstructor(parTypes);
Object[] argList = new Object[1];
argList[0] = map;
Object retObj = ct.newInstance(argList);
This code fails at runtime with "No Such Method Exception". Now, how do I set the param type correctly?! such that the generic map argument in the constructor is identified?
|
The constructor is protected - if you make it public _or_ use `getDeclaredConstructor` instead of `getConstructor` it should work.
(You'll need to use `setAccessible` if you're trying to call this from somewhere you wouldn't normally have access.)
EDIT: Here's a test to show it working okay:
import java.lang.reflect.*;
import java.util.*;
public class UploadBean {
// "throws Exception" just for simplicity. Not nice normally!
public static void main(String[] args) throws Exception {
Class<?> parTypes[] = new Class<?>[1];
parTypes[0] = Map.class;
Constructor ct = UploadBean.class.getDeclaredConstructor(parTypes);
Object[] argList = new Object[1];
argList[0] = null;
Object retObj = ct.newInstance(argList);
}
protected UploadBean(Map<String,?> map){
//do nothing.
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "java, generics, reflection"
}
|
Scheduling review of content
I have a content type that includes a date field called expires. I'd like to set up some way to monitor all nodes of this content type and if the current date is close to the expires field value, send an email. I checked the rules module using the built in scheduler, but I didn't see a way to check a specific node, or a series of nodes.
|
Use `hook_cron()` to check the value of that field when cron runs and fire off an email with `drupal_mail_system()` if the value meets your criteria.
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "rules"
}
|
assigning pointer to another pointer, does the second pointer point to the same address as the first one?
in C programming, I am wondering about the following pointer assignment:
struct transaction_t {
int id;
char *name;
};
typedef struct transaction_t* transaction;
transaction pointer1 = malloc(sizeof(struct transaction_t));
transaction pointer2 = pointer1; /* is this a valid assignment? */
My question is: does the pointer2 point to the same address as pointer1 points to? can I perform the following using pointer2?
pointer2->name = "Chase Bank"
pointer2->id = 100;
For assining pointer1 to pointer2, should I malloc memory for pointer2 first?
|
After the assignment they both point to the same place.
Imagine you and your friend are in a room someone brings an empty box into the room and you point at it. You are now pointing at allocated memory. If your friend points at it too then you are both pointing at the same locations.
Assignments to either will put it in the same box.
You can also overwrite what is in the box.
* * *
It really does help to think of entities pointing and boxes when thinking about pointers in C and how they work. I'd have never been able to write my first linked list without boxes and arrows drawn on a page.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c, pointers, malloc"
}
|
How to set dotted line in Jpgraph with php
I want to set dotted line in jpgraph with php, but for this moment I set only standart line with this code:
$lineplot2 = new LinePlot($pro1, $pro1X);
$lineplot2->SetStyle("solid");
$lineplot2->SetWeight(3);
$lineplot2->SetColor('red');
Can I get example how to set dotted or broken line .. ?
|
`$lineplot2->SetStyle("dotted");`
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, apache, jpgraph"
}
|
How can I connect several links in the input node?
I need a slot to connect multiple links. In the API is an attribute of links to the type of collections:
`links = self.inputs ['ListAttrs']. links`
`for link in links:` ...
How can I connect several links in the input node?
|
Links are created using `node_tree.links.new`:
> `**new(** input, output, verify_limits=True **)**`
>
> Add a node link to this node tree
>
> **Parameters:**
>
> * `input` (NodeSocket, (never None)) – The input socket
> * `output` (NodeSocket, (never None)) – The output socket
> * `verify_limits` (boolean, (optional)) – Verify Limits, Remove existing links if connection limit is exceeded
>
>
> **Returns:** New node link
> **Return type:** NodeLink
|
stackexchange-blender
|
{
"answer_score": 3,
"question_score": 4,
"tags": "pynodes"
}
|
How to reset chapter after each part
How could we reset enumeration after each part? I.e. how can we have part I with chapters 1,2,3 etc, and then part II with chapter 1,2,3 ?
|
\makeatletter
\@addtoreset{chapter}{part}
\makeatletter
will do what you ask, although it is perhaps more normal to also do
\renewcommand{\thechapter{\thepart.\arabic{chapter}}
so the chapters are prefixed with the part number, unless the parts are sufficient;y distinct that you never need to cross reference between them.
|
stackexchange-tex
|
{
"answer_score": 5,
"question_score": 4,
"tags": "chapters, parts"
}
|
What's the right way to setup an image classifier by multiple params?
I'm very new to the data science and machine learning, so apologies for my ignorance. What I'm trying to understand is how to setup an image classifier system (maybe based on CNN) which will classify my image by multiple params. Most of the examples I found are about classifying by single class, i.e. "cat", "dog", "horse", etc, but what I'd like to have is, for example, **{"red", "dog", "tongue"}**. Is there a simple way to do it? The best option would be to have a ready setup, so I can just change their test dataset with mine and see the right formatting. Thanks!
UPDATE:
Also please help me understand if it's a complicated task for an experienced machine learning engineer? What'd be the timing and cost given a dataset?
|
You normally one hot encode your labels so that every possible attribute gets it's own binary representation. So if you have 10 attributes they would be represented as [attr1, attr2, attr3, ..., attr10], with values either 1 if the attribute is present, or 0 if it is not.
Then you train a network with the same number of output neurons as possible categories and use a sigmoid activation function.
|
stackexchange-datascience
|
{
"answer_score": 0,
"question_score": 2,
"tags": "classification, cnn, image classification"
}
|
if multiple dice are thrown, how can I calculate their variance and mean?
from my calculation if 4 6-sided dice are thrown:
$$E[x] = 14.0 $$ $$E[x^2] = 207.66666.. $$ $$Var(x) = E[x^2]-(E[x])^2 = 11.666666666666657$$
would there be some general formula for a dice with each dice having n sides?
|
For a fair die with $n$ sides, we get $$ E[x]=\sum_{i=1}^n \frac{1}{n} i =\frac{1}{n}\sum_{i=1}^n i=\frac{1+n}{2}$$ And $$ E[x^2]=\sum_{i=1}^n \frac{1}{n} i^2 =\frac{1}{n}\sum_{i=1}^n i^2=\frac{1}{6} (1+n) (1+2 n)$$
And of course $$Var[x]= \frac{1}{6} (1+n) (1+2 n)- (\frac{1+n}{2})^2 $$
By the way, since the dice are independent, $Var[X_1 + X_2 + X_3 + X_4 ] = 4 Var[X_1]$ no matter how many sides the dice have. So you only need to calculate for one die and multiply.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "probability, dice"
}
|
Python "object" class. Is it just blank or there is something more about it?
I'm trying to find some more information about the Python base class: `object` but can't find any. Is it just something like `class object: pass` and doesn't deserve any more attention or...?
Where can I find more about it. What do other classes inherit from it?
|
There's some good info here (and in other articles linked from there). Here's the diagram:
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, class, inheritance"
}
|
How to generate circular matrix?
I want to generate a circular matrix in C or C++.
How can I generate the matrix below, for n = 3?
1 2 3
8 9 4
7 6 5
|
In a "circular" matrix, the "middle" of it is circular too, except that it doesn't start with 1. So run round the perimeter and recurse.
void cmat_step( int** M, int a, int i, int j, int dim)
{
int k;
/* fill perimeter */
for( k=0; k<dim; ++k) M[i][j+k] = a++;
for( k=1; k<dim; ++k) M[i+k][j+dim-1] = a++;
for( k=dim-2; k>=0; --k) M[i+dim-1][j+k] = a++;
for( k=dim-2; k>=1; --k) M[i+k][j] = a++;
if ( dim >=2)
{ /* fill middle */
cmat_step( M, a, i+1, j+1, dim-2);
}
}
void cmat( int** M, int dim) { cmat_step( M, 1, 0, 0, dim); }
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 2,
"tags": "c++, c, matrix"
}
|
Confused about residue of a complex, rational function
I am asked to find $\text{Res}(i)$ for $R(z)=\frac{2z+3}{(z-i)(z^2+1)}$. Noticeably, $R(z)=\frac{2z+3}{(z-i)^2(z+i)}$.
While I understand how to find the corresponding partial fraction decomposition for the above equation, I am confused about the nature of $\text{Res}(i)$. Should $\text{Res}(i)$ be the coefficient for the $\frac{A}{(z-i)^2}$ term? Or the coefficient for the $\frac{B}{(z-i)}$ term? Or somehow both?
Thank you for your help!
|
$z=i$ is a double pole of $R(z)=\frac{2z+3}{(z-i)^2(z+i)}$, hence $$\text{Res}\left(R(z),z=i\right) = \lim_{z\to i}\frac{d}{dz}\left((z-i)^2 R(z)\right)=\lim_{z\to i}\frac{d}{dz}\left(\frac{2z+3}{z+i}\right) $$ and $$\text{Res}\left(R(z),z=i\right) =\lim_{z\to i}\frac{2i-3}{(z+i)^2}=\color{red}{\frac{3-2i}{4}}.$$ We have $$ R(z) = \frac{A}{(z-i)^2}+\frac{\color{red}{B}}{z-i}+\frac{C}{z+i}+Q(z) $$ where $Q(z)$ is an entire function and the wanted residue is $B$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "complex analysis, residue calculus, rational functions"
}
|
Is there any advantage to USB 3.0 on an external DVD writer?
Given that many external DVD writers max out at 8x for read and write, and that even a 16x would require a throughput of at most 22 MB/s (which is below the low end of observed throughput for USB 2.0, which is 25 MB/s according to Wikipedia), is there any practical advantage to having an external DVD writer that supports and is connected via USB 3.0 over USB 2.0? Power? Bandwidth saturation due to multiple devices?
|
Short answer : No, unless you are using a high-quality BluRay writer.
A DVD writer at 8x means a max theoretical speed of 8 X 4.5 MB/s which equates to 36 MB/s. USB2 has a real world speed of around 35 to 40 MB/s, therefore is good enough for these drives.
However, for BluRay writers at 12x or 16x, this means a theoretical speed of 54 or 72 MB/s, which is more than USB 2 can handle.
Another difference is power usage, where USB2 can do up to 500 mA, while USB3 can do up to 900 mA. USB2 power may be a limiting consideration when buying a DVD writer.
But I'm not sure that the difference in real world speed in using a 12x/16x drive via USB2 vs USB3 is worth the price difference, especially if you are not planning on using BluRay.
|
stackexchange-superuser
|
{
"answer_score": 4,
"question_score": 6,
"tags": "usb, dvd, usb 3, usb 2"
}
|
Removing second python install
This morning I installed python3.3.2 from source, which is giving me some headaches, so now I want it removed. python3 launches python3.3.2, which is stored in /usr/local/bin. However, when I try to remove it, it wants to remove python3.3.1, stored in /usr/bin. I obviously want to keep this one.
$ which -a python3
/usr/local/bin/python3
/usr/bin/python3
How do I get 'sudo apt-install remove python3' to not remove the necessary 3.3.1 /usr/bin one, and only 3.3.2 one in /local/bin? Thanks for any advice!
|
If you installed it from source, `apt-install` has no idea that it exists.
The easiest way (as most makefiles don't have an `uninstall` target) is to run `make install` again in your 3.3.2 source directory and capture what it sticks where and then remove them.
The cheaper way would be to `rm /usr/local/bin/python3` and probably anything else in `/usr/local/bin/py*` including symlinks to various parts of the suite.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "ubuntu, apt get"
}
|
How to find unresolved variables in Angular 2 templates
I have a project with a generated client. That means, models are autogenerated from a JSON file. When a property name in the backend has changed and I check a template with a changed property in it (e.g. `user.name` became `user.firstName` in the model for `User`), I see that it has green underlining in WebStorm, but the page opens and it just doesn't get displayed. But if I didn't open the template, I wouldn't recognize the problem.
So is there either some setting for WebStorm or for Lint to complain more when the HTML files' properties are recognized as "unresolved variables"?
|
In webstorm, if you perform a code analysis, do you see the unresolved variable in the Inspection Results? <
Otherwise if you are using tslint, codelyzer is an extension for tslint that has various rules specific to angular.
I think the specific codelyzer rule, `no-access-missing-member`, is what you would be looking for. If you set that up, then you could run tslint in your console and get a list of errors.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "angular, templates, webstorm, lint"
}
|
Can we treat mankind as a plural noun?
This comes from The Company Man from Herman Melville:
> And **are** mankind so stupid, so wicked, that, upon the demonstration of these things they will not, amending their ways, devote their superfluities to blessing the world instead of cursing it?
Why is are used here instead of is? Is this a grammatical error?
|
A couple of points here...
Firstly, just because something doesn't accord with standard grammar doesn't mean it's an error. It's perfectly reasonable to be creative with grammar, once you know what you're doing (though someone teaching English as a foreign language is likely to suggest you shouldn't try it).
Second, language changes. Melville died in 1891. Once upon a time, _mankind_ was usually grammatically plural. Nowadays it's usually grammatically singular. On the other hand, if you want it to be plural now, you can still say something like "all of mankind", and that phrase can be plural to much wider acceptance.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 1,
"tags": "grammar"
}
|
C++ User-defined type conversion failure
template<typename T>
class Pack
{
private:
std::function<T()> _Func = nullptr;
public:
Pack()
{
}
Pack(std::function<T()> func)
: _Func(func)
{
}
~Pack()
{
}
operator T()
{
return _Func();
}
};
What I use is `operator T`, I want to call `_Func` implicitly but I cannot even do it explicitly. It seems right but actually error C2440 @MSVC. I use it in two ways:
1. static member of class (succeeded);
2. member of class (failed)
(I don't know whether it matters or not)
I'm really wondering why it performs in two ways, and more importantly, how I can put it into my class as a non-static member and successfully call the `operator T`.
|
Member of the class:
struct test
{
test()
{
p_ = Pack<int>(std::bind(&test::foo, *this));
}
int foo()
{
std::cout << "test::foo" << std::endl;
return 5;
}
Pack<int> p_;
};
int main()
{
test t;
int x = t.p_;
return 0;
}
This works fine on VS 2013 EE.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, visual c++"
}
|
How long is start date? 00h00mm00ss or a 24hour period?
I have simple membership statuses that say: Status 1: from membership date to start date Status 2: from start date to end date.
On start date, the membership has changed from not member to member but the status stayed on Status 1. (I have set the cron every hour so it would be updated the way it should).
When is the time limit: 00h00mm00ss or a 24hour period?
How does it work in CiviCRM?
|
After testing, here is how it works.
If we use again my example with twice the same event date **3rd of April** :
Status 1: from membership date to start date
Status 2: from start date to end date.
Status 1 will change **by the end** of the 3rd of April which means start date from the previous status is "Master" and start date lasts 24 hours. Status 2 will appear on the 4th of April. And this is not related to cron Job.
So if you want to start Status 2 on the 3rd of April at 00h00'00", for example if an Insurance is running from this date or if the member has to be of legal age, then set the end event of Status 1 on start date and -1 Day.
|
stackexchange-civicrm
|
{
"answer_score": 1,
"question_score": 0,
"tags": "civimember"
}
|
How do I recursively create a folder inside another non-existent folder?
I want to create this folder: `$HOME/a/b/c/d` while `$HOME/a` has not yet been created! Is it possible with one line in Terminal?
|
You can use the command `mkdir` with `-p` option to create a folder inside another non-existent folder. Consider an example,
mkdir -p "$HOME/a/b/c/d"
Where the folders `a`,`b`,`c` and `d` do not exist in home before running the command. After execution of the command all these folders will be created recursively inside one another.
You can see from `man mkdir`
-p, --parents
no error if existing, make parent directories as needed
|
stackexchange-askubuntu
|
{
"answer_score": 17,
"question_score": 11,
"tags": "command line"
}
|
How to retrieve all companies data in Intrinio based on tags like apturnover, 52_week_high, capex, ceo, adress etc in csv column? in intrinio
> I want specific tags in CSV column with a list of all companies. I downloaded all companies details but there are only four columns in that CSV file. I want to pass all companies details as identifier and items as some specific tags.
|
Intrinio has limit 150 for data tag and identifier combination. so you can use Intrinio Excel Add-in and write which data tags you want in next column. write macros like =intrinioDataPoint(A2, $B$1) for first data tags, =intrinioDataPoint(A2, $C$1) for second and so on. if you want more combination then checkout intrinio tutorial on youtube.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "api, csv"
}
|
How to increase video speed and frame rate without duplicating frames
I have a long video with a frame rate of 30 FPS that I want to convert into a 200x time-lapse with a frame rate of 60 FPS. My only problem is that avconv is unnecessarily duplicating every other frame in the output, making the 60 FPS output effectively 30 FPS. I want every frame to be unique. At a 200x speed increase and 2x frame rate increase, there is no reason to duplicate frames.
For example, the problem is that the output is using source frames like 1,1,21,21,41,41,... when I want it to use frames 1,11,21,31,41,51,...
Here's the command I'm using:
avconv -i input_30fps.avi -vcodec h264 -an -r 60 -vf "setpts=(1/200)*PTS" output_200x_60fps.avi
|
As happens regularly to me, after spending hours trying to figure it out before asking for help, I find the solution myself just minutes after asking.
It turns out avconv isn't the better replacement to ffmpeg that I thought it was when Linux Mint, IIRC, removed ffmpeg from the official repository in favor of avconv. Anyway, ffmpeg is back and I installed it and found the equivalent command that doesn't duplicate frames:
ffmpeg -i input_30fps.avi -vcodec h264 -an -vf "fps=60, setpts=(1/200)*PTS" output_200x_60fps.avi
|
stackexchange-superuser
|
{
"answer_score": 7,
"question_score": 8,
"tags": "video, ffmpeg, libav, framerate"
}
|
Как узнать, входит ли point в polygon? android, yandex mapkit
Задача в следующем, есть какие-то регионы, их нужно обозначить в полигоны (многоугольник) в приложении используя yandex mapKit. Пользователь может ставить точку в любом месте, и в этот момент должно происходить условие, входит ли эта точка в полигон или нет. Вопрос в следующем, возможно ли такое реализовать средствами yandex mapkit? Если нет, может есть альтернативные решения?
|
В MapKit не предоставляются инструменты взаимодействия с геометрией. Это можно сделать в Java. Посмотрите похожие вопросы.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android, yandexmapkit"
}
|
Will memory always be reclaimed when using 'del'?
l = [1, 2, 3]
del l
From the python docs:
> It is not guaranteed that `__del__()` methods are called for objects that still exist when the interpreter exits.
Does this mean that the list object, in this case `l`, will not be deleted even when the interpreter exits? I mean when the program exits, aren't all the objects reclaimed?
|
> It is not guaranteed that `__del__()` methods are called for objects that still exist when the interpreter exits.
This statement implies that you should not rely on a custom `__del__()` method being executed upon interpreter exit.
The statement _does not_ imply that the interpreter will create a memory leak.
In all cases when Python exits, all memory will be released.
### See also
* What is the **del** method, How to call it?
* When is del useful in python?
* What does “del” do exactly?
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "python, object"
}
|
Solving inequalities number line
So I am currently doing inequality problems and i have the answer to the question but am unsure on how to put that onto a number line.
The question is $-7+b≤6b-2<7b+1$.
The answers i got for this are $b≥-1$ and $b>-3$ and am wondering on if the answer is correct and how to put this onto a number line help would be greatly appreciated.
|
$\color{red}{-7+b} ≤ \color{green}{6b-2} < \color{blue}{7b+1}$ means two inequalities:
**$(1)$** $\color{red}{-7+b} ≤ \color{green}{6b-2}$.
Solving **$(1)$** gives $-1 \leq b$.
**$(2)$** $ \color{green}{6b-2} < \color{blue}{7b+1}$.
Solving **$(2)$** gives $-3 < b$.
In total we have $b \geq -1 >-3$.
$b \geq -1$ is enough.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "inequality, education, number line"
}
|
Random Python dictionary key, weighted by values
I have a dictionary where each key has a list of variable length, eg:
d = {
'a': [1, 3, 2],
'b': [6],
'c': [0, 0]
}
Is there a clean way to get a random dictionary key, weighted by the length of its value? `random.choice(d.keys())` will weight the keys equally, but in the case above I want `'a'` to be returned roughly half the time.
|
This would work:
random.choice([k for k in d for x in d[k]])
|
stackexchange-stackoverflow
|
{
"answer_score": 35,
"question_score": 35,
"tags": "python, random, dictionary"
}
|
UIPopOver from MKAnnotation callout
i'm developing an application for iPad. I have a mapview with several annotations. I need to show a pop-over when the accessory callout method is called, so that the arrow of the popover will point towards the annotation. I am trying to use 'initWithRect' method of the popover, but i'm not getting the co-ordinates(the CGRect in view) of the annotation correctly. How can i get the co-ordinates of an annotation? I need to find out the location of that annotation in the view.
|
Probably, you can use `MKMapView`'s method `convertCoordinate:toPointToView:` with specified annotation coordinates (required property of MKAnnotation Protocol) and view.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "ipad, uipopovercontroller, mkannotation"
}
|
Che cosa significa "sbracciarsi" in questo contesto?
Nel romanzo _Il barone rampante_ , di Italo Calvino, ho letto:
> Cosimo era sull'elce. I rami **si sbracciavano** , alti ponti sopra la terra. Tirava un lieve vento; c'era sole.
Potreste spiegarmi il senso di "sbracciarsi" in questo brano? Ho cercato il verbo "sbracciare" in parecchi dizionari, ma non ho trovato nessuna accezione che abbia a che vedere con gli alberi.
|
Nel contesto da te citato sbracciare significa diramarsi dal fusto dell'albero e protendersi verso l'alto, come se i rami fossero braccia.
Già in un'altra domanda "Le braccia delle palme sono le foglie" si faceva riferimento ai rami come braccia dell'albero.
Inoltre i rami mossi dal vento, paragonati a braccia, ricordano lo sbracciarsi di una persona per attirare l'attenzione.
|
stackexchange-italian
|
{
"answer_score": 4,
"question_score": 1,
"tags": "word meaning, verbs"
}
|
struct - Partial initialize skipping middle components
Suppose I have a `struct` with the following form
struct one {
double d;
char c1;
char c2;
int i;
};
I know I can do a partial initialization like this
one s1={2.71,'e'};
Declaring the values of the first two components only, and leaving the other two blanks. However, what if I want to initialize only the last two components of another `one` `struct`? Am I forced to write
one s2={0.0,'\0','a',42};
or is there a way I can give instructions about `c2` and `i` only, leaving `NULL` inizializations of `d` and `c1` up to the compiler?
|
I have no idea why you want to to this, however you could define a constructor like:
one( char c2Arg, int iArg ) : c2(c2Arg), i(iArg) {}
and call it like:
one s1('a', 42);
Instead of leaving th first two members uninitialized, it is probably better to assign default values to them:
one( char c2Arg, int iArg ) : d(0.0), c1('\0'), c2(c2Arg), i(iArg) {}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c++, struct, initialization, partial"
}
|
Very basic question about the structure of my iPhone game
I'm making an iPhone game in which I have two main views, the planning stage and the action stage. Both of these will have different graphics etc, but I'll obviously need to pass information between them. I've pretty much finished programming the planning stage, and I know how to switch between views, but I'm a little fuzzy on how exactly I should be setting the whole thing up. Should my SwitchViewController, which handles the switching between the two views, also control the passing of the game state and the game moves between the two views? Or is there a better way to do this? Thanks for reading!
|
It would probably make sense to package all your game information up into a single 'gameState' object, and attach that to your app delegate (or some other 'non transient' object).
If you pass it all back and forth, you can run into problems if you ever change your flow, or add a variable and forget to pass it. This approach avoids both those issues.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "iphone, view"
}
|
Disable portb a/d on pic18f25j50
I want PORTB as digital inputs and it seems RB0 to RB3 are not responding to digital inputs..
So how can I disable analog on these port pins?
I'm using mikroc pro for pic..
I had the same problem with pic18f2550 but it had portb a/d enable bit in project settings...
But pic18f25j50 doesn't have this option available anywhere ... His can it be done?
|
The registers you are looking for are ANCON0 and ANCON1. If they are set to zero they are analog and if they are set to one the pins are digital. They control the digital/analog configuration of pins. You can find a description of these registers in the data sheet under section 21.0 10-BIT ANALOG-TO-DIGITAL CONVERTER (A/D) MODULE
|
stackexchange-electronics
|
{
"answer_score": 2,
"question_score": -5,
"tags": "microcontroller, pic, microchip"
}
|
Is there a more accurate LWJGL timer
After looking at timer showed on the LWJGL wiki milliseconds weren't fast enough. It kept an inconsistent speed of the player. I can't find anything on how to produce a more accurate timer, like 3.2 milliseconds instead of 3 milliseconds. I know this sounds stupid, but I'm really stuck.
|
You could use System.nanoTime():
long startTime = System.nanoTime();
//Stuff in-between
long timeTaken = System.nanoTime() - startTime;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, lwjgl, timedelta, delta"
}
|
Sublime Text 2 - alignment of comma separated values
I have installed the Sublime Alignment plugin. It works well for aligning the first character (default is `=`). How can I align this block in Sublime Text 2 in one shot :
> INSERT INTO user VALUES (1, 'Alpha', 'Beta', 'Delta');
> INSERT INTO user VALUES (2, 'A', 'B', 'D');
to look like :
> INSERT INTO user VALUES (1, 'Alpha', 'Beta', 'Delta');
> INSERT INTO user VALUES (2, 'A', 'B', 'D');
Even if I add `,` as the alignment character in sublime alignment, it only works for the first occurence of `,`
|
Align Tab is quite versatile & can accomplish the alignment and it's not limited to just first character.
Install
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 7,
"tags": "alignment, sublimetext2, indentation"
}
|
How to require an alternative js file from a npm package without specifiying full node_modules path
I am using the ES2016 import syntax to load the select2 libray from an npm module (via Webpack):
import 'select2';
This works fine and loads the following file from the node_modules directory.
_node_modules/select2/dist/js/select2.js_
Now within that directory they have a full version of the library which has some extra functionality I need, it is called:
_node_modules/select2/dist/js/select2.full.js_
Is there a way to import this without providing the full relative path to my node_modules folder?
I tried:
import 'select2.full'
but no luck.
|
Try this:
import 'select2/dist/js/select2.full.js'
I think this is the best you are going to get.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 7,
"tags": "javascript, node.js, npm, webpack"
}
|
Event only activate when clicked twice
I am using jQuery to hide/show a side-bar on my HTML page. The `.toggle("slide")` event will activate when an `<li>` element is pressed.
<div class="sidebar" id="SideBar"></div>
<!-- elsewhere in code... -->
<li style="//Styling li Button." id="toggle-bar" onclick="toggleEvent();">toggle bar</li>
{
$("#toggle-bar").click(function(){
$("#SideBar").stop().toggle("slide"); // for left to right slide.
});
}
I used `.stop()` to stop animation after one slide effect but the animation only takes place when user first focuses on the `<li>` element (by clicking on it).then clicking again to trigger animation (I'm assuming)
So, please tell me how to trigger animation only in one click
|
I'm a little confused why you're using the html `onclick` and jquery's `.click()` together on the same element.
I would suggest removing the `onclick` from the html and remove the `.stop()` call, so then your animation is called once, instead of twice. As mentioned by other comments, it would be good to know what `function toggleEvent()` is so we can provide a more accurate answer.
your html:
<div class="sidebar" id="SideBar"></div>
<!-- elsewhere in code... -->
<li style="//Styling li Button." id="toggle-bar">toggle bar</li>
your javascript:
$("#toggle-bar").click(function(){
$("#SideBar").toggle("slide"); // for left to right slide.
});
or if you need `function toggleEvent()` to run instead, your javascript can look like:
$("#toggle-bar").click(toggleEvent);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, jquery, html, css"
}
|
React setState race conditions
I am building a React component that does a lot of calls in the background to gather data. I want the View to be as responsive as possible, loading in data as soon as we get it. However, this is causing race conditions in handling the state properly.
Occasionally one experiment result unsets another. How do I handle this parallelism properly?
const ctrl = this;
this.state.experiments.foreach((experiment) => {
this.props.ReportV4.kpi({
experimentId: experiment.id
}).then(function (report) {
experiment.kpi.significant = report.significanceReached;
experiment.kpi.uplift = report.uplift || "N/A";
ctrl.setState({
experiments: update(ctrl.state.experiments, {[experiment.key]: {$set: experiment}})
});
});
});
|
Yes, this is how JavaScript as a single threaded language maintains its callback stack. Your loop will create certain callbacks in stack. I would like to recommend, you maintain an `experiments` object as a class property. This will contain all callback data upon receiving.
in constructor:
constructor(props) {
super(props);
this.experiment= {};
}
in promise callback:
// populate your experiment whit significant & uplift etc.
this.experiments[experiment.key] = experiment;
this.setState({
experiments: this.experiments
});
You can render these experiments with their key names without even iterating over experiments.
I hope this will help you.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "reactjs"
}
|
How to create function and call function
Can anybody give me one example of creating a simple function which returns the sum of both the input fields?
<html>
<body>
number1:<input type="text" name="number1" />
number2:<input type="text" name="number2" />
<input type=submit name="submit" value="submit"/>
</body>
</html>
|
function addition( $num1,$num2)
{
echo "Result = " . $num1 + $num2;
}
and call the function by
if(isset($_POST["submit"]))
{
$num1=$_POST['number1'];
$num2=$_POST['number2'];
addition( $num1,$num2);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "php, html"
}
|
Modify JIRA Service Desk translation
I have installed Jira Service 3.2.2 and Jira Core 7.2.2.
Whenever I create a new incidence in my project, an email is sent to the user. That email is sent in Spanish and I just want to change a sentence from that email.
I've found some translations in the file
\jira\plugins\installed-plugins\jira-servicedesk-application-3.2.2.jar
in `\i18` folder.
I've changed there the wrong sentence and restarted JIRA but the email is still the original, changes seem to not be applied.
Is it the wrong location for email templates translations?
Thanks in advance!
|
Well, after restarting twice the JIRA server the changes were applied.
That means translations are taken from file:
\jira\plugins\installed-plugins\jira-servicedesk-application-3.2.2.jar
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jira, jira plugin"
}
|
Special code format/ highlighting/ code-escaping
I found a question like this. My problem now is that `/*` leads inside this codeblock to starting a comment. But it is no comment after this sign. I found this earlier, too. And I didn't find a sample her on meta.
Question zero: Where is a problem like this described/ solved her on meta?
Question one: Is there an option to have kind of escaping special characters like in some languages you use `\\n` or `"\"n`?
|
The code there was being formatted as Java because of the java tag. I've added comments to both blocks to explicitly force no syntax highlighting on the first, and XML highlighting on the second.
* * *
You can check out Syntax highlighting language hints for information on how to use the syntax highlighting comments.
|
stackexchange-meta
|
{
"answer_score": 2,
"question_score": 1,
"tags": "support, syntax highlighting"
}
|
How can I change a route in Rails 3 based on user login?
I'm curious if it's possible to send a Rails 3 application to one website if someone lands on the site as a guest and another website if someone lands on the site as a user.
Is this done in routes? Is this done in the controller-tier?
|
You should consider using sessions. They work like this:
session[:any_key] = any value (though it should be small, think database id, instead of entire model)
Most people use session[:user_id]
Resources:
<
<
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 3, routes"
}
|
HTML - Alternative to having an id as a number?
I wanted to get some input on how to best handle my situation.
I want to store a numerical id for each table row(< tr>) but I realize that it isn't good practice to make an id for the < tr> a number. Is there any other way to store an id/number value for a table row besides storing the id as a column field?
Basically when you click on the table row it will take you to another page that loads data from a database depending on the id.
|
It's not "not good practice"; it's not actually illegal unless you are using HTML5, which is more permissive. For compatibility reasons, however, you should not start ids with numbers.
You have two choices: Custom data attributes, or custom attributes. The earlier is preferred, as the latter produces invalid HTML. For example:
<tr customattribute="1"> <!-- not a good idea -->
<tr data-custom-attr="1"> <!-- Better idea/preferred way -->
You will have to access both via JavaScript. If you are using jQuery, for example:
$('selector').data('custom-attr');
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "html"
}
|
CSS - make border bottom shape like trapezoid
I want to create menu where I need a feature like if any user hover the menu there will be a border and the border bottom only. I want to display the bottom border like trapezoid.
> In my case i don't have a div for border, its only border-bottom.
Here is what I've tried:
#myDiv{
background: #FED;
border-bottom: 5px solid red;
}
<div id="myDiv">
My div, I want to make my border bottom like trapezoid.
</div>
How can I achieve this?
|
If I get your correctly, you want to set the border shaped as ~~triangle~~ trapezoid after `#myDiv`. This is basically how you can do it with css..
#myDiv:after {
content: "";
display: block;
border-left: 1vw solid transparent;
border-top: 10px solid red;
border-right: 1vw solid transparent;
}
<div id="myDiv">
My div, I want to make my border bottom like triangle.
</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "css"
}
|
Confusion with method declaration
> **Possible Duplicate:**
> Method Syntax in Objective C
I'm quite new to iPhone development and I'm confused about the method declaration iPhone development using X-code
Please help me identify what is the name of the method here.
`tableView` or `willSelectRowAtIndexPath`
Please explain how did you recognize it. Thanks in advance.
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
if (row == 0) return nil;
return indexPath;
}
|
The method signature is `tableView:willSelectRowAtIndexPath:`. Here you can read about method names in Objective C - < Ask more if you're unsure why and what's going on here.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c"
}
|
Why $\frac{y}{x}$ is not in $k[x,y]/(y^2 - x^3)$?
May be it is a silly question, but I do not understand why $\frac{y}{x}$ is not contained in $A = k[x,y]/(y^2 - x^3)$. What contradiction do I get if $\frac{y}{x}\in A$?
|
Your question boils down to: Are there $f,g\in k[x,y]$ such that $$xf(x,y)-y=(y^2-x^3)g(x,y)?$$ By plugging in $x=0$, this becomes $-y=y^2g(0,y)$, which is absurd.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "abstract algebra"
}
|
Linespacing in TCPDF MultiCell
I haven't found a way to control linespacing in TCPDF's MultiCell as of version 5.9. Nor have I found any method that helps to mimic the same behaviour by using Cell, such as some method that returns the portion of the text that doesn't fit inside a Cell's width.
Any ideas?
I wish I could switch to FPDF (which I prefer), but I can't.
|
$pdf->setCellHeightRatio(0.8);
in TCPDF source code documentation:
* Set the height of the cell (line height) respect the font height.
* @param $h (int) cell proportion respect font height (typical value = 1.25).
* @public
* @since 3.0.014 (2008-06-04)
|
stackexchange-stackoverflow
|
{
"answer_score": 54,
"question_score": 17,
"tags": "tcpdf"
}
|
Breaking a list into strings, not characters
I have a `defaultdict` that looks like this:
"Some text" : ["Some date", "Some date", "Some Date"]
I am trying to access each individual value of each key like so:
for processedTweet, date in tweetsDict.iteritems():
print date
for d in date:
print d
This works fine in a normal Python script. It prints the entire list first then in the for loop it prints each individual date.
But when I send this as part of a Map/Reduce job to Hadoop, it breaks the list into individual characters, not Strings, i.e.:
Some date
becomes
S
o
m
etc. Why is this happening and how can I fix it?
|
The map/reduce job in hadoop is distributing your list values to the for-loop instead of passing the entire list. By default, when python iterates over a string object each iteration returns the next character in the string.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, list, hadoop"
}
|
Matlab speed problems
Can anyone help to understand what/where is the problem?
I am comparing the speed of a basic matlab function like the mean.m with two matlab version 2013b and 2014b with the same machine.
and surprising, the version 2013b is much faster than 2014b.... Some of you have/had the same problem??
Profile summary of mean with 2014b --> 0,024 Profile summary of mean with 2013b --> 0,013
like in my scripts I use the mean function really often the different in running time of the same program in one or the other version is huge..... Whats going on?
the code to compute the profile time:
A=rand(100,1)
time_mean=zeros( 1000,1)
for i=1:1000
tic
mean(A);
time_mean(i)= toc;
end
|
Firstly, it's not wise to use the profiler to compare timings across releases - it's designed to identify slow portions in a single MATLAB release. Secondly, you should use `timeit` to time this sort of thing. I compared R2013b and R2014b on my Windows machine over a range of sizes, and can see what appears to be a small fixed overhead in R2014b of around 0.1ms.
Code is essentially:
for exp = 1:6
A = rand(10^exp, 1);
t(exp) = timeit(@()mean(A));
end
semilogy(1:6, t);
!Plot of execution time for vector mean
If you are making lots of individual calls to `mean`, you might be better off seeing if you can form these into a single call - MATLAB's `mean` can operate down columns or along rows of a matrix...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "matlab"
}
|
git, is it possible to send pull request from master branch?
I guess my title does not self explanatory so let me explain little bit there.
1. I forked a project from Github repo to my company repo.
2. Then I forked the project from my company repo into my personal repo
3. Then I cloned the project from my personal repo.
By default I had/have a master branch. I fixed a lot of things(bugs) and added so many features on this branch. I'm done now and I want to send PR.
AFAIK, PR can be sent by having a branch (which is not exists on origin/upstream) then easily PR can be sent by click on that button on Github page.
Since, I only have master branch and I guess my only solution is cherry-pick from my first commit and then put all my changes on new branch and continue PR process.
I'm wondering is there any other better way to send PR from master branch (to original repo)? any suggestion would be appreciated. Thanks.
|
> Since, I only have master branch and I guess my only solution is cherry-pick from my first commit and then put all my changes on new branch and continue PR process.
You don't have to cherry-pick anything: you can simply create a new branch on top of your current master, which will include immediately all your changes/fixes.
git checkout -b newBranch master
From there, you can initiate a PR using "`newBranch`" instead of master.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "git, github, pull request, cherry pick"
}
|
Why the Call instruction in the x86 architecture saves the return address as EIP+5 instead of 4?
In 'The Computer Organization and design book' it illustrates the call instruction as
1. Decrementing the stack pointer by 4.
2. saving the **EIP+5** into the stack.
3. Jumps to the new address specified.
What I know already is the instructions in this architecture are not typically all 4 byte in length, Hence.
How do we standardize the **EIP** to be added by **5** to the next instruction ?
normally in the MIPS architecture throughout the rest of the book the EIP is incremented by 4 which is intuitive as all the instructions are 32 bits.
|
Not sure which book you are referring to (isn't that book talks only about MIPS and not on x86?)
In any case, I think that the answer is the following: EIP+5 is the address of **the next instruction**. That is, in x86 the next instruction after a (near32) call is 5 bytes away. This is because the call takes 5 bytes:
1byte = the call opcode (E8, for a (near)rel32 call)
4bytes = the 32bit offset to the call target from current EIP.
That is, the new EIP (after the call) is computed by taking the current EIP and adding to it the 4bytes relative offset.
So, if the call instruction itself takes 5 bytes, then the next instruction (the _return address_ ) is at EIP+5.
See also < for all possible calls (I described the rel32 one).
|
stackexchange-cs
|
{
"answer_score": 3,
"question_score": 2,
"tags": "computer architecture"
}
|
Put whole gitlab installation to read-only mode
I wish to deny to push changes to any repository by any user. Technically, I need to switch whole gitlab to read-only mode. Is there simple way to do this?
|
If you don't want to mess with the user privileges (as done in this PR), one approach would be to change the gitlab-shell pre-receive hook.
If the pre-receive hook always "`exit 1`", that should disable any push to any repo.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 8,
"tags": "gitlab"
}
|
Implicit conversion from char** to const char**
Why my compiler(GCC) doesnt implicitly cast from `char**` to `const char**`?
Thie following code:
#include <iostream>
void print(const char** thing) {
std::cout << thing[0] << std::endl;
}
int main(int argc, char** argv) {
print(argv);
}
Gives the following error:
oi.cpp: In function ‘int main(int, char**)’:
oi.cpp:8:12: error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]
oi.cpp:3:6: error: initializing argument 1 of ‘void print(const char**)’ [-fpermissive]
|
Such a conversion would allow you to put a `const char*` into your array of `char*`, which would be unsafe. In `print` you could do:
thing[0] = "abc";
Now `argv[0]` would point to a string literal that cannot be modified, while `main` expects it to be non-const (`char*`). So for type safety this conversion is not allowed.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 17,
"tags": "c++, c, string, gcc, casting"
}
|
CALayer Position Contents to Bottom Left
I am attempting to draw an image onto a CALayer. I only need an image, so I have created my later as follows:
CALayer *layer = [CALayer layer];
I add my image as follows:
NSImage *img = [[NSImage alloc] initWithContentsOfFile:@"path/to/img.png"];
[layer setContents:img];
This works, however it draws my images to fill the entire parent frame (stretching my image in the process).
Reading the docs, I found the following:
[layer setContentsGravity:@"kCAGravityBottomLeft"];
I am attempting to draw my image in the bottom left of the parent frame, however no matter what I do it draws my icon in the bottom center. Is there anyway to specify the bottom left?
|
Try this:
CALayer *layer = [CALayer layer];
layer.contentsGravity = kCAGravityBottomLeft;
layer.contents = (id) aCGImageRef;
Note that `kCAGravityBottomLeft` is declared as `NSString` and the `contents` property expects a `CGImageRef`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "objective c, macos, core animation"
}
|
CSS: How to make selectable boxes?
Say I have a 200x200 image. Then say I want to have a "box" starting at the coordinates 20px by 20px all the way to 50px by 50px (basically, a 30x30 box). I want users to be able to "select" this 30x30 box, like the way GMail's PDF viewer allows user to select boxes containing text.
In this box, I want to put text -- but I don't want this text to be selectable (thus, allowing users to select individual characters, etc.). I only want the containing box to be selectable -- and when user copies, they copy the text inside.
Is this possible in CSS? If so, how?
|
No, its not possible with css, you will to manipulate images using javascript. Have a look at jquery and the plugins available, ou may find something that can style up checkboxes to suit your requirements.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, css"
}
|
Create json array using dataweave
If I have xml like so....
<Root>
<Authority>Water</Authority>
<Sanctions>
<Sanction>
<SanctionCode>11</SanctionCode>
<SanctionDesc>First Sanction</SanctionDesc>
</Sanction>
<Sanction>
<SanctionCode>11</SanctionCode>
<SanctionDesc>Second Sanction</SanctionDesc>
</Sanction>
</Sanctions>
</Root>
Using DataWeave how can I create a json array of Santions using only the SanctionDesc?
I've tried this but it's not right...
%dw 1.0
%output application/json
---
records: payload.Root map {
Authority: $.Authority,
sanctions: $.Sanctions.Sanction map [$.SanctionDesc]
}
I want my output to look like this...
{
"records": [{
"Authority": "Water",
"sanctions": ["First Sanction", "Second Sanction"]
}]
}
|
Try this
%dw 1.0
%output application/json
---
records: {
Authority: payload.Root.Authority,
sanctions: payload.Root.Sanctions..SanctionDesc
}
Or
%dw 1.0
%output application/json
---
records: {
Authority: payload.Root.Authority,
sanctions: payload.Root.Sanctions.*Sanction map $.SanctionDesc
}
Hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "mule, dataweave"
}
|
Are commands executed through SSH transparent to a remote host's administrator?
Can administrators know what commands I execute **non-interactively** through SSH?
For example: does `echo hello` get logged somewhere at `remote` if I run this?
$ ssh me@remote "echo hello"
Can remote commands be otherwise monitored?
|
The administrator could install a modified sshd that records everything from all ssh sessions, interactive or not.
The question is: Do you trust the administrator of the remote system?
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 4,
"tags": "ssh, logs, audit, privacy"
}
|
Excluding the partition field from select queries in Hive
Suppose I have a table definition as follows in Hive(the actual table has around 65 columns):
CREATE EXTERNAL TABLE S.TEST (
COL1 STRING,
COL2 STRING
)
PARTITIONED BY (extract_date STRING)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\007'
LOCATION 'xxx';
Once the table is created, when I run `hive -e "describe s.test"`, I see `extract_date` as being one of the columns on the table. Doing a `select * from s.test` also returns `extract_date` column values. Is it possible to exclude this _virtual_ (?) column when running select queries in Hive.
|
Change this property
set hive.support.quoted.identifiers=none;
and run the query as
SELECT `(extract_date)?+.+` FROM <table_name>;
I tested it working fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "hadoop, hiveql"
}
|
Cannot update the value in Text input
I cannot update the existing value in text input.
<TextField
label='Email Id'
//placeholder={value_email}
onChangeText={(email) => this.setState({ email })}
value={value_email}
/>
here value_email is
const value_email = this.state.userInfo.email;
Thanks.
|
`this.setState({ email }` Sets the email to state object (this.state.email) but you are reading it from `state.userInfo`.
If you are setting it to state variable you need to change to `const value_email = this.state.email;`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "react native, textinput"
}
|
How to transform the first item of the list of values of a dictionary?
Simply a similar question here in relation to this question which also causes me problems, what if I want to transform into a string only the first item of the values of lists for example?
dictionary = {"first":[1, 2, 3],
"second":[4, 5, 6, 7, 8]}
Expect output:
dictionary = {"first":['1', 2, 3],
"second":['4', 5, 6, 7, 8]}
|
Loop over the values of the dictionary and replace the first element with its corresponding string value. Try this:
for v in dictionary.values():
v[0] = str(v[0])
The output:
{'first': ['1', 2, 3], 'second': ['4', 5, 6, 7, 8]}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "python"
}
|
Catching return values from goroutines
The below code gives compilation error saying 'unexpected go':
x := go doSomething(arg)
func doSomething(arg int) int{
...
return my_int_value
}
I know, I can fetch the return value if I call the function normally i.e. without using goroutine or I can use channels etc.
My question is why is it not possible to fetch a return value like this from a goroutine.
|
The strict answer is that you _can_ do that. It's just probably not a good idea. Here's code that would do that:
var x int
go func() {
x = doSomething()
}()
This will spawn off a new goroutine which will calculate `doSomething()` and then assign the result to `x`. The problem is: how are you going to use `x` from the original goroutine? You probably want to make sure the spawned goroutine is done with it so that you don't have a race condition. But if you want to do that, you'll need a way to communicate with the goroutine, and if you've got a way to do that, why not just use it to send the value back?
|
stackexchange-stackoverflow
|
{
"answer_score": 86,
"question_score": 130,
"tags": "go, concurrency, goroutine"
}
|
QT cpp delay in for loop
i have a loop that fill my textBrowser widget. Now i want to have an 1sec delay in my loop. I want that he append one row and wait 1 sec before fill another row. I tried it with sleep in my loop but it doesnt work. He fill my textbrowser without any delay.
*#include <QThread>*
..
sleep(1);
my code looks like that:
for(int i = 0; i < array.count(); i++)
{
QString br = "ID-->"+array[i];
ui->textBrowser->append(br);
}
How can i delay my loop?
|
It is best to use events form a QTimer instead of using a loop. For an example, you can use a slot like following.
int i = 0;
void MainWindow::OnTimer()
{
QString br = "ID-->" + array[i++];
ui->textBrowser->append(br);
if (i < array.count())
{
QTimer::singleShot(1000, this, SLOT(OnTimer()));
}
}
You will have to keep `array` and `i` as a class variables.
But if you just want to get this done somehow, you can use following code in your loop instead of a `sleep`. This will block the `for` loop but continue to process events so the UI will get updated while iterating. But it is kind of a hack.
QEventLoop loop;
QTimer::singleShot(1000, &loop, SLOT(quit()));
loop.exec();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c++, qt, qthread"
}
|
Opacity on Surface background property
The following gave me error
var textSurface = new Surface({
content: 'Some text here',
properties:{
color: 'white',
backgroundColor: rgba(0,0,0,0.7)
}
});
> Uncaught ReferenceError: rgba is not defined
My goal is to keep the text color with set opacity only on the background color. `rgba` works as a css function but it doesn't seem to work in surface's property. Can someone confirm and if there is a workaround?
|
The background color needs to be a string. What you have is an actual JavaScript function that is not defined, hence the error.
backgroundColor: "rgba(0,0,0,0.7)"
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "javascript, css, famo.us"
}
|
Alternatives to Windows Crypto API for C# RSA PKI?
I'm currently building a secure WhatsApp-like messenger for me and my friends. It encrypts all messages with AES and then uses RSA to encrypt the random AES key, it's very similar to PGP. For the desktop client, I have a nicely working version, but there's one thing that bugs me: at the moment I use the Windows Crypto API for generating key pairs and encrypting/decrypting. To make it short: I don't trust them anymore.
So what I'm looking for is a working and stable library that I can use for all these standard tasks of key creation, de-/encryption, etc. I found one over at the code project, but unfortunately it is quite buggy and unstable. Are there any libraries/frameworks that you can recommend? I really don't want to reinvent the wheel.
Thanks,
Rob
|
Bouncycastle has a c# crypto library. It generally tracks their Java library but not perfectly. It is not well documented. However, I have found the source code to be very readable. What I have done in the past is use the Javadocs for the Java API as a starting point, then looked through the roughly corresponding classes in the c# library.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, dll, rsa, public key encryption"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.