_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d16301 | val | Unfortunatly this is a known issue in WPF, the xaml is not taken into account when you refactor the entities behind the bindings. I have been making use of third party refactoring tools such as resharper or coderush to solve the problem, they tend to handle it better than the built in refactor function in visual studio.
A: If you really don't want to change the view (for whatever reasons) you could leave the NumberOfPets property in the original ViewModel and set its getter to the PetCount property of the refactored ViewModel, there fore this won't break the View. | unknown | |
d16302 | val | genome_calls - all genomic calls - not only variants. might have calls with low quality
multisample_variants - variants by samples - where each variant will have all the samples that harbor this mutation in one variant row
single_sample_genome_calls - variants by samples matrix. Variants that exists in multiple samples will have a row per sample | unknown | |
d16303 | val | UPDATE: With Robot Framework this has changed and became easier to do.
Release note: Running and result models have been changed.
*
*TestSuite, TestCase and Keyword objects used to have keywords attribute containing keywords used in them. This name is misleading
now when they also have FOR and IF objects. With TestCase and
Keyword the attribute was renamed to body and with TestSuite it
was removed altogether. The keywords attribute still exists but it is
read-only and deprecated.
*The new body does not have create() method for creating keywords, like the old keywords had, but instead it has separate
create_keyword(), create_for() and create_if() methods. This
means that old usages like test.keywords.create() need to be changed
to test.body.create_keyword().
For examples check out this other answer: How to write FOR loop and IF statement programmatically with Robot Framework 4.0?.
BEFORE Robot Framework 4.0:
IF statement
The if statement should be a Run Keyword If keyword with the arguments you need. It is a keyword like any other so you should list everything else in its args list.
*
*The condition.
*The keyword name for the True branch.
*Separately any args to the keyword for the True branch if there is any. Listed separately.
*
*The ELSE IF keyword if needed.
*The ELSE IF condition.
*The keyword name for the ELSE IF branch.
*Separately any args to the keyword for the ELSE IF branch if there is any. Listed separately.
*
*The ELSE keyword.
*The keyword name for the ELSE branch.
*Separately any args to the keyword for the ELSE branch if there is any. Listed separately.
from robot.api import TestSuite
suite = TestSuite('Activate Skynet')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Run Keyword If', args=[True, 'Log To Console', 'Condition was TRUE', 'ELSE', 'Log To Console', 'Condition was FALSE'])
test.keywords.create('Run Keyword If', args=[False, 'Log To Console', 'Condition was TRUE', 'ELSE', 'Log To Console', 'Condition was FALSE'])
suite.run()
This is how it looks like in the logs:
FOR loop
As for the for loop. It is a special keyword implemented by robot.running.model.ForLoop class that bases on the robot.running.model.Keyword class. Here is the constructor:
It has a flavor parameter, which is the loop type to be say. So it is IN, IN RANGE, IN ZIP, etc.
Now you instantiating a robot.running.model.Keyword which despite you could set its type to for, it won't have flavor attribute. So when you execute your code it will throw the error you see. It is because the ForRunner will try to access the flavor attribute.
File "/usr/local/lib/python3.7/site-packages/robot/running/steprunner.py", line 52, in run_step
runner = ForRunner(context, self._templated, step.flavor)
AttributeError: 'Keyword' object has no attribute 'flavor'
So you have to use the ForLoop class. Also I am using Robot Framework 3.1.2 so the errors might be different in my case but the approach should be the same.
Here is how it should look like:
from robot.running.model import ForLoop
for_kw = ForLoop(['${i}'], ['10'], flavor='IN RANGE')
test.keywords.append(for_kw)
No this will still fail with error:
FOR loop contains no keywords.
So you have to populate it like:
for_kw.keywords.create('No Operation')
The complete example:
from robot.api import TestSuite
from robot.running.model import ForLoop
suite = TestSuite('Activate Skynet')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Log Many', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Log', args=['SKYNET'])
for_kw = ForLoop(['${i}'], ['10'], flavor='IN RANGE')
for_kw.keywords.create('No Operation')
test.keywords.append(for_kw)
suite.run()
If you run this it will only produce an output XML, you have to run rebot manually to have a log and report HTML file. | unknown | |
d16304 | val | I'm guessing the language detection is run again, and there is no value available for that field for the language detection to actually detect anything for.
Run updates without language detection unless you're including the field you're running language detection on.
You might have to define a second request handler without the language detection settings if you have those defined as static settings in your request handler configuration. | unknown | |
d16305 | val | You should be using HEREDOC for this, but here you go:
str = '\'`~!@#:;|$%^>?,)_+-={][&*(<]./"\''
Just use double quotes and escape the single quotes in the string. Simple.
A: Using heredoc:
bla = <<_
'`~!@#:;|$%^>?,)_+-={][&*(<]./"'
_
bla.chop!
you can observe the inspection and copy it:
"'`~!@#:;|$%^>?,)_+-={][&*(<]./\"'"
Simple as that.
A: You don't need to use a heredoc to do this, and you can do this simply without using any escapes in your preparation.
>> %q '`~!@#:;|$%^>?,)_+-={][&*(<]./"'
=> "'`~!@#:;|$%^>?,)_+-={][&*(<]./\"'"
The key here is that you are not using a space character in this collection of characters, and so we can use a space to delimit it.
You can use %q or %Q to do this.
Don't generally use space for delimiter for this, for obvious reasons, but sometimes it very useful.
A: In that string you have every character that can be used to escape a string. So even %q/%Q won't help you to use this string verbatim.
%q('`~!@#:;|$%^>?,\)_+-={][&*\(<]./"')
# quoted parentheses
So, your only option is heredoc. With every other method, you'll have to backslash-escape some characters. | unknown | |
d16306 | val | The error should be clear - the variable you've called jobs actually contains a Page object from the paginator. Which is as it should be, as you assigned jobs to paginator.page(x). So obviously, it contains a Page.
The documentation shows what to do:
{% for job in jobs.object_list %}
etc. | unknown | |
d16307 | val | I guess one might make use of this thread and create a custom version of in function.
The main idea is to use SFINAE (Substitution Failure Is Not An Error) to differentiate associative containers (which have key_type member) from sequence containers (which have no key_type member).
Here is a possible implementation:
namespace detail
{
template<typename, typename = void>
struct is_associative : std::false_type {};
template<typename T>
struct is_associative<T,
std::enable_if_t<sizeof(typename T::key_type) != 0>> : std::true_type {};
template<typename C, typename T>
auto in(const C& container, const T& value) ->
std::enable_if_t<is_associative<C>::value, bool>
{
using std::cend;
return container.find(value) != cend(container);
}
template<typename C, typename T>
auto in(const C& container, const T& value) ->
std::enable_if_t<!is_associative<C>::value, bool>
{
using std::cbegin;
using std::cend;
return std::find(cbegin(container), cend(container), value) != cend(container);
}
}
template<typename C, typename T>
auto in(const C& container, const T& value)
{
return detail::in(container, value);
}
Small usage example on WANDBOX.
A: This gives you an infix *in* operator:
namespace notstd {
namespace ca_helper {
template<template<class...>class, class, class...>
struct can_apply:std::false_type{};
template<class...>struct voider{using type=void;};
template<class...Ts>using void_t=typename voider<Ts...>::type;
template<template<class...>class Z, class...Ts>
struct can_apply<Z,void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = ca_helper::can_apply<Z,void,Ts...>;
namespace find_helper {
template<class C, class T>
using dot_find_r = decltype(std::declval<C>().find(std::declval<T>()));
template<class C, class T>
using can_dot_find = can_apply< dot_find_r, C, T >;
template<class C, class T>
constexpr std::enable_if_t<can_dot_find<C&, T>{},bool>
find( C&& c, T&& t ) {
using std::end;
return c.find(std::forward<T>(t)) != end(c);
}
template<class C, class T>
constexpr std::enable_if_t<!can_dot_find<C&, T>{},bool>
find( C&& c, T&& t ) {
using std::begin; using std::end;
return std::find(begin(c), end(c), std::forward<T>(t)) != end(c);
}
template<class C, class T>
constexpr bool finder( C&& c, T&& t ) {
return find( std::forward<C>(c), std::forward<T>(t) );
}
}
template<class C, class T>
constexpr bool find( C&& c, T&& t ) {
return find_helper::finder( std::forward<C>(c), std::forward<T>(t) );
}
struct finder_t {
template<class C, class T>
constexpr bool operator()(C&& c, T&& t)const {
return find( std::forward<C>(c), std::forward<T>(t) );
}
constexpr finder_t() {}
};
constexpr finder_t finder{};
namespace named_operator {
template<class D>struct make_operator{make_operator(){}};
template<class T, char, class O> struct half_apply { T&& lhs; };
template<class Lhs, class Op>
half_apply<Lhs, '*', Op> operator*( Lhs&& lhs, make_operator<Op> ) {
return {std::forward<Lhs>(lhs)};
}
template<class Lhs, class Op, class Rhs>
auto operator*( half_apply<Lhs, '*', Op>&& lhs, Rhs&& rhs )
-> decltype( named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ) )
{
return named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
}
}
namespace in_helper {
struct in_t:notstd::named_operator::make_operator<in_t> {};
template<class T, class C>
bool named_invoke( T&& t, in_t, C&& c ) {
return ::notstd::find(std::forward<C>(c), std::forward<T>(t));
}
}
in_helper::in_t in;
}
On a flat container, like a vector array or string, it is O(n).
On an associative sorted container, like a std::map, std::set, it is O(lg(n)).
On an unordered associated container, like std::unordered_set, it is O(1).
Test code:
std::vector<int> v{1,2,3};
if (1 *in* v)
std::cout << "yes\n";
if (7 *in* v)
std::cout << "no\n";
std::map<std::string, std::string, std::less<>> m{
{"hello", "world"}
};
if ("hello" *in* m)
std::cout << "hello world\n";
Live example.
C++14, but mainly for enable_if_t.
So what is going on here?
Well, can_apply is a bit of code that lets me write can_dot_find, which detects (at compile time) if container.find(x) is a valid expression.
This lets me dispatch the searching code to use member-find if it exists. If it doesn't exist, a linear search using std::find is used instead.
Which is a bit of a lie. If you define a free function find(c, t) in the namespace of your container, it will use that rather than either of the above. But that is me being fancy (and it lets you extend 3rd party containers with *in* support).
That ADL (argument dependent lookup) extensibity (the 3rd party extension ability) is why we have three different functions named find, two in a helper namespace and one in notstd. You are intended to call notstd::find.
Next, we want a python-like in, and what is more python like than an infix operator? To do this in C++ you need to wrap your operator name in other operators. I chose *, so we get an infix *in* named operator.
TL;DR
You do using notstd::in; to import the named operator in.
After that, t *in* c first checks if find(t,c) is valid. If not, it checks if c.find(t) is valid. If that fails, it does a linear search of c using std::begin std::end and std::find.
This gives you very good performance on a wide variety of std containers.
The only thing it doesn't support is
if (7 *in* {1,2,3})
as operators (other than =) cannot deduce initializer lists I believe. You could get
if (7 *in* il(1,2,3))
to work.
A: The time complexity of Python's in operator varies depending on the data structure it is actually called with. When you use it with a list, complexity is linear (as one would expect from an unsorted array without an index). When you use it to look up set membership or presence of a dictionary key complexity is constant on average (as one would expect from a hash table based implementation):
*
*https://wiki.python.org/moin/TimeComplexity
In C++ you can use std::find to determine whether or not an item is contained in a std::vector. Complexity is said to be linear (as one would expect from an unsorted array without an index). If you make sure the vector is sorted, you can also use std::binary_search to achieve the same in logarithmic time.
*
*http://en.cppreference.com/w/cpp/algorithm/find
*Check if element is in the list (contains)
*Check if element found in array c++
*http://en.cppreference.com/w/cpp/algorithm/binary_search
The associative containers provided by the standard library (std::set, std::unordered_set, std::map, ...) provide the member functions find() and count() and contains() (C++20) for this. These will perform better than linear search, i.e., logarithmic or constant time depending on whether you have picked the ordered or the unordered alternative. Which one of these functions to prefer largely depends on what you want to achieve with that info afterwards, but also a bit on personal preference. (Lookup the documentation for details and examples.)
*
*How to check that an element is in a std::set?
*How to check if std::map contains a key without doing insert?
*https://en.wikipedia.org/wiki/Associative_containers
*http://en.cppreference.com/w/cpp/container
If you want to, you can use some template magic to write a wrapper function that picks the correct method for the container at hand, e.g., as presented in this answer.
A: You can use std::find from <algorithm>, but this works only for datatypes like: std::map and std::vector (etc).
Also note that this will return, iterator to the first element that is found equal to the value you pass, unlike the in operator in Python that returns a bool.
A: You can approach this in two ways:
You can use std::find from <algorithm>:
auto it = std::find(container.begin(), container.end(), value);
if (it != container.end())
return it;
or you can iterate through every element in your containers with for ranged loops:
for(const auto& it : container)
{
if(it == value)
return it;
}
A: Python does different things for in depending on what kind of container it is. In C++, you'd want the same mechanism. Rule of thumb for the standard containers is that if they provide a find(), it's going to be a better algorithm than std::find() (e.g. find() for std::unordered_map is O(1), but std::find() is always O(N)).
So we can write something to do that check ourselves. The most concise would be to take advantage of C++17's if constexpr and use something like Yakk's can_apply:
template <class C, class K>
using find_t = decltype(std::declval<C const&>().find(std::declval<K const&>()));
template <class Container, class Key>
bool in(Container const& c, Key const& key) {
if constexpr (can_apply<find_t, Container, Key>{}) {
// the specialized case
return c.find(key) != c.end();
} else {
// the general case
using std::begin; using std::end;
return std::find(begin(c), end(c), key) != end(c);
}
}
In C++11, we can take advantage of expression SFINAE:
namespace details {
// the specialized case
template <class C, class K>
auto in_impl(C const& c, K const& key, int )
-> decltype(c.find(key), true) {
return c.find(key) != c.end();
}
// the general case
template <class C, class K>
bool in_impl(C const& c, K const& key, ...) {
using std::begin; using std::end;
return std::find(begin(c), end(c), key) != end(c);
}
}
template <class Container, class Key>
bool in(Container const& c, Key const& key) {
return details::in_impl(c, key, 0);
}
Note that in both cases we have the using std::begin; using std::end; two-step in order to handle all the standard containers, raw arrays, and any use-provided/adapted containers.
A: I think one of the nice features of the "in" operator in python is that it can be used with different data types (strings v/s strings, numbers v/s lists, etc).
I am developing a library for using python constructions in C++. It includes "in" and "not_in" operators.
It is based on the same technique used to implement the in operator posted in a previous answer, in which make_operator<in_t> is implemented. However, it is extended for handling more cases:
*
*Searching a string inside a string
*Searching an element inside vector and maps
It works by defining several overloads for a function: bool in__(T1 &v1, T2 &v2), in which T1 and T2 consider different possible types of objects. Also, overloads for a function: bool not_in__(T1 &v1, T2 &v2) are defined. Then, the operators "in" and "not_in" call those functions for working.
The implementation is in this repository:
https://github.com/ploncomi/python_like_cpp | unknown | |
d16308 | val | Okay, it turns out this is actually really easy, as long as you have a handle to the device. Just use the GetPointerDeviceRects() function =] | unknown | |
d16309 | val | Don't make a testing set too small. A 20% testing dataset is fine. It would be better, if you splitted you training dataset into training and validation (80%/20% is a fair split). Considering this, you shall change your code in this way:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
x_test, x_val, y_test, y_val = train_test_split(X_train, y_train, test_size=0.25)
This is a common practice to split a dataset like this. | unknown | |
d16310 | val | One can initialize the data for the days using strings, then convert the strings to datetimes. A print can then deliver the objects in the needed format.
I will use an other format (with dots as separators), so that the conversion is clear between the steps.
Sample code first:
import pandas as pd
data = {'day': ['3-20-2019', None, '2-25-2019'] }
df = pd.DataFrame( data )
df['day'] = pd.to_datetime(df['day'])
df['day'] = df['day'].dt.strftime('%d.%m.%Y')
df[ df == 'NaT' ] = ''
Comments on the above.
The first instance of df is in the ipython interpreter:
In [56]: df['day']
Out[56]:
0 3-20-2019
1 None
2 2-25-2019
Name: day, dtype: object
After the conversion to datetime:
In [58]: df['day']
Out[58]:
0 2019-03-20
1 NaT
2 2019-02-25
Name: day, dtype: datetime64[ns]
so that we have
In [59]: df['day'].dt.strftime('%d.%m.%Y')
Out[59]:
0 20.03.2019
1 NaT
2 25.02.2019
Name: day, dtype: object
That NaT makes problems. So we replace all its occurrences with the empty string.
In [73]: df[ df=='NaT' ] = ''
In [74]: df
Out[74]:
day
0 20.03.2019
1
2 25.02.2019
A: Not sure if this is the fastest way to get it done. Anyway,
df = pd.DataFrame({'Date': {0: '3-20-2019', 1:"", 2:"2-25-2019"}}) #your dataframe
df['Date'] = pd.to_datetime(df.Date) #convert to datetime format
df['Date'] = [d.strftime('%d-%m-%Y') if not pd.isnull(d) else '' for d in df['Date']]
Output:
Date
0 20-03-2019
1
2 25-02-2019 | unknown | |
d16311 | val | You can use memmove to copy the remainder of the string to the position of the characters to remove. Use strlen to determine how much bytes to move. Note you cannot use strcpy because the source and destination buffers overlap.
if (zuma[k] == zuma[k + 1] && zuma[k] == zuma[k + 2])
{
int len = strlen(zuma+k+3) + 1; // +1 to copy '\0' too
memmove(zuma+k, zuma+k+3, len);
k = 0;
} | unknown | |
d16312 | val | Please check and make sure that you were able to set up your project with a compatible Google Play services SDK as discussed in Setting Up Google Play Services. If you haven't installed the Google Play services SDK yet, go get it now by following the guide to Adding SDK Packages.
Solutions given in this blog post and GitHub post might also give you possible workaround and might help. | unknown | |
d16313 | val | Fixed. Four (4) things have to be done:
1) Data is a concern, hence clean data a bit more
2) Put more noice into the model
3) Batchnorm after activation at almost last layer
4) Switch to DenseNet201 which learns much deeper
x = base_model.output
x = GlobalMaxPooling2D(name='feature_extract')(x)
# Add Gaussian noices
x = GaussianNoise(0.5)(x)
# Add batchnorm AFTER activation
x = Activation('relu')(x)
x = BatchNormalization()(x)
x = Dense(512, activation='linear')(x)
# Add batchnorm AFTER activation w/o DropOut
x = Activation('relu')(x)
x = BatchNormalization()(x)
x = Dense(len(classIDs), activation="softmax", name='all_classes_hatto')(x)
classifier = Model(inputs=base_model.input, outputs=[x])
This works and I finally got an oustanding model now (the blue line).
Steve | unknown | |
d16314 | val | @ECHO Off
SETLOCAL
set /p nickname=Enter your nickname:
echo.
echo +------------------+
SET "nick=%nickname%"
:loop1
IF DEFINED nick IF "%nick:~17,1%" neq "" GOTO shownick
SET "nick=%nick% "
IF "%nick:~17,1%" neq "" GOTO shownick
SET "nick= %nick%"
GOTO loop1
:shownick
echo ^|%nick%^|
echo +------------------+
GOTO :EOF
Copy the name to another variable (nick)
If nick is not empty, then if its 18th character exists, go to shownick
otherwise, append a space to the end of nick
test again for 18th character, if not exist, prepend a space to nick and continue until character 18 exists.
Note that the syntax %nick:~17,1% means the1` character starting at "character 18" where the string starts at "character 0"
A: A slightly different variant of what Magoo came up with:
@echo off
color 0a
setlocal Enabledelayedexpansion
mode 80,30
set /p "nickname=Enter your nickname: "
ECHO %nickname%>x&FOR %%? IN (x) DO SET /A strlength=%%~z? - 2&del x
set "spaces="
for /l %%a in (%strlength%, 1, 13) do set "spaces=!spaces! "
pause
cls
echo.
echo +------------------+
echo ^| %nickname%%spaces%^|
echo +------------------+
pause
A: Append a bunch of spaces and then strip out as many characters as you want for your fixed field width. I just left the exclamation mark there as a visual indicator for your debugging:
set "n=%n% !"
set n=%n:~0,10%
Here's an example usage incorporated into your script. I'm storing in a separate variable since the original value is being modified and you might need it later and also because if the name entered is longer than ten characters then it's going to be truncated. The naming scheme is sort of inspired by COBOL although it might prove to become tedious to incorporate the length into the variables name.
@echo off
set /p nickname=Enter your nickname:
set "zz10=%nickname% "
set zz10=%zz10:~0,10%
echo +------------------+
echo + %zz10% +
echo +------------------+
Since the word "nickname" plus two percent characters is ten characters wide I'm guessing that might be why you specified a maximum width of ten. While that does make it a little easier to lay out the banner obviously there's no requirement for that. | unknown | |
d16315 | val | You need to keep the subscriptions active between routes. You can do this using this package (written by the same author as FlowRouter so it all works nicely together):
https://github.com/kadirahq/subs-manager
Alternatively, create a Meteor method to return the data and save it in your Session. In this case it won't be reactive, so it depends on your needs.
A: Any subscription you make that's external to the routing will be in global scope, which will then mean that data from that subscription is available everywhere. All you need to do is set up the subscription say in the root layout file for your site and then that data will be kept in your local minimongo store at all times.
The Todo list collection in the Todo app example here is an example of this, this is the code from that example:
Tasks = new Mongo.Collection("tasks");
if (Meteor.isServer) {
// This code only runs on the server
Meteor.publish("tasks", function () {
return Tasks.find();
});
}
if (Meteor.isClient) {
// This code only runs on the client
Meteor.subscribe("tasks");
You can then query that local data as you would normally. | unknown | |
d16316 | val | The reason you are getting the error is because the function bubble requires an int[] as a parameter.
Currently you have bubble() which in its current state is "parameterless"
Replace it with bubble(mas);
A: You need to pass the parameter in your call to bubble in main:
bubble(mas);
A: change your code like this :
static int[] bubble(int [] mas)
{
int temp;
for (int i = 0; i < mas.Length; i++)
{
for (int j = 0; j < mas.Length - 1; j++)
if (mas[j] > mas[j + 1])
{
temp = mas[j + 1];
mas[j + 1] = mas[j];
mas[j] = temp;
}
}
foreach (var element in mas)
{
Console.WriteLine("Sorted elements are: {0}", element);
}
}
static void Main(string[] args)
{
int[] mas = new int[5];
Console.WriteLine("Please enter the elements of the array: ");
for (int i = 0; i < 5; i++)
{
mas[i] = Convert.ToInt32(Console.ReadLine());
}
bubble(mas);
} | unknown | |
d16317 | val | <chrono> would be a better library if you're using C++11.
#include <iostream>
#include <chrono>
#include <thread>
void f()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
f();
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "f() took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
<< " milliseconds\n";
}
Example taken from here.
A: It depends what you want: time measures the real time while clock measures the processing time taken by the current process. If your process sleeps for any appreciable amount of time, or the system is busy with other processes, the two will be very different.
http://en.cppreference.com/w/cpp/chrono/c/clock
A: The time_t structure is probably going to be an integer, which means it will have a resolution of second.
The first piece of code: It will only count the time that the CPU was doing something, so when you do sleep(), it will not count anything. It can be bypassed by counting the time you sleep(), but it will probably start to drift after a while.
The second piece: Only resolution of seconds, not so great if you need sub-second time readings.
For time readings with the best resolution you can get, you should do something like this:
double getUnixTime(void)
{
struct timespec tv;
if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;
return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}
double start_time = getUnixTime();
double stop_time, difference;
doYourStuff();
stop_time = getUnixTime();
difference = stop_time - start_time;
On most systems it's resolution will be down to few microseconds, but it can vary with different CPUs, and probably even major kernel versions.
A: <chrono> is the best. Visual Studio 2013 provides this feature. Personally, I have tried all the methods mentioned above. I strongly recommend you use the <chrono> library. It can track the wall time and at the same time have a good resolution (much less than a second).
A: How about gettimeofday()? When it is called it updates two structs (timeval and timezone), with timing information. Usually, passing a timeval struct is enough and the timezone struct can be set to NULL. The updated timeval struct will have two members tv_sec and tv_usec. tv_sec is the number of seconds since 00:00:00, January 1, 1970 (Unix Epoch) and tv_usec is additional number of microseconds w.r.t. tv_sec. Thus, one can get time expressed in very good resolution.
It can be used as follows:
#include <time.h>
struct timeval start_time;
double mtime, seconds, useconds;
gettimeofday(&start_time, NULL); //timeval is usually enough
int seconds = start_time.tv_sec; //time in seconds
int useconds = start_time.tv_usec; //further time in microseconds
int desired_time = seconds * 1000000 + useconds; //time in microseconds | unknown | |
d16318 | val | if you really want to save all login failed attempts in a text file, then
this
$file = 'failedlogins.txt';
$entry = "Username: ". $name . " - " . $_SERVER['REMOTE_ADDR'] . " - " . date('l jS \of F Y h:i:s A') . "\r\n";
file_put_contents($file, $entry, FILE_APPEND);
or
$f = fopen("failedlogins.txt", "a");
$entry = "Username: ". $name . " - " . $_SERVER['REMOTE_ADDR'] . " - " . date('l jS \of F Y h:i:s A') . "\r\n";
fwrite($f, $entry);
fclose($f);
it will output on the file something like:
Username: Superman - 127.0.0.1 - Thursday 18th of June 2015 11:59:08 AM
Username: Batman - 127.0.0.1 - Thursday 18th of June 2015 11:59:08 AM | unknown | |
d16319 | val | I believe you are mistaken. getBoundingBox() returns the lat/long boundaries of what is visible on the screen. The code will take the pixel x,y value of the two corners and covert that into lat/long and that is what is used. It is not "snapped" to actual map tiles. The result of getBoundingBox() should return the area of the red box. | unknown | |
d16320 | val | .edu{
display: flex;
flex-direction: row;
align-self: flex-start;
}
<body>
<section>
<h2>EDUCATION</h2>
<div class="edu">
<p id='e1'><strong>M.A. in Teaching</strong>, University of North Carolina</p>
<p id='e2'><strong>June 2021 - May 2022</strong></p>
<p id='e3'><strong>B.A., Human Development & Family Studies major & Education minor</strong>, University of North Carolina</p>
</div>
</section>
<hr>
<section>
<h2>EXPERIENCE</h2>
</body>
A: *
*id should be unique so change #e1 from third p element to your choice but diff.
*Used clear:left so that float property on left of hr is cleared
*You can also use cleafix hack to <hr> , by adding clearfix class to <hr> and add this CSS
.clearfix::after {
content: "";
clear: both;
display: table;
}
*
*You can also add vertical rules using border-right as I specified in code
* {
box-sizing: border-box/*So that padding used below don't effect width*/
}
hr {
clear: left
}
#e1 {
float: left;
width: 33%; /*Width so that content is divided in 3colums*/
height: 100px;
/*Height specified so that border become equal for all others and act as a vertical rule*/
border-right: 2px solid red;
padding: 5px;
}
#e2 {
float: right;
width: 33%;
height: 100px;
padding: 5px;
}
#e3 {
float: left;
width: 33%;
height: 100px;
border-right: 2px solid red;
padding: 5px;
}
<section>
<h2>EDUCATION</h2>
<p id='e1'><strong>M.A. in Teaching</strong>, University of North Carolina</p>
<p id='e2'><strong>June 2021 - May 2022</strong></p>
<p id='e3'><strong>B.A., Human Development & Family Studies major & Education minor</strong>, University of North Carolina</p>
</section>
<hr>
<section class="hed2">
<h2>EXPERIENCE</h2> | unknown | |
d16321 | val | Modifying the loop itself may help at some degree. Read this article http://jsperf.com/fastest-array-loops-in-javascript/11
Also this https://blogs.oracle.com/greimer/entry/best_way_to_code_a
In general fastest way for your loop is while loop in reverse, with simplified the test condition:
var i = arr.length; while (i--) {/*....*/}
A: Do you have to render one by one? Why dont you setup first an array like a JSON array and add it to eventSources? The best way for your calendar to render large number of events is to let Fullcalendar do the job for you. You are trying ,in my perspective ofc, do what fullcalendar internally already does. Check the example below and this is if you have to do this client side, i would do this server side.
var jsonarray = [];
for (var eventIndex = 0; eventIndex < resp.select_events.length; eventIndex++){
/* c.fullCalendar('renderEvent',{
id: event.id,
title: eventName,
start: event.event_date,
description: eventDesc,
write: event.write
},true);*/
var event = resp.select_events[eventIndex];
var myevent = {
"id": event.id,
"title": eventName,
"start": event.event_date,
"description": eventDesc,
"write": event.write
};
jsonarray.push(myevent);
}
c.fullCalendar('addEventSource', jsonarray);
Let em know if you have any doubt | unknown | |
d16322 | val | As a jQuery object is, as the name implies, an object, you can access its properties as you would any standard object.
In this case you can use bracket notation to call a function held in one of those properties. For example:
createModal.prototype.open = function () {
var functionVar = this.options.animateType;
$(this.modal)[functionVar]();
} | unknown | |
d16323 | val | Apple removed this sentence from the docs, because it's not true. Team ID and keychain-access-groups are the most important things that should match.
Check the github link below a code example of two apps reading and writing the same keychain item:
https://github.com/evgenyneu/keychain-swift/issues/103#issuecomment-491986324 | unknown | |
d16324 | val | You can't use CHECK here. CHECK is for table and column constraints.
Two further notes:
*
*If this is supposed to be a statement level constraint trigger, I'm guessing you're actually looking for IF ... THEN RAISE EXCEPTION 'message'; END IF;
(If not, you may want to expand and clarify what you're trying to do.)
*The function should return NEW, OLD or NULL. | unknown | |
d16325 | val | Try this one:
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:link outcome="review" value="#{requestClass.requestID}" >
<f:param name="id" value="#{requestClass.requestID}" />
</h:link>
</p:column>
A: try this code
<h:outputLink value="#{bean.url}">
<h:outputText value="Go to another page."/>
<f:param name="paramid" value="#{bean.id}" />
</h:outputLink> | unknown | |
d16326 | val | If I'm not mistaken, doing:
type = Column(EmployeeType.db_type())
instead of
type = Column(DeclEnumType(EmployeeType))
should do it. | unknown | |
d16327 | val | Try this one, this may help You..
HTML :
<a id="add" href="searchpage.html" class="show_hide">Click</a>
JS:
$(document).ready(function () {
$('.show_hide').click(function (e) {
e.preventDefault(); //to prevent default action of link tag
$('#add').slideToggle(1000);
});
});
And Here is Demo. | unknown | |
d16328 | val | Again... there may be a more elegant regex...
Certainly feel free to google for "good" regex's for finding URLs if this one falls short.
<cfset myText = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com or at https://foo.com or http://123.com" />
<cfset myNewText = rereplaceNoCase( myText, '((http(s)?://)?((www\.)?\w+\.\w{2,6}))', '<a href="http://\4">\1</a>', 'all' ) />
A: This will parse URL in string that starts with http or www and terminated by a space
<cfset myString = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com">
<cfset URLinString = rereplaceNoCase(myString, '(((http(s)?://)|(www))\.?(\S+))', '<a href="http://\1">\1</a>', 'all')> | unknown | |
d16329 | val | Use a service that both view models can access and that stores the info whether Control2 should be visible or not. Ideally, the service would be registered as singleton with your di-container and injected into the view models.
Alternatively, you can use an event aggregator, which is basically a singleton service, too, but focused on distributing events rather than holding a state.
A: You can use events, You can raise event from Control2VM and hadnle it in Control1VM and set GridControl2Visibility to false. | unknown | |
d16330 | val | void goFoo(int a) {
for (int a = 0; a < 5; a++) { }
}
it is similar to
void goFoo() {
int a;
for (int a = 0; a < 5; a++) { }
}
so multiple declaration of a on the same scope, it is not acceptable.
or simply it is similar to
void goFoo() {
int a;
int a;
}
Also See
*
*java-variable-scope-shadowing
A: You can make a local variable shadow an instance/static variable - but you can't make one local variable (your loop counter) shadow another local variable or parameter (your parameter).
From the Java Language Specification, section 14.4.3:
If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable.
Note the "field name" part - it's specifying that it has to be a field that is shadowed.
And from section 8.4.1:
The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.
These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor.
(It goes on to talk about local classes and anonymous classes, but they're irrelevant in your case.)
A: The scope of the variable depends on the hierarchy of the block as well.
ie if u use like this
void goFoo(int a) {
// No problem naming parameter as same as instance variable
for (int b = 0; b < 5; b++) { }
//Now the compiler complains about the variable a on the for loop
// i thought that the loop block had its own scope so i could shadow
// the parameter, why the compiler didnt throw an error when i named
// the parameter same as the instance variable?
int b; // you can do this.
}
That is if a variable is declared in the outer block then you can not declare the same in the block which is inner. the other way you can do it.
A: But you don't declare the second "a" in that new scope, as your code shows. It's in the scope of the goFoo() block itself.
A: The problem isn't that the loop is shadowing the class field, the name is already used by the parameter.
Two options: One is to change the loop:
for (a = 0; a < 5; a++) { }
This uses the parameter as the index variable. Not clear why you would have a parameter, but all the same...
The other option is to rename the loop variable or the parameter to something else.
A: It is not shadowing, it is a conflict here. Both a are in the method scope. One cannot define two variables of same name in the same scope.
A: In Java (unlike, say, in c++) you cannot declare a local variable when another local variable with the same name is "in scope".
You cannot do this in Java
void foo() {
int a;
{
int a; // You cannot declare 'a' here because a
// from the outer block is still in scope
// here. Local variables in Java cannot be
// shadowed by another local variable with
// the same name. Only instance variables
// can be shadowed by the local variables
// with the same name.
}
}
However c++ allows you to do this
void foo()
{
int a;
a = 10;
cout << a << endl; // prints 10 duh
{
int a; // this declaration shadows the local
// variable 'a' from the outer scope.
a = 20; // assigns 20 to the variable 'a' in
// current inner scope, like you'd expect.
cout << a << endl; // prints 20.
}
cout << a << endl; // prints 10
} | unknown | |
d16331 | val | I think this is about that block in class:
class ExampleClass
{
/** Start of Use Trait Body **/
use TraitOne;
use TraitTwo;
use TraitThree;
/** End of Use Trait Body **/
} | unknown | |
d16332 | val | The go to definition works just fine. The problem was that eclipse didn't know where to find the source. You can go to window > preferences > pydev > interpreter > New folder, and add the folders missing. Even though you've added site-packages to the configuration, you still have to add subfolders separately to get code assist and to be able to go to the definition.
A: Pydev (also bundle with the Aptana distro) does not seem to have any bug exactly similar to the one you are describing.
Here is the list of bugs including the word "definition" for PyDev: bugs
You could open a bug report there with the exact version of eclipse, pydev, java used
But first:
What version of Pydev are you using? The open-source one or the commercial one (i.e. open-source + Pydev extensions)?
Because the matrix feature is quite clear:
Feature List Pydev "Open Source" Pydev Extensions
---------------------------------------------------------------
Go to definition BRM* Pydev Extensions(2)
BRM*: Bicycle Repair Man is an open-source program that provides 'go-to-definition' and refactoring. Its 'go-to-definition' only works for Python, and only works 'well' for global or local tokens (does not work very well on methods from parameters or on 'self'). It is currently 'unsupported'.
Pydev Extensions (2): Pydev extensions provides a 'go-to-definition' that works for python and jython, and should work even on methods from parameters and 'self'. | unknown | |
d16333 | val | I advise you rather use ready Mailer class for that - http://phpmailer.worxware.com/ is the best choice. I use it for many years and you can configure SMTP connection very easy | unknown | |
d16334 | val | Have not tried this, but it should be something like this
$args = array(
'taxonomy' => 'obra_tema',
'orderby' => 'id',
'order' => 'DESC',
);
$themes = get_terms($args);
You might have to adjust the order field or the order by direction. | unknown | |
d16335 | val | Departments='" & replace(Sheet3.Range("Dept_name").Value, "'", "''") & _ "' and Metric | unknown | |
d16336 | val | In your webpack.config.js file add resolve.alias which you want to make alias. It looks like something this below:
resolve: {
alias: {
'@page': path.resolve(__dirname, '{path you want to make alias}')
}
}
Since you are using cypress, you have to update the resolve path in cypress.config.js. Here is mine cypress.config.js
import { defineConfig } from 'cypress'
import webpack from '@cypress/webpack-preprocessor'
import preprocessor from '@badeball/cypress-cucumber-preprocessor'
import path from 'path'
export async function setupNodeEvents (on, config) {
// This is required for the preprocessor to be able to generate JSON reports after each run, and more,
await preprocessor.addCucumberPreprocessorPlugin(on, config)
on(
'file:preprocessor',
webpack({
webpackOptions: {
resolve: {
extensions: ['.ts', '.js', '.mjs'],
alias: {
'@page': path.resolve('cypress/support/pages/')
}
},
module: {
rules: [
{
test: /\.feature$/,
use: [
{
loader: '@badeball/cypress-cucumber-preprocessor/webpack',
options: config
}
]
}
]
}
}
})
)
// Make sure to return the config object as it might have been modified by the plugin.
return config
}
And import in other file via that alias you set in cypress.config.js. Here is mine for example:
import page from '@page/visit.js'
const visit = new page()
When('I visit duckduckgo.com', () => {
visit.page()
})
A: I think both answers are nearly there, this is what I have for src files:
const webpack = require('@cypress/webpack-preprocessor')
...
module.exports = defineConfig({
...
e2e: {
setupNodeEvents(on, config) {
...
// @src alias
const options = {
webpackOptions: {
resolve: {
alias: {
'@src': path.resolve(__dirname, './src')
},
},
},
watchOptions: {},
}
on('file:preprocessor', webpack(options))
...
path.resolve() resolves a relative path into an absolute one, so you need to start the 2nd param with ./ or ../.
Also, don't use wildcard * in the path, you just need a single folder that will be substituted for the alias in the import statement.
If in doubt, check the folder returned (in the terminal)
module.exports = defineConfig({
...
e2e: {
setupNodeEvents(on, config) {
const pagesFolder = path.resolve(__dirname, './cypress/pages')
console.log('pagesFolder', pagesFolder) | unknown | |
d16337 | val | You don't need to use jquery plugin for that. Yii2 has several widgets which you can use: Some of them are:
1) Yii2 Jui DatePicker
2) Kartik yii2-widget-datepicker
3) 2amigos yii2-date-picker-widget
You can use anyone of these.
A: You need to install or update your composer.
If you are using Ubuntu or Linux Operating System, open command prompt and run this command:
composer require --prefer-dist yiisoft/yii2-jui
This will create the jui folder which contains all the required plugins such as datepicker or any other you want to use in your website.
Now you just have to place this code in your form.php in views folder
use yii\jui\DatePicker;
<?= $form->field($model, 'from_date')->widget(\yii\jui\DatePicker::classname(), [
//'language' => 'ru',
'dateFormat' => 'MM-dd-yyyy',
]) ?> | unknown | |
d16338 | val | Assuming you are trying to overwrite element "1" in your json object using php, try this:
$newjson = json_decode($json, true);
$newjson["1"] = Array();
$newjson = json_encode($newjson);
If you want to add an element:
$newjson = json_decode($json, true);
$newjson[] = Array();
$newjson = json_encode($newjson); | unknown | |
d16339 | val | The meaning of inline is just to inform the compiler that the finction in question will be defined in this translation as well as possibly other translation units. The compiler uses this information for two purposes:
*
*It won't define the function in the translation unit as an externally visible, unique symbol, i.e., you won't get an error about the symbol being defined multiple times.
*It may change its view on whether it wants to call a function to access the finctionality or just expand the code where it is used. Whether it actually will inline the code will depend on what the compiler can inline, what it thinks may be reasonable to inline, and possibly on the phase of the moon.
There is no difference with respect to what sort of function is being inlined. That is, whether it is a constructor, a member function, a normal function, etc.
BTW, member functions defined inside the class definition are implicitly declared inline. There is no need to mention it explicitly. __forecedinline seems to be a compiler extension and assuming it does what it says is probably a bad idea as compilers are a lot better at deciding on what should be inlined than humans. | unknown | |
d16340 | val | You could call the EnumWindows function with an lambda expression. Then the EnumWindowsProc Callback would be inline and you can access to local variables:
List<IntPtr> list = new List<IntPtr>();
WinApi.EnumWindows((hWnd, lParam) =>
{
//check conditions
list.Add(hWnd);
return true;
}, IntPtr.Zero);
You could capsulate this inline call in an extra function, e.g.:
List<IntPtr> GetMatchingHWnds()
{
List<IntPtr> list = new List<IntPtr>();
WinApi.EnumWindows((hWnd, lParam) =>
{
//check conditions
list.Add(hWnd);
return true;
}, IntPtr.Zero);
return list;
} | unknown | |
d16341 | val | As mentioned in my comment, this is not possible with .htaccess.
Reason being: the hash part (known as the fragment) is not actually sent to the server, and so Apache would not be able to pick it up. Servers may only pick up everything before that, which is described in the Syntax section of this article.
As an alternative, I would recommend that you use JavaScript to convert the fragment before scrolling to its location. You can do that by pulling in the value of [window.]location.hash (the part in square parenthises is optional as location is also available in the global scope) if it exists, as shown below:
if (window.location.hash) {
// Function to 'slugify' the fragment
// @see https://gist.github.com/mathewbyrne/1280286#gistcomment-1606270
var slugify = function(input) {
return input.toString().toLowerCase().trim()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
// Now get the hash and 'slugify' it
var hash = slugify(window.location.hash.split('#')[1]);
// Go to the new hash by setting it
window.location.hash = '#' + hash;
} | unknown | |
d16342 | val | Such SQL is not supported in VFP. You can write that as:
SELECT csa.primary_city as city ;
, csa.state as state_id ;
, SPACE(30) as state_name ;
, csa.approximate_latitude as latitude ;
, csa.approximate_longitude as longitude ;
FROM citystate csa ;
INNER JOIN ;
(SELECT primary_city, state, MAX(VAL(area_land)) as maxALand ;
FROM citystate ;
GROUP BY primary_city, state ) csb ;
ON csb.primary_city = csa.primary_city ;
AND csb.state = csa.state ;
WHERE VAL(csa.area_land) = csb.maxALand
A: VFP has not problem at all with 'such SQL', contrary to the pronouncement of master Basoz on the matter.
Normally you should get a type mismatch error because of the comparison of land_area to max(val(land_area)). Fox is nowhere near as eager with implicit conversions as, for example, MS SQL Server, and hence you have to match data types correctly.
However, not knowing what your table structures are it is difficult to offer specific pointers as to where the problem may be. Here are two similar queries using sample data available in VFP (using the freight cost as a stand-in for land_area value):
_VFP.DoCmd("set path to " + set("PATH") + ";" + _SAMPLES)
use Northwind/orders alia nw_orders in sele("nw_orders") shar noup agai
sele o.shipcountry, o.shipcity, o.shipname, o.orderid, o.freight ;
from nw_orders o ;
wher o.freight == ( ;
sele max(x.freight) from nw_orders x wher x.shipcountry == o.shipcountry ) ;
orde by 1 ;
into curs nw_result
brow last nowa
use Tastrade/orders alia tt_orders in sele("tt_orders") shar noup agai
sele o.ship_to_country, o.ship_to_city, o.ship_to_name, o.order_number, o.freight ;
from tt_orders o ;
wher o.freight == ( ;
sele max(x.freight) from tt_orders x wher x.ship_to_country == o.ship_to_country ) ;
orde by 1 ;
into curs tt_result
brow last nowa
Tastrade and Northwind are very similar in structure and contain very similar data; one or the other should be available in your VFP installation. However, neither sample database seems to in the public domain, at least not in the VFP incarnation. That is why I put Northwind first, since it is publicly available in versions for MS SQL Server etc. pp., and dumping its orders table to Fox format should not present insurmountable difficulties.
Here's a C# LINQPad script for running the Northwind query via OLEDB:
const string DIR = @"d:\dev\sub\FoxIDA\data\Northwind\";
const string SQL = @"
sele o.shipcountry, o.shipcity, o.shipname, o.orderid, o.freight
from orders o
wher o.freight == (sele max(x.freight) from orders x wher x.shipcountry == o.shipcountry)
orde by 1";
using (var con = new System.Data.OleDb.OleDbConnection("provider=VFPOLEDB;data source=" + DIR))
{
using (var cmd = new System.Data.OleDb.OleDbCommand(SQL, con))
{
con.Open();
cmd.ExecuteReader().Dump();
}
}
Obviously, you'd need to adapt the DIR definition to where the data is located on your machine. Equally obviously you'd have to use a 32-bit version of LINQPad, since there is no 64-bit OLEDB driver for VFP. Here's the result: | unknown | |
d16343 | val | There is no such thing as "if the type name is XYZSharedPtr, it is instead std::shared_ptr<XYZ>" inbuilt into C++.
The authors of the code created a type alias somewhere, either
using IGenericResultSharedPtr = std::shared_ptr<IGenericResult>;
or
typedef std::shared_ptr<IGenericResult> IGenericResultSharedPtr;
(or possibly wrapped in a macro - who knows). Ask your IDE to find the definition :) | unknown | |
d16344 | val | Have you looked at the BitArray class? It should be pretty much exactly what you're looking for.
A: Try following,
.Net 4 has inbuilt BigInteger type
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx
.Net 2 project on code project
http://www.codeproject.com/KB/cs/biginteger.
Another alternative,
http://www.codeplex.com/IntX/
A: Unless you have millions of employees that all need to be scheduled at the same time, I'd be tempted to store your 96 booleans as a char array with 0 meaning "free" and 1 meaning "busy". Simple to index/access/update. The rest of the employees schedules can sit in their database rows on disk where you simply don't care about "96 megabytes".
If you can find a class which implements a bit array, you could use that. (You could code one easily, too). But does it really matter spacewise?
Frankly, if your organization really has a million employees to schedule, surely you can afford a machine which has space for a 96 mB array as well as the rest of your code?
The one good excuse I can see for using bit vectors has to do with execution time cost. If you scheduling algorithm essentially ANDs one employee bit vector against another looking for conflicts, and does that on large scale, bit vectors might reduce the computation time to do this by a factor of roughly 10 (use a two *long*s per employee to get your 96 bits). I'd wait till my algorithm worked before I worried about this.
A: You could use and array of bytes. I don't think any language supports an array of bits, as a byte is the smallest addressable piece of memory. Other options are an array of booleans, but each boolean I believe is stored as a byte anyway, so there would be wasted memory, but it might be easier to work with. It really depends on how many days you are going to work with. You could also just store the start and end of the shift and use other means to figure out if there are overlapping schedules. This would probably make the most sense, and be the easiest to debug.
A: BitArray has already been mentioned, it uses an array of ints much like you planned to do anyway.
That also means that it adds an extra layer of indirection (and some extra bytes); it also does a lot of checking everywhere to make sure that eg the lengths of two bitarrays is the same when operating on them. So I would be careful with them. They're easy, but slower than necessary - the difference is especially big (compared to handling the array yourself) for smallish bitarrays. | unknown | |
d16345 | val | Dependency injection does not depend on the typescript. Whenever we boot up the nest app, a Dependency Injection (DI) container gets created for us. DI is just an object.
Nest will look at the all different classes that we created except controllers. It will register all those different classes with the DI container. The container will check all the dependencies that are required for each class and map this class to its dependencies:
class1 ---> dependencies
class2 ---> dependencies
class3 ---> it might now have any dependency
Then eventually we want to create the controller. we tell DI to create the controller with the required dependencies. DI will look at the constructor argument and see all the dependencies that are required. the container will see that it needs to create a service and service needs to create some dependencies.
So DI container will create the instances of required dependencies and store each instance internally so if in the future another class needs to those instances it can use them. Now dependencies are already created and DI container will use those to create the Controller and return it.
As you see we do not worry about creating all those services ourselves. DI container will take care of it for us.
Dependency injection is used for reusing the code and test the app easier.
A: Take a look at the example. This:
@Injectable()
export default class RequestService {
constructor(
@InjectRepository(RequestEntity)
private requestEntityRepository: Repository<RequestEntity>,
) {}
Is being transpiled to this:
let RequestService = class RequestService {
constructor(requestEntityRepository) {
this.requestEntityRepository = requestEntityRepository;
}
...
RequestService = __decorate([
common_1.Injectable(),
__param(0, typeorm_1.InjectRepository(RequestEntity_1.default)),
__metadata("design:paramtypes", [typeorm_2.Repository])
], RequestService);
exports.default = RequestService;
A: Dependency injection in general does not depend on typescript, and even in NestJS it can be done in (mostly) plain JavaScript by using Babel as a transpiler. I've gone into a bit of detail here about how the decorators work with typescript, and Semyon Volkov has shown how the decorators transpile as well. So inherently, no, it doesn't depend on Typescript, the way Nest wants you to do it (being opinionated and all) does.
In your example, Nest will read the type of design:paramtypes and see that there is a CatsService class, so it knows to match up the class names and inject a CatsService here. There's a lot more going on under the hood, when it comes to keeping track of what modules have access to what, but that's the general idea. | unknown | |
d16346 | val | A standalone tool with lots of metrics (including cc) is ndepend.
A: I believe CodeRush had it 'interactively'.. but heck, why bother, there are sources on the web that will give you commercial-free ideas and implementation.
A: Coderush from Developer Express will do this and it works well. I vouch for it. (and have no relation to the company other than a long time customer)
A: McCabe IQ (www.mccabe.com/iq.htm) developed by the man who authored Cyclomatic Complexity, Tom McCabe.
A: Code Metrics is an excellent free plug-in for reflector that analyzes code size & complexity.
A: Visual Studio 2008 Team System (or just VS 2008 Developer Edition) has Code Metrics.
StudioTools is a free addin for VS 2005 and VS 2008. NDepend is good too. | unknown | |
d16347 | val | fixed the issue, I set the default to 0, now there is no error and it works properly. | unknown | |
d16348 | val | In the ViewModel class
public void UnsubscribeFromCallBack()
{
this.event -= method;
}
In the .xaml.cs page
protected override void OnDisappearing()
{
base.OnDisappearing();
PageViewModel vm = (this.BindingContext as PageViewModel);
vm.UnSubscribeFromCallback();
} | unknown | |
d16349 | val | Your code wait only the first promise before the equal comparison.
You need wait the execution of all promises
var copyLink = page.copyLink();
var actual;
return Promise.all([copyLink.firstCampaign, copyLink.secondCampaign]).then(results => results[0].should.equal(results[1])).should.be.fulfilled; | unknown | |
d16350 | val | Although this one looks old for the benefit of others who happen to stumble upon the same one
please add
<driver-class>com.mysql.jdbc.Driver</driver-class> to your driver definition in standalone.xml
complete entry
<drivers>
<driver name="com.mysql" module="com.mysql">
<driver-class>com.mysql.jdbc.Driver</driver-class>
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
</driver>
</drivers> | unknown | |
d16351 | val | There are several way to have expected behavior:
*
*Named constructor
class DataGroup final {
public:
// ...
static DataGroup Group1(const std::vector<int>& groupNr,
const std::string& group)
{ return DataGroup{groupNr, group, ""}; }
static DataGroup Group2(const std::vector<int>& groupNr,
const std::string& group)
{ return DataGroup{groupNr, "", group}; }
// ...
};
DataGroup d = DataGroup::Group2({1, 2}, "MyGroup");
*Tagged constructor
struct group1{};
struct group2{};
class DataGroup final {
public:
// ...
DataGroup(group1, const std::vector<int>& groupNr,
const std::string& group) : DataGroup{groupNr, group, ""} {}
DataGroup(group2, const std::vector<int>& groupNr,
const std::string& group) : DataGroup{groupNr, "", group} {}
// ...
};
DataGroup d{group2{}, {1, 2}, "MyGroup");
*named parameters (see there for possible implementation)
// ...
DataGroup d{groupNr = {1, 2}, group2 = "MyGroup");
A: For overloading a function/constructor, they must have 2 distinct signatures. Since your intended types to be supplied are the same for both cases, you have to supply a 3rd parameter with a possibly default value for one of them. But again, watch for uninitialized local fields, since they will be auto-initialized by the compiler-generated code.
A: One of the solutions here would be to simply have base class with "common" member
groupNr(groupNr)
and other two separate member have in each derived class, then you would initialize base member groupNr by calling constructor of base class when initializing derived one:
class DataGroup {
public:
explicit DataGroup (const std::vector<int>& groupNrs)
: groupNrs(groupNr){};
std::vector<int> groupNrs{};
};
class DataGroup1 : public DataGroup {
public:
explicit DataGroup1 (const std::vector<int>& groupNrs,
const std::string& group1)
: DataGroup(groupNrs)
, group1(group1){};
std::string group1{};
};
class DataGroup2 : public DataGroup {
public:
explicit DataGroup2 (const std::vector<int>& groupNrs,
const std::string& group2)
: DataGroup(groupNrs)
, group2(group2){};
std::string group2{};
}; | unknown | |
d16352 | val | The biggest potential problems you are running up against is the fact that you assume a line is valid if it begins with a c, t or r without first validating the remainder of the line matches the format for a circle, triangle or rectangle. While not fatal to this data set, what happens if one of the lines was 'cat' or 'turtle'?
By failing to validate all parts of the line fit the "mold" so to speak, you risk attempting to output values of r, h & w or s that were not read from the file. A simple conditional check of the read to catch the potential failbit or badbit will let you validate you have read what you think you read.
The remainder is basically semantics of whether you use the niceties of C++ like a vector of struct for rectangles and whether you use a string instead of char*, etc. However, there are certain benefits of using a string to read/validate the remainder of each line (or you could check the stream state and use .clear() and .ignore())
Putting those pieces together, you can do something like the following. Note, there are many, many different approaches you can take, this is just one approach,
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
typedef struct { /* simple typedef for vect of rectangles */
int width, height;
} rect_t;
int main (int argc, char **argv) {
vector<double> cir; /* vector of double for circle radius */
vector<double> tri; /* vector of double for triangle side */
vector<rect_t> rect; /* vector of rect_t for rectangles */
string line; /* string to use a line buffer */
if (argc < 2) { /* validate at least one argument given */
cerr << "error: insufficient input.\n"
"usage: " << argv[0] << " filename\n";
return 1;
}
ifstream f (argv[1]); /* open file given by first argument */
if (!f.is_open()) { /* validate file open for reading */
cerr << "error: file open failed '" << argv[1] << "'.\n";
return 1;
}
while (getline (f, line)) { /* read each line into 'line' */
string shape; /* string for shape */
istringstream s (line); /* stringstream to parse line */
if (s >> shape) { /* if shape read */
if (shape == "c") { /* is it a "c"? */
double r; /* radius */
string rest; /* string to read rest of line */
if (s >> r && !getline (s, rest)) /* radius & nothing else */
cir.push_back(r); /* add radius to cir vector */
else /* invalid line for circle, handle error */
cerr << "error: invalid radius or unexpected chars.\n";
}
else if (shape == "t") {
double l; /* side length */
string rest; /* string to read rest of line */
if (s >> l && !getline (s, rest)) /* length & nothing else */
tri.push_back(l); /* add length to tri vector */
else /* invalid line for triangle, handle error */
cerr << "error: invalid triangle or unexpected chars.\n";
}
else if (shape == "r") { /* is it a rect? */
rect_t tmp; /* tmp rect_t */
if (s >> tmp.width && s >> tmp.height) /* tmp & nohtin else */
rect.push_back(tmp); /* add to rect vector */
else /* invalid line for rect, handle error */
cerr << "error: invalid width & height.\n";
}
else /* line neither cir or rect, handle error */
cerr << "error: unrecognized shape '" << shape << "'.\n";
}
}
cout << "\nthe circles are:\n"; /* output valid circles */
for (auto& i : cir)
cout << " c: " << i << "\n";
cout << "\nthe triangles are:\n"; /* output valid triangles */
for (auto& i : tri)
cout << " t: " << i << "\n";
cout << "\nthe rectangles are:\n"; /* output valid rectangles */
for (auto& i : rect)
cout << " r: " << i.width << " x " << i.height << "\n";
}
By storing values for your circles, triangles and rectangles independent of each other, you then have the ability to handle each type of shape as its own collection, e.g.
Example Use/Output
$ ./bin/read_shapes dat/shapes.txt
error: unrecognized shape '3'.
error: unrecognized shape '10'.
the circles are:
c: 12
c: 2
c: 2.4
the triangles are:
t: 2.9
t: 2.9
the rectangles are:
r: 3 x 4
Look things over and let me know if you have further questions. The main takeaway is to insure you validate down to the point you can insure what you have read is either a round-peg to fit in the circle hole, a square-peg to fit in a square hole, etc..
A: The only thing I added was a getline where I put a comment at the "else" of the loop.
while(infile >> names) {
if(names.at(0) == 'c') {
double r;
infile >> r;
cout << "radius = " << r << endl;
} else if(names.at(0) == 'r') {
double w;
double h;
infile >> w;
infile >> h;
cout << "width = " << w << ", height = " << h << endl;
} else if(names.at(0) == 't') {
double s;
infile >> s;
cout << "side = " << s << endl;
} else {
// discard of the rest of the line using getline()
getline(infile, names);
//cout << "discard: " << names << endl;
}
}
Output:
radius = 12
radius = 2
width = 3, height = 4
radius = 2.4
side = 2.9
side = 2.9 | unknown | |
d16353 | val | make a point on this node you are append the string and then you pass it to the object.In the object you need to pass the string which is key term of your json.
while((line = reader.readLine())!=null)
{
builder.append(line);
}
A: *
*Their is an easy way to turn a inputstrem to a string:
InputStream inputStream = url.openStream();
Scanner in = new Scanner(inputStream).useDelimiter("\\A");
String str = in.hasNext() ? in.next() : null;
*prefer to use JSONObject.optXxx(field) rather than JSONObject.getXxx(field), this you don' t need to worry whether a field in the json data or whether it can convert to your desired type. Besides, JSONObject.optXxx(field, fallback) has a fallback value if the field doesn' t exist or cannot conver to the specific type.
*(optional) if you would like to use JSONObject.getXxx(), you can first check the whether the filed in the json data using JSONObject.has(fieldname)
hope it' s useful. | unknown | |
d16354 | val | Yes. Strong exception guarantee means that the operation completes successfully or leaves the data unchanged.
Exception neutral means that you let the exceptions propagate.
A: It is exception safe. To be more safe, why not use vector<shared_ptr<int>>
template<typename Type, typename Func>
void StrongSort( vector<shared_ptr<Type>>& elems, Func fun)
{
vector<shared_ptr<Type>> temp ( elems.begin(), elems.end());
sort(temp.begin(), temp.end(), fun);
swap(elems, temp);
}
vector<shared_ptr<int>> ints;
ints.push_back(shared_ptr<int>(new int(3)));
ints.push_back(shared_ptr<int>(new int(1)));
ints.push_back(shared_ptr<int>(new int(2)));
StrongSort(ints, [](shared_ptr<int> x, shared_ptr<int> y) -> bool { return *x < *y; }); | unknown | |
d16355 | val | It seems like your relations are inverted. You are asking for food_category through food. So food has a food_category and food_category belongs to food if this should be hasOne or hasMany I can't see from your example.
Database
foods table
id
name
food_categories table
id
name
food_id
models/Food.php
class Food extends Eloquent {
public function food_category()
{
return $this->hasOne('FoodCategory');
}
}
models/FoodCategory.php
class FoodCategory extends Eloquent {
}
A: Try with eager loading:
$foods = Food::with('FoodCategory')->get();
A: I think to resolve this question, you have two choice:
Fisrt:
public function category()
{
return $this->belongsTo('FoodCategory');
}
Then do {{ $food->category->name }} which is more elegant
Second: just add 'id'
public function food_category()
{
return $this->belongsTo('FoodCategory','food_category_id');
} | unknown | |
d16356 | val | Call the commit function of either the cursor or connection after SELECT ... INTO is executed, for example:
...
dbCursor.execute(query)
dbCursor.commit()
Alternatively, automatic commit of transactions can be specified when the connection is created using autocommit. Note that autocommit is an argument to the connect function, not a connection string attribute, for example:
...
dbCxn = db.connect(cxnString, autocommit=True)
... | unknown | |
d16357 | val | This approach may be a little functional.
You need to first replace the ], in every row to an empty string I have used this Regex to split it.
After that, I split the strings by whitespaces which are more than 2 characters.
Then finally I used .map to project over the splitted items to parse it back and make an array of array.
const inputData = {
rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"],
["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"],
["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]`
};
const pattern = /\](,)\s{2,}?/gm
const res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]")
.split(/\s{2,}/gm)
.map(x => JSON.parse(x));
const output = { KPI: res };
console.log(output); | unknown | |
d16358 | val | If you're adding view controllers to the view of another view controller, then you need to use container containment. You can do that in IB with container views. That makes it easier, than making custom container controllers in code.
A: The Absolute best way is to maintain ViewControllers according to their functionality (ex. one might be dashboardView one might be settingsView). Now when moving from one view controller to another is to use navigationController.
The practice I follow is to declare one navigationController in appDelegate when your app starts and then keep reusing this. Example -
YourAppDelegate *delegate=(YourAppDelegate *)[[UIApplication sharedApplication] delegate];
MyViewController1 *myVC = [[ FLOHome alloc ]initWithNibName:@"MyViewController1" bundle:[NSBundle mainBundle]];
[delegate.navigationController pushViewController:myVC animated:NO];
This is the absolute best way when dealing with viewControllers. navigationController handles whole lot of stuff like memory management, caching views to make them snappy. You could keep pushing viewcontrollers and poping them when you exit from them... | unknown | |
d16359 | val | The poor man's way is to simply remove/comment-out either the getter or setter and recompile: all the errors will be your references. ;)
EDIT: Instead of deleting it (which could be invalid syntax), change the visibility of the particular get/set to private.
A: I would suggest you to evalutate the ReSharper product which has extremely powerful features that enhance Visual Studio a lot.
Find Usages is what you are looking for.
If you find the ReSharper to be ok (and you will!) then go ahead and buy a license after evaluation.
Just make sure to try it out at least! | unknown | |
d16360 | val | Use Split.
for more details
https://stackoverflow.com/a/55358328/11794336
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static const String example = 'abc; def; ghi;';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ListView(
children: example
.split(';') // split the text into an array
.map((String text) => Text(text)) // put the text inside a widget
.toList(), // convert the iterable to a list
)
),
);
}
} | unknown | |
d16361 | val | You can use a lambda with & if you so desire:
square = lambda { |x| x**2 }
a.map!(&square)
This sort of thing is pointless busywork with a block so simple but it can be nice if you have a chain of such things and the blocks are more complicated:
ary.select(&some_complicated_criteria)
.map(&some_mangling_that_takes_more_than_one_line)
...
Collecting bits of logic in lambdas so that you can name the steps has its uses.
A: You should do this
a.map! { |i| i**2 }
Read the docs.
A: As a matter of rule, you cannot add parameters to methods using the &:sym syntax.
However, if you follow my suggestion here you could do the following:
class Symbol
def with(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
a.map!(&:**.with(2))
# => [9, 16, 25, 36]
A: You can only use the &: shortcut syntax if you are calling a method on the object with no arguments. In this case, you need to pass 2 as an argument to the ** method.
Instead, expand the block to the full syntax
a.map! { |n| n**2 } | unknown | |
d16362 | val | By definition, many-to-many associations can only be used when the association table does not have any other columns besides the foreign keys to the parent tables.
Instead, you should use two ManyToOne/OneToMany associations.
Here's a forum topic on this subject (with an example):
http://www.coderanch.com/t/218431/ORM/databases/Hibernate-Annotations-many-many-association | unknown | |
d16363 | val | Code below create csv files by year with data with all headers and values, in example below will be 3 files: data_2017.csv, data_2018.csv and data_2019.csv.
You can add another year to years = ['2017', '2018', '2019'] if needed.
Winning Numbers formatted to be as 1-2-3-4-5.
from bs4 import BeautifulSoup
import requests
import pandas as pd
base_url = 'https://www.lotterycorner.com/tx/lotto-texas/'
years = ['2017', '2018', '2019']
with requests.session() as s:
for year in years:
data = []
page = requests.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
soup = BeautifulSoup(page.content, 'html.parser')
rows = soup.select(".win-number-table tr")
headers = [td.text.strip() for td in rows[0].find_all("td")]
# remove header line
del rows[0]
for row in rows:
td = [td.text.strip() for td in row.select("td")]
# replace whitespaces in Winning Numbers with -
td[headers.index("Winning Numbers")] = '-'.join(td[headers.index("Winning Numbers")].split())
data.append(td)
df = pd.DataFrame(data, columns=headers)
df.to_csv(f'data_{year}')
To save only Winning Numbers, replace df.to_csv(f'data_{year}') with:
df.to_csv(f'data_{year}', columns=["Winning Numbers"], index=False, header=False)
Example output for 2017, only Winning Numbers, no header:
9-14-16-27-45-51 2-4-15-38-48-53 8-22-23-29-34-36
6-10-11-22-30-45 5-10-16-22-26-46 12-14-19-34-39-47
4-5-10-21-34-40 1-25-35-42-48-51
A: This should export the data you need in a csv file:
from bs4 import BeautifulSoup
from csv import writer
import requests
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2019')
soup = BeautifulSoup(page.content,'html.parser')
header = {
'date': 'win-nbr-date col-sm-3 col-xs-4',
'winning numbers': 'nbr-grp',
'jackpot': 'win-nbr-jackpot col-sm-3 col-xs-3',
}
table = []
for header_key, header_value in header.items():
items = soup.find_all(class_=f"{header_value}")
column = [','.join(item.get_text().split()) if header_key=='winning numbers'
else ''.join(item.get_text().split()) if header_key == 'jackpot'
else item.get_text() for item in items]
table.append(column)
rows = list(zip(*table))
with open("winning numbers.csv", "w") as f:
csv_writer = writer(f)
csv_writer.writerow(header)
for row in rows:
csv_writer.writerow(row)
header is a dictionary mapping what will be your csv headers to their html class values
In the for loop we're building up the data per column. Some special handling was required for "winning numbers" and "jackpot", where I'm replacing any whitespace/hidden characters with comma/empty string.
Each column will be added to a list called table. We write everything in a csv file, but as csv writes one row at a time, we need to prepare our rows using the zip function (rows = list(zip(*table)))
A: Don't use BeautifulSoup if there are table tags. It's much easier to let Pandas do the work for you (it uses BeautifulSoup to parse tables under the hood).
import pandas as pd
years = [2017, 2018, 2019]
df = pd.DataFrame()
for year in years:
url = 'https://www.lotterycorner.com/tx/lotto-texas/%s' %year
table = pd.read_html(url)[0][1:]
win_nums = table.loc[:,1].str.split(" ",expand=True).reset_index(drop=True)
dates = pd.DataFrame(list(table.loc[:,0]), columns=['date'])
table = dates.merge(win_nums, left_index=True, right_index=True)
df = df.append(table, sort=True).reset_index(drop=True)
df['date']= pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)
df.to_csv('file.csv', index=False, header=False)
Output:
print (df)
date 0 1 2 3 4 5
0 2017-01-04 5 7 36 39 40 44
1 2017-01-07 2 5 14 18 26 27
2 2017-01-11 4 13 16 19 43 51
3 2017-01-14 7 8 10 18 47 48
4 2017-01-18 6 11 17 37 40 49
5 2017-01-21 2 13 17 39 41 46
6 2017-01-25 1 14 19 32 37 46
7 2017-01-28 5 7 30 48 51 52
8 2017-02-01 12 19 26 29 37 54
9 2017-02-04 8 13 19 25 26 29
10 2017-02-08 10 15 47 49 51 52
11 2017-02-11 24 25 26 29 41 53
12 2017-02-15 1 4 5 43 53 54
13 2017-02-18 5 11 14 21 38 44
14 2017-02-22 4 8 21 27 52 53
15 2017-02-25 16 37 42 46 49 54
16 2017-03-01 3 24 33 34 45 51
17 2017-03-04 2 4 5 17 48 50
18 2017-03-08 15 19 24 33 34 47
19 2017-03-11 5 6 24 28 29 37
20 2017-03-15 4 11 19 27 32 46
21 2017-03-18 12 15 16 23 38 43
22 2017-03-22 3 5 15 27 36 52
23 2017-03-25 21 25 27 30 36 48
24 2017-03-29 7 9 11 18 23 43
25 2017-04-01 3 21 28 33 38 52
26 2017-04-05 8 20 21 26 51 52
27 2017-04-08 10 11 12 47 48 52
28 2017-04-12 5 26 30 31 46 54
29 2017-04-15 2 11 36 40 42 53
.. ... .. .. .. .. .. ..
265 2019-07-20 3 35 38 45 50 51
266 2019-07-24 2 9 16 22 46 49
267 2019-07-27 1 2 6 8 20 53
268 2019-07-31 20 24 34 36 41 44
269 2019-08-03 6 17 18 20 26 34
270 2019-08-07 1 3 16 22 31 35
271 2019-08-10 18 19 27 36 48 52
272 2019-08-14 22 23 29 36 39 49
273 2019-08-17 14 18 21 23 40 44
274 2019-08-21 18 28 29 36 48 52
275 2019-08-24 11 31 42 48 50 52
276 2019-08-28 9 21 40 42 49 53
277 2019-08-31 5 7 30 41 44 54
278 2019-09-04 4 26 36 37 45 50
279 2019-09-07 22 23 31 33 40 42
280 2019-09-11 8 11 12 30 31 49
281 2019-09-14 1 3 24 28 31 41
282 2019-09-18 3 24 26 29 45 50
283 2019-09-21 2 20 31 43 45 54
284 2019-09-25 5 9 26 38 41 44
285 2019-09-28 16 18 39 45 49 54
286 2019-10-02 9 26 39 42 47 49
287 2019-10-05 6 10 18 24 32 37
288 2019-10-09 14 18 19 27 33 41
289 2019-10-12 3 11 15 29 44 49
290 2019-10-16 12 15 25 39 46 49
291 2019-10-19 19 29 41 46 50 51
292 2019-10-23 4 5 11 35 44 50
293 2019-10-26 1 2 26 41 42 54
294 2019-10-30 10 11 28 31 40 53
[295 rows x 7 columns]
A: Here is a concise way with bs4 4.7.1+ that uses :not to exclude header and zip to combine columns for output. Results are as on page. Session is used for efficiency of tcp connection re-use.
import requests, re, csv
from bs4 import BeautifulSoup as bs
dates = []; winning_numbers = []
with requests.Session() as s:
for year in range(2017, 2020):
r = s.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
soup = bs(r.content)
dates.extend([i.text for i in soup.select('.win-nbr-date:not(.blue-bg)')])
winning_numbers.extend([re.sub('\s+','-',i.text.strip()) for i in soup.select('.nbr-list')])
with open("lottery.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
w.writerow(['date','numbers'])
for row in zip(dates, winning_numbers):
w.writerow(row)
A: This one works:
import requests
from bs4 import BeautifulSoup
import io
import re
def main():
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2018')
soup = BeautifulSoup(page.content,'html.parser')
week = soup.find(class_='win-number-table row no-brd-reduis')
wn = (week.find_all(class_='nbr-grp'))
file = open ("vit.txt","w+")
for winning_number in wn:
line = remove_html_tags(str(winning_number.contents).strip('[]'))
line = line.replace(" ", "")
file.write(line + "\n")
file.close()
def remove_html_tags(text):
import re
clean = re.compile('<.*?>')
return re.sub(clean, '', text)
This part of the code loops through the wn variable and writes every line to the "vit.txt" file:
for winning_number in wn:
line = remove_html_tags(str(winning_number.contents).strip('[]'))
line = line.replace(" ", "")
file.write(line + "\n")
file.close()
The "stripping" of the <li> tags could be probably done better, e.g. there should be an elegant way to save the winning_number to a list and print the list with 1 line. | unknown | |
d16364 | val | This is the default behaviour of Mobile adaptive card actions. Adaptive card renders the buttons according to the width of the screens and provides you a scroll bar below to scroll through the buttons.
A: Updated Answer:
This is a known issue in the MS Teams Mobile App already raised with the team here:
https://github.com/microsoft/AdaptiveCards/issues/3919
Someone is working on it and it should be solved in the next month. | unknown | |
d16365 | val | Yes, you can enroll the Identity again using the same secret. Assuming that the max number of enrollments has not been exceeded - but the default is "-1" (unlimited).
FYI each time you enroll you get different credentials, but they are valid for the same Identity. | unknown | |
d16366 | val | call_user_func_array($func,$parameters);
$func is function name as string , $parameters is parameteres to $func as array.
read the doc :-
http://php.net/manual/en/function.call-user-func-array.php
usage:-
<?php
function abc($str){
print $str;
}
call_user_func_array("abc",array('Working'));
?>
When it put in your question:-
public function docut($url){
global $filesize77;
global $cutpost;
$cutarray = array('cuturls', 'adlinkme', 'cutearn', 'cutwin');
if(empty($cutpost) or $cutpost===$cutarray[3]){
if($filesize77 <= '1073741824'){
return array(call_user_func_array(array($this,$cutarray[0]),$url),$cutarray[0]);
}else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){
return array( call_user_func_array(array($this,$cutarray[0]),call_user_func_array(array($this,$cutarray[0]),$url)),$cutarray[0]);
}else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){
return array(call_user_func_array(array($this,$cutarray[0]),call_user_func_array(array($this,$cutarray[1]),call_user_func_array(array($this,$cutarray[2]),$url))),$cutarray[0]);
}
}
}
A: Just use the {..}(..) syntax. I.e $this->{$cutarray[0]}(...)
public function docut($url){
global $filesize77;
global $cutpost;
$cutarray = ['cuturls', 'adlinkme', 'cutearn', 'cutwin'];
if(empty($cutpost) or $cutpost===$cutarray[3]){
if($filesize77 <= '1073741824') {
return [$this->{$cutarray[0]}($url), $cutarray[0]];
} else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){
return [$this->{$cutarray[0]}($this->$cutarray[1]($url)), $cutarray[0]];
} else if($filesize77 > '2147483648' and $filesize77 <= '3221225472') {
return [$this->{$cutarray[0]}($this->{$cutarray[1]}($this->{$cutarray[2]}($url))), $cutarray[0]];
}
}
If you add more cases to this function, you should really think about wrapping this inside an loop or something else. Currently your code is very hard to read and understand...
public function docut($url){
global $filesize77;
global $cutpost;
$cutarray = ['cuturls', 'adlinkme', 'cutearn', 'cutwin'];
if(empty($cutpost) or $cutpost === $cutarray[3]) {
switch {
case: $filesize77 > 0x80000000 && $filesize77 <= 0xC0000000:
$url = $this->{$cutarray[2]}($url);
case: $filesize77 > 0x40000000 && $filesize77 <= 0x80000000:
$url = $this->{$cutarray[1]}($url);
case $filesize77 < 0x40000000;
$url = $this->{$cutarray[0]}($url);
}
return [$url, $cutarray[0]];
}
} | unknown | |
d16367 | val | You could potentially add a global variable in the function like this:
def change():
global y
y="changed!"
y="hello"
change()
print(y)
However, I wouldn't really recommend this as it could lead to minor bugs later on. | unknown | |
d16368 | val | Use three separate instance variables in your view controller to store the table views. Then in the delegate methods you can do something like this:
if (tableView == myFirstTableView) {
// Do whatever you need for table view 1.
} else if (tableView == mySecondTableView) {
// Do whatever you need for table view 2.
} | unknown | |
d16369 | val | http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
Best tutorial for trace the error.
A: Run your app under the debugger, then when your app crashes you will have access to the call stack.
Furthermore, if you display the console window, you will get more textual information (including a call stack) at the moment of the crash.
If you are using Xcode 4, have a look at the attached picture.
A: You have to set Exception Breakpoint
Go to the Breakpoints navigator, click the + button at the bottom, and add an Exception Breakpoint.
Now you will know the exact line where any of your exception will occur (e.g. line of crash). best of luck!! | unknown | |
d16370 | val | You can use this redirect rule in your site root .htaccess:
RedirectMatch 301 ^/(.+)\.asp$ /$1/
A: I'm not sure that works on wordpress, you can make it using PHP like
$currentUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
if(strpos($currentUrl, ".asp")) {
header("HTTP/1.1 301 Moved Permanently");
$currentUrl = str_replace(".asp", "/", $currentUrl);
header("Location:". $currentUrl);
die();
} | unknown | |
d16371 | val | Most likely this is caused by some race conditions due to the fact that you modify the array from multiple threads. And if two threads happen to try and alter the array at the same time, you get into problems.
Make sure you serialize the access to the array, this should solve the problem. You can use a semaphore for that:
var profWorkDaysBreak = [time_workbreaks]()
let groupServiceWorkDayBreaks = DispatchGroup()
let semaphore = DispatchSemaphore(value: 0)
...
profWorkDays.forEach { workDay in
groupServiceWorkDayBreaks.enter()
time_workbreaks.getAll(weekDayId: workDay.id) { results, error in
if let error = error {
print(error)
}
if let results = results {
// acquire the lock, perform the non-thread safe operation, release the lock
semaphore.wait()
profWorkDaysBreak.append(contentsOf: results) // The error happens here !
semaphore.signal()
}
groupServiceWorkDayBreaks.leave()
}
}
...
groupServiceWorkDayBreaks.wait()
The semaphore here acts like a mutex, allowing at most one thread to operate on the array. Also I would like to emphasise the fact that the lock should be hold for the least amount of time possible, so that the other threads don't have to wait for too much.
A: Here is the only way i got my code running reliable so far..
i skipped contents of completely and just went to a forEach Loop
var profWorkDaysBreak = [time_workbreaks]()
let groupServiceWorkDayBreaks = DispatchGroup()
...
///WorkdaysBreakENTER AsyncCall
//UnreliableCode ?
profWorkDays.forEach {workDay in
groupServiceWorkDayBreaks.enter()
time_workbreaks.getAll(weekDayId: workDay.id) { results, error in
if let error = error {
print(error)
}
if let results = results {
results.forEach {profWorkDayBreak in
profWorkDaysBreak.append(profWorkDayBreak)
}
/*
//Alternative causes error !
profWorkDaysBreak.append(contentsOf: results)
*/
}
groupServiceWorkDayBreaks.leave()
}
}
...
groupServiceWorkDayBreaks.wait() | unknown | |
d16372 | val | This is a version issue. You've somehow found a link for the development version of Django, while you're using release 1.4. One of the things that's changed since the release is that URL names in templates used not to need quotes, but now they do. That's why the error message has the URL name within two sets of quotes.
You should use this version of the tutorial to match the Django version you have. (You could install the development version, but that's not recommended - stick to the release.) | unknown | |
d16373 | val | I don't see a built-in way to do it.
However, it's definitely possible to implement on your own.
Just create a transaction class representing each call you make to a NetConnection instance.
This transaction class, for example "NetTransaction", should keep a private static list of all active transactions, and should store the result handler function in a private instance variable that is to be called when a transaction completes (on result, on status, or on timeout). Note that this handler is unified, so it handles all kinds of results (success/error/timeout/canceled).
In your transaction class's constructor, add "this" new instance to the active transactions list, start a timeout timer if a non-zero timeout is specified (adding an event listener pointing to the cancelTransaction function described below), and then perform the network call last.
When you complete a transaction (success/error/timeout/canceled), remove it from the active transactions list, cancel the timeout timer if one was set, and finally forward a meaningful result to the result handler function.
The trick to making this all work is that you must create result and status handler functions in the transaction class, and pass THOSE to your call to NetConnection. Those two functions will be responsible for INTERCEPTING the network result (result or status), completing the transaction (as described above), and forwarding a unified result to the REAL result handler function that was passed to the constructor.
Here's the stripped down insides of the base NetTransaction class with the basic necessities. My implementation has more stuff, including generating transaction ids (just a simple static counter, a method for looking up an active transaction by id number. It also has overridable get/set methods for the transaction's data object, so I can have automatic header wrapping/unwrapping for custom data protocols in classes deriving from NetTransaction (e.g. WidgetNetTransaction).
static private var active_transactions:Array = new Array(); //active network requests pending a result
static private var transaction_count:int = 0; //incremented each time a NetTransaction instance is created so each one can have a unique transaction id number assigned to it
private var transaction_id:int; //Transaction identifier, which may assist a widget in managing its own concurrent transactions. It comes from a static field, auto-incremented in the NetTransaction constructor, so it is always unique for each NetTransaction within the current session... unless more than 2147483648 transactions occur in a single session and the value wraps around, but by then, old transactions wil be forgotten and there shouldn't be any problems as a result.
private var description:String; //an optional description string to describe the transaction or what it is supposed to do (especially for error-reporting purposes).
private var request_data:Object; //this stores the data that will be forwarded to your web server
private var result_handler:Function; //this is the method to be called after intercepting a result or status event. it's left public, because it's acceptable to modifiy it mid-transaction, although I can't think of a good reason to ever do so
private var internal_responder:Responder; //internal responder attached to the transaction
private var timeout:int;
private var timeout_timer:Timer;
//Constructor
public function NetTransaction( network_service:NetworkService, request_data:Object, result_handler:Function = null, description:String = null, timeout:int = 0 )
{
//Throw something a little more friendly than a null-reference error.
if (network_service == null)
throw new ArgumentError( "A NetworkService object must be specified for all NetTransaction objects." );
if (timeout < 0)
throw new ArgumentError( "Timeout must be 0 (infinite) or greater to specify the number of milliseconds after which the transaction should be cancelled.\rBe sure to give the transaction enough time to complete normally." );
//Save information related to the transaction
this.result_handler = result_handler;
this.request_data = request_data;
this.internal_responder = new Responder( net_result, net_status ); //should use override versions of these methods
this.description = description;
this.timeout = timeout;
this.timeout_timer = null;
//Grab a new transaction id, add the transaction to the list of active transactions, set up a timeout timer, and finally call the service method.
this.transaction_id = transaction_count++;
active_transactions.push( this ); //transaction is now registered; this is done BEFORE setting the timeout, and before actually sending it out on the network
if (timeout > 0) //zero, represents an infinite timeout, so we'll only create and start a timer if there is a non-zero timeout specified
{
timeout_timer = new Timer( timeout, 1 );
timeout_timer.addEventListener( TimerEvent.TIMER, this.cancelTransaction, false, 0, true );
timeout_timer.start();
}
network_service.call( internal_responder, request_data );
}
//Finalizes a transaction by removing it from the active transactions list, and returns true.
//Returns false to indicate that the transaction was already complete, and was not found in the active transactions list.
private function completeTransaction():Boolean
{
var index:int = active_transactions.indexOf( this );
if (index > -1)
{
active_transactions.splice( index, 1 );
if (timeout_timer != null)
{
timeout_timer.stop();
timeout_timer.removeEventListener( TimerEvent.TIMER, this.cancelTransaction, false );
}
return true;
}
else
{
//Transaction being removed was already completed or was cancelled
return false;
}
}
//An instance version of the static NetTransaction.cancelTransaction function, which automatically passes the transaction instance.
public function cancelTransaction( details_status_object:Object = null )
{
NetTransaction.cancelTransaction( this, details_status_object );
}
//Cancels all active transactions immediately, forcing all pending transactions to complete immediately with a "NetTransaction.Call.Cancelled" status code.
static public function cancelAllActiveTransactions( details_status_object:Object )
{
for each (var transaction:NetTransaction in active_transactions)
transaction.cancelTransaction( details_status_object );
}
//Cancels the transaction by spoofing an error result object to the net_status callback.
static public function cancelTransaction( transaction:NetTransaction, details_status_object:Object )
{
//Build cancel event status object, containing somewhat standard properties [code,level,description,details,type].
var status:NetTransactionResultStatus = new NetTransactionResultStatus(
"NetTransaction.Call.Cancelled",
"error", //cancelling a transaction makes it incomplete, so the status level should be "error"
"A network transaction was cancelled. The description given for the transaction was: " + transaction.description,
details_status_object, //include, in the details, the status object passed to this method
"" //no type specified
);
//Call the net_status handler directly, passing a dynamic Object-typed version of the NetTransactionResultStatus to the net_status handler.
transaction.net_status( status.ToObject() );
}
//Result responder. Override, then call when you're ready to respond to pre-process the object returned to the result_handler.
protected function net_result( result_object:Object ):void
{
if (completeTransaction())
if (result_handler != null)
result_handler.call( null, new NetTransactionResult( this, result_object, null ) );
}
//Status responder. Override, then call when you're ready to respond to pre-process the object returned to the result_handler.
protected function net_status( status_object:Object ):void
{
if (completeTransaction())
if (result_handler != null)
result_handler.call( null, new NetTransactionResult( this, null, NetTransactionResultStatus.FromObject( status_object ) ) );
}
The NetTransactionResult and NetTransactionResultStatus classes are just simple data classes I've set up for type-safe results to be sent to a unified result handler function. It interprets results as an error if the NetTransactionResult has a non-null status property, otherwise, it interprets the result as a success and uses the included data. The NetworkService class you see is just a wrapper around the NetConnection class that handles specifying the call path, and also handles all the low-level NetConnection error events, packages status messages compatible with the NetTransaction class, and finally calls cancelAllTransactions.
The beauty of this setup is that now no matter what kind of error happens, including timeouts, your result handler for a transaction will ALWAYS be called, with all the information you need to handle the result (success/error/timeout/canceled). This makes using the NetConnection object almost as simple and reliable as calling a local function!
A: Not really. Unless you write your own functionality for aborting after a specified amount of time, using a Timer object (or better, a GCSafeTimer object, if you don't know that one, google it). | unknown | |
d16374 | val | You have real mess in your code. Firstly you shouldn't connect to web in main thread (it blocks app, cause "application not responding"). For fetching JSON I would recommend RoboSpice.
Secondly in ImageAdapter.getItem you should return MyArr.get(position) not position.
A: I think greenapps and MAGx2 have the right hints for the solution.
I'd like to add that it might be better to use a few open source libraries for the other things.
*
*picasso for image downloading + displaying
*gson for json parsing
*okhttp for normal downloads
Also, don't use things like this:
imageView.getLayoutParams().height= 100;
It really messes up when you view on other devices with different DPI | unknown | |
d16375 | val | Try this
import numpy as np
import pandas as pd
sample_date = { 'countries': ['USA','Canada','USA','UK','USA','UK','DE'],
'car_type': ['sedan','sedan','Hatchback','coupe','sedan','coupe','coupe'],
'years': [2010,2010,2011,2011,2017,2017,2010],
'price': [4000,np.NaN,4000,4000,np.NaN,np.NaN,4000]}
data = pd.DataFrame(sample_date)
fillValue = 4000
data['price'].fillna(value=fillValue, inplace=True)
print('update Dataframe:')
print(data)
mean_value=data['price'].mean()
print(mean_value)
answer will be 4000 as I'm replacing NaN with neighbors as '4000' | unknown | |
d16376 | val | I might help:
IF ( select count(1) from ( _your selection_ ) a ) > 0 THEN
_RUN your script_;
END IF
A: this is one way:
DECLARE
type t1
IS
TABLE OF hr.employees.first_name%type;
t11 t1;
BEGIN
SELECT e.first_name bulk collect
INTO t11
FROM hr.employees e
WHERE E.EMPLOYEE_ID=999;
IF(t11.count! =0) THEN
FOR i IN 1..t11.count/*here you can write your own query */
LOOP
dbms_output.put_line(t11(i));
END LOOP;
ELSE
dbms_output.put_line('oh..ho..no rows selected' );
END IF;
END;
/
any clarification plz let me know.. | unknown | |
d16377 | val | Easiest way would be to use -edge detection followed by histogram: & text:. This will generate a large list of pixel information that can be passed to another process for evaluation.
convert 120c6af0-73eb-11e4-9483-4d4827589112_embed.png \
-edge 1 histogram:text:- | cut -d ' ' -f 4 | sort | uniq -c
The above example will generate a nice report of:
50999 #000000
201 #FFFFFF
As the count of white pixels is less then 1% of black pixels, I can say the image is empty.
This can probably be simplified by passing -fx information to awk utility.
convert 120c6af0-73eb-11e4-9483-4d4827589112_embed.png \
-format '%[mean] %[max]' info:- | awk '{print $1/$2}'
#=> 0.00684814
A: If you are talking about the amount of opaque pixels vs the amount of transparent pixels, then the following will tell you the percentage of opaque pixels.
convert test.png -alpha extract -format "%[fx:100*mean]\n" info:
39.0626
Or if you want the percentage of transparent pixels, use
convert test.png -alpha extract -format "%[fx:100*(1-mean)]\n" info:
60.9374 | unknown | |
d16378 | val | You need a value to edit $firstDayOfMonth based on the first day of the array (in this example i am starting on monday) using October 2012:
<?php
function testme() {
$month = 10;
$year = 2012;
$days = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
echo $firstDayOfMonth = date('w',mktime(0,0,0,$month,1,$year)); // a zero based day number
/* IMPORTANT STATEMENT
value based on the starting day of array
E.G. (starting_day = value):
Tuesday = 5
Wednesday = 4
Thursday = 3
Friday = 2
Saturday = 1
Sunday = 0
Monday = -1
*/
$firstDayOfMonth = $firstDayOfMonth - 1;
/* END IMPORTANT STATEMENT */
$daysInMonth = date('t',mktime(0,0,0,$month,1,$year));
$calendar = ' <!-- start cal -->';
$calendar = '<table border="1" class="calendar">'."\r\n";
$calendar .= '<thead><tr><th class="calendar-day-head">'.implode('</th><th class="calendar-day-head">',$days ).'</th></tr></thead><tbody>';
$calendar .= "\r\n".'<tr class="calendar-row">';
$calendar .= str_repeat('<td class="calendar-day-np"> </td>', $firstDayOfMonth); // "blank" days until the first of the current week
$calendar .= '';
$dayOfWeek = $firstDayOfMonth + 1; // a 1 based day number: cycles 1..7 across the table rows
for ($dayOfMonth = 1; $dayOfMonth <= $daysInMonth; $dayOfMonth++)
{
$date = sprintf( '%4d-%02d-%02d', $year, $month, $dayOfMonth );
$calendar .= '';
$calendar .= '<td class="calendar-day">
'.$dayOfMonth.' <br />';
$calendar .= '';
$calendar .= '</td>'."\r\n";
if ($dayOfWeek >= 7)
{
$calendar.= '</tr>'."\r\n";
if ($dayOfMonth != $daysInMonth)
{
$calendar .= '<tr class="calendar-row">';
}
$dayOfWeek = 1;
}
else
{
$dayOfWeek++;
}
}
//echo 8-$dayOfWeek;
$calendar .= str_repeat('<td class="calendar-day-np"> </td>', 8 - $dayOfWeek); // "blank" days in the final week
$calendar .= '</tr></table>';
$calendar .= ' <!-- end cal -->';
echo $calendar;
}
?>
The /* IMPORTANT STATEMENT */ is key because the mktime() method creates the date based on Sunday being the first day of the week so this overrides it.
See Result Here: Link | unknown | |
d16379 | val | Is the linked spreadsheet opened on the desktop? What happens if you create a new sheet in the same folder and try to open it instead?
A: I think SQL Server needs to access to TEMP folders to copy or create some files.
If the folder does not exist or ther SQL Service account does not have enough permission to access the folders, you'll get the exception.
Run Procmon.exe on the server and execute the query again. You can see what's happening and where the SQL Server wants to access. | unknown | |
d16380 | val | You can try to match the date with a regular expression (this one ensures that it matches the format (DD/MM/YYYY or MM/DD/YYYY):
if (date.match( /^\d{2}\/\d{2}\/\d{4}$/ )) {
alert("Valid input!");
} else {
alert("Wrong input!");
}
This regular expression /^\d{2}\/\d{2}\/\d{4}$/ returns true if the string matches the following pattern:
*
*2 digits
*Forward slash
*2 digits
*Forward slash
*4 digits
Here's a JS Fiddle that shows it working.
Here's another (more "Eloquent") solution (return a JavaScript Date through a function):
function findDate(string) {
var dateTime = /(\d{2})\/(\d{2})\/(\d{4})/;
var match = dateTime.exec(string);
return new Date(Number(match[3]),
Number(match[2]) - 1,
Number(match[1]));
}
alert(findDate("30-01-2003"));
Also - I'd recommend reading Regular Expressions - Eloquent JavaScript
A: If you want to validate the format and that it's a valid date, you have to check the values. That can be done with a regular expression but it's much simpler using a Date, e.g.
// Validate dd/mm/yyy date string
function isValidDMY(s) {
var b = s.split('/');
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1];
}
console.log(isValidDMY('4/4/2015')); // true
console.log(isValidDMY('29/2/2015')); // false
There really is no point in insisting on leading zeros for single digit numbers for user input dates, so the above accepts either 4/4/2015 or 04/04/2015.
Edit
If you insist on leading zeros for day and month number, you can check that too by changing the last line to:
return /^(\d\d\/){2}\d{4}$/.test(s) && d && d.getMonth() == b[1]; | unknown | |
d16381 | val | Printing nodes whose grandparent is a multiple of 5 is complicated as you have to look "up" the tree. It is easier if you look at the problem as find all the nodes who are a multiple of 5 and print their grandchildren, as you only have to go down the tree.
void printGrandChildren(BSTNode<Key,E> *root,int level) const{
if(!root) return;
if(level == 2){
cout<<root->key()<<" ";
return;
}else{
printGrandChildren(root->left(),level+1);
printGrandChildren(root->right(),level+1);
}
}
Then modify your findNodes to
void findNodes(BSTNode<Key,E> *root) const
{
if(root==NULL) return;
else
{
if(root->key()%5==0)
{
printGrandChildren(root,0);
}
else
{
findNodes(root->left());
findNodes(root->right());
}
}
}
A: Try this:
int arr[height_of_the_tree]; //arr[10000000] if needed;
void findNodes(BSTNode<Key,E> *root,int level) const {
if(root==NULL) return;
arr[level] = root -> key();
findNodes(root -> left(), level + 1);
if(2 <= level && arr[level - 2] % 5 == 0) cout << root->key() << " ";
findNodes(root -> right(), level + 1);
}
int main() {
...
findNodes(Binary_search_tree -> root,0);
...
}
A: If you're just trying to print our all child nodes which have an ancestor which has a key which is a multiple of 5, then one way would be to pass a bool to your findNodes function which stores this fact.
Something along the lines of:
void findNodes(BSTNode<Key,E>* node, bool ancesterIsMultOf5) const
{
if (node)
{
if (ancesterIsMultOf5)
std::cout << node->key() << std::endl;
ancesterIsMultOf5 |= (node->key() % 5 == 0);
findNodes(node->left(), ancesterIsMultOf5);
findNodes(node->right(), ancesterIsMultOf5);
}
}
Alternately, if you're trying to draw the tree, it has been answered before: C How to "draw" a Binary Tree to the console
A: Replace the following
cout<<root->key()<<" ";
with
if(root->left)
{
if(root->left->left)
cout<<root->left->left->key()<< " ";
if(root->left->right)
cout<<root->left->right->key()<< " ";
}
if(root->right)
{
if(root->right->left)
cout<<root->right->left->key()<< " ";
if(root->right->right)
cout<<root->right->right->key()<< " ";
} | unknown | |
d16382 | val | We can do something using two main figures:
*
*openpyxl package to retrieve the data from the Excel sheet.
pip3 install openpyxl
*String Operation to compare the value if its == 15 minutes:
*Insert into a list.
*If you want to appened it into the Excel sheet, again. Please, check this reference writing into Excel using openpyxl
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:\\Users\\Admin\\Desktop\\demo.xlsx"
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
m_row = sheet_obj.max_row
aList = []
# Loop will print all values
# of first column
for i in range(2, m_row + 1):
cell_obj = sheet_obj.cell(row = i, column = 1)
if (cell_obj.value[:-2] == 15):
aList.append(cell_obj.value)
For more information about openpyxl, please check this hyperlink;
How to read from Excel sheet using openpyxl
A: I managed to find a solution using Python, so this is no longer an issue. Thank you.
data2 = data.set_index('Time').resample('15T').mean()
data2 | unknown | |
d16383 | val | As for Facebook, unfortunately this is not possible using email since users may choose not to share their real email with you.
One way, for Facebook, is to store the Facebook user id (you should be doing this anyway) and retrieve the newly registered user friends' ids and check if any of these ids present in your DB.
A: I implemented this on one of my sites. When users register for an account, I require an email address. I give them an option to find their email accounts (gmail, hotmail, aol, and yahoo all have oauth services you can use to get contacts). I also give them the option for LinkedIn, Facebook, and Twitter. This doesn't work as well as those 3 social networks won't disclose email addresses (and rightfully so). So each user that authenticates, I log their id from that service. Then I get the id's of their friends, and see if any of those friends have associated their account with my site. The key for this to work is to encourage your users to associate those accounts. | unknown | |
d16384 | val | Since the ServerVariables indexer returns a string, your code snippet calls the GetHostEntry string overload. Its documentation describes a three-step lookup algorithm, with two separate queries. The GetHostEntry IPAddress overload documentation doesn't describe any similar process, so perhaps it saves a query. Then again, it seems to provide the same info (all IP address and host names), so maybe it's the same, but just documented differently. | unknown | |
d16385 | val | You will need to edit your question with your adapter's XML as well as implementation JavaScript...
Also, make sure to read the SQL adapters training module.
What you need to do is have your function get the values:
function myFunction (value1, value2) { ... }
And your SQL query will use them, like so (just as an example how to pass variables to any SQL query, doesn't matter if it contains an IN condition or not):
SELECT * FROM person where name='$[value1]' or id=$[value2];
Note the quotation marks for value1 (for text) and lack of for value2 (for numbers). | unknown | |
d16386 | val | If $handler is an instance of PDO you could do it like this:
<?php
require_once JPATH_SITE.'/includes/dbAudio.php';
// Audio id is stored in `$_GET['recordID']`
$stmt = $handler->prepare('SELECT * FROM audio WHERE id = ?');
$stmt->bindParam(1, $_GET['recordID']);
$stmt->execute();
$r = $stmt->fetch(PDO::FETCH_OBJ);
print_r($r);?>
According to what properties are there in $r you can output them. | unknown | |
d16387 | val | "I have put the headers into my src/ directory of my project, so I am able to include them with "
That's not the usual way to do! You should have an installation of this library in your environment (there are some instructions how to do this for your particular case available in this tutorial from the libnoise online documentation), and add the additional include paths to search using the
Project Properties->C/C++ Build->Settings-><actual C++ Compiler>->Includes->Include paths (-I)
settings.
"Are there any other configurations I am missing?"
Check the
Project Properties->C/C++ Build->Settings-><actual toolchain linker>->Libraries
properties page.
You'll need to provide noise in the Libraries list there, and eventually an additional Library search path pointing to the actual libs installation. The latter depends on how and where you have the libnoise installed in your environment. | unknown | |
d16388 | val | My 5 cents:
*
*The only way to have things as smooth as possible is to read whatever the INSTALL/README/other instructions say and follow them as closely as possible. Try the default options first. No other silver bullets, really.
*If things don't go smooth, bluntly copy-paste the last error message into google. With high probability you are not the first one to get it and you'll easily find the fix.
*If you are the first one to get it, re-read INSTALL/README and think twice on what might be the peculiarity of your particular system config. If you don't know of any, prepare for longer battles. Whenever possible, I would avoid dealing with software that gets me to this point.
*An exception to the above rule is a linker error. Those are usually easy to understand and most often mean that your system libraries don't match the ones expected by the software. Re-read documentation, fetch the correct libraries, recompile. On some distributions this might be a lot of pain, though.
*My personal experience shows that whenever I get a compilation error which I can't resolve easily, going into the code and looking at the specific line which caused the error helps more than anything else.
Excuse me if that's all obvious stuff.
A: *
*Understand what are the steps in general/particular build process (feature checks, dependency checks, generation of derived sources, compilation, linking, installation, etc.)
*Understand the tools used for the above (automake might be an exception here :)
*Check the prerequisites (OS and libraries versions, additional packages, etc.)
*Have a clean build environment - installing everything with all possible features on the same system will sure get you into dependency conflicts sooner or later.
Hope this helps. | unknown | |
d16389 | val | It would appear that when running headless chrome from, at least, inside Visual Studio the "no-sandbox" option is required.
options.AddArgument("no-sandbox");
Found by accident here:
https://stackoverflow.com/a/39299877/71376 | unknown | |
d16390 | val | When looking for all implementations of a given super method, the AST is of little help, as even with its bindings it only has references from sub to super but not the opposite direction.
Searching in the opposite direction uses the SearchEngine. If you look at JavaElementImplementationHyperlink the relevant code section can be found around line 218 (as of current HEAD)
You will have to first find the IMethod representing the super method. Then you prepare a SearchRequestor, an IJavaSearchScope, and a SearchPattern before finally calling engine.search(..). Search results are collected in ArrayList<IJavaElement> links.
A good tradition of Eclipse plug-in development is "monkey see, monkey do", so I hope looking at this code will get you started on your pursuit :) | unknown | |
d16391 | val | To find all text within double quotes, try this.
grep -o '"[^"]*"' list.txt
The single quotes are to prevent the pattern from the shell; the actual pattern says to match a double quote, followed by a sequence of characters which are not double quote, followed by another double quote. The -o option to grep says to only print the matches (the default is to print the whole line when there is a match on the pattern).
A: perl -nle'print $1 while /"([^"]*)"/g' list.txt
With GNU grep if you have one occurrence per line:
grep -Po '(?<=")[^"]*(?=")' list.txt
A: kent$ echo 'File "abc.txt" not found.'|sed -r 's/.*"([^"]*)".*/\1/g'
abc.txt
A: echo 'File "abc.txt" not found.' | awk '{print substr($2,2,length($2)-2)}' | unknown | |
d16392 | val | The error is self-explanatory: chrome.sockets is undefined.
There's no sockets API in the extension documentation, but it is defined for the chrome apps. | unknown | |
d16393 | val | To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div> | unknown | |
d16394 | val | Why not just clone the remote repo to local repo directly?
Usually, a fork is used for the following purpose: (i don't know if it's your case or not, I can only assume)
Why to fork?
Whenever you have your own repository in which you don't want others to "touch" the code directly but you still allow others to contribute or to fix bugs, you achieve it by a fork.
The original repository is a READ-ONLY for you since you are not a contributor, the fork, on the other hand, is under your account so you have full permissions to read/write.
On your fork, you develop your changes and when you are done you are "asking" the owner of the original repository to add (merge) your changes back to his repository, you do it using pull request.
This is the logic behind the fork.
In your case, I can only assume that the "main" repository need to be monitored for all changes, why? maybe it is the main repository for distribution, might be automation manipulating this repo, and so on.
To make it short - the fork is used when the original repo is read-only to you while allowing you to contribute back to it.
A:
Why not just clone the remote repo to local repo directly?
You could indeed do that. But then how would you make a pull request?
Pull requests are not a Git feature. Instead, they are an add-on, provided by various web hosting providers such as Bitbucket and GitHub. (Compare with the email messages from git request-pull; git request-pull is a Git feature. You can run git request-pull locally.
Note that because they are an add-on, each adder-on-er (is that an actual word?) may have a few tweaks of their own, that the other doesn't, but there's something pretty common here: A GitHub pull request can only be created using the GitHub web site. Unless you can write directly to the original GitHub repository, this requires creating a GitHub fork. A Bitbucket pull request can only be created using the Bitbucket web site. Unless you can write directly to the original Bitbucket repository, this requires creating a Bitbucket fork.
Assuming this pattern holds for GitLab—I have not used GitLab and can't say for sure, but it seems awfully likely—that would explain why you have to create a GitLab fork. | unknown | |
d16395 | val | The stored procedure was bombing out, someone said you can step through sql storec procedures from VS, how do I do that? | unknown | |
d16396 | val | I found an example here -
*
*How to play an android notification sound
This is the code that is used
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
ring.play();
} catch (Exception e) {}
On the other hand, if you want to customize the sound (as I ausume you do), you should use this code taken from here
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE
;
A: Simply put this below code inside the block which will be triggered when notification occurs..
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.mySound);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true); // Set false if you don't want it to loop
mMediaPlayer.start(); | unknown | |
d16397 | val | Create a static class. Something like this:
public static class ClientConfig{
public static string Name{get;set;}
public static bool IsAdult{get;set;}
public static int Age{get;set;}
public static void Load(){
// load your values
// ClientConfig.Name = name from file etc.
}
public static void Save(string newName, int age, bool value){
// save your values to the config file
}
}
And call ClientConfig.Load() first time when your app starts, for example (or whenever you need to retrieve config data)
A: It really looks to me that you need to access a field in a lazy way (i.e. only if needed, when needed). If so .NET has Lazy class for such cases which also provides thread safety out of the box:
public static Lazy<string> Name { get; } = new Lazy<string>(() => ReadNameFromFile());
Lazy will also ensure that you only create value once (i.e. call initiailization method) and on later calls it will simply return already retrieved value. | unknown | |
d16398 | val | You could use a Datagrid as well, with each column pointing to the appropriate part of the data source (possibly even the same field, depending on what you're doing). You can then just use the ImageCell as the renderer for the second and third colums.
I think you're just not understanding that Adobe, in the own woolly-headed little way, is separating the Model from the View on your behalf. You hand the Model to the View and then get out of the way. The extent of what you can/should change is just telling it what renderer to pop your data into.
In fact, the fl.controls don't give you much control at all about how they work--I wouldn't go down the road of trying to create a custom itemRenderer with any signifcant functionality for them if you don't fully understand how the Display List works and if you're not comfortable digging around in the debugger and ferreting out all kinds of undocumented information.
For more details (to the extent anyone knows anything about how these work), see
http://www.adobe.com/devnet/flash/quickstart/datagrid_pt1.html
http://www.adobe.com/devnet/flash/quickstart/datagrid_pt2.htmlhttp://www.adobe.com/devnet/flash/quickstart/datagrid_pt3.html
http://www.adobe.com/devnet/flash/quickstart/tilelist_component_as3.html
Do you have the option to use the Flex Framework instead of pure Flash? It makes this kind of extension much more satisfying. It's aimed more at application developers, whereas Adobe sees Flash users more as designers. | unknown | |
d16399 | val | Now on newer versions (using 12 here), in Tools/Options/Java/Gradle exists a checkbox "Prefer Maven Projects over Gradle (needs restart)", check that and you have the solution.
A: It seems that Netbeans 11 and newer will consider the project as gradle if both pom.xml and build.gradle files exist in the project.
I had the same problem and found no option to tell Netbeans that I want to treat my project as being maven and not gradle.
Solution is (as @skomisa commented) to rename build.gradle and settings.gradle to something else like build.gradle_disabled, settings.gradle_disabled and then Netbeans will see your project as maven
A: The only way I managed to convince netbeans 11 to use my pom.xml:
Close the project, close netbeans.
Clean up the cache folder (in Linux: ~/.cache/netbeans/11.0)
Restart netbeans, reopen the project. | unknown | |
d16400 | val | I was trying to do something like the original question: join a filtered table with another filtered table using an outer join. I was struggling because it's not at all obvious how to:
*
*create a SQLAlchemy query that returns entities from both tables. @zzzeek's answer showed me how to do that: get_session().query(A, B).
*use a query as a table in such a query. @zzzeek's answer showed me how to do that too: filtered_a = aliased(A).filter(...).subquery().
*use an OUTER join between the two entities. Using select_from() after outerjoin() destroys the join condition between the tables, resulting in a cross join. From @zzzeek answer I guessed that if a is aliased(), then you can include a in the query() and also .outerjoin(a), and it won't be joined a second time, and that appears to work.
Following either of @zzzeek's suggested approaches directly resulted in a cross join (combinatorial explosion), because one of my models uses inheritance, and SQLAlchemy added the parent tables outside the inner SELECT without any conditions! I think this is a bug in SQLAlchemy. The approach that I adopted in the end was:
filtered_a = aliased(A, A.query().filter(...)).subquery("filtered_a")
filtered_b = aliased(B, B.query().filter(...)).subquery("filtered_b")
query = get_session().query(filtered_a, filtered_b)
query = query.outerjoin(filtered_b, filtered_a.relation_to_b)
query = query.order_by(filtered_a.some_column)
for a, b in query:
...
A: from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
bs = relationship("B")
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('a.id'))
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)
s.add_all([A(bs=[B(), B()]), A(bs=[B()])])
s.commit()
# with_labels() here is to disambiguate A.id and B.id.
# without it, you'd see a warning
# "Column 'id' on table being replaced by another column with the same key."
subq = s.query(A, B).join(A.bs).with_labels().subquery()
# method 1 - select_from()
print s.query(A, B).select_from(subq).all()
# method 2 - alias them both. "subq" renders
# once because FROM objects render based on object
# identity.
a_alias = aliased(A, subq)
b_alias = aliased(B, subq)
print s.query(a_alias, b_alias).all() | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.