text stringlengths 1 2.12k | source dict |
|---|---|
c++, template-meta-programming, c++20
true, \
IS_NONEMPTY(__VA_ARGS__), \
Args...> {}; | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
// cover all const and volatile permutations
INVOCABLE_TRAITS_SPEC(,, )
INVOCABLE_TRAITS_SPEC(const,, )
INVOCABLE_TRAITS_SPEC(,volatile, )
INVOCABLE_TRAITS_SPEC(const, volatile, )
// and also variadic function versions
INVOCABLE_TRAITS_SPEC(,, ...)
INVOCABLE_TRAITS_SPEC(const,, ...)
INVOCABLE_TRAITS_SPEC(,volatile, ...)
INVOCABLE_TRAITS_SPEC(const, volatile, ...)
#undef INVOCABLE_TRAITS_SPEC
/* pointers to data members */
template <typename C, typename R>
struct invocable_traits_impl<R C::*>
: public invocable_traits_class<R,
std::invoke_result_t<R C::*,C>,
C,
false,
false,
false,
false> {};
// pointers to functions
template <typename R, typename... Args>
struct invocable_traits_impl<R(*)(Args...)> : public invocable_traits_impl<R(Args...)> {};
template <typename R, typename... Args>
struct invocable_traits_impl<R(*)(Args...) noexcept> : public invocable_traits_impl<R(Args...) noexcept> {};
template <typename R, typename... Args>
struct invocable_traits_impl<R(*)(Args..., ...)> : public invocable_traits_impl<R(Args..., ...)> {};
template <typename R, typename... Args>
struct invocable_traits_impl<R(*)(Args..., ...) noexcept> : public invocable_traits_impl<R(Args..., ...) noexcept> {};
// get at operator() of any struct/class defining it (this includes lambdas)
// bit of machinery for better error messages
template <typename T>
concept HasCallOperator = requires(T t)
{
t.operator();
};
template <typename T, bool isCallable>
struct invocable_traits_extract : invocable_traits_impl<decltype(&T::operator())> {}; | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
template <typename T>
struct invocable_traits_extract<T, false>
{
static_assert(std::is_class_v<T>, "passed type is not a class, and thus cannot have an operator()");
static_assert(!std::is_class_v<T> || HasCallOperator<T>, "passed type is a class that doesn't have an operator()");
// to reduce excessive compiler error output
static constexpr std::size_t arity = 0;
static constexpr auto is_const = false;
static constexpr auto is_volatile = false;
static constexpr auto is_noexcept = false;
static constexpr auto is_variadic = false;
using declared_result_t = void;
using invoke_result_t = void;
using class_t = void;
template <size_t i> struct arg_t { using type = void; };
};
template <typename T>
struct invocable_traits_impl : invocable_traits_extract<T, HasCallOperator<T>> {};
}
template <typename T>
struct invocable_traits : detail::invocable_traits_impl<std::decay_t<T>> {};
testing code:
void test(int)
{}
void test2(int) noexcept
{}
void testEllipsis(int,...)
{}
struct tester
{
const int yolo(char) const
{}
void yoloEllipsis(char, ...) noexcept
{}
static long yoloStatic(short)
{}
void operator()(int in_) {}
const int field;
};
int main()
{
auto lamb = [](const int& in_) {return "ret"; };
using type1 = decltype(lamb);
using traits1 = invocable_traits<type1>;
static_assert(std::is_same_v<const char*, traits1::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type1, int>, traits1::invoke_result_t>, "");
static_assert(std::is_same_v<traits1::invoke_result_t, traits1::declared_result_t>, "");
static_assert(std::is_same_v<decltype(lamb), traits1::class_t>, "");
static_assert(std::is_same_v<const int&, traits1::arg_t<0>>, "");
static_assert(traits1::is_const, ""); | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using type2 = decltype(&test);
using traits2 = invocable_traits<type2>;
static_assert(std::is_same_v<void, traits2::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type2, int>, traits2::invoke_result_t>, "");
static_assert(std::is_same_v<traits2::invoke_result_t, traits2::declared_result_t>, "");
static_assert(std::is_same_v<int, traits2::arg_t<0>>, "");
using type2b = decltype(&test2);
using traits2b = invocable_traits<type2b>;
static_assert(std::is_same_v<void, traits2b::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type2b, int>, traits2b::invoke_result_t>, "");
static_assert(std::is_same_v<traits2b::invoke_result_t, traits2b::declared_result_t>, "");
static_assert(std::is_same_v<void, traits2b::class_t>, "");
static_assert(std::is_same_v<int, traits2b::arg_t<0>>, "");
static_assert(!traits2b::is_variadic, "");
static_assert(traits2b::is_noexcept, "");
using type2c = decltype(&testEllipsis);
using traits2c = invocable_traits<type2c>;
static_assert(std::is_same_v<void, traits2c::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type2c, int>, traits2c::invoke_result_t>, "");
static_assert(std::is_same_v<traits2c::invoke_result_t, traits2c::declared_result_t>, "");
static_assert(std::is_same_v<int, traits2c::arg_t<0>>, "");
static_assert(traits2c::is_variadic, "");
auto& fref = test;
using type2d = decltype(fref);
using traits2d = invocable_traits<type2d>;
static_assert(std::is_same_v<void, traits2d::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type2d, int>, traits2d::invoke_result_t>, "");
static_assert(std::is_same_v<traits2d::invoke_result_t, traits2d::declared_result_t>, "");
static_assert(std::is_same_v<int, traits2d::arg_t<0>>, ""); | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
void (*farr[3])(int) = { &test };
using type2e = decltype(farr[0]);
using traits2e = invocable_traits<type2e>;
static_assert(std::is_same_v<void, traits2e::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type2e, int>, traits2e::invoke_result_t>, "");
static_assert(std::is_same_v<traits2e::invoke_result_t, traits2e::declared_result_t>, "");
static_assert(std::is_same_v<int, traits2e::arg_t<0>>, "");
using type3 = decltype(&tester::yolo);
using traits3 = invocable_traits<type3>;
static_assert(std::is_same_v<int, traits3::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type3, tester, char>, traits3::invoke_result_t>, "");
static_assert(!std::is_same_v<traits3::invoke_result_t, traits3::declared_result_t>, "");
static_assert(std::is_same_v<char, traits3::arg_t<0>>, "");
static_assert(traits3::is_const, "");
using type3a = const volatile decltype(&tester::yolo);
using traits3a = invocable_traits<type3a>;
static_assert(std::is_same_v<int, traits3a::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type3a, tester, char>, traits3a::invoke_result_t>, "");
static_assert(!std::is_same_v<traits3a::invoke_result_t, traits3a::declared_result_t>, "");
static_assert(std::is_same_v<char, traits3a::arg_t<0>>, "");
static_assert(traits3::is_const, ""); | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using type3b = decltype(&tester::yoloEllipsis);
using traits3b = invocable_traits<type3b>;
static_assert(std::is_same_v<void, traits3b::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type3b, tester, char>, traits3b::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type3b, tester, char, char>, traits3b::invoke_result_t>, "");
static_assert(std::is_same_v<traits3b::invoke_result_t, traits3b::declared_result_t>, "");
static_assert(std::is_same_v<tester, traits3b::class_t>, "");
static_assert(std::is_same_v<char, traits3b::arg_t<0>>, "");
static_assert(traits3b::is_variadic, "");
static_assert(traits3b::is_noexcept, "");
using type3c = const volatile decltype(&tester::yoloEllipsis);
using traits3c = invocable_traits<type3c>;
static_assert(std::is_same_v<void, traits3c::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type3c, tester, char>, traits3c::invoke_result_t>, "");
static_assert(std::is_same_v<traits3c::invoke_result_t, traits3c::declared_result_t>, "");
static_assert(std::is_same_v<tester, traits3c::class_t>, "");
static_assert(std::is_same_v<char, traits3c::arg_t<0>>, "");
static_assert(traits3c::is_variadic, "");
static_assert(traits3c::is_noexcept, "");
using type3d = decltype(&tester::yoloStatic);
using traits3d = invocable_traits<type3d>;
static_assert(std::is_same_v<long, traits3d::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type3d, short>, traits3d::invoke_result_t>, "");
static_assert(std::is_same_v<traits3d::invoke_result_t, traits3d::declared_result_t>, "");
static_assert(std::is_same_v<void, traits3d::class_t>, "");
static_assert(std::is_same_v<short, traits3d::arg_t<0>>, "");
static_assert(!traits3d::is_variadic, ""); | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using type4 = const volatile decltype(&tester::field);
using traits4 = invocable_traits<type4>;
static_assert(std::is_same_v<std::invoke_result_t<type4, tester>, traits4::invoke_result_t>, "");
static_assert(!std::is_same_v<traits4::invoke_result_t, traits4::declared_result_t>, "");
static_assert(std::is_same_v<const int &&, traits4::invoke_result_t>, "");
static_assert(traits4::arity == 0, "");
using type5 = std::add_rvalue_reference_t<decltype(lamb)>;
using traits5 = invocable_traits<type5>;
static_assert(std::is_same_v<const char*, traits5::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type5, int>, traits5::invoke_result_t>, "");
static_assert(std::is_same_v<traits5::invoke_result_t, traits5::declared_result_t>, "");
static_assert(std::is_same_v<const int&, traits5::arg_t<0>>, "");
using type6 = std::add_lvalue_reference_t<decltype(lamb)>;
using traits6 = invocable_traits<type6>;
static_assert(std::is_same_v<const char*, traits6::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type6, int>, traits6::invoke_result_t>, "");
static_assert(std::is_same_v<traits6::invoke_result_t, traits6::declared_result_t>, "");
static_assert(std::is_same_v<decltype(lamb), traits6::class_t>, "");
static_assert(std::is_same_v<const int&, traits6::arg_t<0>>, "");
// functor
using type7 = tester;
using traits7 = invocable_traits<type7>;
static_assert(std::is_same_v<void, traits7::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type7, int>, traits7::invoke_result_t>, "");
static_assert(std::is_same_v<traits7::invoke_result_t, traits7::declared_result_t>, "");
static_assert(std::is_same_v<int, traits7::arg_t<0>>, "");
auto lamb2 = [](const int& in_, ...) mutable noexcept {return "ret"; }; | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
auto lamb2 = [](const int& in_, ...) mutable noexcept {return "ret"; };
using type8 = decltype(lamb2);
using traits8 = invocable_traits<type8>;
static_assert(std::is_same_v<const char*, traits8::invoke_result_t>, "");
static_assert(std::is_same_v<std::invoke_result_t<type8, int>, traits8::invoke_result_t>, "");
static_assert(std::is_same_v<traits8::invoke_result_t, traits8::declared_result_t>, "");
static_assert(std::is_same_v<const int&, traits8::arg_t<0>>, "");
static_assert(traits8::is_variadic, "");
static_assert(traits8::is_noexcept, "");
static_assert(!traits8::is_const, "");
/*using traits9 = invocable_traits<int>;
static_assert(std::is_same_v<const char*, traits9::invoke_result_t>, "");
static_assert(std::is_same_v<const int&, traits9::arg_t<10>>, "");*/
}
Answer: Improving error messages
A question from the earliest version of the code you posted was how to get nicer error messages. The way to get those is to have things fail as quickly as possible, so the error message you get comes from close to the actual use of the invocable_traits class, instead of from somewhere deep in the bowels of its implementation.
Prefer using requires clauses over static_assert() if possible. For example, you can write:
template <std::size_t i, typename... Args>
requires (i < sizeof...(Args))
struct invocable_traits_arg_impl
{
using type = std::tuple_element_t<i, std::tuple<Args...>>;
};
The compiler will be able to produce much better error messages for constraints, including showing you what the values were on both sides of the < for example.
Second, don't defer constraints to inherited classes. Ideally, you should write something like:
template <typename T>
requires Callable<T>
struct invocable_traits : detail::invocable_traits_impl<std::decay_t<T>> {}; | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
Where the concept Callable would check if T is in fact a callable. This concept would look like:
template <typename T>
concept Callable = (
PointerToMemberFunction<T>
|| PointerToDataMember<T>
|| FunctionObject<T>
);
Which in turn relies on more concepts that need to be implemented.
#undef any macros you #define
Preprocessor macros know nothing about namespaces, class and function scopes. If you #define any in a header file that should not be part of the public API, make sure you #undef them in the same file. You do this for INVOCABLE_TRAITS_SPEC, but not for IS_NONEMPTY. | {
"domain": "codereview.stackexchange",
"id": 42733,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
javascript, jquery, event-handling
Title: Javascript array from IP address
Question: I want to make this code better. It works now but I think it can be better. I have a working sample on jsfiddle.
When the page loads I have the End IP Address disable until the data is entered. Then I take the values of the input with id attribute txtstartIpAddr and use it as the value for the input with id attribute txtendIpAddr. Any help would be great.
$(document).ready(function () {
$("#txtstartIpAddr").kendoMaskedTextBox({
mask: "000.000.000.000",
});
$("#txtendIpAddr").kendoMaskedTextBox({
mask: "000.000.000.000",
});
$('#txtstartIpAddr').blur(function() {
$("#txtendIpAddr").removeAttr('disabled');
var startIpAddr = $('#txtstartIpAddr').val();
//console.log(startIpAddr);
var IPArray = startIpAddr.split('.');
if (IPArray.length === 4)
{
var IPClone = "";
for(var i = 0; i < 2; i++) {
IPClone += IPArray[i] + ".";
}
$("#txtendIpAddr").val(IPClone);
}
});
});
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet"/>
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
<div class="form-group">
<label for="usr">Start IP Address</label>
<input type="text" class="form-control" id="txtstartIpAddr">
</div>
<div class="form-group">
<label>End IP Address</label>
<input type="text" class="form-control" id="txtendIpAddr" disabled=true>
</div> | {
"domain": "codereview.stackexchange",
"id": 42734,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, event-handling",
"url": null
} |
javascript, jquery, event-handling
Answer: Overall your code is readable and it is clear to me what you are trying to accomplish by reading the code alone. Your variable names describe their content, with one caveat described below.
Bugs
IP's
The mask restricts which valid ip's you can enter into your textbox, namely only all valid ip's with 3 numbers for each octet. It also allows a wide range of invalid ip's (everything above 255).
Masks on programmatically changed fields
It appears that the library you are using does not work well with input fields that are changed by code. When typing in a field that has been changed by javascript it does not retain the mask, and sometimes add's underscores.
Unlock on invalid ip
You are unlocking the end ip address input even when entering something invalid in the start input box. You are unlocking it even when only clicking in the start input box.
Standards
var, let and const
Virtually every modern browser supports let and const. They superseded var, because their behaviour is more consistent than var.
Variable casing
Follow casing conventions for variables. One such guide can be found on google's github. Local variables are always written in lowerCamelCase. If you see something written in UpperCamelCase it usually denotes a class. Someone reading your code might initially assume IPArray or IPClone to be a class, until they find where it is intialised. Keeping to these conventions makes it easier to read someone's code.
A11y
A11y stands for accessibility. When writing html you should make sure that your application is accessible for people using screenreaders for example.
When using <label> it should be paired with an input field. One way to do this is using the for attribute to pair it with an element. Your first label is paired with an element called usr, which does not exist. To do it correctly, you should put the id of the element you want to link as the value for your for attribute. See the documentation on mdn for more information. | {
"domain": "codereview.stackexchange",
"id": 42734,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, event-handling",
"url": null
} |
javascript, jquery, event-handling
Another way is to surround the form field with the label like so:
<label>
Your description
<input type="text">
</label> | {
"domain": "codereview.stackexchange",
"id": 42734,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, event-handling",
"url": null
} |
javascript, jquery, event-handling
By pairing your labels correctly with your form fields you get two benefits. Clicking the label will focus the corresponding form field. Screen readers will use the description of your form field to announce the input field, rather than announcing that there is an input field containing ___.___.___.___.
Alternatives
Validation instead of masks
Masks are somewhat limited by their nature. Consider using validation instead. There are various libraries to do this, but in this case you can even do it all in html if you want. The pattern you need to use becomes a bit convoluted though.
input:valid {
background: green;
color: white;
}
input:invalid {
background: red;
color: black;
}
<input pattern="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])">
Array manipulation
Instead of manually concatenating strings, you can use array manipulation to your advantage. If you use .slice(...) (docs) you can keep only part of the array you are still interested in, then join the parts together with a dot.
$(document).ready(function () {
$("#txtstartIpAddr").kendoMaskedTextBox({
mask: "000.000.000.000",
});
$("#txtendIpAddr").kendoMaskedTextBox({
mask: "000.000.000.000",
});
$('#txtstartIpAddr').blur(function() {
$("#txtendIpAddr").removeAttr('disabled');
const startIpAddr = $('#txtstartIpAddr').val();
const parts = startIpAddr.split('.');
if (parts.length === 4)
{
const clonedIp = `${parts.slice(0, 2).join('.')}.` | {
"domain": "codereview.stackexchange",
"id": 42734,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, event-handling",
"url": null
} |
javascript, jquery, event-handling
$("#txtendIpAddr").val(clonedIp);
}
});
});
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet"/>
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
<div class="form-group">
<label for="usr">Start IP Address</label>
<input type="text" class="form-control" id="txtstartIpAddr">
</div>
<div class="form-group">
<label>End IP Address</label>
<input type="text" class="form-control" id="txtendIpAddr" disabled=true>
</div> | {
"domain": "codereview.stackexchange",
"id": 42734,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery, event-handling",
"url": null
} |
beginner, kotlin
Title: commandline Password-Generator in Kotlin
Question: So I (a newbie to programming) wrote this password-generator as one of my very first programs in Kotlin. I started with Java a few weeks ago. I soon realized that Java was too hard for me, so I switched to Kotlin. And this is the result. A cmd-only password-generator. I'd like to know if this code is useful at all and what I can improve.
fun main() {
script()
}
fun script() {
var password: String
var passwordLength: String
var passwordAlphabet: String
var passwordNumbers: String
var passwordCharsIncluded: String
var passwordUppercase: String
println("Password Generator")
println("Complete the following attributes to generate your password")
println("length:")
passwordLength = readln()
while (passwordLength.toByte() < 6) {
println("The minimum length is 6 characters, please enter a new length:")
passwordLength = readln()
}
println("allow alphabetic characters?")
passwordAlphabet = readln()
println("allow numbers?")
passwordNumbers = readln()
println("allow uppercase?")
passwordUppercase = readln()
println("include special characters:")
passwordCharsIncluded = readln()
if (passwordCharsIncluded == "default") {
while (passwordLength.toByte() < 32) {
println("The 'default' option requires a length of at least 32.")
println("Would you like to change the length?")
var answer = readln()
if (answer.equals("yes") || answer.equals("y")) {
println("Enter new length:")
passwordLength = readln()
} else if (answer == "no") {
println("include special characters:")
passwordCharsIncluded = readln()
break
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42735,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, kotlin",
"url": null
} |
beginner, kotlin
password = generatePassword(
passwordLength,
passwordAlphabet,
passwordNumbers,
passwordCharsIncluded,
passwordUppercase
)
if (password.equals("error")) {
println("An error occurred, please restart the program. ")
} else {
println("Your password has been successfully generated:")
println(password)
}
}
fun generatePassword(
passwordLength: String,
passwordAlphabeticCharacters: String,
passwordNumbers: String,
passwordCharsIncluded: String,
passwordUppercase: String
): String {
var password: String = ""
var testPassed: Boolean = true
var alphabetRange = mutableListOf<Char>()
var alphabetSelected: Boolean = false
var numberRange = mutableListOf<Char>()
var numberSelected: Boolean = false
var specialCharRange = mutableListOf<Char>()
var uppercaseSelected: Boolean = false
var additionalSpecialChars = passwordCharsIncluded.toCharArray()
var defaultSpecialChars = "^!$%&/()=?+*#_<>".toCharArray()
// The following if-statements create three lists with the choosen characters.
if (passwordAlphabeticCharacters.equals("yes") || passwordAlphabeticCharacters.equals("y")) {
alphabetSelected = true
for (lowercaseChar in 'a'..'z') {
alphabetRange.add(lowercaseChar)
}
if (passwordUppercase.equals("yes") || passwordUppercase.equals("y")) {
uppercaseSelected = true
for (uppercaseChar in 'A'..'Z') {
alphabetRange.add(uppercaseChar)
}
}
alphabetRange.shuffle()
}
if (passwordNumbers.equals("yes") || passwordNumbers.equals("y")) {
numberSelected = true
for (num in '0'..'9') {
numberRange.add(num)
}
numberRange.shuffle()
} | {
"domain": "codereview.stackexchange",
"id": 42735,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, kotlin",
"url": null
} |
beginner, kotlin
if (passwordCharsIncluded.equals("default")) {
for (char in defaultSpecialChars) {
specialCharRange.add(char)
}
} else {
for (char in additionalSpecialChars) {
specialCharRange.add(char)
}
}
specialCharRange.shuffle()
// The password is created by selecting a random char that's being added at the end.
var counter1: Byte = 0
while (counter1 < passwordLength.toByte()) {
if (alphabetSelected && numberSelected) {
var randomRange = generateRandomNumber(0, 1)
if (randomRange == 0) {
var randomIndex = generateRandomNumber(0, alphabetRange.size - 1)
password += alphabetRange[randomIndex]
} else if (randomRange == 1) {
var randomIndex = generateRandomNumber(0, numberRange.size - 1)
password += numberRange[randomIndex]
}
} else if (alphabetSelected) {
var randomIndex = generateRandomNumber(0, alphabetRange.size - 1)
password += alphabetRange[randomIndex]
} else if (numberSelected) {
var randomIndex = generateRandomNumber(0, numberRange.size - 1)
password += numberRange[randomIndex]
}
counter1++
} | {
"domain": "codereview.stackexchange",
"id": 42735,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, kotlin",
"url": null
} |
beginner, kotlin
if (!passwordCharsIncluded.isBlank()) {
var tempPassword = password.toCharArray()
for (i in tempPassword.indices) {
if (passwordLength.toShort() < 10) {
var randomNum = generateRandomNumber(0, 2)
if (randomNum > 1) {
var randomIndex = generateRandomNumber(0, specialCharRange.size - 1)
tempPassword[i] = specialCharRange[randomIndex]
}
} else if (passwordLength.toShort() > 10) {
var randomNum = generateRandomNumber(0, 3)
if (randomNum > 1) {
var randomIndex = generateRandomNumber(0, specialCharRange.size - 1)
tempPassword[i] = specialCharRange[randomIndex]
}
}
}
password = String(tempPassword)
}
// Test if all conditions are given in the final password.
if (alphabetSelected) {
val regex = Regex("[a-z]")
if (!regex.containsMatchIn(password)) {
testPassed = false
}
}
if (uppercaseSelected) {
val regex = Regex("[A-Z]")
if (!regex.containsMatchIn(password)) {
testPassed = false
}
}
if (numberSelected) {
val regex = Regex("[0-9]")
if (!regex.containsMatchIn(password)) {
testPassed = false
}
}
// The password is being returned if all tests are passed.
if (testPassed) {
return password;
} else {
return "error";
}
}
fun generateRandomNumber(startValue: Int, endValue: Int): Int {
return (startValue..endValue).random()
}
Answer:
I started with Java a few weeks ago. I soon realized that Java was too hard for me
Excellent choice! Nobody needs Java the dinosaur these days ;-] You'll write code much more efficiently with Kotlin. | {
"domain": "codereview.stackexchange",
"id": 42735,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, kotlin",
"url": null
} |
beginner, kotlin
I've got one suggestion to offer that will allow you to greatly simplify your application by removing virtually all of the boolean variables when you create an enum like this one:
enum class PasswordOption {
Letters,
Numbers,
UpperCase,
LowerCase,
SpecialCharacters
}
You then create only a single set:
var passwordOptions = EnumSet.noneOf(PasswordOption::class.java)
that you update according to user input:
println("allow alphabetic characters?")
if(readln().matches(Regex("y(es)?", RegexOption.IGNORE_CASE))) passwordOptions.add(PasswordOption.Letters)
Notice here the matches extension and the Regex pattern that checks for either yes or y and is case-insensitive at the same time. If the result is true, you add a new flag to the options.
Later inside the generatePassword function you check those flags:
if (passwordOptions.contains(PasswordOption.Letters)) {
// ...
}
``` | {
"domain": "codereview.stackexchange",
"id": 42735,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, kotlin",
"url": null
} |
php, wordpress, php7
Title: Building a pre-loader for performance gains in Wordpress
Question: As the title states, I am building a pre-loader for Wordpress running on PHP 7.3.5+ that will deliver performance boosts in loading, as well as metrics such as Google Page Speed.
This is something that we do at work, and I could quite easily copy what has been used there but feel it is 'stolen knowledge'. I could be writing anything and have very little understanding of what I am typing as it was developed by seniors.
So, given that I know what the basics of the pre-loader are (load critical styles, defer certain scripts, remove unwanted WP scripts) I had a bash at creating one myself that appears to work:
// If there are problems with caching,
// change this version number
define('CACHE_VERSION', '1.0.0');
class WpboilerInliner {
function __construct() {
add_action( 'init', array(&$this, 'init') );
add_action( 'wp_head', array(&$this, 'addCriticalCss') );
add_action( 'wp_footer', array(&$this, 'addGeneralCss') );
}
// This will add the critical CSS to the header
function addCriticalCss() {
// Set to not load in the admin as this will 'break' it
if(!is_admin()) {
$criticalFonts = '<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;1,300&display=swap" rel="stylesheet"> ';
$criticalCSSContent = file_get_contents( get_template_directory_uri() . '/css/atf.css' );
$criticalCSS = "<style type='text/css'>
<!-- BEGIN CRITICAL STYLES -->
{$criticalCSSContent}
<!-- END CRITICAL STYLES -->
</style>";
echo $criticalFonts . $criticalCSS;
}
} | {
"domain": "codereview.stackexchange",
"id": 42736,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, wordpress, php7",
"url": null
} |
php, wordpress, php7
echo $criticalFonts . $criticalCSS;
}
}
// General styles, these will be added in the footer
function addGeneralCss() {
// Add the filename to be added to the footer(below the fold) here
// Add files in their correct cascade order
// e.g filename.css
// filename.min.css
// subdirectory/filename.css
$generalCssFileName = array(
'general.css',
'type.css',
);
foreach($generalCssFileName as $cssFileName) {
$linkFormat = '<link rel="stylesheet" href="' . get_template_directory_uri() . '/css/%s?ver=%s" />';
$cssLink = sprintf($linkFormat, $cssFileName, CACHE_VERSION);
echo $cssLink;
}
}
function init() {
// Remove everything to do with emojis
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' );
add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 );
// Remove version number from header
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'wlwmanifest_link');
remove_action( 'wp_head', 'rsd_link' );
// Removes shortlink
remove_action( 'wp_head', 'wp_shortlink_wp_head' );
// Removes feed links
remove_action( 'wp_head', 'feed_links', 2 );
// // Removes comments feed
remove_action( 'wp_head', 'feed_links_extra', 3 ); | {
"domain": "codereview.stackexchange",
"id": 42736,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, wordpress, php7",
"url": null
} |
php, wordpress, php7
// // Removes comments feed
remove_action( 'wp_head', 'feed_links_extra', 3 );
/**
* Filter function used to remove the TinyMCE emoji plugin
*
* @param array $plugins
* @return array Difference between the two arrays
*/
function disable_emojis_tinymce( $plugins ) {
if( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
} else {
return array();
}
}
/**
* Remove emoji CDN hostname from DNS prefetching hints
*
* @param array $urls URLs to print for resource hints
* @param string $relation_type The relation type the URLs are printed for
* @return array Difference between the two arrays
*/
function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) {
if( 'dns-prefetch' == $relation_type ) {
/** This filter is documented in wp-includes/formatting.php */
$emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );
$urls = array_diff( $urls, array( $emoji_svg_url ) );
}
return $urls;
}
// Load JS files
wp_enqueue_script('wpboiler-critical-js', get_template_directory_uri() . '/js/atf.min.js', array(), CACHE_VERSION, false);
wp_enqueue_script('wpboiler-general-js', get_template_directory_uri() . '/js/general.min.js', array(), CACHE_VERSION, true);
}
}
$wpboilerInliner = new WpboilerInliner(); | {
"domain": "codereview.stackexchange",
"id": 42736,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, wordpress, php7",
"url": null
} |
php, wordpress, php7
}
$wpboilerInliner = new WpboilerInliner();
Are there ways of improving this? It has not yet been tested with plugins, but on a basic install it seems to work as expected (from what I can tell). I came into an issue with the admin area when trying to load in the fonts and the critical styles which is why they are wrapped in !is_admin(). Functions disable_emojis_tinymce() and disable_emojis_remove_dns_prefetch() were taken from a post by Kinsta.
Are there methods I can improve here? Are there some major errors that I am likely to encounter with what I have currently written? My PHP knowledge is limited so I understand some of the more basic concepts such as sprintf and the basic use of arrays and loops.
Answer: I honestly haven’t used Wordpress much - just assisted with a company project that used it about 6 years ago. The biggest thing I notice is that the syntax used to declare arrays is the legacy syntax, which is fine but could be converted to the shorter syntax - i.e. []. I know it only saves five characters but it is more in-line with JavaScript's shorthand array declaration style.
For instance, these three lines in the constructor:
add_action( 'init', array(&$this, 'init') );
add_action( 'wp_head', array(&$this, 'addCriticalCss') );
add_action( 'wp_footer', array(&$this, 'addGeneralCss') );
Could be updated to:
add_action( 'init', [&$this, 'init'] );
add_action( 'wp_head', [&$this, 'addCriticalCss'] );
add_action( 'wp_footer', [$this, 'addGeneralCss'] );
And I could be wrong but the & before $this can be removed. The documentation for passing callables states:
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed.
Notice that it doesn't state the object needs to be passed by reference.
In the function addGeneralCss() there is a loop over file names. | {
"domain": "codereview.stackexchange",
"id": 42736,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, wordpress, php7",
"url": null
} |
php, wordpress, php7
In the function addGeneralCss() there is a loop over file names.
$generalCssFileName = array(
'general.css',
'type.css',
);
foreach($generalCssFileName as $cssFileName) {
$linkFormat = '<link rel="stylesheet" href="' . get_template_directory_uri() . '/css/%s?ver=%s" />';
$cssLink = sprintf($linkFormat, $cssFileName, CACHE_VERSION);
echo $cssLink;
}
That is 9+ lines to add two <link> tags. While it is great to avoid repetition, making a loop for two items may not be worth the cost of setting up the loop.
echo '<link rel="stylesheet" href="' . get_template_directory_uri() . '/css/general.css?ver=' . CACHE_VERSION . '" />';
echo '<link rel="stylesheet" href="' . get_template_directory_uri() . '/css/type.css?ver=' . CACHE_VERSION . '" />';
The method init is a bit long. There are multiple calls to remove_action() with wp_head as the first parameter, although some calls have a third parameter. If it wasn't for that third parameter in some cases it may be simple to loop over an array containing values for the second parameter.
The function disable_emojis_tinymce() contains an if with an else block.
if( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
} else {
return array();
}
The if block contains a return statement so the else can be removed.
if( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
}
return array();
If the line in the if block was longer, then it may be worth reversing the logic, to decrease the indentation level:
if( !is_array( $plugins ) ) {
return array();
}
return array_diff( $plugins, array( 'wpemoji' ) );
This concept of avoiding the else is part of the Object Calisthenics - you can read more about it here. | {
"domain": "codereview.stackexchange",
"id": 42736,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, wordpress, php7",
"url": null
} |
python, numpy
Title: Fastest way to find common events in 2 time series numpy arrays and calulate synchronisation statistic
Question:
Given 2 numpy arrays a1 and a2 (composed only of 0 and 1's), find index locations of all 0's in a1 and a2.
Find matching index positions if any between array a1 and a2.
Calculate a metric.
a1 array shape is 2161
a2 array shape is 2161
e.g.
a1 = [0,1,1,0,1,0,1]
a2 = [1,1,0,0,1,1,0]
The indices of all 0's in a1 are 0, 3, and 5.
The indices of all 0's in a2 are 2, 3, and 6.
The only common index between a1 and a2 is thus 3.
function_1 performs step1 and step2 and step3
function1_iterations repeats function_1 after randomly shuffling a1 and repeating metric calculation 1000 times. This is for the purpose of finding if metric is statistically significant.
I perform below code on 100 million array pairs, multiprocessed on 256 cores. Best runtime for 100 million array pairs is about 40 mins. Is there any way I can make it significantly efficient? I need to be running this on billions of array pairs.
My code below is the fastest that I could come up with some help from people from codereview earlier:
def function_1(self, a1, a2):
event_index1, = np.where(a1 == 0)
event_index2, = np.where(a2 == 0)
n1, = event_index1.shape
n2, = event_index2.shape
if n1 == 0 or n2 == 0:
return 0, 0
n_matches, = np.intersect1d(event_index1, event_index2, assume_unique=True,).shape
c_ij = c_ji = n_matches/2
metric_1= (c_ij + c_ji) / math.sqrt(n1 * n2)
return metric_1 | {
"domain": "codereview.stackexchange",
"id": 42737,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy",
"url": null
} |
python, numpy
def function1_iterations(self,a1,a2,repeat = 1000,original_metric1):
list_metric1 = []
a1_copy = copy.deepcopy(a1)
for i in range(0, repeat):
np.random.shuffle(a1_copy) # shuffle bits in array and recalculate 1000 times
metric_1 = self.function_1(a1= a1_copy, a2 = a2)
list_metric1.append(metric_1)
list_metric1= np.array(list_metric1)
significance_val = len(np.where(list_metric1>= [original_metric1])[0])/repeat
return significance_val
Answer: Ignoring your function1_iterations: function_1 should call neither where nor intersect1d. Your metric expression numerator just evaluates to n_matches. A faster vectorised approach will be, either in the integer or boolean domain, perform the equivalent of sum(!a1 & !a2):
import math
from timeit import timeit
import numpy as np
def function_1_old(a1, a2):
event_index1, = np.where(a1 == 0)
event_index2, = np.where(a2 == 0)
n1, = event_index1.shape
n2, = event_index2.shape
if n1 == 0 or n2 == 0:
return 0, 0
n_matches, = np.intersect1d(event_index1, event_index2, assume_unique=True, ).shape
c_ij = c_ji = n_matches / 2
metric_1 = (c_ij + c_ji) / math.sqrt(n1 * n2)
return metric_1
def function_1_arith(a1: np.ndarray, a2: np.ndarray) -> float:
zeros1 = 1 - a1
zeros2 = 1 - a2
n1 = np.sum(zeros1)
n2 = np.sum(zeros2)
if n1 == 0 or n2 == 0:
return 0
n_matches = np.sum(zeros1 * zeros2)
return n_matches / np.sqrt(n1 * n2)
def function_1_bool(a1: np.ndarray, a2: np.ndarray) -> float:
zeros1 = np.logical_not(a1)
zeros2 = np.logical_not(a2)
n1 = np.sum(zeros1)
n2 = np.sum(zeros2)
if n1 == 0 or n2 == 0:
return 0
n_matches = np.sum(np.logical_and(zeros1, zeros2))
return n_matches / np.sqrt(n1 * n2) | {
"domain": "codereview.stackexchange",
"id": 42737,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy",
"url": null
} |
python, numpy
n_matches = np.sum(np.logical_and(zeros1, zeros2))
return n_matches / np.sqrt(n1 * n2)
def function_1_demorgan(a1: np.ndarray, a2: np.ndarray) -> float:
n1 = a1.size - np.sum(a1)
n2 = a2.size - np.sum(a2)
if n1 == 0 or n2 == 0:
return 0
n_matches = np.sum(np.logical_not(np.logical_or(a1, a2)))
return n_matches / np.sqrt(n1 * n2)
def function_1_count(a1: np.ndarray, a2: np.ndarray) -> float:
n1 = a1.size - np.count_nonzero(a1)
n2 = a2.size - np.count_nonzero(a2)
if n1 == 0 or n2 == 0:
return 0
n_matches = np.count_nonzero(np.logical_not(np.logical_or(a1, a2)))
return n_matches / np.sqrt(n1 * n2)
def function_1_binary(a1: np.ndarray, a2: np.ndarray) -> float:
n1 = a1.size - np.count_nonzero(a1)
n2 = a2.size - np.count_nonzero(a2)
if n1 == 0 or n2 == 0:
return 0
n_matches = np.count_nonzero(~(a1 | a2))
return n_matches / np.sqrt(n1 * n2)
def test() -> None:
methods = (function_1_old, function_1_arith, function_1_bool, function_1_demorgan, function_1_count,
function_1_binary)
a1 = np.array((0, 1, 1, 0, 1, 0, 1), dtype=bool)
a2 = np.array((1, 1, 0, 0, 1, 1, 0), dtype=bool)
# Testing against expected results, with OP's original sample arrays
for method in methods:
assert np.isclose(1/3, method(a1, a2), rtol=0, atol=1e-12)
rand = np.random.default_rng(seed=0) # for reproducible results
def sample():
return rand.integers(low=0, high=2, size=(10_000,), dtype=bool)
a1, a2 = sample(), sample()
# Test for regression with bigger sample arrays
reference = None
for method in methods:
result = method(a1, a2)
if method is function_1_old:
reference = result
else:
assert np.isclose(reference, result, rtol=0, atol=1e-12) | {
"domain": "codereview.stackexchange",
"id": 42737,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy",
"url": null
} |
python, numpy
# Performance measurement with those arrays
n = 1_000
for method in methods:
dur = timeit(lambda: method(a1, a2), number=n)
print(f'{method.__name__}: {dur/n*1e6:.1f} us')
'''
function_1_old: 386.6 us
function_1_arith: 54.8 us
function_1_bool: 44.2 us
function_1_demorgan: 43.1 us
function_1_count: 6.9 us
function_1_binary: 6.7 us
'''
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 42737,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy",
"url": null
} |
python, beginner, python-2.x
Title: Find differences between two directories
Question: Coming from another language than Python, I would like to see if my code is "pythonic" enough and follows good practices.
It compares two directories, showing all files that are in one and not in the other. Moreover, you can add up to two options:
a to also compare the content of the files
s to save the results into a file
Note: this is in Python 2.7, and I don't have access to argparse.
import filecmp
import os.path
import sys | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-2.x
def print_help():
print "Use : python cmp_dir.py <dir_1> <dir_2> [-a] [-s <file>]"
print "dir_1 and dir_2 : directories to compare"
print "-a : also compare data inside files"
print "-s : save results inside <file>"
sys.exit()
def show_diff_in_dir(dir_name, list_diff, file_to_save_results):
msg = "files or subdirs only in %s : %s " % (dir_name, list_diff)
if file_to_save_results:
file_to_save_results.write(msg + "\n")
else:
print msg
def show_diff_in_files(dir_name, diff_files, file_to_save_results):
msg = "different files in %s : %s " % (dir_name, diff_files)
if file_to_save_results:
file_to_save_results.write(msg + "\n")
else:
print msg
def compare_dir_trees(dir1, dir2, compare_file_data, file_to_save_results):
dirs_cmp = filecmp.dircmp(dir1, dir2)
if dirs_cmp.left_only:
show_diff_in_dir(dir1, dirs_cmp.left_only, file_to_save_results)
if dirs_cmp.right_only:
show_diff_in_dir(dir2, dirs_cmp.right_only, file_to_save_results)
if compare_file_data and dirs_cmp.diff_files:
show_diff_in_files(dir1, dirs_cmp.diff_files, file_to_save_results)
for common_dir in dirs_cmp.common_dir:
new_dir1 = os.path.join(dir1, common_dir)
new_dir2 = os.path.join(dir2, common_dir)
compare_dir_trees(new_dir1, new_dir2, compare_file_data, file_to_save_results)
if __name__ == "__main__":
compare_file_data = False
file_to_save_results = None
if len(sys.argv) < 3:
print_help()
else:
dir_a = sys.argv[1]
dir_b = sys.argv[2]
if len(sys.argv) == 4:
if sys.argv[3] == "-a":
compare_file_data = True
else:
print_help()
elif len(sys.argv) == 5:
if sys.argv[3] == "-s":
file_to_save_results = open(sys.argv[4], "w")
else:
print_help() | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-2.x
else:
print_help()
elif len(sys.argv) == 6:
if sys.argv[3] == "-a" and sys.argv[4] == "-s":
compare_file_data = True
file_to_save_results = open(sys.argv[5], "w")
elif sys.argv[5] == "-a" and sys.argv[3] == "-s":
compare_file_data = True
file_to_save_results = open(sys.argv[4], "w")
else:
print_help()
elif len(sys.argv) > 6:
print_help()
print "Compare dirs %s and %s" % (dir_a, dir_b)
print "Start compare"
compare_dir_trees(dir_a, dir_b, compare_file_data, file_to_save_results)
if file_to_save_results:
file_to_save_results.close()
print "End compare" | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-2.x
Answer: Code doesn't work
for common_dir in dirs_cmp.common_dir: fails, because dirs_cmp does not have a common_dir.
The correct attribute is common_dirs. I'm going to assume this was some sort of copy-paste error (but that would be very odd since it was in the middle of the code!).
Python 2.7 -vs- Python 3.x
Python 2.7 is "obsolete". You should move to Python 3.x instead.
However, there may be times when you must use Python 2.7.
In these cases, it is much better to write code which will run equally well in both interpreters. __future__ is your friend here.
In Python 2.7, you can add at the top of your script:
from __future__ import print_function
and the Python 2.7 interpreter will then allow you to use Python 3.x style print() statements.
The Python 3.x interpreter will ignore this import, because the future is now.
Don't exit
Avoid calling sys.exit() at all costs. It unconditionally terminates your Python interpreter.
Why is that a problem? If you ever want to call print_help() and then do more things, you can't. For example, unit testing frameworks will call a function and compare the expected results with the actual results. If that unit testing framework is written in Python, the unit testing framework abruptly stops.
A simple way around this is to move your mainline code into its own function. After calling print_help(), follow that with return and the main() function will exit to its caller (such as the mainline code); the Python interpreter will not be terminated until the mainline code reaches the natural end of its execution.
def main(argv):
...
if len(argv) < 3:
print_help()
return
...
if __name__ == '__main__':
main(sys.argv) | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-2.x
if __name__ == '__main__':
main(sys.argv)
As a benefit of the return, the rest of the code in the function doesn't need to be inside an else: block, making your code more "left leaning".
Working with resources
You've got 3 open() statements and one close(). If an exception occurs at any point in the code, the close() will not happen, and a file-system resource may be leaked. It won't matter here, since you don't do any exception handling, and the file-system resource will be released by the Python interpreter, but it is better to get into good habits.
The with statement should be used to automatically close resources.
The resources will be closed at the end of the with block, regardless of whether the block is exited by
reaching the end of the block,
executing an early return statement, or
an exception being raised.
Nested function blocks
This is an advanced topic, but it simplifies your code a lot.
You keep recursing into a function with the parameters compare_file_data, file_to_save_results passed, unchanged.
The parameters aren't really part of the recursive function;
rather, they are just "configuration" variables.
Really, you want these parameters to be "global", but you've probably heard globals are bad to use.
Make them global, locally, with a nested function block.
def compare_dir_trees(dir1, dir2, compare_file_data, file_to_save_results):
def show_diff_in_dir(dir_name, list_diff):
...
def show_diff_in_files(dir_name, diff_files):
...
def compare_dirs(dir1, dir2):
...
compare_dirs(dir1, dir2) | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-2.x
def compare_dirs(dir1, dir2):
...
compare_dirs(dir1, dir2)
Calling compare_dir_trees() will set the compare_file_data, file_to_save_results parameters for the entire execution of that function, which is composed of one statement: compare_dirs(dir1, dir2).
That function has access to those parameters, as do the other show_diff_in_ functions.
Standard Output -vs- Output to File
sys.stdout is a file handle.
You can write to it just like you can write to file_to_save_results.
You just don't need to open or close it.
This means your show_diff_in_ functions can be simplied to just writing to the passed in file handle, and not worry about choosing to print or write.
Actually, print(..., file=file_to_save_results) would be even simplier, as it takes care of the "\n" for you.
Argument Parsing
If you look for the optional arguments -a and -s <filename> in sys.argv, and remove them if found, you will simplify argument parsing.
Specifically, you don't need to handle -a -s <filename> differently from -s <filename> -a!
Reworked Code
from __future__ import print_function
import filecmp
import os.path
import sys
def print_help():
print("Use : python cmp_dir.py <dir_1> <dir_2> [-a] [-s <file>]")
print("dir_1 and dir_2 : directories to compare")
print("-a : also compare data inside files")
print("-s : save results inside <file>")
def compare_dir_trees(dir1, dir2, compare_file_data, output):
def compare_dirs(dir1, dir2):
dirs_cmp = filecmp.dircmp(dir1, dir2)
if dirs_cmp.left_only:
print("files or subdirs only in %s : %s " % (dir1, dirs_cmp.left_only),
file=output)
if dirs_cmp.right_only:
print("files or subdirs only in %s : %s " % (dir2, dirs_cmp.right_only),
file=output) | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-2.x
if compare_file_data and dirs_cmp.diff_files:
print("different files in %s : %s " % (dir1, dirs_cmp.diff_files),
file=output)
for common_dir in dirs_cmp.common_dirs:
new_dir1 = os.path.join(dir1, common_dir)
new_dir2 = os.path.join(dir2, common_dir)
compare_dir(new_dir1, new_dir2)
compare_dirs(dir1, dir2)
def main(argv):
compare_file_data = False
file_to_save_results = None
if '-s' in argv:
pos = argv.index('-s')
if pos + 1 < len(argv):
file_to_save_results = argv[pos + 1]
del argv[pos:pos+2]
if '-a' in argv:
argv.remove('-a')
compare_file_data = True
if len(argv) != 3:
print_help()
return
dir_a = argv[1]
dir_b = argv[2]
print("Compare dirs %s and %s" % (dir_a, dir_b))
print("Start compare")
if file_to_save_results:
with open(file_to_save_results, "w") as file:
compare_dir_trees(dir_a, dir_b, compare_file_data, file)
else:
compare_dir_trees(dir_a, dir_b, compare_file_data, sys.stdout)
print("End compare")
if __name__ == '__main__':
main(sys.argv)
This works with both Python 2.7 and Python 3.x | {
"domain": "codereview.stackexchange",
"id": 42738,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-2.x",
"url": null
} |
python, beginner, python-3.x
Title: Kaprekar's constant
Question: I'm new to Python and as a first exercise, I've written a function (module?) to calculate Kaprekar's constant using Python 3.
I'd like some feedback on whether this is Pythonic enough, and if I can improve it.
import collections
def kaprekar(value):
print("Starting value: %d" % value)
# Check our range
if value < 1 or value > 9998:
print("Input value must be between 1 and 9998, inclusive.")
return
numstr = str(value)
# Pad with leading 0s if necessary
numstr = '0' * (4 - len(numstr)) + numstr
# Make sure there are at least two different digits
if len(collections.Counter(numstr)) == 1:
print("Input value must consist of at least two different digits.")
return
# If we've gotten this far it means the input value is valid
# Start iterating until we reach our magic value of 6174
n = 0
while (value != 6174):
n += 1
numstr = str(value)
# Pad with leading 0s if necessary
numstr = '0' * (4 - len(numstr)) + numstr
# Get ascending and descending integer values
asc = int(''.join(sorted(numstr)))
dec = int(''.join(sorted(numstr)[::-1]))
# Calculate our new value
value = dec - asc
print("Iteration %d: %d" % (n, value))
# We should always reach the constant within 7 iterations
if n == 8:
print("Something went wrong...")
return -1
print("Reached 6174 after %d iterations." % n)
return n
Update
Thanks for the feedback, everyone!
Answer: Validation | {
"domain": "codereview.stackexchange",
"id": 42739,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x",
"url": null
} |
python, beginner, python-3.x
Update
Thanks for the feedback, everyone!
Answer: Validation
The range check if value < 1 or value > 9998 could be more Pythonically expressed as if not 1 <= value <= 9998. (I would prefer to avoid hard-coding 9998 altogether, though. See below.)
To ensure that there are at least two different digits, you can just use a set.
An easier way to zero-pad a number to four places is '{:04d}'.format(value). That line of code is written twice; it may be worthwhile to extract it into a function.
Returning None and -1 to indicate validation errors and excessive iterations is unusual for Python. When you encounter an error, raise an exception instead.
Algorithm
The implementation presupposes that you know the answer (6174, within 7 iterations). That's a bit dissatisfying at an intellectual level; it feels like a unit test. As an alternative to checking whether the known goal has been reached, you could check whether the sequence has reached a fixed point.
You hard-code a lot of special numbers: 4, 9998, 6174, 8. It would be nice to reduce the usage of such constants, and where they are necessary, clarify their purpose. The Wikipedia page mentions that there is a 3-digit Kaprekar Process; it would be nice to have code that is easily adaptable to that related problem.
The loop has two purposes: check if the goal has been reached, and count the number of iterations. You have chosen to make the former into the loop termination condition. (It's customary to omit the parentheses there, by the way.) I think that converting it into a counting loop works better, as it brings unity to the thee lines n = 0, n += 1, and if n == 8: ….
By postponing the conversion to int when defining asc, you can simplify the derivation of dec a bit.
Suggested implementation
def kaprekar(value):
def digit_str(n, places):
return ('{:0%dd}' % places).format(n) | {
"domain": "codereview.stackexchange",
"id": 42739,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x",
"url": null
} |
python, beginner, python-3.x
#PLACES, GOAL, ITERATION_LIMIT = 3, 495, 7
PLACES, GOAL, ITERATION_LIMIT = 4, 6174, 8
digits = digit_str(value, PLACES)
if value <= 0:
raise ValueError("Input value must be positive.")
if len(digits) != PLACES:
raise ValueError("Input value must be %d digits long." % PLACES)
if len(set(digits)) < 2:
raise ValueError("Input value must consist of at least two different digits.")
for iterations in range(ITERATION_LIMIT):
print("Iteration %d: %s" % (iterations, digits))
if value == GOAL:
print("Reached %d after %d iterations." % (GOAL, iterations))
return iterations
asc = ''.join(sorted(digits))
dsc = asc[::-1]
value = int(dsc) - int(asc)
digits = digit_str(value, PLACES)
raise StopIteration("Something went wrong...")
Further enhancement
This version separates the iteration logic from the output routines by using a generator. It also makes no presuppositions about The Answer.
import sys
def kaprekar(digits):
if int(digits) <= 0:
raise ValueError("Input value must be positive.")
if len(set(digits)) < 2:
raise ValueError("Input value must consist of at least two different digits.")
places = len(digits)
prev_digits = None
while digits != prev_digits:
yield digits
prev_digits = digits
asc = ''.join(sorted(digits))
dsc = asc[::-1]
value = int(dsc) - int(asc)
digits = ('{:0%dd}' % places).format(value)
def main(_, numstr):
try:
for iterations, digits in enumerate(kaprekar(numstr)):
print("Iteration {i}: {d}".format(i=iterations, d=digits))
print("Reached {d} after {i} iterations".format(i=iterations, d=digits))
except ValueError as e:
print(e, file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main(*sys.argv) | {
"domain": "codereview.stackexchange",
"id": 42739,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x",
"url": null
} |
python, algorithm, backtracking
Title: Optimize "Fill magic square" in python with backtracking
Question: I have written a python program with backtracking that fills a n * n magic square. It solves for n = 4 in 4.5 seconds but gets stuck when I run it for n = 5 on my machine. How can I optimize the algorithm to make it run faster?
from time import perf_counter
def fillMatrix(n):
nSquared = n * n
lineSum = n * (nSquared + 1) / 2
candidates = set(range(1, nSquared + 1))
matrix = [[None for _ in range(n)] for _ in range(n)]
def isValid(row, col):
# row
rowSum = 0
isFull = True
for item in matrix[row]:
if not item:
isFull = False
continue
rowSum += item
if rowSum > lineSum:
return False
if isFull and rowSum != lineSum:
return False
# column
colSum = 0
isFull = True
for i in range(n):
item = matrix[i][col]
if not item:
isFull = False
continue
colSum += item
if colSum > lineSum:
return False
if isFull and colSum != lineSum:
return False
# diagonal
if row != col and row + col != n - 1:
return True
diagSum = 0
isFull = True
for i in range(n):
item = matrix[i][i]
if not item:
isFull = False
continue
diagSum += item
if diagSum > lineSum:
return False
if isFull and diagSum != lineSum:
return False | {
"domain": "codereview.stackexchange",
"id": 42740,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, backtracking",
"url": null
} |
python, algorithm, backtracking
diagSum = 0
isFull = True
for i in range(n):
item = matrix[n - i - 1][i]
if not item:
isFull = False
continue
diagSum += item
if diagSum > lineSum:
return False
if isFull and diagSum != lineSum:
return False
return True
def solve(row, col):
if matrix[row][col] == None:
for candidate in candidates.copy():
matrix[row][col] = candidate
if not isValid(row, col):
matrix[row][col] = None
continue
candidates.remove(candidate)
if row == n - 1 and col == n - 1:
return True
currentSolution = False
if col == n - 1:
currentSolution = solve(row + 1, 0)
else:
currentSolution = solve(row, col + 1)
if currentSolution:
return True
candidates.add(candidate)
matrix[row][col] = None
return False
return True
t1 = perf_counter()
print(solve(0, 0))
print(matrix)
t2 = perf_counter()
print(f'{t2 - t1}s')
fillMatrix(5) | {
"domain": "codereview.stackexchange",
"id": 42740,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, backtracking",
"url": null
} |
python, algorithm, backtracking
Answer: Optimization is pointless
Random magic square hunting peters out very quickly. If n is the order of
a magic square (the number of cells in a row), the domain to be searched for
valid magic squares grows at the rate of (n*n)!. If we conceptualize a magic
square as a one-dimensional list of length n*n, a naive brute-force search
would iterate over all permutations of that list. For n=3 that is doable,
because there are only 362880 lists to check. But for n=4, that domain
becomes about 21 trillion. Since there are known
to be 880 4x4 magic squares, that means random hunting in that space will emit
a hit once per 23.8 billion checks. Python cannot do that.
Even smart searches don't survive long in that environment. Your implementation takes some advantage of the known constraints of
the problem to short-circuit the searching and speed things up. But there are
pressing limits here as well. Consider an algorithm that leverages the
constraints even more effectively than your code. Instead of filling in the grid one cell and
at time and then checking for violated constraints, one could pre-compute all
possible ways of creating a valid row/column/diagonal, given the size of
the magic square (n), the implied magic constant (the needed sum for every
row/column/diagonal), and its universe of eligible numbers (1..n inclusive).
One could also pre-compute a lookup index mapping any partially-completed
row/column/diagonal to the other numbers that would complete it in a valid way.
In addition, the algorithm could proceed in a way that maximizes the
interactions among the constraints: first fill the diagonals, then row 0, then
column 0, row 1, column 1, etc. The benefit of that kind of crossing approach
is that each prior step imposes additional constraints on subsequent steps, thus
reducing the number of viable sums that have to be searched.
Such an algorithm would be considerably faster for various reasons: (1) it | {
"domain": "codereview.stackexchange",
"id": 42740,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, backtracking",
"url": null
} |
python, algorithm, backtracking
Such an algorithm would be considerably faster for various reasons: (1) it
would fill in valid rows/columns/diagonals in a single shot (rather than one
cell at a time); (2) no checking for validity would be required because the
algorithm would be premised on only filling in valid rows/columns/diagonals;
(3) most important, the scope of the search space would be much smaller since
we would only be considering combinations of numbers that achieve valid sums
rather than naively filling in the next cell and then checking for violations. Unfortunately, none of that is enough.
# Let's explore magic squares of size 3 through 7 to see their
# magic constant along with the number of valid ways that a
# row/column/diagonal can add up to that constant. | {
"domain": "codereview.stackexchange",
"id": 42740,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, backtracking",
"url": null
} |
python, algorithm, backtracking
from itertools import combinations
for n in range(3, 8):
n_stop = n * n + 1
magic_constant = int(n * n_stop / 2)
universe = tuple(range(1, n_stop))
valid_rows = tuple(
c
for c in combinations(universe, n)
if sum(c) == magic_constant
)
print(n, magic_constant, len(valid_rows))
# Output.
3 15 8
4 34 86
5 65 1394
6 111 32134
7 175 957332
By the time we get n=7 even our smart algorithm will be utterly swamped.
For magic squares of size 7 there are nearly 1M ways to get the needed sum of
175. And even that number is a big underestimate of the size of the domain.
Because that code snippet uses combinations() it is normalizing the valid
ways to make the needed sums. When filling in any particular
row/column/diagonal, we would actually need to check every permutation of the
current combination being examined. Furthermore, the magnitudes printed above
represent only the size of the domain at the top level (where we fill in the
first diagonal). That magnitude would need to be multiplied by the
constraint-surviving permutations that occur at deeper levels as we fill in
the grid according to our crossing plan. As a result, I'm pretty confident that our
envisioned algorithm could handle n=5, but I am quite pessimistic about
n=6, and n=7 seems impossible.
There are a variety of square-generating algorithms. A different approach
is to grab one of the known algorithms to generate specific magic squares -- for
example, up and to the right.
And if that seems too boring, one could also take a square generated in such
a manner and transform it in a variety of ways (also see). | {
"domain": "codereview.stackexchange",
"id": 42740,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, backtracking",
"url": null
} |
php, security
Title: Security of my upload script #2
Question: I recently asked this question and got a response. I made improvements, it now checks if the file is an image and/or used UUID to store the images, and now I want to see if it's good or not.
How secure is my upload script?
include 'includes/header.php';
if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($userLoggedIn)) {
# code...
header('Location: profile.php');
exit();
}
$date_time = date('Y-m-d_H-i-s');
$errors = [];
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.',$_FILES['fileToUpload']['name']);
$file_ext = strtolower(end ($tmp));
$imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false){
$errors = "Only jpeg, jpg, png and gif files are allowed.";
}
if ($file_size > 55097152) {
$errors = 'File is too large.';
}
if(!$errors) {
$picToUpload = uniqid() . '.' . $imageFileType;
if( !move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $picToUpload)) {
echo "Error uploading files";
die();
}
$file_path = "assets/images/profile_pics/" . basename($picToUpload);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $file_path, $username);
$stmt->execute();
$stmt->close();
header('Location: profile.php');
exit();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42741,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, security",
"url": null
} |
php, security
header('Location: profile.php');
exit();
}
}
}
$_SESSION['error'] = '<b><p style="color: #000; font-size: 30px; top: 34%;right: 60%;position: absolute;">
' . $errors . '</p></b>';
header('Location: profile.php');
exit(); | {
"domain": "codereview.stackexchange",
"id": 42741,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, security",
"url": null
} |
php, security
Answer: I think this implementation is still lacking improvement vs the previous version.
Image size
First of all, the maximum allowed size for pictures is too large. But the biggest problem is that the pictures are stored in raw form without any optimization. So if a user uploads a picture of 10 Mb straight from their smartphone, then the picture will consume 10 Mb on the server. Since it is a profile picture the ultimate size should be closer to 50 Kb than 50 Mb. Because it should be compressed further and resized. There are massive gains to be made. Standard practice actually. Bonus: resizing the image is a good way to ensure that the uploaded file is actually an image in a proper format.
Speed
The other problem is that pages will be slow to load. Constraining pictures within a frame of 200px by 300px for example will not change anything - the browser will load the picture in full size. As long as you are developing in local mode you won't notice. It's when you go live that the slowness will become apparent.
Even in this day and age, visitors expect pages that load fast, lightning fast. They get impatient with sites that are slow and irresponsive. Bottom line, you are wasting storage space, bandwidth and people's time.
Think about your carbon footprint too. The Internet is largely running on coal. Definitely not green at all.
So, I strongly recommend that you not only resize and optimize but convert all pictures to PNG format on your end to streamline things.
Unique identifier and privacy
My advice is to ditch uniqid because as already explained it goes not guarantee uniqueness and you are not even requesting additional entropy. The odds of a collision are slim but still. The more data you have, the more there is a chance the "unthinkable" will happen.
If you are using Mysql you can use the UUID() function instead. I don't think PHP has an equivalent built-in function.
I find myself in disagreement with @KIKO Software over one point. | {
"domain": "codereview.stackexchange",
"id": 42741,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, security",
"url": null
} |
php, security
I find myself in disagreement with @KIKO Software over one point.
Using an incremented ID for the profile picture is more convenient, but using an incremented or predictable identifier also makes scraping and enumeration of users easier. Probably not something you really want due to privacy considerations - remember how content was scraped massively from Facebook, Linkedin etc. I don't like it either, but this is defensive coding vs convenient coding.
OK, maybe this is not the next Facebook but you have to think ahead and be aware of the future consequences of design choices you are making today.
Constants
Regarding the picture directory, it's hard-coded twice in your piece of code. It is a parameter that should go in a configuration file. So that when you need to migrate files, you won't have to rewrite the whole table in your database and change your code on top of that.
You should use a full path, not a relative path. If you restructure your code, move files to directories etc, the path could become invalid as a result and you will have to debug and rewrite your code. It can be more flexible.
Security
Security-wise the function looks sound. Since the file name is not under the control of the user (potential attacker) it is difficult to interfere with it.
Question: how is $userLoggedIn set ? You are checking that the variable is not empty, is your assumption well-tested ?
SQL performance
I might change this statement a bit:
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?"); | {
"domain": "codereview.stackexchange",
"id": 42741,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, security",
"url": null
} |
php, security
and use the ID instead of the username as criterion. The ID can be loaded as a session variable along with other data. The assumption is that the username field may not be covered by an index unlike the ID, thus updates will be slower especially on a large table. Check your table structure and run an execution plan to find out more. It goes without saying that there should be a unique constraint on the username.
Type confusion
At the top of your code $errors is defined as an array:
$errors = [];
The intention being to be able to report multiple errors. But in practice you are only handling one error at a time eg:
$errors = "Only jpeg, jpg, png and gif files are allowed.";
and $errors becomes a string.
To remain consistent you could do:
$errors[] = "Only jpeg, jpg, png and gif files are allowed.";
And then you can report more than one error at a time, for example "File too large" and "Wrong image format". Currently the previous error is overwritten, if any. As long as the array length is zero it means there is no error.
if(!$errors) { will work as expected, it could also be expressed with the empty function. | {
"domain": "codereview.stackexchange",
"id": 42741,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, security",
"url": null
} |
c
Title: c beginners calculator
Question: I wrote this simple calculator and I want to know if there is any problems in it or if there is any way to enhance the code and make it simpler and easier and I also want to know if I'm starting to get into the intermediate level instead of beginners level and thank you
#include<stdio.h>
void main()
{
int mode, n1, n2;
float num1, num2, rslt;
char op;
puts("a simple calculator");
printf("enter the first number : ");
scanf("%f", &num1);
printf("which operation you want '+ - / * or mode' : ");
scanf(" %c", &op);
printf("enter the second number : ");
scanf("%f", &num2);
switch(op)
{
case '+' :
rslt = num1 + num2;
printf("\n %f + %f = %.3f\n\n", num1, num2, rslt);
break;
case '-' :
rslt = num1 - num2;
printf("\n %f - %f = %.3f\n\n", num1, num2, rslt);
break;
case '*' :
rslt = num1 * num2;
printf("\n%f * %f = %.3f\n\n", num1, num2, rslt);
break;
case '/' :
rslt = num1 / num2;
printf("\n%f / %f = %.3f\n\n", num1, num2, rslt);
break;
case '%' :
n1 = num1;
n2 = num2;
switch(n1%n2)
{
case 0 :
printf("\n%d can be devided by %d\n\n", n1, n2);
break;
case 1 :
printf("\n%d can not be devided by %d\n\n", n1, n2);
break;
}
break;
default :
printf("\ninvalid input\n\n");
}
}
Answer: Your code is OK, for a beginner, so please don't worry too much about these comments. I bet you program is fine until you enter the data "break me".
The reason I can list these points so easily, is because I've done them more times than I care to think of, and I've probably done some of them today. Code Review is always a case of do what I say, not what I do.
I hope that helps, if there is anything that isn't clear please say and I will try and make it clearer. | {
"domain": "codereview.stackexchange",
"id": 42742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c",
"url": null
} |
c
Your code lacks comments. There are all sorts of wise people who say you should have x% comments in your code, but all you need to do is to explain what your code does. Sound stupid, but when you look at this in a years time, you will know what I mean.
Variable names should be descriptive, it means you don't need to write so many comments. n1, n2, num1, num2 and op are all examples of variable names I think could be more descriptive/precise. You shouldn't have to think when you read code, firstNumber and secondNumber are easier to understand than n1 and n2.
Initialise variables unless you are 100% certain you don't need to. rslt is not initialised when op is % or default. This could cause a crash or at least garbage data. Also check what happens if scanf fails (can it fail?), is the output parameter set to a certain safe value?
Only declare a single variable per line. It makes it easier to check what has been initialised and what hasn't and to change types.
why did you use puts() and the printf()? Why not just printf() to make the code more uniform?
The printf statements inside the switch statements could be moved to the end to 'refactor' you code slightly.
Putting a switch inside a switch increases the complexity of the code massively. In this case it might be better to replace the whole block with:
.
{
int n1 = (static_cast<int>(num1);
int n2 = (static_cast<int>(num2);
printf("\n%d can %sbe divided by %d\n\n", n1, ((n1%n2)?"":"not"), n2);
}
EDIT To move the printf outside of the switch, you just need to place the opcode in the general string using the variable you already have op:
printf("\n%f / %f %c %.3f\n\n", num1, num2, op, rslt);
The problem is with the % and default branches of the switch, but you can just use return after their printfs to skip the general one. | {
"domain": "codereview.stackexchange",
"id": 42742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c",
"url": null
} |
formatting, postscript
Title: Document formatting markup engine in Postscript
Question: I've been rewriting this same sort of thing off and on over the years, but finally here's the "perfected" monstrosity. Some kruft in the middle with attempting to predict the number of spaces that will be set on the final line. But since that figure is always wrong, the line data structure has to be scanned anyway. So there are certainly lines of code involved in the earlier effort that contribute nothing. I have tried to remove some.
The program is implemented as a protocol-prologue but the code could certainly be repackaged in a different format. This file has the user manual (which also needs outlining and redrafting) appended and will distill to a pdf with Acrobat or Ghostscript's ps2pdf. A pdf of the manual already so generated is available here. [Edit: program has been broken up into multiple files. see below for link to psinc tool which can generate a single-file version (without the manual in-lined, so
it still needs to be run with -DNOSAFER to enable file operators).]
So in addition to comments on programming style or shudder correctness, I'd also be very interested in thoughts about the markup language itself.
The markup is primarily straight text. Markup commands are triggered with the @ sign followed by a keyword and in most cases a [ bracketed argument ]. One big flaw in the behavior of the scanner of the program is that you cannot nest the same delimiter in a single line.
Something like:
@i[italic @b[bold-italic]]
will scan wrongly, taking the argument to @i as italic @b[bold-italic and leaving the extra ] for further confusion. So within the same source-line,
nested delimiters must use distinct pairs from among <>(){}[] which are all equivalent, plus 2 bonus ones :; and `' which require an extra space after the command name, plus any other non-whitespace character may be used as a delimiter and pairs with the first occurrence of itself.
Short example:
@heading{@code[ibis.ps]} | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
@code[ibis] is a markup language and typesetting engine implemented entirely
in the postscript language. It can set text in varying alignments (left (duh),
right, centered, justified) with embedded font changes, and rudimentary kerning
support.
produces output:
Edit: Since there have been no answers, I am updating with the latest revision which breaks up the program into multiple files for easier comprehension.
It will still distill to a pdf but you may need to add -DNOSAFER to enable file operators. Bill Casselman's psinc can be used to combine the set into a single ps file.
GitHub
ibis.ps:
%!
%see (manual.ibis) for description and usage.
%(../debug.ps/db5.ps)run %currentfile cvx debug
% ibisdict defs
%
%/ibisdict 50 dict begin currentdict def %define internally
50 dict /ibisdict 1 index def begin %define in userdict
(util.ps) run
(stack.ps) run
(device.ps) run
(kerning.ps) run
(textset.ps) run
(manuscript.ps) run
(styles.ps) run
%
% Main interface.
% /ibis{} function
%
/src null def % input file
/buf 200 string def % line buffer
/exitflag false def
% call process on each line
%
/ibis { % file|string ibis -
dup type /stringtype eq { (r) file } if
dup type /filetype ne { NOT_A_FILE } if
/src exch def
%pstack()=
{
src buf readline {
dup length 0 eq { blank }{ /justblank false store } ifelse
%dup dup length 1 sub get = quit
process
heol
}{
%process
exit
}ifelse
%heol
exitflag { exit } if
} loop
eol %setline
dev /marksonpage get { showpage } if
} bind def
% @@ define the at-sign as a command to print itself
sigil { sigil settext } def
/comment { pop () } def % delete the remaining source line, yield empty string back to /process
/c //comment def
/default {
text begin
setfontfam
72 setmargin
x Y moveto
} bind def | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
/default {
text begin
setfontfam
72 setmargin
x Y moveto
} bind def
%end ibis and return to postscript
/bye {/exitflag true store} bind def
% Print manual only if /manual is defined (eg. `gs -dmanual ibis.ps`).
% Uncomment this line to enable this, which allows running ibis.ps on other files.
% For ease of development, the source is maintained in this form to enable fast
% testing of changes. While the manual is being developed (in parallel), it also
% serves as an example and testbed.
%/manual where { pop }{ currentfile flushfile } ifelse
%/i load == quit
%stepon
%traceon
default % nb. calls text begin. dictstack now contains: <ibisdict> <text>
%currentfile /ibis load debug
%currentfile ibis
(manual.ibis) (r) file ibis
%(stack:)= pstack(---)= currentfile flushfile
util.ps:
%
%% Simple Functions and Data Structures
% optionally dump text to stdout while writing
% eg. gs -ddumptext ibis.ps
/dumptext where { pop
/show { dup == show } bind def
/ashow { dup == ashow } bind def
/widthshow { dup == widthshow } bind def
/kshow { dup == kshow } bind def
} if
% dicttomark is essentially the same as level-2 >> operator
% but it is used in an attempt at level-1 compatibility
% but primarily for historical reasons:
% in 2011, xpost did not have >>
%
% mark k1 v1 .. kN vN dicttomark dict(N)
/dicttomark { counttomark dup dict begin 2 idiv { def } repeat pop currentdict end } bind def
% Composite Index/Key inc/dec -
% (n.b. dicts are composite objects, as are arrays and strings)
/inc { 2 copy get 1 add put } bind def
/dec { 2 copy get 1 sub put } bind def
% /numeric-variable addend += -
/+= { 1 index load add store } bind def
/-= { neg += } bind def
/*= { 1 index load mul store } bind def
stack.ps:
%
%% Stack Data Structure
% | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
stack.ps:
%
%% Stack Data Structure
%
% Stack type is an array where element 0 contains the index of the top of the stack.
% An overflow of the stack will trigger a rangecheck error in `put`.
% An underflow will trigger a typecheck in get
%
% n stack array{n+1}:[0]=0
/stack { 1 add array dup 0 0 put } bind def % who needs the real stack when there's pstack??
/top { dup 0 get get } bind def % S top a
/spop { dup top exch 0 dec } bind def % S spop a (S{n}->S'(n-1})
/spush { % S a spush - (S{n}->S'{n+1})
dup type /stringtype eq { dup length string copy } if
1 index 0 inc
1 index 0 get exch put
} bind def
/sdrop { % S i sdrop - (S{i}->removed)
%(sdrop:)=
1 index 0 get % S i c
1 index sub %1 sub % S i c-i-1
%pstack()=
dup 0 gt {
{ % S i
2 copy 2 copy % S i S i S i
1 add get put % S' i
1 add % S i=i+1
} repeat % S' i
}{
pop
} ifelse
pop
0 dec % S'
} bind def
% 1 2 3 4 5 6 < array index
% -----------
% a b c d e f 2 sdrop
% a c d e f 6-2=4 -1=3
% a c d e f
%/t { 6 a b c d e f } cvlit def t 2 sdrop t ==
device.ps:
%
%% Output Device
% ibisdict defs
%
% Output device is described only by its bounding box.
% As text is set on the page, the upper bound decreases so the box remains invariant.
%
/dev mark
/size [ clippath pathbbox ]
/bounds null
/marksonpage false
/pagenum 1
dicttomark def % /dev
/savebounds { dev /bounds [ x y X Y ] put } bind def
/restorebounds { dev /bounds get aload pop setbounds } bind def
/setbounds { % x y X Y setbounds -
%/Y exch store /X exch store /y exch store /x exch store
{Y X y x}{exch store}forall
} bind def
/setmargin { % pts setmargin -
dev /size get aload pop
4 index sub 4 1 roll 4 index sub 4 1 roll
4 index add 4 1 roll 4 index add 4 1 roll
setbounds pop savebounds
} bind def
0 setmargin % define x y X Y in ibisdict, now | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
/nextpage {
showpage
dev /marksonpage false put
dev /pagenum inc
restorebounds
x Y moveto
} bind def
kerning.ps:
%
%% Kerning Functions
% ibisdict defs
%
/kpairs 26 dict def
% (ab) n kaddpair -
/kaddpair {
1 index 1 get % (ab) n 98
exch [ 3 1 roll >> % (ab) <<98 n>>
exch 0 get % <<98 n>> 97
exch kpairs 3 1 roll put
} bind def
% 97 98 kgetpair n
/kgetpair {
kpairs 3 2 roll 2 copy known { % k2 <<>> k1
get % k2 <<>>
exch 2 copy known { % <<>> k2
get
}{
pop pop 0
} ifelse
}{
pop pop pop 0
} ifelse
} bind def
% proc str kstringwidth dx dy
/kstringwidth {
dup stringwidth 3 2 roll % p x y s
dup length 1 gt { % p x y s
0 1 2 index length 2 sub % p x y s 0 1 len(s)-2
{ % p x y s i
2 copy get % p x y s i s[i]
2 index 3 2 roll 1 add get % p x y s s[i] s[i+1]
gsave 0 0 moveto
5 index exec
currentpoint % p x y s dx dy
grestore
4 3 roll add 3 1 roll % p x y+=dy s dx
4 3 roll add 3 1 roll % p x+=dx y s
} for
} if % p x y s
pop 3 2 roll pop % x y
} bind def | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
%some tweaks for on-screen Palatino (ie. URW Palladio)
(ac) 7 kaddpair
(al) 3 kaddpair
(am) 3 kaddpair
(an) 3 kaddpair
(av) -10 kaddpair
(bl) 4 kaddpair
(ca) 4 kaddpair
(ce) 8 kaddpair
(ch) -3 kaddpair
(ck) 4 kaddpair
(co) 5 kaddpair
(cu) -5 kaddpair
(de) -5 kaddpair
(ec) 13 kaddpair
(ed) 7 kaddpair
(el) 15 kaddpair
(em) 12 kaddpair
(en) 7 kaddpair
(ex) -8 kaddpair
(he) 5 kaddpair
(hi) 5 kaddpair
(ie) 4 kaddpair
(il) -12 kaddpair
(in) -5 kaddpair
(it) -4 kaddpair
(le) 5 kaddpair
(li) -3 kaddpair
(ll) -2 kaddpair
(lo) 5 kaddpair
(ly) 7 kaddpair
(mm) -10 kaddpair
(nd) 5 kaddpair
(nn) -10 kaddpair
(no) 5 kaddpair
(nt) 5 kaddpair
(om) -2 kaddpair
(on) -2 kaddpair
(os) 4 kaddpair
(ou) -10 kaddpair
(re) 7 kaddpair
(ri) 10 kaddpair
(rl) 3 kaddpair
(rn) -5 kaddpair
(rp) 5 kaddpair
(se) 5 kaddpair
(sp) -5 kaddpair
(ss) 5 kaddpair
(st) 4 kaddpair
(te) 5 kaddpair
(ti) 7 kaddpair
(to) 7 kaddpair
(tp) 10 kaddpair
(tr) -3 kaddpair
(ul) -5 kaddpair
(us) -5 kaddpair
(ut) -10 kaddpair
(xe) -5 kaddpair
(xt) -2 kaddpair
(Al) -15 kaddpair
(An) -10 kaddpair
(Te) -5 kaddpair
(Th) -7 kaddpair
%(a) 0 get (v) 0 get kgetpair =(-----)=
textset.ps:
%
%% /text Dictionary
% text defs
% Text setting
%
/text mark
%parameters
/leftgap 0 % proportion of the gap to skip at the left. .5==centered 1==flush-right
/justify? true
/kerning? true
/fontsize 10
/lead 12
/italic 0
/bold 0
/tty 0
/fontchange true % set to true to make a font-parameter change take effect
/spacecount 0
/charcount 0
/gap 0
/spaceadjust 0
/charadjust 0
/justblank false
/fontfam null | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
/setfontfam {
text /fontfam [ % -roman- -italic- -bold- -bold-italic-
/Palatino-Roman findfont fontsize scalefont
/Palatino-Italic findfont fontsize scalefont
/Palatino-Bold findfont fontsize scalefont
/Palatino-BoldItalic findfont fontsize scalefont
/Courier findfont fontsize .9 mul scalefont
/Courier-Oblique findfont fontsize .9 mul scalefont
/Courier-Bold findfont fontsize .9 mul scalefont
/Courier-BoldOblique findfont fontsize .9 mul scalefont
] put
}
% currentline is used as an extendable array of tuples
% [ [ (text) <<font>> lead kern? ]* ]
% where kern is set to false for the typewriter fonts.
/currentline 100 stack
% "end" the currentline by flushing it to the page
/eol {
currentline 0 get 0 gt {
updatelead
/Y lead -=
/lead leadchange /leadchange lead store store
%text /spacecount dec
chopline
countspaces
countchars
/gap { mark X currentpoint pop sub } stopped { cleartomark mark 0 } if exch pop store
/spaceadjust spacecount 0 ne { gap spacecount div }{ 0 } ifelse store
/charadjust charcount 0 ne { gap charcount div }{ 0 } ifelse store
setline
%(0)=only
/spacecount 0 store
} if
y Y lt { x Y moveto }
{ nextpage } ifelse
}
% "hard" return
/heol { ( ) setword }
% type the daughter line unjustified
/blank {
justblank not {
[ /eol cvx /justify? justify? /store cvx ] cvx /justify? false store exec
/Y lead .5 mul -=
/justblank true store
} if
} | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
/countspaces {
0
currentline first 0 get 0 exch getinterval {
0 get
%( ) eq { 1 add } if
{
32 eq { 1 add } if
} forall
} forall
%spacecount =
%dup =
/spacecount exch store
}
/countchars {
0
currentline first 0 get 0 exch getinterval {
0 get length add
} forall
/charcount exch store
}
% trim leading/trailing space
/chopline {
currentline 0 get 1 ge {
{
currentline 1 get 0 get dup ( ) eq exch () eq or not
{
exit
} if
%(chopping initial space)=
%(-)=only
currentline 1 sdrop
text /spacecount dec
currentline 0 get 1 lt {
exit
} if
} loop
} if
currentline 0 get 1 ge {
{
currentline top 0 get ( ) ne {
exit
} if
%(chopping trailing space)=
%(-)=only
currentline spop pop
text /spacecount dec
currentline 0 get 1 lt {
exit
} if
} loop
} if
}
% scan currentline and set lead to the max lead from the line
% stash previous value as /leadchange
/updatelead {
/leadchange lead store
currentline first 0 get 0 exch getinterval
{
2 get dup leadchange gt { /leadchange exch store }{ pop } ifelse
} forall
%lead leadchange lt { /lead leadchange /leadchange lead store store } if
%/lead leadchange store
/lead leadchange /leadchange lead store store
} | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% show the text in currentline using associated font(s).
% clear currentline.
/setline {
x Y
%(setline:)= pstack()=
moveto
leftgap gap mul 0 rmoveto % this implements flush-right and centered by leftgap=0|.5|1
currentline first 0 get 0 exch getinterval
%dup == spaceadjust =only( )=only spacecount =
{
%pstack()=
%aload pop
dup 0 get 1 index 1 get
setfont
exch 3 get
{
justify? {
dup ( ) eq { spaceadjust 0 rmoveto } if
spacecount 0 eq {
{ kgetpair charadjust add 0
currentfont /FontMatrix get dtransform rmoveto }
}{
{ 1 index 32 eq { pop pop spaceadjust 0 }{ kgetpair 0 } ifelse
currentfont /FontMatrix get dtransform rmoveto }
} ifelse
}{
{ kgetpair 0 currentfont /FontMatrix get dtransform rmoveto }
} ifelse
exch kshow
}{
justify? {
spacecount 0 eq {
show
}{
spaceadjust 0 32 4 3 roll widthshow
} ifelse
}{
show
} ifelse
} ifelse
} forall
currentline 0 0 put
dev /marksonpage true put
%eol
} | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% allocate new string
% allocate [ (str) <<font>> lead kern? ] tuple
% push to currentline stack
/addwordtoline {
dup length string copy
%dup length 1 add string dup 3 1 roll copy pop % copy and append space
%dup dup length 1 sub ( ) putinterval
%currentpoint pop =
%(setword:)= pstack()=
%currentline == flushpage flush(%lineedit)(r)file pop
kerning? tty 0 eq and {
{ kgetpair 0 currentfont /FontMatrix get dtransform rmoveto }
1 index kstringwidth
}{
dup stringwidth
} ifelse
%pstack()=
pop dup currentpoint pop add X ge {
eol %setline
%fontchange {
fontfam tty 4 mul bold 2 mul add italic add get setfont
/fontchange false store
%} if
} if
0 rmoveto
currentfont lead kerning? tty 0 eq and 4 array astore
currentline exch spush
}
% do nothing for initial empty or blank strings.
% check stringwidth+currentpoint and flush currentline
% by calling eol (which calls setline) if too long.
% rmoveto by the stringwidth
% add word to currentline.
/setword {
dup ( ) eq {
currentline 0 get 0 eq {
%(-)=only
text /spacecount dec
pop
}{
currentline top 0 get ( ) eq {
%(-)=only
text /spacecount dec
pop
}{
addwordtoline
} ifelse
} ifelse
}{
dup () eq {
pop
}{
addwordtoline
} ifelse
} ifelse
} | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% used like show, this is the call for adding text to the output.
% chops text into words and calls setword on each.
/settext {
fontchange {
fontfam tty 4 mul bold 2 mul add italic add get setfont
/fontchange false store
} if
%show
/initialspace false store
( ){ anchorsearch {/initialspace true store}{ exit } ifelse } loop %strip initial spaces
initialspace { ( ) setword } if
( ) {
%search exch setword not { exit } if
search {
setword
{ anchorsearch not {exit} if } loop
%currentline 0 get 0 gt {
%(+)=only
( ) dup setword
text /spacecount inc
%} if
}{
setword
%(+)=only
%( ) setword
%text /spacecount inc
exit
} ifelse
} loop
}
dicttomark def % /text
manuscript.ps:
%
%% Manuscript Processing
% ibisdict defs
% find takes 3 procedures, a string and search-string
% and executes on_a and on_b upon the returned substrings if found
% or the not procedure if not found
/find { % {not} {on_b} {on_a} (aXb) (X) find -
search { % n b a (b) (X) (a)
4 1 roll pop % n b (a) a (b)
4 1 roll % n (b) b (a) a
5 -1 roll pop % (b) b (a) a
/exec cvx 5 3 roll % (a) a exec (b) b
/exec cvx 6 array astore cvx exec
%exec exec
}{ % n b a (a_b)
4 1 roll pop pop % (a_b) n
exec
} ifelse
} bind def
%{(n)= =}{(b)= =}{(a)= =} (pretextpost) (text) find
%(stack:)= pstack
%quit
%shift a 1-element composite object off of a larger composite object
/first { % (abc) first (bc) (a)
dup 1 1 index length 1 sub getinterval exch
0 1 getinterval
} bind def | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% delimiter pairs
/pairs mark
([)(]) (<)(>) (\()(\)) ({)(}) (`)(') (:)(;)
dicttomark def % /pairs
% ([) rhs (])
% (q) rhs (q)
% (") rhs (")
/rhs { pairs exch 2 copy known { get }{ exch pop } ifelse } bind def
% the nest stack contains unclosed delimiters for nested short-form segments
% but only if not immediately found on the same input line
% eg. @i{ @b( @t< > ) }
/nest 10 stack def
% {on_a} (]) deferal {[{on_a} (])] nest exch spush}
% create a save-it-for-later proc
% for the not-found clause of find
/deferal {
2 array astore
[ exch /nest cvx /exch cvx /spush cvx ] cvx
} bind def
% execute proc on the 'a' portion of string, return 'b' portion
% on_a is a 'fin' function from an alteration
% {on_a} ([a]b) delim (b)
/delim {
exch /process cvx exch /exec cvx 3 array astore cvx exch % {on_a} = {process {on_a} exec}
first rhs % on_a (a]b) (])
3 copy exch pop % on_a (a]b) (]) on_a (])
deferal % on_a (a]b) (]) not %not-clause
{} % on_a (a]b) (]) not on_b %on_b clause: leave string on stack
5 2 roll % not on_b on_a (a]b) (])
%(delim)= pstack()=
find
} bind def
% execute a short-form command, taking delimited argument from string,
% return remainder of string
% ([arg]rem) /name short (rem)
/short {
%(short)= pstack()=
alt exch get % s d
dup /ini get exec % s d ?
exch /fin get % s ? {}
[ 3 1 roll /exec cvx ] cvx exch % undo s
delim
} bind def
% the pending stack contains unclosed environments bracketed by @Begin() @End()
%
/pending 10 stack def | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% (name) checkpending -
/checkpending {
%(checking pending stack)= pending ==
{
pending 0 get -1 1 { % (name) i
%pstack()=
pending 1 index get % (name) i []
0 get 2 index
%pstack()=
eq { % (name) i
%pstack()=
stop
} if
pop
} for
} stopped { % (name) i
pending 1 index get 1 get % (name) i fin-arg
3 2 roll alt exch get /fin get exec % i
pending exch sdrop
}{ Err:symbol-not-in-pending-stack } ifelse
} bind def
% perform the @Begin() action for an enviroment
% ([name]rem) long (rem)
/long {
first rhs % (name]rem) (])
{Err:long-form-arg-cannot-span-lines}
{}
{
%pstack()=
dup length string copy
dup alt exch get /ini get exec
2 array astore pending exch
%pstack()=
spush
%pending ==
}
5 3 roll % {} {} {} (name]rem) (])
find
} bind def
% perform the @End() action for an environment
% ([name]rem) long-end (rem)
/long-end {
first rhs % (name]rem) (])
{Err:long-form-arg-cannot-span-lines}
{}
{checkpending} %search pending stack and remove match
5 3 roll % {} {} {} (name]rem) (])
find
} bind def
% long-form commands to enter/leave an environment
/Begin { long } def
/End { long-end } def
% execute the first token from the string and process the remainder
% str execute -
/execute { token { exec process }{ BAD_COMMAND } ifelse } bind def
% the "at" sign indicates the start of an embedded command
/sigil <40> def
% scan argument string for the sigil and execute command after processing prefix
/command {
{settext} {execute} {settext} 4 3 roll
sigil find
} bind def | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% scan string for embedded @commands
% and call settext for other text.
/process { % str process -
%(process:)= pstack()=
dup length 0 eq {
pop
%blank
}{
nest 0 get 0 gt {
{command} {process} nest top aload pop % str {!} {B} {A} (X)
exch [ exch % str {!} {B} (X) [ {A}
nest exch /spop cvx exch /pop cvx exch %/process cvx exch
/exec cvx
] cvx exch % str {!} {B} {A}' (X)
5 4 roll exch % {!} {B} {A} str (X)
find
% {process}{process} nest top aload pop % {!} {B} {A} (X)
% exch [
% %{nest spop pop process {defered "on_a"} exec}
% exch nest exch /spop cvx exch /pop cvx exch /process cvx exch /exec cvx
% ] cvx exch % {!} {B} {A}' (X)
% 5 4 roll exch % {!} {B} {A} str (X)
% find
}{
command
} ifelse
} ifelse
} bind def
styles.ps:
%
%% Alterations, aka Environments -- the basis of Styles
% ibisdict and alt defs
%
% dict for alteration dictionaries
/alt 20 dict def
% install an environment in the alterations dict
% name dict newalter -
%
% dict should contain 2 procs
% - ini ? implements the "on" action
% ? fin - implements the "off" or "undo" action
% where ini returns an object that should be
% passed to fin
/newalter {
%install in alt dict
2 copy alt 3 1 roll put
%create short-form procedure
pop [ 1 index /short cvx ] cvx def
} bind def
% if fontchange is true, settext will reload the font from fontfam
% using the current values of bold italic tty
/updatefont { /fontchange true store } bind def | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
%roman font
/r mark
/ini { tty 4 mul bold 2 mul italic add add
/bold 0 store
/italic 0 store
/tty 0 store
updatefont }
/fin { dup 2 mod /italic exch store
2 idiv dup 2 mod /bold exch store
2 idiv /tty exch store
updatefont }
dicttomark newalter
%add italic if roman or bold
% or oblique if tty
/i mark
/ini { italic /italic 1 store updatefont }
/fin { /italic exch store updatefont }
dicttomark newalter
%add bold
/b mark
/ini { bold /bold 1 store updatefont }
/fin { /bold exch store updatefont }
dicttomark newalter
%tty font
/t mark
/ini { tty /tty 1 store updatefont }
/fin { /tty exch store updatefont }
dicttomark newalter
/font+ mark
/ini { [ fontsize /fontsize 1.25 *= lead /lead 1.25 *= ]
setfontfam updatefont }
/fin { aload pop /lead exch store /fontsize exch store
setfontfam updatefont }
dicttomark newalter
/font- mark
/ini { [ fontsize /fontsize .8 *= lead /lead .8 *= ]
setfontfam updatefont }
/fin { aload pop /lead exch store /fontsize exch store
setfontfam updatefont }
dicttomark newalter | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
% name [ alt-entries ] addstyle -
% a style composes named alt dicts into a new alt dict
% which performs the combined effects.
% /ini functions are executed left-to-right at the beginning.
% /fin functions are executed right-to-left at the end.
/addstyle { % name arr
[ /mark cvx 2 index % name arr [ mark arr
{ % name arr [ mark ... arr[i]
alt exch get % name arr [ mark ... dict
/ini get /exec cvx % name arr [ mark ... {ini} exec
} forall
%(1:)= pstack() =
(]) cvn cvx
%(2:)= pstack() =
] cvx % name arr { mark {{ini} exec}* ] }
mark /ini 4 2 roll exch % name mark /ini {{ini exec}*} arr
[ exch % name mark /ini {ini*} [ arr
{ % name mark /ini {ini*} [ ... arr[i]
alt exch get % name mark /ini {ini*} [ ... dict
/fin get /exec cvx % name mark /ini {ini*} [ ... {fin} exec
counttomark 2 roll % name mark /ini {ini*} [ {fin} exec ...
} forall
%(3:)= pstack() =
/aload cvx /pop cvx counttomark 2 roll % n [ /ini{ini*} [ aload pop {fin exec}*
] cvx /fin exch % name [ /ini{ini*} /fin{fin*}
dicttomark
newalter
} def
/eolbefore mark
/ini { ( ) addwordtoline eol 0 }
/fin { pop }
dicttomark newalter
/eolafter mark
/ini { 0 }
/fin { pop ( ) addwordtoline eol }
dicttomark newalter
/hardeol mark
/ini {
[
text /heol get text /heol { ( ) addwordtoline eol } put
text /settext get text /settext {
fontchange {
fontfam tty 4 mul bold 2 mul add italic add get setfont
/fontchange false store
} if
addwordtoline
} put
]
}
/fin {
aload pop
text /settext 3 2 roll put
text /heol 3 2 roll put
}
dicttomark newalter
/noblank mark
/ini { text /blank get text /blank { } put }
/fin { text /blank 3 2 roll put }
dicttomark newalter | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
/nojustify mark
/ini { justify? /justify? false store }
/fin { /justify? exch store }
dicttomark newalter
/fullgap mark
/ini { text /leftgap get text /leftgap 1 put }
/fin { text /leftgap 3 2 roll put }
dicttomark newalter
/halfgap mark
/ini { text /leftgap get text /leftgap .5 put }
/fin { text /leftgap 3 2 roll put }
dicttomark newalter
/addindent mark
/ini { x /x x 36 add store }
/fin { /x exch store }
dicttomark newalter
/addrightindent mark
/ini { X /X X 36 sub store }
/fin { /X exch store }
dicttomark newalter
/tightlead mark
/ini { lead /lead .9 *= }
/fin { /lead exch store }
dicttomark newalter
/right { hardeol fullgap nojustify eolafter } addstyle
/center { hardeol halfgap nojustify eolafter } addstyle
/verbatim { hardeol noblank nojustify eolafter } addstyle
/quotation { addindent addrightindent tightlead eolbefore eolafter } addstyle
/heading { eolbefore b i font+ eolafter } addstyle
/code { b t } addstyle
manual.ibis:
@heading{@code[ibis.ps]}
@code[ibis] is a markup language and typesetting engine implemented entirely
in the postscript language. It can set text in varying alignments (left (duh),
right, centered, justified) with embedded font changes, and rudimentary kerning
support.
@heading{Introduction}
As this manual's implementation illustrates, @code[ibis] can be used as a prologue
with the remaining document appended to the same source. Thus, the whole
word-processor is embedded @i *in* the document. Or it can be `run` from another
postscript program, and then execute upon any desired file (including whatever
file is @code[currentfile] currently).
Text is broken into words and fitted onto lines, adjusting spacing
for fully-justified blocks.
A comment in the source may be introduced by the @code[@@ comment] command, or its
shorter alias @code[@@ c].
It consumes the remained text on the source line.
@@ comment This is a comment.
@comment This is a comment.
@c This is a comment. | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
@@ comment This is a comment.
@comment This is a comment.
@c This is a comment.
@Begin{quotation}
The Scribe markup language defined the words, lines, pages, spacing, headings, footings, footnotes, numbering, tables of contents, etc. in a way similar to HTML.
@right{-- @code[http://en.wikipedia.org/wiki/Scribe_(markup_language)]}
@End{quotation}
There are various ways of executing a command to change
a section of text. All commands are introduced by the @@ character,
known internally as the "sigil".
The simple command @code{i} for italics, can use the short form
with various sets of delimiters.
@Begin{verbatim}
@@ i[italics] produces @{/tab currentpoint pop def}@i[italics]
@@ i(italics) @{tab currentpoint exch pop moveto}@i(italics)
@@ i<italics> @{tab currentpoint exch pop moveto}@i<italics>
@@ i{italics} @{tab currentpoint exch pop moveto}@i{italics}
@@ i `italics' @{tab currentpoint exch pop moveto}@i `italics'
@@ i :italics; @{tab currentpoint exch pop moveto}@i :italics;
@End{verbatim}
These last two require an extra space after the command name since
the backquote and colon are not postscript delimiters.
If a short-form @code{i} command has its arguments all on
one source-line, then the @i{ini/fin} pair of functions are orchestrated
as part of parsing the line. Otherwise if the closing delimiter is not
on the same source line, a [right-delimiter {fin}] tuple is placed on a
stack which governs the searching
and parsing of subsequent lines.
The long form uses the same command names, but it is now the @i{argument}
to the @@ Begin{} or @@ End{} command.
@@ Begin{i}@Begin{i}Start italics.
@@ End{i}@End{i}End italics.
Incidentally, since the command name is scanned with 'token' and
executed with 'exec', it can even be a postscript procedure.
@{/oldfont currentfont def}
@Begin{verbatim}
@@ {/Courier 11 selectfont}text in Courier
@{/Courier 11 selectfont}text in Courier
@End{verbatim}
@{oldfont setfont} | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
Explicit font-changes of this sort are not the primary intention.
Rather, the document should be described using logical names for
the semantic type of information being indicated. These names
should then be implemented as styles to achieve the desired
visual effect. Or define the styles first and then use them.
But use them.
Rather than deal with single font changes, ibis prefers to
work with a font @i{family} with 3 orthogonal options:
@r{Roman}/@t{Tty}, @b{Bold}/Not-Bold, @i{Italic}/Not-Italic,
which can be variously combined.
The product of this is 8 fonts. The eight fonts defined in
this prototype are: @code{ /Palatino-Roman /Palatino-Italic
/Palatino-Bold /Palatino-BoldItalic /Courier /Courier-Oblique
/Courier-Bold } and @code{ /Courier-BoldOblique }.
Only "short-form" commands take a delimited argument.
The @@ {arbitrary ps code} commands are not "short-form",
and do not take an argument but apply directly to the current state.
But they do receive the remaining portion of the line as a string,
so a custom command may consume data from the string and yield the
remainder to be printed (it should leave a string on the stack).
@Begin{verbatim}
Now with @b[bold].
@t[ typewriter-text @i<oblique> ]
@t[T @b{B @i<I @r `Roman should override all of' italics,> bold,} and typewriter] flags.
@End{verbatim}
@Begin{right}
Flush-Right Text.
@End{right}
@Begin{center}
Centered text,
@End{center}
I finally remembered what "deferal" was all about. So let's
see if it works. It should allow bracketed commands to span
multiple lines.
Like so: @i[ This sentence
should be all italics
despite spanning lines,
in a line-oriented
scanning routine. ]
And back to normal.
Haha! I just read in the scribe paper that @@ Begin() and @@ End()
sections should always be properly nested.
So I just wasted some effort getting this to work: | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
@Begin{verbatim}
@@ Begin{i} italic @@ Begin{b} bold-italic @@ End{i} bold @@ End{b} normal
@Begin{i} italic @Begin{b} bold-italic @End{i} bold @End{b} normal
@End{verbatim}
@{alt/r get/ini get exec pop updatefont}But it's probably best to
nest things properly anyway.
This should be considered "backup" behavior.
An interest has developed in changing the font size. Currently,
this can be hacked with explicit postscript.
@{/fontsize 5 += /lead 3 += setfontfam updatefont}Big text.
@{/fontsize 5 -= /lead 3 -= setfontfam updatefont}back to normal.
@{/fontsize 2 *= /lead 1.5 *= setfontfam updatefont}Double-size text.
@{/fontsize .5 *= /lead .75 *= setfontfam updatefont}back to normal.
@{alt/r get/ini get exec pop updatefont}Has the lead actually been
reset, or am I fooling myself?
I think I may have written a bug where the lead can only increase.
This extra text explains the purpose for this extra rambling text.
Whew. Fixed.
A shorter command for font size changes has been implemented as
@code[font+] and @code[font-] which can be used short-form, long-form,
or composed in a style.
I just read in the scribe user manual that the same brackets should
be able to nest. This I have to fix. I had assumed that the variety
of bracket choices () [] {} <> was for the convenience of the implementation,
but I was wrong. It is for the convenience of the user, and the
implementation has a little more work to do. Currently ibis does not
correctly handle nesting of the same delimiters, and you should use
different ones when nesting so it doesn't get confused.
@heading{Styles}
I think I've built-up the requisite functionality to implement styles
in a sensible manner. It's unfortunate that I can't locate the Scribe
Expert Manual where specifying styles is supposed to be explained. | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
So far, a style is a short-hand for any number of "alterations" which
can be installed and uninstalled in a controlled manner. An alteration
is a dictionary containing two procedures: @i{ini} and @i{fin}, where
@i{ini} returns an object which is later passed to @i{fin}.
The font operations have been implemented in terms of alteration dictionaries.
The @@ i{} command tweaks a variable called @i{italic} and sets a variable
called @i{fontchange} to @b{true}. The @i{ini} function for @i{i} returns
the previous value of @i{italic} so that @i{fin}, upon receiving this value
may restore it.
So a @b{style} is a composition of these alteration dictionaries.
And pretty-much any behavior desired can be realized by constructing
custom alteration dictionaries to be composed. The values returned by
the @i{ini} functions are collected in an array which constitutes the
style's @i{ini} function's return value. The style's @i{fin} function
receives this array, calls @code{aload pop} and the composed @i{fin}
functions are executed in the reverse order to consume their arguments
naturally from the operand stack.
@comment Lots of blank lines here --V
I cleaned-up the internal handling of @code{eol} commands, so you should
be able to add extra newlines between paragraphs in the source which
are removed and normalized for the output. The @code{blank} function
which is called for blank lines sets a flag and does nothing if
repeatedly called. A non-blank line clears the flag.
And it appears to be working. A new (blank) line in the output can be
forced by adding a space (or other invisible element?) to the currentline
and then calling @code[eol]. Simplest at the moment is using
@code[addwordtoline] which bypasses the space-chopping that @code[settext]
does.
@comment Lots of blank lines here --^
@bye | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
formatting, postscript
@comment Lots of blank lines here --^
@bye
Questions:
• Is the overall structure sound?
• Are there improvements to be made to the formatting or algorithms?
• Should the kerning code try to read from some standardized format for kerning tables?
• Is there a better algorithm for parsing bracketed text that avoids the problem of getting similar brackets wrong?
• Are there obvious features or styles missing that should be added?
• Is a custom/customizable markup language desirable or should it be reworked to use an existing markup syntax?
Answer: (I've just skimmed the better part of the code presented, and not spent deep thought about purpose or suitability.)
Good to see judicious use of bind.
(I've seen /bd { bind def } bind def in longish scripts.)
While I welcome stack effect comments and could follow naming wherever I tried, I wouldn't be against more comments.
I don't think PostScript files meant to be included are exempted from
The first line of a PostScript language file must, by convention, begin
with the characters %! (percent and exclamation, often referred to as
“percent-bang”).
Please leave comment lines starting %% to Document Structuring, especially at the beginning of a file.
In the manual, it would seem to need more line breaks to see the effect on leads.
The multiplicative inverse of 1.5 is not .75. Rather, I'd advocate 1.5 /=. | {
"domain": "codereview.stackexchange",
"id": 42743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "formatting, postscript",
"url": null
} |
python
Title: Converting a YouTube embed link to a regular link in Python
Question: I am fairly new to Python, C# is what I usually code in.
I have the following:
https://www.youtube.com/embed/FjHGZj2IjBk?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0
And I want to convert it to:
https://www.youtube.com/watch?v=FjHGZj2IjBk
I wrote a basic function, and it works, but is it done in the best, most readable way?
embed_links = [
"https://www.youtube.com/embed/NL5ZuWmrisA?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0",
"https://www.youtube.com/embed/gnZImHvA0ME?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0",
"https://www.youtube.com/embed/FjHGZj2IjBk?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0"
]
def convert_to_regular_youtube_link(embed_link):
embed_link_split = embed_link.split('/')
video_id_with_params = embed_link_split[4]
head, sep, tail = video_id_with_params.partition('?')
video_id = head
final_youtube_link = f'https://www.youtube.com/watch?v={video_id}'
return final_youtube_link
for link in embed_links:
print(convert_to_regular_youtube_link(link)) | {
"domain": "codereview.stackexchange",
"id": 42744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
for link in embed_links:
print(convert_to_regular_youtube_link(link))
Answer: The functional approach to your problem is a good start. But relying on splitting and indexing strings, more specifially URLs and accessing their parts by index may be error-prone.
Use standard library tools to parse URLs
There are urrlib.parse and pathlib providing you with functions to parse and manipulate URLs and paths.
Naming
The parameter name embed_link may be improved upon. It is rather a URL, so why not just call it that. Also consider capitalizing global constants.
Use if __name__ == '__main__' guard
... so that your script does not run, if one only wants to import the function.
Use docstrings
... to document your functions. Briefly explain what they are doing.
Type hinting
You may (or may not) use type hints to clarify to the user what types of parameters your function expects and what it returns.
Suggested change:
from pathlib import Path
from urllib.parse import urlparse, urlunparse
EMBED_URLS = [
"https://www.youtube.com/embed/NL5ZuWmrisA?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0",
"https://www.youtube.com/embed/gnZImHvA0ME?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0",
"https://www.youtube.com/embed/FjHGZj2IjBk?controls=2&fs=0&rel=0&modestbranding=1&showinfo=0&autohide=1&iv_load_policy=3&cc_load_policy=0&autoplay=0"
]
def convert_to_watch_url(embed_url: str) -> str:
"""Convert a YouTube embed URL into a watch URL."""
scheme, netloc, path, params, query, fragment = urlparse(embed_url)
video_id, path = Path(path).stem, '/watch'
return urlunparse((scheme, netloc, path, params, f'v={video_id}', fragment))
def main() -> None:
"""Convert and print the test URLs."""
for embed_url in EMBED_URLS:
print(convert_to_watch_url(embed_url))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 42744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c++, performance, beginner, programming-challenge
Title: Function wrapper that prints the result
Question: (English)
I was recently challenged to make a simple program that does the following:
Function f accepts as a parameter a function g, which returns a value. Function f must return a function h which returns and prints the value that function g returns.
After some research I got the solution and the program was successful, but I wonder if the code is done in the best way. I would appreciate immensely a critique.
This is the code:
Hace poco me retaron a realizar un programa sencillo que realiza lo siguiente:
La función f acepta como parámetro una función g, la cual regresa un valor. La función f debe de regresar una función h la cual regresa e imprime el valor que regresa la función g.
Luego de investigar un poco conseguí la solución y el programa resulto exitoso, pero me pregunto si el código esta hecho de la mejor manera. Agradecería inmensamente una critica.
Este es el código:
#include <iostream>
using namespace std;
auto g() // Función que regresara el valor principal
{
return 123;
}
template <class FT>
auto f(FT* fref) // Función que recibira una referencia de una función
{
return [=]() -> auto // Regresa una función creada a partir de "fref"
{
cout << fref() << endl;
return fref();
};
}
int main()
{
auto h = f(&g); // Llamando la función f pasando la referencia de la función g
auto resultado = h();
cout << resultado << endl;
return 0;
}
Answer: I see one substantial problem with your implementation:
f() calls fref() twice - bad enough if each call consumes considerable resources,
probably plain wrong where the call has side effects.
(The funny part is main() introducing a variable to hold the result without need.) | {
"domain": "codereview.stackexchange",
"id": 42745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, beginner, programming-challenge",
"url": null
} |
c#, asynchronous, networking
Title: Task-based TCP socket wrapper class
Question: Recently I've been entertaining the idea of making a small encrypted chat app as a way to learn about UI, encryption and networking in C#. After some research/work, I've produced the below protocol class that can reliably and asynchronously communicate over TCP Sockets in a console integration test.
However, I've still got some lingering questions with regards to my use of Tasks, particularly with the AwaitMessageOfType, ContinuousSend, and ContinuousReceive methods. They work, but I have a strong suspicion that they'll fail to scale if I try to create an actual server application that's potentially juggling dozens of protocol instances at once. Is there a better/more proper solution?
Also, feel free to critique my coding style. If something makes your eyes bleed, I'd like to avoid making it a habit. Thanks!
namespace Tightbeam_Common
{
/// <summary>
/// Class used to wrap and interface with a Socket instance in a structured manner.
/// </summary>
public class TightbeamProtocol
{
//Public-readonly enum used to display the general state of the protocol instance
public ProtocolState State { get; private set; }
//A pre-connected TCP socket, provided during construction.
private Socket link;
//NodeInfo for both ends of the connection.
private NodeInfo personalInfo;
private NodeInfo? partnerInfo;
//Key structs.
//The partner RSA public key and shared AES private key are received/generated dynamically.
private RSAKeypair personalKeypair;
private RSAKeypair partnerKeypair;
private AESKey sharedPrivateKey; | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
//Outgoing message queue.
private Queue<NetworkMessage> outgoinqQueue = new();
//Received message queue.
public Queue<NetworkMessage> ReceivedMessages = new();
//Event that fires whenever an inbound message is fully received, deserialized and enqueued.
public event EventHandler? MessageReceived;
//4-byte buffer used to receive the length of following data streams
private byte[] lengthBuffer = new byte[sizeof(int)];
//Buffer used to spool incoming serial data.
private byte[]? dataBuffer = null;
//Integer used to hold byte read progress.
private int bytesReceived = 0;
public bool anyReceivedMessages
{
get
{
return (ReceivedMessages.Count > 0);
}
}
private bool anySpooledMessages
{
get
{
if (outgoinqQueue.Count == 0) { return false; }
return true;
}
}
private int spooledMessages
{
get
{
return outgoinqQueue.Count;
}
}
public TightbeamProtocol(Socket socket, NodeInfo info, RSAKeypair personalKeypair)
{
State = ProtocolState.StartingUp;
//Construct instance members
link = socket;
personalInfo = info;
this.personalKeypair = personalKeypair;
//Spin up continuous I/O tasks
Task.Run(() => this.ContinuousSend());
Task.Run(() => this.ContinuousReceive());
//Start handshake handler
Task.Run(() => this.PerformHandshake());
Console.WriteLine(this.GetHashCode() + " Construction complete");
} | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
private async Task PerformHandshake()
{
//Send handshake to partner
Handshake outboundHandshake = new Handshake(personalInfo);
EnqueueMessage(outboundHandshake, Encryption.None);
//Await/act upon partner handshake
Console.WriteLine(this.GetHashCode() + " Handshake sent...");
NetworkMessage handshakeMessage = await AwaitMessageOfType(typeof(Handshake));
Console.WriteLine(this.GetHashCode() + " Handshake RECEIVED!");
Handshake partnerHandshake = Serializer.DeserializeContent<Handshake>(handshakeMessage.Data)!;
partnerInfo = partnerHandshake.senderInfo;
partnerKeypair = partnerInfo.PublicKey;
//Key exchange
Console.WriteLine(this.GetHashCode() + " Key Exchange sent...");
AESKey localKey = Cryptographer.GenerateAESKey();
EnqueueMessage(new KeyExchange(localKey), Encryption.RSA);
NetworkMessage exchangeMessage = await AwaitMessageOfType(typeof(KeyExchange));
KeyExchange receivedExchange = Serializer.DeserializeContent<KeyExchange>(exchangeMessage.Data, personalKeypair)!;
sharedPrivateKey = Cryptographer.CascadingKeySelect(localKey, receivedExchange.AESKey);
Console.WriteLine(this.GetHashCode() + " " + string.Join(", ", sharedPrivateKey.Key));
Console.WriteLine(this.GetHashCode() + " Key Exchange COMPLETE!");
//Unlock protocol instance
ReceivedMessages.Clear();
State = ProtocolState.Operational;
}
private async Task<NetworkMessage> AwaitMessageOfType(Type type)
{
while (true)
{
var messageQuery = from msg in ReceivedMessages
where msg.ContentType == type
select msg; | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
if (messageQuery.Any()) { return messageQuery.First(); }
await Task.Delay(100);
}
}
/// <summary>
/// <br>Starts the graceful shutdown process of a connected protocol instance.</br>
/// <br>Graceful shutdown waits for all enqueued messages to be sent, and then closes the socket connection.</br>
/// </summary>
public async Task StartShutdown()
{
State = ProtocolState.ShuttingDown;
//TODO queue graceful disconnect packet
while (anySpooledMessages) { await Task.Delay(50); }
try
{
link.Shutdown(SocketShutdown.Both);
}
finally
{
link.Close();
State = ProtocolState.Inert;
}
}
/// <summary>
/// Wraps a given content object and header information into a NetworkMessage instance, and enqueues it accordingly.
/// </summary>
public void EnqueueMessage<T>(T content, Encryption encryption)
{
if (State > ProtocolState.Operational) { return; }
byte[] serializedContent;
switch (encryption)
{
case Encryption.AES:
serializedContent = Serializer.SerializeContent(content, sharedPrivateKey);
break;
case Encryption.RSA:
serializedContent = Serializer.SerializeContent(content, partnerKeypair);
break;
default:
serializedContent = Serializer.SerializeContent(content);
break;
}
var newMessage = new NetworkMessage(serializedContent, typeof(T), encryption);
outgoinqQueue.Enqueue(newMessage);
} | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
/// <summary>
/// Persistent Task that continuously attempts to dequeue and send any spooled messages.
/// </summary>
private async Task ContinuousSend()
{
while (State < ProtocolState.Inert)
{
if (anySpooledMessages)
{
NetworkMessage message = outgoinqQueue.Dequeue()!;
byte[]? data = Serializer.SerializeMessage(message, true);
try
{
Console.WriteLine(this.GetHashCode() + " Sending message of type: " + message.ContentType.ToString());
await link.SendAsync(data, SocketFlags.None);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
/// <summary>
/// Persistent Task that continuously attempts to receive inbound bytes.
/// </summary>
private async Task ContinuousReceive()
{
while (State < ProtocolState.ShuttingDown)
{
if (link.Available > 0)
{
byte[] data = new byte[link.Available];
try
{
await link.ReceiveAsync(data, SocketFlags.None);
SortData(data);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
//Brief 100ms delay to allow bytes to accumulate in the socket.
await Task.Delay(100);
}
} | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
/// <summary>
/// Sorts given inbound bytes into the correct buffer.
/// </summary>
private void SortData(byte[] data)
{
int i = 0;
while (i != data.Length)
{
int availableBytes = data.Length - i;
if (dataBuffer is not null)
{
//Data buffer has been initialized; assume length buffer has been prepared and read into data buffer.
int requestedBytes = dataBuffer.Length - bytesReceived;
int transferredBytes = Math.Min(requestedBytes, availableBytes);
Array.Copy(data, i, dataBuffer, bytesReceived, transferredBytes);
i += transferredBytes;
ParseData(transferredBytes);
}
else
{
//Data buffer is un-initialized; assume we are reading into the length buffer.
int requestedBytes = lengthBuffer.Length - bytesReceived;
int transferredBytes = Math.Min(requestedBytes, availableBytes);
Array.Copy(data, i, lengthBuffer, bytesReceived, transferredBytes);
i += transferredBytes;
ParseData(transferredBytes);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
ParseData(transferredBytes);
}
}
}
/// <summary>
/// Acts upon received data once a buffer is full.
/// </summary>
private void ParseData(int count)
{
bytesReceived += count;
if (this.dataBuffer is null)
{
//Attempt to parse length buffer.
if(bytesReceived != sizeof(int)) { /*Pass - awaiting length buffer completion.*/ }
else
{
//Parse length buffer to determine content stream size and initialize data buffer accordingly.
int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
if (dataLength < 0 || dataLength > int.MaxValue) { throw new InvalidOperationException("Message length is out of bounds!"); }
else { dataBuffer = new byte[dataLength]; bytesReceived = 0; }
}
}
else
{
//Attempt to parse contents of data buffer.
if (bytesReceived != dataBuffer.Length) { /*Pass - awaiting data buffer completion.*/ }
else
{
//Parse data buffer into a NetworkMessage.
NetworkMessage? message = Serializer.DeserializeMessage(dataBuffer);
if (message is null) { throw new InvalidDataException("Received corrupt or invalid data - could not deserialize to NetworkMessage."); }
//Decrypt data if needed.
if (message.Encryption == Encryption.AES) { message.DecryptData(sharedPrivateKey); }
ReceivedMessages.Enqueue(message);
Console.WriteLine(this.GetHashCode() + " Received message of type: " + ReceivedMessages.Peek().ContentType.ToString());
OnMessageReceived(); | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
//Reset data buffer and byte reception tally for next message.
dataBuffer = null;
bytesReceived = 0;
}
}
}
private void OnMessageReceived()
{
//Alert any subscribers that we've received a new message.
EventHandler? handler = MessageReceived;
handler?.Invoke(this, EventArgs.Empty);
}
}
public enum ProtocolState
{
StartingUp,
Operational,
ShuttingDown,
Inert,
Exception
}
}
```
Answer: Class members
Please try to follow the same naming convention across all your members
If you use camel Casing for private members then do for all your private members
If you have members that are counterpart of each other then try to use the same naming
So, instead of having outgoingQueue and ReceivedMessages
Try to name them like : sentMessages and ReceivedMessages
Prefer expression bodied property getter over lengthy getter definition
public ProtocolState State { get; private set; }
private Socket link;
private NodeInfo personalInfo;
private NodeInfo? partnerInfo;
private RSAKeypair personalKeypair;
private RSAKeypair partnerKeypair;
private AESKey sharedPrivateKey;
private Queue<NetworkMessage> sentMessages = new();
public Queue<NetworkMessage> ReceivedMessages = new();
public event EventHandler? MessageReceived;
private byte[] lengthBuffer = new byte[sizeof(int)];
private byte[]? dataBuffer = null;
private int bytesReceived = 0;
public bool AnyReceivedMessages => ReceivedMessages.Count > 0;
private bool anySpooledMessages => sentMessages.Count != 0;
private int spooledMessages => sentMessages.Count;
If you came from the C++ world then you want to organize your members in the way that public ones come first then the rest of them
by not interleaving implementation details with publicly available members
Constructor | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
by not interleaving implementation details with publicly available members
Constructor
You can take advantage of ValueTuples (and deconstruction) to assign multiple parameters to class members
Instead of repeating the same action (Task.Run(...)) over and over again you can create a collection of async methods and repeat the same action against them
Task.Run returns a Task which is not captured by you
To make your intent more clear please prefer discard operator (_ = Task.Run(...))
Instead of repeating everywhere this piece of code Console.WriteLine(this.GetHashCode() + " ...."); please create a helper method
public TightbeamProtocol(Socket socket, NodeInfo info, RSAKeypair keypair)
{
State = ProtocolState.StartingUp;
(link, personalInfo, personalKeypair) = (socket, info, keypair);
foreach (var action in new Func<Task>[] { () => ContinuousSend(), () => ContinuousReceive(), () => PerformHandshake() })
_ = Task.Run(action);
LogDebugInfo("Construction complete");
}
private void LogDebugInfo(string message) => Console.WriteLine($"{GetHashCode()} {message}");
AwaitMessageOfType
This piece of code looks really weird to me: await AwaitMessageOfType
To avoid stuttering code please rename your method like GetMessageOfTypeByWaitingUntilItArrives
The while(true) statements are considered most of the time as code smell
You can easily refactor your code to express your intent in a much cleaner way
Your version: Perform indefinitely the retrieve for a given message. If it is present then break the loop otherwise wait 100 milliseconds
My version: Wait 100 milliseconds periodically until you receive a given message | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
private async Task<NetworkMessage> GetMessageOfTypeByWaitingUntilItArrives(Type type)
{
NetworkMessage message = null;
while (message = (from msg in ReceivedMessages
where msg.ContentType == type
select msg).FirstOrDefault() == null)
{
await Task.Delay(100);
}
return message;
}
UPDATE #1 Continuation
StartShutdown
In the comment of this method you are stating that this is a graceful shutdown
Most of the time this means you are waiting X seconds to finish as many outstanding operations as possible
and when X has been passed then abort all the pending actions
So there is a time constraint (or in other words there is a guarantee) that the system will terminate after X seconds and will not hang there forever
I assume because of this method might be time consuming that's why you have created two different enum values to describe the current state
So far (in this and in the previous methods), you have used the State as a Progress tracking mechanism
You have used it to inform the consumer of your class about the current situation
The thing is most of the time consumers are interested about the state changes
They want to know when the given object has transitioned from X to Y
You might consider to have an event for this transitions as well
while (anySpooledMessages) { await Task.Delay(50); }: This code basically the Donkey in Shrek: "Are we there yet?"
Here you have a synchronisation or rendezvous point: One thread waits for the other thread to advance
There are lots of built-in signalling primitives which can be used to signal from a thread to another that a certain point has been reached
In this particular case an AutoResetEvent could call Set inside the ContinuousSend method whenever the queue is empty and here you could call the Wait method
The Wait call is blocking if you want to have a non-blocking version then please visit this SO topic
EnqueueMessage | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
EnqueueMessage
Even though enums are numeric values under the hood I've never used less than or greater than operators on them
The really simple reason is that it is fragile
Now your enum has the default values and no comments indicate that the ordering is important
So, if some future maintainer changes the ordering then your system will break
If some future maintainer assigns values to each state it might break the system depending on the values
So ,an alternative solution is to use black or whitelisting
Check whether or not the current state is listed inside the refusal collection, if so then return early
Check whether or not the current state is listed inside the approval collection, if so then carry on
Depending on the level of paranoia, the length of each list, future requirements, etc. you should decide which approach you would use
Your switch statement can be really easily converted into a switch expression, which is more concise (even the IDE has built-in refactoring mechanism for this)
byte[] serializedContent = encryption switch
{
Encryption.AES => Serializer.SerializeContent(content, sharedPrivateKey),
Encryption.RSA => Serializer.SerializeContent(content, partnerKeypair),
_ => Serializer.SerializeContent(content),
};
Let me correct here my suggestion regarding outgoingQueue
I've suggested to call it sentMessages which I can see now is misleading
A more accurate name would be toBeSentMessages
UPDATE #2 Continuation
ContinuousSend
Let's start with the naming. Most of the time in case of C# methods are starting with a verb (like Start, Get, Move, etc.).
If you want to follow this guideline then I would suggest SendContinuously or SendUntilInert or TryContinuouslySending, etc.
State < ProtocolState.Inert: I've already shared my opinion about enum values and less than or greater than operators | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
By the way this is yet again a rendezvous point: Do something until another thread signals otherwise
Here you could use a ManualResetEventSlim, which does not automatically goes back to "normal" state after the signal has reached the interested party (the Wait-er)
The MRES does define a property called IsSet, which can be checked whether or not it's time to change the behaviour
It works in the same way as CancellationToken's IsCancellationRequested or CountdownEvent's IsSet
Here you can learn more about signalling (it is old (so bit outdated) but gold)
If you choose to use CancellationToken then you might need to consider to pass that token to the link.SendAsync method to perform collaborative cancellation
I have two recommendations regarding your error handling
You don't need to explicitly call ToString on the exception, Console.WriteLine will happily do this on your behalf
It might make sense for debugging purposes to log some information about the message itself, not just the exception
ContinuousReceive
In case of Send the exit condition is Inert, while here it is the Shutdown state
I don't know your requirements but for my intuition it does not make too much sense to receive more messages while I try to shutdown the communication
So, I do believe here you could use the same signalling object as you do in case of sending
Some people (even methodologies like object calisthenics) suggest to try to stick to one level of indentation in your methods
In this method your main functionality is at the 3rd level
One common way to reduce indentation is the usage of early exit instead of guard expression
Another way is to separate responsibilities into their own method
Step 1: Use guard expression
if (link.Available <= 0) { await Task.Delay(100); continue; }
byte[] data = new byte[link.Available];
try
{
await link.ReceiveAsync(data, SocketFlags.None);
SortData(data);
}
catch (Exception ex)
{
Console.WriteLine(ex);
} | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
Step 2: separate responsibilities
private async Task ReceiveContinuously()
{
await PerformActionUntilResetEventIsSet(Receive, inertStateSignal);
}
private async Task PerformActionUntilResetEventIsSet(Func<Task> action, ManualResetEventSlim resetEvent)
{
while (!resetEvent.IsSet) await action();
}
private async Task Receive()
{
if (link.Available <= 0)
{
await Task.Delay(100);
return;
}
byte[] data = new byte[link.Available];
try
{
await link.ReceiveAsync(data, SocketFlags.None);
SortData(data);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
UPDATE #3 Continuation
I forgot to mention in the Receive method that it might make sense to use ArrayPool to avoid allocating bytes arrays frequently.
SortData
The i variable name is so meaningless that it ruins the understanding of your intent
Please try to use better names like alreadyTransferredBytes or Processed, Consumed, Parsed, whatever ...
Inside your while loop the branches execute almost the same code
I would suggest to try to minimize your branching by putting there only those calculations that are different
Step 1: Extract the common part
int requestedBytes;
Array destination;
if (dataBuffer is not null)
{
requestedBytes = dataBuffer.Length - bytesReceived;
destination = dataBuffer;
}
else
{
requestedBytes = lengthBuffer.Length - bytesReceived;
destination = lengthBuffer;
}
//The common part
int availableBytes = data.Length - alreadyTransferredBytes;
int transferredBytes = Math.Min(requestedBytes, availableBytes);
Array.Copy(data, alreadyTransferredBytes, destination, bytesReceived, transferredBytes);
alreadyTransferredBytes += transferredBytes;
ParseData(transferredBytes);
Step 2: Simplify the branching
Array destination = dataBuffer ?? lengthBuffer; | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
Step 2: Simplify the branching
Array destination = dataBuffer ?? lengthBuffer;
int requestedBytes = destination.Length - bytesReceived;
int availableBytes = data.Length - alreadyTransferredBytes;
int transferredBytes = Math.Min(requestedBytes, availableBytes);
Array.Copy(data, alreadyTransferredBytes, destination, bytesReceived, transferredBytes);
alreadyTransferredBytes += transferredBytes;
ParseData(transferredBytes);
ParseData
Inside the dataBuffer is null branch none of the else are really needed
Since return and throw break the normal flow that's why you can use them for early exits
The resulting code will be more streamlined and easier to understand IMHO
if (bytesReceived != sizeof(int))
return;
int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
if (dataLength < 0 || dataLength > int.MaxValue)
throw new InvalidOperationException("Message length is out of bounds!");
dataBuffer = new byte[dataLength];
bytesReceived = 0;
Further simplifying the logic, you can end up a code like this
bytesReceived += count;
if (dataBuffer is null)
{
if (bytesReceived != sizeof(int))
return; //early exit
int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
if (dataLength < 0 || dataLength > int.MaxValue)
throw new InvalidOperationException("Message length ..."); //early exit
dataBuffer = new byte[dataLength];
bytesReceived = 0;
return; //early exit
}
if (bytesReceived != dataBuffer.Length)
return; //early exit
NetworkMessage message = Serializer.DeserializeMessage(dataBuffer)
?? throw new InvalidDataException("Received corrupt ..."); //early exit
if (message.Encryption == Encryption.AES)
message.DecryptData(sharedPrivateKey);
ReceivedMessages.Enqueue(message);
LogDebugInfo($"Received message of type: {ReceivedMessages.Peek().ContentType}");
OnMessageReceived();
dataBuffer = null;
bytesReceived = 0;
One can argue against many early exits compared to the single return principle/law | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c#, asynchronous, networking
One can argue against many early exits compared to the single return principle/law
If you want to follow that law then try to use smaller functions | {
"domain": "codereview.stackexchange",
"id": 42746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asynchronous, networking",
"url": null
} |
c++, object-oriented
Title: Model for a multi-channel programmable electrical power supply
Question: I am modeling a programmable electrical power supply which has multiple independent channels (or "ports") in a class I'm calling Supply. One of its features is the ability to put pairs of ports in parallel in order to increase the power that can be supplied to a load. Conceptually, it looks similar to this:
(Of course the real power supply is more complicated than a switch since you can't just short the outputs of two voltage sources.)
The number of ports \$N\$ in the power supply varies from instance to instance, but is always a constant for a given power supply instance and is always an even number. Two ports can be put in parallel with each other but not three or more. Consequently, the number of outputs (where "output" is defined as either a single port or a combined pair of ports) can vary from \$N/2\$ (when all ports are combined with another one) to \$N\$ (when no ports are in parallel with one another).
Since the number of outputs may vary over the lifetime of the power supply instance, there needs to be an easy way for the code that controls the power supply to iterate through all of the power supply's outputs as well as access the \$n\$th port or output (e.g. to set the desired output voltage). I've designed the Supply class to provide an iterator and an accessor to an object (called Output) which tracks the port number(s) assigned to a given output.
I'd like a review for the interface which allows iterating through the outputs and accessing a particular one. Note that the actual Supply class is more complicated because it is highly programmable, so I've only included the relevant code for review below.
Supply.h:
#include <utility>
#include <vector>
/** \brief Multi-port power supply. | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
/** \brief Multi-port power supply.
Two adjacent ports of the power supply can be combined in parallel to increase the output power capability.
*/
class Supply {
public:
/** \brief Type definition for a number assigned to a Supply port. */
typedef unsigned int port_number;
/** \brief Type definition for a number assigned to a Supply output. */
typedef port_number output_number;
/** \brief Power supply output which can be connected to a load.
An output can be a single (one port) or combined (two ports in parallel) connection.
*/
class Output {
friend class Supply;
public:
/**\brief Enumeration of the port wiring options. */
enum output_type {
single = 1, /**< Output consists of only one port. */
combined = 2 /**< Output consists of two ports in paralle. */
};
/**\brief Special port number used to indicate that the secondary port is not in use (i.e. the
Output is of type Supply::Output::single and only uses the primary). */
const static port_number no_port = 0;
private:
std::pair<port_number, port_number> ports; /**< \brief The port number(s) assigned to an Output. */
output_type m_type; /**< \brief Indicates whether the Output is configured as single or combined. */
/**\brief Assigns a port to the primary slot of the Output
\param[in] p the port to assign to the primary slot
\throw std::logic_error if an attempt is made to assign Supply::Output::no_port to the primary
pairs of the Output
\throw std::logic_error if the argument port is already assigned to the Output's secondary slot
*/
void primary(port_number p); | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
/**\brief Assigns or removes a port to the secondary slot of the Output
\param[in] p the port to assign to the primary slot. If set to Supply::Output::no_port the secondary
slot will be unassigned (i.e. the Output is of type Supply::Output::single).
\throw std::logic_error if the argument port is already assigned to the Output's primary slot
*/
void secondary(port_number p);
/**\brief Constructs a combined Output
\param[in] port1 the primary port
\param[in] port2 the secondary port
*/
Output(port_number port1, port_number port2);
/**\brief Constructs a single Output
\param[in] p the primary port
*/
Output(port_number p);
public:
/**\brief Returns Supply::Output::single if the Output's secondary slot is unassigned (i.e. set to
Supply::Output::no_port), Supply::Output::combined otherwise.
*/
output_type type() const;
/**\brief Returns the primary port */
port_number primary() const;
/**\brief Returns the secondary port, if it is assigned
\throw std::out_of_range if the secondary port is not assigned
*/
port_number secondary() const;
bool contains(port_number p) const;
};
private:
/**\brief The total number of ports contained in the Supply. */
port_number num_ports;
/**\brief Type definition for the container of Outputs. */
typedef std::vector<Output> output_list;
output_list m_outputs; /**<\brief List of configured Outputs. */
public:
/**\brief Type definition for an iterator allowing client code to access the Supply's Outputs. */
typedef output_list::iterator output_iterator;
/**\brief Constructs a Supply with `num_ports` ports. All ports are initialized as single Outputs. */
Supply(port_number num_ports) : num_ports(num_ports) {
m_outputs.reserve(num_ports); | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
for (Supply::port_number p = 1; p <= num_ports; ++p) {
m_outputs.push_back(Supply::Output(p));
}
}
/**\brief Returns an iterator to the first Output.
Outputs are sorted so that the first one has the lowest port number assigned (either as primary
or secondary).
*/
output_iterator first_output() {
return m_outputs.begin();
}
/**\brief Returns an iterator to the end of the Output list.
Outputs are sorted so that the first one has the lowest port number assigned (either as primary
or secondary).
*/
output_iterator last_output() {
return m_outputs.end();
}
/**\brief Returns a reference to the Output at specified location `n`, with bounds checking.
\throw std::out_of_range if `pos` is not within the range of Outputs contained by the Supply.
*/
const Output& output(output_number n) const {
// n starts with 1, outputs are indexed starting with 0
return m_outputs.at(n - 1);
}
/**\brief Returns a reference to the Output at specified location `n`. No bounds checking is
performed.
*/
const Output& operator[](output_number n) const {
// n starts with 1, outputs are indexed starting with 0
return m_outputs[n - 1];
}
/**\brief Returns the number of ports supported by the Supply.
This number never changes during the lifetime of a Supply. */
port_number ports() const { return num_ports; }
/**\brief Returns the number of Outputs configured for the Supply.
Depending on the configuration of the Outputs, there may be as many as one Output per Supply port
(all Outputs are of type Supply::Output::single) or as few as half the number of Outputs as
number of ports in the Supply (all Outputs are of type Supply::Output::combined).
*/
output_number outputs() const { return static_cast<output_number>(m_outputs.size()); } | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
// NOTE: would actually be private, and called when a triggering event causes the Supply to call this function
/**\brief Creates a combined Output using the given two ports.
Both `port1` and `port2` must be in the Supply as an Output of type Supply::Output::single, and `port1` cannot
be the same port as `port2`.
\throw std::logic_error if `port1 == port2`.
\throw std::logic_error if `port1` does not exist in the Supply as an Output of type Supply::Output::single
\throw std::logic_error if `port2` does not exist in the Supply as an Output of type Supply::Output::single
*/
void combine_ports(port_number port1, port_number port2);
// NOTE: would actually be private, and called when a triggering event causes the Supply to call this function
/**\brief Splits a combined Output composed of the given two ports into two single Outputs.
Both `port1` and `port2` must be in an Output of type Supply::Output::combined (though either can
be the primary), and `port1` cannot be the same port as `port2`.
\throw std::logic_error if `port1 == port2`.
\throw std::logic_error if the Supply does not have an Output of type Supply::Output::combined which is
composed of the two given ports.
*/
void split_ports(port_number port1, port_number port2);
};
/**\brief Returns `true` if the argument Supply::Outputs are considered equal, `false` otherwise.
Two Supply::Outputs are considered equal if:
* both are Supply::Output::single and the same port is assigned to both primaries.
* both are Supply::Output::combined and the same port is assigned to both primaries and the same port
is assigned to both secondaries.
*/
inline bool operator==(const Supply::Output& lhs, const Supply::Output& rhs) {
if (lhs.primary() != rhs.primary()) return false;
Supply::Output::output_type pairs = lhs.type(); | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
Supply::Output::output_type pairs = lhs.type();
if (pairs == Supply::Output::single) {
// lhs is single so lhs == rhs if rhs is also single
return rhs.type() == Supply::Output::single;
} else {
// lhs is combined so lhs == rhs if rhs is combined and lhs.secondary() == rhs.secondary()
if (rhs.type() != Supply::Output::combined) return false;
else {
// both are combined, make sure the secondaries match
return lhs.secondary() == rhs.secondary();
}
}
}
/**\brief Returns `true` if the argument Supply::Outputs are considered unequal, `false` otherwise.
See operator==() for rules regarding the equality of Supply::Outputs.
*/
inline bool operator!=(const Supply::Output& lhs, const Supply::Output& rhs) {
return !(lhs == rhs);
}
/**\brief Returns `true` if the argument Supply::Outputs are considered equivalent, `false` otherwise.
Not as strict as operator==(). Two Supply::Outputs are equivalent if
* both are Supply::Output::single and the same port is assigned to both primaries.
* both are Supply::Output::combined and the same two port numbers are assigned. The difference from
operator==() is that the ports can be assigned to opposite pairs.
*/
inline bool equivalent(const Supply::Output& lhs, const Supply::Output& rhs) {
if (lhs.type() != rhs.type()) return false;
if (lhs.type() == Supply::Output::single) {
return lhs.primary() == rhs.primary();
} else {
// both lhs and rhs must be combined so check that the same two port numbers are used
return (lhs.primary() == rhs.primary() || lhs.primary() == rhs.secondary()) &&
(lhs.secondary() == rhs.primary() || lhs.secondary() == rhs.secondary());
}
}
/**\brief Returns `true` if the Supply::Output on the left-hand side is compares less than the one
on the right-hand side. | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
One Supply::Output is considered less than another if it has a port number assigned to it that is less
than the port(s) assigned to the other.
*/
inline bool operator<(const Supply::Output& lhs, const Supply::Output& rhs) {
Supply::port_number lhs_min = lhs.primary();
Supply::port_number rhs_min = rhs.primary();
if (lhs.type() == Supply::Output::combined) lhs_min = std::min(lhs_min, lhs.secondary());
if (rhs.type() == Supply::Output::combined) rhs_min = std::min(rhs_min, rhs.secondary());
return lhs_min < rhs_min;
}
Supply.cpp:
#include <algorithm>
#include <exception>
#include "Supply.h"
Supply::Output::Output(Supply::port_number port1, Supply::port_number port2) {
ports.first = port1;
ports.second = port2;
m_type = combined;
}
Supply::Output::Output(port_number p) {
ports.first = p;
ports.second = no_port;
m_type = single;
}
Supply::port_number Supply::Output::primary() const {
return ports.first;
}
Supply::port_number Supply::Output::secondary() const {
// If single, just return no_port without throwing an exception?
if (m_type == single) throw std::out_of_range("Can't access secondary port in a two-pair Supply::Output");
else return ports.second;
}
void Supply::Output::primary(Supply::port_number p) {
if (p == no_port) throw std::logic_error("Supply::Output must have a port assigned to its primary");
if (m_type == combined && p == ports.second) {
throw std::logic_error("Supply::Output cannot use the same port for both the primary and secondary");
}
ports.first = p;
}
void Supply::Output::secondary(Supply::port_number p) {
if (p == ports.first) {
throw std::logic_error("Supply::Output cannot use the same port for both the primary and secondary");
}
ports.second = p;
if (p == no_port) m_type = single;
else m_type = combined;
}
Supply::Output::output_type Supply::Output::type() const { return m_type; } | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
Supply::Output::output_type Supply::Output::type() const { return m_type; }
bool Supply::Output::contains(Supply::port_number p) const {
if (primary() == p) return true;
if (m_type == combined) return (secondary() == p);
else return false;
}
void Supply::combine_ports(Supply::port_number port1, Supply::port_number port2) {
if (port1 == port2) throw std::logic_error("port1 cannot equal port2");
output_list::iterator iter1 = m_outputs.end();
output_list::iterator iter2 = m_outputs.end();
for (output_list::iterator iter = m_outputs.begin(); iter != m_outputs.end(); ++iter) {
Supply::Output& o = *iter;
if (o.type() == Supply::Output::single && o.primary() == port1) iter1 = iter;
if (o.type() == Supply::Output::single && o.primary() == port2) iter2 = iter;
}
if (iter1 == m_outputs.end()) throw std::logic_error("Could not find port1");
if (iter2 == m_outputs.end()) throw std::logic_error("Could not find port2");
if (port1 < port2) {
Supply::Output& o = *iter1;
o.secondary(port2); // add port2 to the Output that port1 is already part of
m_outputs.erase(iter2); // remove the Output that port2 was part of
} else {
Supply::Output& o = *iter2;
o.secondary(port1); // add port1 to the Output that port2 is already part of
m_outputs.erase(iter1); // remove the Output that port1 was part of
}
std::sort(m_outputs.begin(), m_outputs.end());
}
void Supply::split_ports(Supply::port_number port1, Supply::port_number port2) {
if (port1 == port2) throw std::logic_error("port1 cannot equal port2");
Supply::Output otest(port1, port2); // construct a combined Output to test against for equality
bool found = false; // set to true if/when the combined Output with the two argument ports is found
for (output_list::iterator iter = m_outputs.begin(); iter != m_outputs.end(); ++iter) {
Supply::Output& o = *iter; | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
if (o.type() == Supply::Output::combined && equivalent(o, otest)) {
found = true;
m_outputs.erase(iter);
break;
}
}
if (!found) {
throw std::logic_error("Could not find a combined Output with port1 and port2");
}
m_outputs.push_back(Supply::Output(port1));
m_outputs.push_back(Supply::Output(port2));
std::sort(m_outputs.begin(), m_outputs.end());
}
Some important notes:
Supply::split_ports() and Supply::combine_ports() would be private in the real class since the code that controls the Supply does not directly control this feature (it communicates with the power supply using I2C, and the appropriate I2C command controls this feature); I've made these functions public for demonstration purposes only.
Port numbers and output numbers start with 1, not 0 as is usual in C++ for accessing the first element in a std::vector.
I've included the < comparison operator for sorting Outputs, but for brevity I haven't included >, etc.
My compiler at work is the aging VS2005 compiler so I can't use C++11 or beyond. Feel free to make suggestions that would apply for a more modern compiler, just note that I won't be able to use them at this time.
I've made Output a nested class since an Output only makes sense in the context of a Supply. Also, Supply is a friend of Output so that Supply can create and modify Output objects. The only public functions of Output are const getter functions so Output is immutable to all code except Supply.
Here's a usage example:
#include <iostream>
#include <fstream>
#include "Supply.h" | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
#include "Supply.h"
void iterate_outputs(std::ostream& os, Supply supply) {
for (Supply::output_iterator iter = supply.first_output(); iter!= supply.last_output(); ++iter) {
if (iter->type() == Supply::Output::single) {
os << "single output: {" << iter->primary() << "}\n";
} else {
os << "combined output: {" << iter->primary() << ", " << iter->secondary() << "}\n";
}
}
os << "There are " << supply.ports() << " ports and " << supply.outputs() << " outputs.\n\n";
}
int main() {
std::fstream fs("output.txt");
std::ostream& os = fs; // or std::cout
os << std::boolalpha;
Supply supply(8);
os << "Number of ports = " << supply.ports() << '\n';
os << "Iterating through ports:\n";
for (Supply::port_number p = 1; p <= supply.ports(); ++p) {
os << "this is port " << p << '\n';
}
os << '\n';
os << "Iterating through single outputs:\n";
iterate_outputs(os, supply);
supply.combine_ports(5, 6);
supply.combine_ports(1, 2);
supply.combine_ports(3, 4);
supply.combine_ports(7, 8);
os << "Iterating through combined outputs:\n";
iterate_outputs(os, supply);
supply.split_ports(6, 5);
supply.split_ports(1, 2);
os << "Iterating through mixed single/combined outputs:\n";
iterate_outputs(os, supply);
os << "Third output is ";
const Supply::Output& o3 = supply[3];
if (o3.type() == Supply::Output::single) {
os << "single output: {" << o3.primary() << "}\n";
} else {
os << "combined output: {" << o3.primary() << ", " << o3.secondary() << "}\n";
}
const Supply::Output& o4 = supply.output(4);
if (o4.type() == Supply::Output::single) {
os << "single output: {" << o4.primary() << "}\n";
} else {
os << "combined output: {" << o4.primary() << ", " << o4.secondary() << "}\n";
} | {
"domain": "codereview.stackexchange",
"id": 42747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.