qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
9,837,050 |
In MSTest, the `[Shadowing]` attribute helps you to unit test a private method from another assembly. Here is the related link : [What is the Shadowing attribute that the VS uses when it generates unit tests?](https://stackoverflow.com/questions/3443755/what-is-the-shadowing-attribute-that-the-vs-uses-when-it-generates-unit-tests)
My questions are:
1. Should private methods be unit tested separately?
2. Is it a good (?) practice to change private method's accessor to `internal` just to make it available for unit testing in some other test project/assembly? (using `InternalsVisibleTo`)
3. If private methods get tested indirectly through the public method that calls them, can it be called "unit" testing?
|
2012/03/23
|
[
"https://Stackoverflow.com/questions/9837050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411924/"
] |
1. No, private methods should not be tested. Your application will interact with public API only. So you should test expected behavior of your class for this interaction. Private methods is a part of inner logic implementation. Users of your class should not be care how it implemented.
2. No, it is not good. See above. You should test public API only.
3. You should test only public methods. You don't care if public method will call to private method or will not until test is passed. If test fails, fix implemetation. But don't test private methods anyway.
UPDATE (how to define what to test):
Ideally (in test-first approach) test is the first user of your class. When you write test, you try to imagine how users will use your class. Users will not interact with private methods (Reflection is cheating). So and your test, as first user of your class, should not interact with private methods.
|
214,215 |

I would like to have these expressions aligned so that the kerning and slightly different character widths do not result in an uneven overall appearance. I tried using an `align` environment within `algorithm` but it resulted in errors. Here is a MWE:

```
\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Euclid’s algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
```
Source: <https://www.writelatex.com/examples/euclids-algorithm-an-example-of-how-to-write-algorithms-in-latex/mbysznrmktqf>
|
2014/11/27
|
[
"https://tex.stackexchange.com/questions/214215",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9610/"
] |
Something like this?
```
\begin{tikzpicture}
% Set horizontal range
\pgfmathsetmacro{\nx}{8}
% Set vertical range
\pgfmathsetmacro{\ny}{2.5}
\pgfmathsetmacro{\xmin}{2*(sqrt(\ny+1)-1)/\ny}
\pgfmathsetmacro{\xmint}{2/sqrt(\ny)}
\pgfmathsetmacro{\xminb}{4/\ny}
\pgfmathsetmacro{\xmax}{2*\nx}
\begin{axis}[xmin=0,xmax=\xmax,axis x line*=middle, axis y line*=left, xtick=\empty, ytick=\empty]
\addplot[red,domain=\xmin:\xmax,samples=100]{1/x^2-1/x};
\addplot[domain=\xminb:\xmax,samples=100]{-1/x};
\addplot[domain=\xmint:\xmax,samples=100]{1/x^2};
\end{axis}
\end{tikzpicture}
```
You can set the horizontal and vertical range in the first lines, the units for nx and ny are the coordinates of the minimum point of the graph.
|
46,044,981 |
I have the following code:
```
func TestRemoveElement(t *testing.T) {
nums := []int{3, 2, 2, 3}
result := removeElement(nums, 3)
if result != 2 {
t.Errorf("Expected 2, but it was %d instead.", result)
}
}
func removeElement(nums []int, val int) int {
for i, v := range nums {
if v == val {
nums = append(nums[:i], nums[i+1:]...)
}
}
return len(nums)
}
```
The statement inside the `if` statement is the most popular way of replacing an element in a slice per this [answer](https://stackoverflow.com/questions/25025409/delete-element-in-a-slice). But this fails deleting the last element due to `i+1`. i.e if a match is found in the last element, `i+1` is out of bounds. What better way to replace elements that considers last elements?
|
2017/09/04
|
[
"https://Stackoverflow.com/questions/46044981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5241780/"
] |
It looks like you are trying to remove all elements equal to `val`. One way to do this is to copy values not equal to `val` to the beginning of the slice:
```
func removeElement(nums []int, val int) []int {
j := 0
for _, v := range nums {
if v != val {
nums[j] = v
j++
}
}
return nums[:j]
}
```
Return the new slice instead of returning the length. It will be more convenient for the caller.
If you only want to remove the first element equal to `val`, then use this code:
```
func removeElement(nums []int, val int) []int {
for i, v := range nums {
if v == val {
return append(nums[:i], nums[i+1:]...)
}
}
return nums
}
```
|
19,640,710 |
My buttons aren't lining up correctly... whats wrong?
```
private void loadPuzzleButtons()
{
if (active_puzzle != null)
{
int devider = 5;
int count = 0;
JToggleButton puzzleButton[] = new JToggleButton[active_puzzle.getNumberOfPieces()];
for(int row = 0; row < active_puzzle.getRows(); row++)
{
for(int column = 0; column < active_puzzle.getColumns(); column++)
{
puzzleButton[count] = new JToggleButton(new ImageIcon( active_puzzle.getPieces()[count].getPieceImage() ) );
puzzleButton[count].setLocation(200 + active_puzzle.getPieceWidth() * column + devider * column,
200 + active_puzzle.getPieceHeight() * row + devider * row);
puzzleButton[count].setContentAreaFilled(false);
puzzleButton[count].setBorderPainted(false);
puzzleButton[count].setBorder(null);
mainPuzzlerPanel.add(puzzleButton[count]);
mainPuzzlerPanel.validate();
count++;
}
}
mainPuzzlerPanel.repaint();
}
}
```
Here is a photo of the output: [http://i.imgur.com/Zdink2Q.png](https://i.imgur.com/Zdink2Q.png)

Sorry I'd give you my whole code but its larger and well I'm not going to do that...
Thank you in advance, do ask if you need more info!
I figured it out to those who wan't to see how I solved the problem.
```
private void loadPuzzleButtons()
{
if (active_puzzle != null)
{
int count = 0;
GridLayout puzzleLayout = new GridLayout(active_puzzle.getRows(),active_puzzle.getColumns(),3,3);
puzzlePanel.setLayout(puzzleLayout);
JToggleButton puzzleButton[] = new JToggleButton[active_puzzle.getNumberOfPieces()];
for(int row = 0; row < active_puzzle.getRows(); row++)
{
for(int column = 0; column < active_puzzle.getColumns(); column++)
{
puzzleButton[count] = new JToggleButton(new ImageIcon(active_puzzle.getPieces()[count].getPieceImage()));
puzzleButton[count].setContentAreaFilled(false);
puzzleButton[count].setBorderPainted(false);
puzzleButton[count].setBorder(null);
puzzlePanel.add(puzzleButton[count]);
puzzlePanel.validate();
count++;
}
}
puzzlePanel.repaint();
}
}
```
|
2013/10/28
|
[
"https://Stackoverflow.com/questions/19640710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4102299/"
] |
Try to use [LayoutManager](http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html) to fill panel properly
|
61,849,978 |
I'm working to show notifications from Server-Sent Event. I checked that every time the browser tries to reconnect with the source about 3 seconds after each connection is closed. That event is getting a call too fast, so my server is loaded too.
So how do I change the reopening time to increase? I have to do at least 60 seconds, so tell me how to do it?
I'm trying the following code.
```html
<table class="table" id="notification"></table>
<script type="text/javascript">
var ssevent = null;
if (!!window.EventSource) {
ssevent = new EventSource('ssevent.php');
ssevent.addEventListener('message', function(e){
if(e.data){
json = JSON.parse(e.data);
if(json){
json.forEach(function(v,i){
html = "<tr><td>"+ v.text +"</td><td>"+ v.date +"</td></tr>";
});
$('#notification').append(html);
}
}
}, false);
ssevent.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED){
console.log("Connection was closed.");
}
}, false);
} else {
console.log('Server-Sent Events not support in your browser');
}
</script>
```
The file of event stream is as follow.
```php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include_once "config.php";
$time = isset($_SESSION['last_event_time']) ? $_SESSION['last_event_time'] : time();
$result = $db->quesry("SELECT * FROM event_noti WHERE event_time < {$time} ")->rows;
$_SESSION['last_event_time'] = time();
if($result){
$json = array();
foreach ($result as $row){
$json[] = array(
'text' => $row['event_text'],
'date' => date("Y-m-d H:i", $row['event_time']),
);
}
echo "data: ". json_encode($json) . "\n\n";
flush();
}
```
|
2020/05/17
|
[
"https://Stackoverflow.com/questions/61849978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6293856/"
] |
There exist universally accepted definitions of lock-freedom and wait-freedom, and the definitions provided in your question are consistent with those. And I would strongly assume that the C++ standard committee certainly sticks to definitions that are universally accepted in the scientific community.
In general, publications on lock-free/wait-free algorithms assume that CPU instructions are wait-free. Instead, the arguments about progress guarantees focus on the *software algorithm*.
Based on this assumption I would argue that any `std::atomic` method that can be translated to a single atomic instruction for some architecture is wait-free on that specific architecture. Whether such a translation is possible sometimes depends on how the method is used though. Take for example `fetch_or`. On x86 this can be translated to `lock or`, but only if you *do not use its return value*, because this instruction does not provide the original value. If you use the return value, then the compiler will create a CAS-loop, which is lock-free, but not wait-free. (And the same goes for `fetch_and`/`fetch_xor`.)
**So which methods are actually wait-free depends not only on the compiler, but mostly on the target architecture.**
Whether it is technically correct to assume that a single instruction is actually wait-free or not is a rather philosophical one IMHO. True, it might not be guaranteed that an instruction finishes execution within a bounded number of "steps" (whatever such a step might be), but the machine instruction is still the smallest unit on the lowest level that we can see and control. Actually, if you cannot assume that a single instruction is *wait-free*, then strictly speaking it is not possible to run any real-time code on that architecture, because real-time also requires strict bounds on time/the number of steps.
---
This is what the C++17 standard states in `[intro.progress]`:
>
> Executions of atomic functions that are either defined to be lock-free (32.8) or indicated as lock-free (32.5)
> are *lock-free executions*.
>
>
> * If there is only one thread that is not blocked (3.6) in a standard library function, a lock-free execution in that thread shall complete. [ Note: Concurrently executing threads may prevent progress of a lock-free
> execution. For example, this situation can occur with load-locked store-conditional implementations. This property is sometimes termed obstruction-free. — end note ]
> * When one or more lock-free executions run concurrently, at least one should complete. [ Note: It is difficult for some implementations to provide absolute guarantees to this effect, since repeated and particularly inopportune interference from other threads may prevent forward progress, e.g., by repeatedly stealing a cache line for unrelated purposes between load-locked and store-conditional instructions. Implementations should ensure that such effects cannot indefinitely delay progress under expected operating conditions, and that such anomalies can therefore safely be ignored by programmers. Outside this document, this property is sometimes termed lock-free. — end note ]
>
>
>
---
The other answer correctly pointed out that my original answer was a bit imprecise, since there exist two stronger subtypes of wait-freedom.
* **wait-free** - A method is wait-free if it guarantees that every call finishes its execution in a *finite* number of steps, i.e., it is not possible to determine an upper bound, but it must still be guaranteed that the number of steps is *finite*.
* **wait-free bounded** - A method is wait-free bounded if it guarantees that every call finishes its execution in a *bounded* number of steps, where this bound may depend on the number of threads.
* **wait-free population oblivious** - A method is wait-free population oblivious if it guarantees that every call finishes its execution in a *bounded* number of steps, and this bound does not depend on the number of threads.
So strictly speaking, the definition in the question is consistent with the definition of *wait-free bounded*.
In practice, most wait-free algorithms are actually wait-free bounded or even wait-free population oblivious, i.e., it is possible to determine an upper bound on the number of steps.
|
48,092,940 |
Does anyone have a working function available to use within Oracle using PL/SQL which implements the Luhn Mod 16 Algorithm to generate a check digit for an input code number such as the following example? `0B012722900021AC35B2`
LOGIC
1. Map from HEX into Decimal equivalent `0 B 0 1 2 7 2 2 9 0 0 0 2 1 A C 3 5 B 2` - becomes `0 11 0 1 2 7 2 2 9 0 0 0 2 1 10 12 3 5 11 2`
2. Start with the last character in the string and move left doubling every other number -
Becomes `0 22 0 2 2 14 2 4 9 0 0 0 2 2 10 24 3 10 11 4`
3. Convert the "double" to a Base 16 (Hexadecimal) format. If the conversion results in numeric output, retain the value.
Becomes: `0 16 0 2 2 E 2 4 9 0 0 0 2 2 10 18 3 A 11 4`
4. Reduce by splitting down any resultant values over a single digit in length.
Becomes `0 (1+6) 0 2 2 E 2 4 9 0 0 0 2 2 10 (1+8) 3 A 11 4`
5. Sum all digits. Apply *the last numeric value* returned from the previous sequence of calculations (if the current value is A-F substitute the numeric value from step 1)
Becomes `0 7 0 2 2 7 2 4 9 0 0 0 2 2 10 9 3 5 11 4`
6. The sum of al l digits is 79 `(0+7+0+2+2+7+2+4+9+0+0+0+2+2+10+9+3+5+11+4)`
7. Calculate the value needed to obtain the next multiple of 16, in this case the next multiple 16 is 80 therefore the value is 1
8. The associated check character is `1`
Thanks Lee
|
2018/01/04
|
[
"https://Stackoverflow.com/questions/48092940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9172160/"
] |
How about this?
```
CREATE OR REPLACE TYPE VARCHAR_TABLE_TYPE AS TABLE OF VARCHAR2(1000);
DECLARE
luhn VARCHAR2(100) := '0B012722900021AC35B2';
digits VARCHAR_TABLE_TYPE;
DigitSum INTEGER;
BEGIN
SELECT REGEXP_SUBSTR(luhn, '.', 1, LEVEL)
BULK COLLECT INTO digits
FROM dual
CONNECT BY REGEXP_SUBSTR(luhn, '.', 1, LEVEL) IS NOT NULL;
FOR i IN digits.FIRST..digits.LAST LOOP
digits(i) := TO_NUMBER(digits(i), 'X'); -- Map from HEX into Decimal equivalent
IF digits.COUNT MOD 2 = i MOD 2 THEN -- every second digit from left
digits(i) := 2 * TO_NUMBER(digits(i)); -- doubling number
digits(i) := TO_CHAR(digits(i), 'fmXX'); -- Convert the "double" to a Base 16 (Hexadecimal) format
IF (REGEXP_LIKE(digits(i), '^\d+$')) THEN
-- Reduce by splitting down any resultant values over a single digit in length.
SELECT SUM(REGEXP_SUBSTR(digits(i), '\d', 1, LEVEL))
INTO digits(i)
FROM dual
CONNECT BY REGEXP_SUBSTR(digits(i), '\d', 1, LEVEL) IS NOT NULL;
END IF;
END IF;
END LOOP;
FOR i IN digits.FIRST..digits.LAST LOOP
-- I don't understand step 5), let's simulate it
IF digits(i) = 'E' THEN digits(i) := 7; END IF;
IF digits(i) = 'A' THEN digits(i) := 5; END IF;
END LOOP;
-- The sum of all digits
SELECT SUM(COLUMN_VALUE)
INTO DigitSum
FROM TABLE(digits);
-- Calculate the value needed to obtain the next multiple of 16
DBMS_OUTPUT.PUT_LINE ( 16 - DigitSum MOD 16 );
END;
```
|
57,067,069 |
I got some strings like above, and I want to get the start time and end time for HHH, I have no idea of how to match the expected string. Is anyone can help me on regular expression to make this come true.
```
AAA
2019-07-13 02:01 - 2019-07-17 01:59 CST (-5)
BBB
2019-07-13 17:01 - 2019-07-17 16:59 AEST (+10)
CCC
2019-07-13 15:01 - 2019-07-17 14:59 CST (+8)
DDD
2019-07-13 15:01 - 2019-07-17 14:59 CST (+8)
EEE
2019-07-13 15:01 - 2019-07-17 14:59 CST (+8)
FFF
2019-07-13 09:01 - 2019-07-17 08:59 CET (+2)
GGG
2019-07-13 09:01 - 2019-07-17 08:59 CET (+2)
HHH
2019-07-13 09:01 - 2019-07-17 08:59 CET (+2)
III
2019-07-13 03:01 - 2019-07-17 02:59 EST (-4)
JJJ
2019-07-13 03:01 - 2019-07-17 02:59 EST (-4)
KKK
2019-07-13 00:01 - 2019-07-16 23:59 PST (-7)
LLL
2019-07-13 15:01 - 2019-07-17 14:59 CST (+8)
MMM
2019-07-13 09:01 - 2019-07-17 08:59 CET (+2)
2019-07-13 07:01 UTC - 2019-07-17 06:59 UTC
```
|
2019/07/17
|
[
"https://Stackoverflow.com/questions/57067069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6279001/"
] |
This expression is likely to extract those desired dates and times right after the `HHH`:
```
(?<=HHH)\s*(\s*\d{4}\s*-\s*\d{2}\s*-\s*\d{2})\s+(.+?)\s+-\s+(\s*\d{4}\s*-\s*\d{2}\s*-\s*\d{2}\s*)\s(.+?)\s+[A-Z]{3}
```
and it can be also much simplified.
The expression is explained on the top right panel of [this demo](https://regex101.com/r/qwI2y1/1/) if you wish to explore/simplify/modify it.
### Test
```
re = /(?<=HHH)\s*(\s*\d{4}\s*-\s*\d{2}\s*-\s*\d{2})\s+(.+?)\s+-\s+(\s*\d{4}\s*-\s*\d{2}\s*-\s*\d{2}\s*)\s(.+?)\s+[A-Z]{3}/
str = '
2019-07-13 09:01 - 2019-07-17 08:59 CET (+2)
HHH
2019-07-13 09:01 - 2019-07-17 08:59 CET (+2)'
str.scan(re) do |match|
puts match.to_s
end
```
### Output
```
["2019-07-13", "09:01", "2019-07-17", "08:59"]
```
|
238,856 |
Recently, I read a book called "Swallowed Star". In the story, a virus changes human DNA enough for humans to have unbelievable superpowers and skills. Some even obtain the ability to have their own gravitational pull and not breathe in space.
I want to know if it is actually possible for genes to be able to cause such things, or is it just impossible theoretically speaking if there isn't enough matter?
PS. Sorry if this sounds like a stupid question. I don't have the knowledge of space and viruses to answer this myself. Please forgive me.
|
2022/12/03
|
[
"https://worldbuilding.stackexchange.com/questions/238856",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99833/"
] |
Viruses and pathogens can affect everything that is based on genetic expression or biochemistry: there are known examples of pathogens changing the behavior of their hosts, for example, not forgetting that any pathogen tries to turn its host into a replicator of themselves.
What a virus cannot do is changing the laws of physics.
>
> Some even obtain the ability to have their own gravitational pull and not breathe in space
>
>
>
Changing the gravitational pull would require at least one of the three:
1. changing the gravitational constant G
2. changing the mass of the infected
3. changing the distance between the infected and the pulled object
1 is impossible based on what we know today about physics.
2 is trivial, a virus can induce mass weight or mass loss, but the effect is hardly appreciable, unless you want to step in the realm of mama jokes.
3 is also trivial and again hardly appreciable. We get closer or farther to many objects in our daily life, without even realizing that our gravitational pull on them is changing, because it's such a low pull that it can be taken as 0
|
21,075,929 |
I'm trying to preserve the current height of the page when doing an Ajax call. Almost the whole content is hidden before showing the new content, so the browser scrolls to the top of the page because there is no content below during the transition.
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
$('#content').fadeOut();
setTimeout(function() {
$('#content').html(response).fadeIn();
}, 500);
});
});
```
I thought about adding a class like:
```
linksPages.on('click',function(e){
e.preventDefault();
jQuery.post(MyAjax.url, {action : 'ajax' ,href : $(this).attr('href') }, function(response) {
//$('#content').fadeOut();
$('#content').addClass('cortinaIn');
setTimeout(function() {
$('#content').html(response).fadeIn();
$('#content').removeClass('cortinaIn');
$('#content').addClass('cortinaOut');
}, 500);
$('#content').removeClass('cortinaOut');
});
});
```
and define the `cortinaIn` and `cortinaOut` CSS rules:
```
.cortinaIn {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(0, 1);
transform-origin: center center;
-ms-transform:scale(0, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(0, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(0, 1); /* Opera */
-o-transform-origin: center center;
}
.cortinaOut {
transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0.1s;
-moz-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-moz-transition-duration: 0.3s;
-moz-transition-timing-function: ease-out;
-moz-transition-delay: 0.1s;
-webkit-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
-webkit-transition-delay: 0.1s;
-o-transition-property: transform, -webkit-transform, -o-transform, -ms-transform;
-o-transition-duration: 0.3s;
-o-transition-timing-function: ease-out;
-o-transition-delay: 0.1s;
transform:scale(1, 1);
transform-origin: center center;
-ms-transform:scale(1, 1); /* IE 9 */
-ms-transform-origin: center center;
-webkit-transform:scale(1, 1); /* Safari and Chrome */
-webkit-transform-origin: center center;
-o-transform:scale(1, 1); /* Opera */
-o-transform-origin: center center;
}
```
And this works fine, but I'm not able to find "fade in" and "face out" effects with CSS transforms. Any idea to achieve this behavior?
|
2014/01/12
|
[
"https://Stackoverflow.com/questions/21075929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571840/"
] |
The `popoverControllerDidDismissPopover:` in the delegate is not called when 'dismissPopoverAnimated:' is used.
From the [Apple Documentation](https://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#jumpTo_4) for `popoverControllerDidDismissPopover:` in `UIPopoverControllerDelegate`:
>
> The popover controller does not call this method in response to programmatic calls to the dismissPopoverAnimated: method. If you dismiss the popover programmatically, you should perform any cleanup actions immediately after calling the dismissPopoverAnimated: method.
>
>
>
|
15,951,412 |
Sometimes I see constructs like [`$('<img/>')`](https://stackoverflow.com/questions/6124409/image-size-before-is-in-dom). How is `$('<img/>')` different from `$('img')` and where can I read more about this?
I tried looking at [jQuery Selectors](http://api.jquery.com/category/selectors/) but found nothing related to this format.
|
2013/04/11
|
[
"https://Stackoverflow.com/questions/15951412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257965/"
] |
The jQuery function is overloaded to construct new jQuery elements when passed a string that looks like HTML. From the [docs](http://api.jquery.com/jQuery/#jQuery2):
>
> If a string is passed as the parameter to $(), jQuery examines the
> string to see if it looks like HTML (i.e., it starts with `<tag ... >`).
> If not, the string is interpreted as a selector expression, as
> explained above. But if the string appears to be an HTML snippet,
> jQuery attempts to create new DOM elements as described by the HTML.
> Then a jQuery object is created and returned that refers to these
> elements.
>
>
>
|
46,971,445 |
This is my `BindingAdapter`:
```
@BindingAdapter(value = *arrayOf("bind:commentsAdapter", "bind:itemClick", "bind:avatarClick", "bind:scrolledUp"), requireAll = false)
fun initWithCommentsAdapter(recyclerView: RecyclerView, commentsAdapter: CommentsAdapter,
itemClick: (item: EntityCommentItem) -> Unit,
avatarClick: ((item: EntityCommentItem) -> Unit)?,
scrolledUp: (() -> Unit)?) {
//Some code here
}
```
`initWithCommentsAdapter` is a top level function
This is my layout (an essential part):
```
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="some.example.path.CommentsViewModel"/>
<variable
name="commentsAdapter"
type="some.example.path.CommentsAdapter"/>
</data>
<android.support.v7.widget.RecyclerView
...
bind:avatarClick="@{(item) -> viewModel.avatarClick(item)}"
bind:itemClick="@{viewModel::commentClick}"
bind:commentsAdapter="@{commentsAdapter}"
bind:isVisible="@{viewModel.commentsVisibility}"
bind:scrolledUp="@{() -> viewModel.scrolledUp()}"
/>
</layout>
```
When I assign lambda with kotlin method call in the layout, I have such error during building:
```
e: java.lang.IllegalStateException: failed to analyze:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:cannot find method avatarClick(java.lang.Object)
in class some.example.path.CommentsViewModel
****\ data binding error ****
```
or if I assign method by reference:
```
e: java.lang.IllegalStateException: failed to analyze:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Listener class kotlin.jvm.functions.Function1
with method invoke did not match signature of any method viewModel::commentClick
file:C:\Android\Projects\...\fragment_comments.xml
loc:70:12 - 83:17
****\ data binding error ****
```
But I have such methods with proper type, not Object
**Question**
How can I assign Kotlin lambda for custom @BindingAdapter in Kotlin in the layout?
**Edit**
The relevant part of the viewModel:
```
class CommentsViewModel(model: CommentsModel): BaseObservable() {
//Some binded variables here
...
fun commentClick(item: EntityCommentItem) {
//Some code here
}
fun avatarClick(item: EntityCommentItem) {
//Some code here
}
fun scrolledUp() {
//Some code here
}
...
}
```
The variables binding works just fine
|
2017/10/27
|
[
"https://Stackoverflow.com/questions/46971445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4710549/"
] |
**Short Answer**
Instead of using Kotlin generic lambda types, use **interfaces** with a single method that matches both return type and parameters of your method reference (`itemClick`) or your listener (`avatarClick`).
You can also use abstract classes with a single abstract method, also with matching parameters and return type.
**Explanation**
Actually the [Databinding docs](https://developer.android.com/topic/libraries/data-binding/expressions#method_references) never mention that the Kotlin lambda types work as Databinding listeners or method references, probably because under the hood these lambda types translate to Kotlin's `Function1`, `Function2`... which are generics, and thus some of their type information doesn't make it to the executable and therefore is not available at runtime.
Why your `scrolledUp` binding did work though? Because type `() -> Unit` has no need for generics. It could have worked even with `Runnable`.
**Code**
```
interface ItemClickInterface {
// method may have any name
fun doIt(item: EntityCommentItem)
}
@BindingAdapter(
value = ["commentsAdapter", "scrolledUp", "itemClick", "avatarClick"],
requireAll = false
)
fun initWithCommentsAdapter(
view: View,
commentsAdapter: CommentsAdapter,
scrolledUp: () -> Unit, // could have been Runnable!
itemClick: ItemClickInterface,
avatarClick: ItemClickInterface
) {
// Some code here
}
```
|
11,175,453 |
This question has been asked before but i still don't understand it fully so here it goes.
If i have a class with a property (a non-nullable double or int) - can i read and write the property with multiple threads?
I have read somewhere that since doubles are 64 bytes, it is possible to read a double property on one thread while it is being written on a different one. This will result in the reading thread returning a value that is neither the original value nor the new written value.
When could this happen? Is it possible with ints as well? Does it happen with both 64 and 32 bit applications?
I haven't been able to replicate this situation in a console
|
2012/06/24
|
[
"https://Stackoverflow.com/questions/11175453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/907734/"
] |
>
> If i have a class with a property (a non-nullable double or int) - can i read and write the property with multiple theads?
>
>
>
I assume you mean "without any synchronization".
`double` and `long` are both 64 *bits* (8 bytes) in size, and are *not* guaranteed to be written atomically. So if you were moving from a value with byte pattern ABCD EFGH to a value with byte pattern MNOP QRST, you could *potentially* end up seeing (from a different thread) ABCD QRST or MNOP EFGH.
With properly aligned values of size 32 bits or lower, atomicity is guaranteed. (I don't remember seeing any guarantees that values *will* be properly aligned, but I believe they are by default unless you force a particular layout via attributes.) The C# 4 spec doesn't even mention alignment in section 5.5 which deals with atomicity:
>
> Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.
>
>
>
Additionally, atomicity isn't the same as volatility - so without any extra care being taken, a read from one thread may not "see" a write from a different thread.
|
263,517 |
I'm trying to set a different existing material on 5 Instances made with Instance on Points. Trying both 3.0.1 and 3.1 to no avail.
Is there any value or attribute that signifies which instance you are on?
I want to build a setup for texture painting with 5 copies of a character and therefore I am linking a rigify rig with the meshes that gets instanced. That seems to make it trickier if not impossible to do custom attributes.
Either want to change material for each copied instance or have some way to swap textures in a shader graph. As long as you can paint a different texture on each copy.
I've tried these three answers to similar issue without results:
[Set material for instances problem (Blender 3.0)](https://blender.stackexchange.com/questions/244208/set-material-for-instances-problem-blender-3-0),
[Control Instance Color with Geometry Nodes](https://blender.stackexchange.com/questions/213224/control-instance-color-with-geometry-nodes),
[How to assign a different material color to each geometry nodes instance](https://blender.stackexchange.com/questions/254648/how-to-assign-a-different-material-color-to-each-geometry-nodes-instance)
|
2022/05/13
|
[
"https://blender.stackexchange.com/questions/263517",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/27347/"
] |
After a bit of faffing around, I've so far established that the *Set Material Index* node will work only if the incoming geometry, with materials assigned to slots, is on the same branch. The materials do not have to be assigned to faces of the incoming geometry... it just has to have its slots filled.
In this example, the incoming geometry is just a plane, with 4 material slots.
[](https://i.stack.imgur.com/Vl4WS.png)
Cubes instanced on a line have their instance indices stashed, before *Realize Instance* wipes them.
A function of the stashed indices is used to *Set Material Index*, while the (material-slot-bearing) incoming geometry is on the same branch.
The incoming geometry has been tagged, so can be selectively deleted before output.
[](https://i.stack.imgur.com/9LAB4.png)
The GN-generated cubes are now assigned the separate materials, per-instance, as expected.
|
3,068,306 |
I am trying to concatenate clobs in a PL/SQL loop and it has been returning null whilst when using DBMS\_OUTPUT prints out the loop values and when executing each result of the clobs gives an output as well.
The system is meant to execute an already stored SQL in a table based on the report name passed into it. This particular report has many report names; hence the concatenation of each of the reports. The arguments passed are the report name, version of the report you're interested in, the kind of separator you want, and an argument list for the unknowns in the SQL if any. There are also two main types of SQL; 1 that needs the table\_name be replaced with a temp table\_name and another that needs an ID be appended to a table\_name in the SQL.
please find below the code for the REPREF1 function.
```
CREATE OR REPLACE FUNCTION REPREF1(P_VER IN VARCHAR2 DEFAULT 'LATEST',
P_SEPARATOR IN VARCHAR2 DEFAULT ', ',
P_ARGLIST IN VAR DEFAULT NULL) RETURN CLOB IS
L_CLOB CLOB;
FUNCTION GET_CLOB(P_REPNAM IN VARCHAR2,
P_VER IN VARCHAR2 DEFAULT 'LATEST',
P_SEPARATOR IN VARCHAR2 DEFAULT ', ',
P_ARGLIST IN VAR DEFAULT NULL) RETURN CLOB IS
---------------------------------------------------------------------------------
-- TITLE - GET_CLOB beta - b.0 DATE 2010Mar12
--
-- DESCRIPTION - A function that return a report based on the report name put in
--
-- USAGE - select get_clob(p_repnam,p_ver, p_separator, var(varay(val_1,...val_n), varay(val_1,...val_n))) FROM dual
-----------------------------------------------------------------------------------------------------------------------------
V_SQL VARCHAR2(32767);
L_RESULT CLOB;
V_TITLE VARCHAR2(4000);
V_REPDATE VARCHAR2(30);
V_CNT NUMBER(2);
V_NUMARG NUMBER(3);
V_CDCRU NUMBER(3);
V_BCNT NUMBER(3);
V_NEWTABDAT VARCHAR2(30);
V_NEWTABLIN VARCHAR2(30);
L_COLLIST VARAY;
V_VER VARCHAR2(6);
N PLS_INTEGER;
V_CNTTAB NUMBER(3);
-- EXEC_SQL_CLOB
FUNCTION EXEC_SQL_CLOB(P_SQL IN VARCHAR2,
P_NUMARG IN NUMBER,
P_COLLIST IN VARAY DEFAULT NULL,
P_ARGLIST IN VARAY DEFAULT NULL,
P_SEPARATOR IN VARCHAR2 DEFAULT '') RETURN CLOB IS
------------------------------------------------------------------------------------------------------
-- TITLE - EXEC_SQL_CLOB beta - b.0 DATE 2010Mar22
--
-- DESCRIPTION - A function that returns a clob value after executing the sql query that is passed into it
--
-- USAGE - select exec_sql_clob(p_sql, p_numarg, var(varay(val_1, val_2,...val_n), varay(val_1, val_2,...val_n))) FROM dual
---------------------------------------------------------------------------------------------------------------
L_CUR INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
L_STATUS INTEGER;
V_COL VARCHAR2(4000);
L_RESULT CLOB;
L_COLCNT NUMBER DEFAULT 0;
L_SEPARATOR VARCHAR2(10) DEFAULT '';
V_NUMARG NUMBER(3);
BEGIN
-- parse the query for the report
DBMS_SQL.PARSE(L_CUR, P_SQL, DBMS_SQL.NATIVE);
-- whilst it is not more than 255 per line
FOR I IN 1 .. 255
LOOP
BEGIN
-- define each column in the select list
DBMS_SQL.DEFINE_COLUMN(L_CUR, I, V_COL, 2000);
L_COLCNT := I;
EXCEPTION
WHEN OTHERS THEN
IF (SQLCODE = -1007) THEN
EXIT;
ELSE
RAISE;
END IF;
END;
END LOOP;
-- If query has no bind variables
IF (P_ARGLIST IS NULL) THEN
IF (P_NUMARG = 0) THEN
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
-- Query has bind variables
ELSE
-- Check if the numarg passed is the same has stored in the table
SELECT NUMARG
INTO V_NUMARG
FROM REPVER
WHERE REPCODE = P_SQL;
-- If number of arguments is greater than 0
IF (V_NUMARG > 0) THEN
-- Check if the number of arguments are the same
IF (P_NUMARG = V_NUMARG) THEN
-- Replace the bind variables in the query
FOR J IN 1 .. P_ARGLIST.COUNT
LOOP
DBMS_SQL.BIND_VARIABLE(L_CUR, P_COLLIST(J), P_ARGLIST(J));
END LOOP;
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
ELSE
-- If the number of argument is equal to 0
IF (P_NUMARG = 0) THEN
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
END IF;
END IF;
-- Close cursor
DBMS_SQL.CLOSE_CURSOR(L_CUR);
RETURN L_RESULT;
END EXEC_SQL_CLOB;
BEGIN
-- Check if the version entered is null or latest
IF (P_VER IS NULL)
OR (UPPER(P_VER) = UPPER('LATEST')) THEN
SELECT MAX(VER)
INTO V_VER
FROM REPORT B, REPVER R
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF;
ELSE
V_VER := P_VER;
END IF;
-- Check if the repname and version entered exists
SELECT COUNT(*)
INTO V_CNT
FROM REPORT B, REPVER R
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND VER = V_VER
AND B.REPREF = R.REPREF;
IF (V_CNT > 0) THEN
-- Store the SQL statement, title and number of arguments of the report name passed.
SELECT REPCODE, REPTITLE, NUMARG, COLLIST
INTO V_SQL, V_TITLE, V_NUMARG, L_COLLIST
FROM REPVER R, REPORT B
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
V_REPDATE := TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI');
L_RESULT := V_TITLE || ' (' || P_REPNAM || ' version ' || V_VER || ') generated ' || V_REPDATE || CHR(13) || CHR(13);
-- Check for some specific type of queries
SELECT COUNT(*)
INTO V_CDCRU
FROM REPVER R, REPORT B
WHERE CTDDATA = 'Y'
AND UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
SELECT COUNT(*)
INTO V_BCNT
FROM REPVER R, BODCREPS B
WHERE BENLIST = 'Y'
AND UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
IF (V_CDCRU > 0) THEN
V_NEWTABDATA := 'CT_' || 'DAT_' || P_ARGLIST(1) (P_ARGLIST(1).FIRST);
V_NEWTABLINK := 'CT_' || 'LIN_' || P_ARGLIST(1) (P_ARGLIST(1).FIRST);
-- Check if the tables exist
SELECT COUNT(*)
INTO V_CNTTAB
FROM ALL_TABLES
WHERE TABLE_NAME = V_NEWTABDAT
OR TABLE_NAME = V_NEWTABLIN
AND OWNER = 'SCOTT';
IF (V_CNTTAB > 0) THEN
V_SQL := UPPER(V_SQL);
V_SQL := REPLACE(V_SQL, 'CT_DAT_CRU', V_NEWTABDAT);
V_SQL := REPLACE(V_SQL, 'CT_LIN_CRU', V_NEWTABLIN);
ELSE
V_SQL := 'SELECT ''THE TABLE NOT CREATED YET''
FROM DUAL';
END IF;
END IF;
IF (V_BCNT > 0) THEN
V_SQL := UPPER(V_SQL);
V_SQL := REPLACE(V_SQL, 'LIST', P_ARGLIST(1) (P_ARGLIST(1).LAST));
END IF;
IF (P_ARGLIST IS NULL) THEN
-- execute the query
L_RESULT := L_RESULT || EXEC_SQL_CLOB(V_SQL, V_NUMARG, L_COLLIST, NULL, P_SEPARATOR);
ELSE
N := P_ARGLIST.COUNT;
-- execute the query
L_RESULT := L_RESULT || EXEC_SQL_CLOB(V_SQL, V_NUMARG, L_COLLIST, P_ARGLIST(N), P_SEPARATOR);
END IF;
RETURN L_RESULT;
ELSE
RAISE_APPLICATION_ERROR(-20012, P_REPNAM || ' or ' || P_VER || ' DOES NOT EXIST ');
END IF;
END GET_CLOB;
BEGIN
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
SELECT CONCAT_CLOB(GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST))
INTO L_CLOB
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
-- DBMS_OUTPUT.PUT_LINE (COUNT(i.REPNAM));
END LOOP;
RETURN L_CLOB;
END REPREF1;
/
```
Cheers,
Tunde
Many thanks APC for making the code look better.
@Robert, the last loop in the code returns null even with the CONCAT\_CLOB aggregate function that concatenates clobs.
```
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
SELECT CONCAT_CLOB(GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST))
INTO L_CLOB
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
END LOOP;
```
when I try this,
```
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
L_CLOB := L_CLOB || CHR(13) || GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST);
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
END LOOP;
```
It also gives null; but this time the dbms output for the repnam are not complete.
|
2010/06/18
|
[
"https://Stackoverflow.com/questions/3068306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197945/"
] |
Don't know about your code. Here is how it works for me:
Whenever I create a function returning a clob value I do this:
```
function foo return clob is
l_clob clob;
begin
dbms_lob.createtemporary(lob_loc => l_clob, cache => true, dur => dbms_lob.call);
...
return l_clob;
end;
```
When concatenating values into a clob I use a function:
```
procedure add_string_to_clob(p_lob in out nocopy clob
,p_string varchar2) is
begin
dbms_lob.writeappend(lob_loc => p_lob, amount => length(p_string), buffer => p_string);
end;
```
|
28,487 |
I want to run a Mathematica code repeatedly, even after the kernel shuts down when it is out of memory, because I have designed my program to continue appending the data to a file. Currently, I have to restart the kernel manually every 10 minutes. Does anyone have an idea how one can automate this process? Thanks.
|
2013/07/12
|
[
"https://mathematica.stackexchange.com/questions/28487",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/8523/"
] |
If you preselect a range of cells before execution you can continue execution past kernel quit using the option below. Selection and evaluation can be automated and done repeatedly.
```
SetOptions[$FrontEnd, "ClearEvaluationQueueOnKernelQuit" -> False]
```
Ref : <https://stackoverflow.com/a/13740555/879601>
(`MemoryConstrained` looks a good solution for your specific problem though.)
|
50,304,502 |
I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error.
|
2018/05/12
|
[
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] |
If you have created and assigned value to the variable and still it shows `getter 'value' was called on null`,
try to `Run` or `Restart` your app instead of `Hot Reload`. Because `Hot Reload` will not call `initstate()` (where variables assign their values) which will be only called by `Restarting` the app.
|
44,063,027 |
I need to show confirm dialog message as html, this is how looks my dialog in component:
```
this.confirmationService.confirm({
header: "Change user status",
message: "Do you want to change user status to <strong>" + status + "</strong >?",
accept: () => {
//
}
});
```
and this is how it looks like on a page:
[](https://i.stack.imgur.com/jttBV.png)
I tried to do this two ways but without success
```
<p-confirmDialog width="500" appendTo="body">
<template pTemplate="body">
<span class="ui-confirmdialog-message">{{message}}</span>
</template>
```
```
<p-confirmDialog width="500" [innerHTML]="message"></p-confirmDialog>
```
|
2017/05/19
|
[
"https://Stackoverflow.com/questions/44063027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471882/"
] |
so this is kind of old, but for the future- the solution is to change the quote type of `message`.
so, change
```
message: "Do you want to change user status to <strong>" + status + "</strong >?",
```
to
```
message: `Do you want to change user status to <strong>" + status + "</strong >?`,
```
|
24,789,585 |
I am trying to update users **via AJAX** from my index view, so I have the following view:
```
<% @users.each do |user| %>
<tr>
<td><%= user.email %></td>
<td>
<%= form_for [:admin, user], :remote => true, :authenticity_token => true, :format => :json do |f| %>
<%= f.radio_button :approved, true, :checked => user.approved, :id => "user_approved_#{user.id}", :onclick => "this.form.submit();"%> Yes
<%= f.radio_button :approved, false, :checked => !user.approved, :id => "user_not_approved_#{user.id}", :onclick => "this.form.submit();" %> No
<% end %>
</td>
</tr>
<% end %>
```
And I have the controller update method that looks like this:
```
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update(user_params)
format.json { render nothing: true }
else
format.json { render nothing: true}
end
end
end
```
Even though the record gets correctly updated, it renders an empty page with the following URL: `admin/users/2.json` or whatever id is the record that was just updated.
Any idea how can I make it just render the index view where the form was submitted from?
|
2014/07/16
|
[
"https://Stackoverflow.com/questions/24789585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196150/"
] |
You should change your onclick handler, from `this.form.submit()` to `$(this).closest("form").trigger("submit");`
As you have it now you are directly submitting the form, so jquery-ujs can't handle the event.
|
71,252,692 |
When updating one DataFrame based on info from second one the NaN's are not transferred.
With below code
```
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'A':[1,2,3,4,5], 'B':[4,5,6,7,8]})
df2 = pd.DataFrame({'A':[1,2,3], 'B':[7,np.nan,6]})
df1.update(df2)
```
The new DataFrame will look as below:
[](https://i.stack.imgur.com/2JbAm.png)
So the value from df2 is not transferred as this is a NaN
[](https://i.stack.imgur.com/MPJy5.png)
Normally this is probably an expected outcome but not in the particular case that I'm working on.
For the moment how I deal with it is that I replace all NaNs with a value or string that signalizes to me that it's something I need to check but I was wondering if there is an actual solution to pass the NaN as an update?
[](https://i.stack.imgur.com/bWc7H.png)
|
2022/02/24
|
[
"https://Stackoverflow.com/questions/71252692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16659145/"
] |
Try this,
```
bool isCountryChanged = false; // for update UI when country changed.
appBar: AppBar(
backgroundColor: Colors.transparent,
leading: const Icon(
Icons.public,
color: Colors.black,
size: 27,
),
title: const Text(
"Kelime Öğren",
style: TextStyle(color: Colors.black),
),
elevation: 0,
actions: [
DropdownButton<String>(
items: countryFlags
.map((country, flag) {
return MapEntry(
country,
DropdownMenuItem<String>(
value: flag,
child: Text(flag, style: TextStyle(fontSize: 20),),
));
})
.values
.toList(),
value: defaultFlag,
onChanged: (String? country) {
setState(() {
defaultFlag = country!;
isCountryChanged = true; });
// display circular indicator for 1 second.
Future.delayed(Duration(milliseconds: 1000), () async {
setState(() {
isCountryChanged = false; });
});
},
)
],
),
body:isCountryChanged? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
strokeWidth: 5,
); : // do stuff
```
|
41,553,641 |
```
["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
```
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
```
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
```
All of the above we being populated like this:
```
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
```
|
2017/01/09
|
[
"https://Stackoverflow.com/questions/41553641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1504299/"
] |
Assuming all the sub-arrays have the same length, you can use a simple `for` loop that iterates over the index of one of them, and use that to access each of the sub-arrays at that index. Then combine all of them into the associative array for each customer.
```
$result = array();
$keys = array_keys($array);
$len = count($array[$keys[0]]); // Get the length of one of the sub-arrays
for ($i = 0; $i < $len; $i++) {
$new = array();
foreach ($keys as $k) {
$new[$k] = $array[$k][$i];
}
$result[] = $new;
}
```
|
61,469,253 |
I have an `appsettings.json` file where I want to transform the value located at:
```
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
```
I found the following answer so I know that an app service can retrieve values directly from the key vault:
<https://stackoverflow.com/a/59994040/3850405>
This is not the reason for asking. Since Microsoft offers `JSON variable substitution` I still think this should be possible since the only problem is the nested value. The question above is similar but I would like to specify a bit more what has already been tested and where I got stuck.
<https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/transforms-variable-substitution?view=azure-devops&tabs=Classic#json-variable-substitution>
It is possible to use Pipelines -> Library -> Variable group
[](https://i.stack.imgur.com/j9Fid.png)
or a Azure Key Vault Task to get the secret value.
[](https://i.stack.imgur.com/vpNSS.png)
The problem is the secret value can not contain dots:
[](https://i.stack.imgur.com/q88an.png)
>
> Please provide a valid secret name. Secret names can only contain
> alphanumeric characters and dashes.
>
>
>
Neither in a linked Variable group or in a Azure Key Vault Task I'm allowed to rewrite a secret name to another variable name.
Looking at the sample below if the secret name was `ConnectionStringsDefaultConnection` I could access the value like this `$(ConnectionStringsDefaultConnection)` but I don't know how to rename it.
<https://azuredevopslabs.com/labs/vstsextend/azurekeyvault/>
I have found a task that could get the job done but it requires a third party Release task. This is not acceptable since the project only allows Tasks written by Microsoft.
[](https://i.stack.imgur.com/m3BTf.png)
<https://daniel-krzyczkowski.github.io/How-to-inject-Azure-Key-Vault-secrets-in-the-Azure-DevOps-CICD-pipelines/>
I also know that a Pipeline variable can be used to store the value but we wan't to have a single source of truth and that is the Azure Key Vault Secret.
[](https://i.stack.imgur.com/adDYD.png)
|
2020/04/27
|
[
"https://Stackoverflow.com/questions/61469253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3850405/"
] |
Read a similar question from VSTS (Visual Studio Team Services) and was able to solve it.
Created a `Pipeline variable` called `ConnectionStrings.DefaultConnection` that had a reference value to my linked variable group.
If my secret was named `ConnectionStringsDefaultConnection` I would hook this up as a linked variable and then add `$(ConnectionStringsDefaultConnection)` as a value.
[](https://i.stack.imgur.com/llmm4.png)
Source:
<https://stackoverflow.com/a/47787972/3850405>
|
2,016 |
Hi guys, can any one please give me an examples of Subtextual sound and Visual amplification sound within a film.
|
2010/07/16
|
[
"https://sound.stackexchange.com/questions/2016",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/442/"
] |
Emmanuel,
Can you clarify what exactly you are asking? I say this because it would be useful to have some idea about what specifically you are looking to find out.
Film sound will contain a lot of subtexts in varying degrees. From a basic illiciting of an emotional response from the audience (animal sounds layered into vehicle sounds for example) right through to sounds meaning 2 different things at the same time. For example, I just put in the sound of a ticking Grandfather's Clock into a scene. Firstly because you can see one in the background, this adds sense of realism to the show. Secondly because it's an old sound you don't come across so much these days and as the room we are in is an antique shop then it adds to the sense of the old. Same sound but given 2 meanings.
As for Visual Amplification, it's not a term I've ever come across in relation to sound. Are you talking about [Added Value](http://filmsound.org/chion/Added.htm)?
Ian
|
9,834,289 |
Using the native Android MediaPlayer class I am able to play Shoutcast streams. Furthermore, using streamscraper (http://code.google.com/p/streamscraper/) I am able to get the metadata for the current playing song in the stream.
I would like to know if there is a way to be notified when the song in the radio stream changes, using my current setup (MediaPlayer and streamscraper).
If someone could point me in the right direction, I would be grateful.
|
2012/03/23
|
[
"https://Stackoverflow.com/questions/9834289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345191/"
] |
Shorthand properties (such as `border`) are not supported by `jQuery.css()`.
<http://api.jquery.com/css/>
|
30,568,353 |
I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor?
|
2015/06/01
|
[
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] |
To let Jackson know how to create an object for deserialization, use the [`@JsonCreator`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonCreator.html) and [`@JsonProperty`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonProperty.html) annotations for your constructors, like this:
```
@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name,
@JsonProperty("resultType") ImportResultItemType resultType,
@JsonProperty("message") String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
```
|
6,662,497 |
I have some links that have \_2 if they are duplicates, I want to keep the href the same but change the text to remove the \_2, sometimes there's an \_3 or \_4 so I just want to remove from the text everything after the \_.
Here is an example of the href's I want to change
```
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002837/Dior-Charlize-Theron-2">Charlize-Theron_2</a></div>
</li>
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002840/Dior-Natalie-Portman">Natalie-Portman</a></div>
</li>
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002838/Dior-Sharon-Stone-4">Sharon-Stone_4</a></div>
</li>
```
I have already found a code that replaces the hyphens with space's and this works well, so my code so far is
```
$(".images li").find("a").each(function(i){
$(this).text($(this).text().replace(/-/g," "));
$(this).text($(this).text().replace(/_/g,""));//removes the _
});
```
Any Ideas? Thanks for replys
|
2011/07/12
|
[
"https://Stackoverflow.com/questions/6662497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526938/"
] |
you can try this:
```
$(this).text($(this).text().replace(/_\d+$/, "_"));
```
|
39,851,616 |
I tried to switch to popup alert and click on OK button, but i got an error saying that xpath (for OK button) is not found.
But this is working for me sometimes using the same code. Could anyone help me out on this. I tried all possible ways that is available in blogs. But i couldn't make it
|
2016/10/04
|
[
"https://Stackoverflow.com/questions/39851616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318753/"
] |
you need to move control to your pop-up window first before doing any operation on pop-up window:-
below code is to move selenium control on pop-up window
```
driver.switchTo().alert();
```
by writing below line
```
alert.accept();
```
alert will get close
|
131,056 |
In the [Matrix](https://matrix.org/) instant messaging protocol, when using the reference implementation of the Matrix server (called `synapse`), there is an [admin API](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/) with functions like [resetting a password](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/user_admin_api.rst#reset-password) for a user etc..
Accessing this requires an [`access_token`](https://matrix.org/docs/spec/client_server/latest#using-access-tokens) "API key" of a server admin user.
How do I get one?
|
2019/06/20
|
[
"https://webapps.stackexchange.com/questions/131056",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/75677/"
] |
Solution to find your access token:
1. Log in to the account you want to get the access token for. Click on the name in the top left corner, then "Settings".
2. Click the "Help & About" tab (left side of the dialog).
3. Scroll to the bottom and click on `<click to reveal>` part of Access
Token.
4. Copy your access token to a safe place.
|
67,651,333 |
I have built a python class, which takes a string as input
I have put 3 functions in the python class.
First function is to count no of upper and lower case
Second function is to truncate the string
Third function is to check if the string is a palindrome
```
class stringUtility():
def _init_(self,string):
self.string = string
def upperlower(self):
upper = 0
lower = 0
for i in range(len(self.string)):
# For lower letters
if (ord(self.string[i]) >= 97 and ord(self.string[i]) <= 122):
lower += 1
# For upper letters
elif (ord(self.string[i]) >= 65 and ord(self.string[i]) <= 90):
upper += 1
print('Lower case characters = %s' %lower,
'Upper case characters = %s' %upper)
# # Driver Code
# string = 'jjfkhgbhf'
# #upperlower(string)
def trimString(self):
trimmedString = self.string[:10] + "..."
if len(self.string) <= 10:
print(self.string)
else:
print(trimmedString)
# string2 = "fdsfsdfsdfsdf"
# #trimString(string2)
def checkPalindrome(self):
reverseString = self.string[::-1]
convert_to_palindrome = self.string + reverseString[1:]
if reverseString == self.string:
print('input is a palindrome')
else:
print(convert_to_palindrome )
# string3 = 'dad'
# checkPalindrome(string3)
person2 = stringUtility.upperlower('mayanDFSDDk')
```
But i am getting the error:
```
File "class.py", line 58, in <module>
person2 = stringUtility.upperlower('mayanDFSDDk')
File "class.py", line 11, in upperlower
for i in range(len(self.string)):
AttributeError: 'str' object has no attribute 'string'
```
|
2021/05/22
|
[
"https://Stackoverflow.com/questions/67651333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
There's a lot amiss with Windows Terminal [#10153](https://github.com/microsoft/terminal/issues/10153), since the developers were as they say [*"shooting from the hip"*](https://www.collinsdictionary.com/us/dictionary/english/to-shoot-from-the-hip). There's no study of the available documentation, testing, etc.
The bug report is not talking about [xterm](https://invisible-island.net/xterm/xterm.html), since its DECRQM does actually return a value for [bracketed-paste](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h4-Functions-using-CSI-_-ordered-by-the-final-character-lparen-s-rparen:CSI-?-Pm-h:Ps-=-2-0-0-4.1F7D). Here's a screenshot in [vttest](https://invisible-island.net/vttest/vttest.html) illustrating that:
[](https://i.stack.imgur.com/lPl1Q.png)
`XTSAVE` and `XTRESTORE` are old features dating back to December 1986, preceding the VT420 PCTerm (announced in February 1992) by a little over 5 years. Since DEC participated in developing xterm during the 1980s (see [copyright notice](https://github.com/ThomasDickey/xterm-snapshots/blob/b2ecdc26094793725db0353b0699e4d31446351e/charproc.c#L57)), one might have assumed that its terminals division would have accommodated this. But that's so long ago, that it's unlikely that someone can point out why that didn't happen.
Like the cursor save/restore, the private-mode save/restore feature does not use a stack.
Back to the question: the point of #10153 is that the Windows Terminal developers choose to not make it xterm-compatible by providing the control responses that would enable an application to determine what state it is in. Perhaps at some point Windows Terminal will provide a solution. However, `DECRQM` is a VT320 (and up) feature, while [Windows Terminal](https://invisible-island.net/ncurses/terminfo.src.html#tic-ms-terminal) identifies itself as a VT100 (but masquerades as xterm).
Further reading:
* [XTerm Control Sequences (Miscellaneous)](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Miscellaneous)
* [Unit test framework for terminal emulation #1746](https://github.com/microsoft/terminal/issues/1746)
* [Add support for the DECSCNM Screen Mode #3773](https://github.com/microsoft/terminal/issues/3773) (eventually resolved)
* [RE: ms-terminal in terminfo.src](https://lists.gnu.org/archive/html/bug-ncurses/2019-08/msg00004.html) (not resolved, see [#8303](https://github.com/microsoft/terminal/issues/https://github.com/microsoft/terminal/issues/8303))
|
59,067,075 |
array = ["£179.95", "£199.95", "£89.95"]
How to multiple this values add get the total values in ios swift 4.
Please help me.
|
2019/11/27
|
[
"https://Stackoverflow.com/questions/59067075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11923334/"
] |
Try this. This will Works.
```
$a = 1;
$x = 1;
$array = [];
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
if( $a == $x ){
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
}
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
```
**OUTPUT:**
```
Array
(
[0] => Array
(
[name] => name
[type] => type
[label] => label
)
[1] => Array
(
[name] => name
[type] => type
[label] => label
)
[2] => Array
(
[name] => name
[type] => type
[label] => label
)
)
```
|
6,040,640 |
I have an sql query in which I need to select the records from table where the time is between 3:00 PM yesterday to 3:00 PM today *if* today's time is more than 3:00 PM.
If today's time is less than that, like if today's time is 1:00 PM. then then my query should take today's time as 1:00 PM (which should return me records).
**I need to get the time between 3:00pm yesterday to 3:00pm today if todays time is more than 3:00pm
if todays time is less than 3:00pm then get the 3:00pm yesterday to current time today**
|
2011/05/18
|
[
"https://Stackoverflow.com/questions/6040640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96180/"
] |
The best way of handling this is to use an [IF statement](http://www.techonthenet.com/oracle/loops/if_then.php):
```
IF TO_CHAR(SYSDATE, 'HH24') >= 15 THEN
SELECT x.*
FROM YOUR_TABLE x
WHERE x.date_column BETWEEN TO_DATE(TO_CHAR(SYSDATE -1, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
AND TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
ELSE
SELECT x.*
FROM YOUR_TABLE x
WHERE x.date_column BETWEEN TO_DATE(TO_CHAR(SYSDATE -1, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
AND SYSDATE
END IF;
```
Conditional WHERE clauses are non-sargable.
Previously:
-----------
If I understand correctly, you want to get records within the last day. If the current time is 3 PM or later, the time should be set to 3 PM. If earlier than 3 PM, take the current time...
```
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT CASE
WHEN TO_CHAR(SYSDATE, 'HH24') >= 15 THEN
TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
ELSE SYSDATE
END AS dt
FROM DUAL) y ON x.date_column BETWEEN dt - 1 AND dt
```
### Note:
`dt - 1` means that 24 hours will be subtracted from the Oracle DATE.
### Reference:
* [TO\_CHAR](http://www.techonthenet.com/oracle/functions/to_char.php)
* [TO\_DATE](http://www.techonthenet.com/oracle/functions/to_date.php)
|
18,877,580 |
Consider the following snippet:
```
"12-18" -Contains "-"
```
You’d think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. I’m not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it.
|
2013/09/18
|
[
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] |
The `-Contains` operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
>
> -Contains
> Description: Containment operator. **Tells whether a collection of reference values includes a single test value.**
>
>
>
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
```
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
```
I think what you want is the [`-Match`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match) operator:
```
"12-18" -Match "-"
```
Which returns `True`.
**Important:** As pointed out in the comments and in the [linked documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match), it should be noted that the `-Match` operator uses [regular expressions](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-6) to perform text matching.
|
2,880,449 |
after some simplification, we get (2004y)/(y-2004)=x
and by looking at the prime factorization of 2004 we observe there are only 12 ways in which 2004 can be expressed as the product of two integers.
which gives us 12 ordered pairs.But the answer is 45. how?(sorry for not using mathjax my browser does not support it)
|
2018/08/12
|
[
"https://math.stackexchange.com/questions/2880449",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/570638/"
] |
Guide:
Once we get $$2004y+2004x=xy$$
$$-2004y-2004x+xy=0$$
$$2004^2-2004y-2004x+xy=2004^2$$
$$(2004-x)(2004-y)=2004^2=2^4\cdot 3^2\cdot 167^2$$
Can you complete the task?
|
50,603,368 |
Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
```
|
2018/05/30
|
[
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] |
You can't update the state like this.
>
> Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
>
>
>
Read [React docs](https://reactjs.org/docs/react-component.html#state).
You can do something like this :
```
let newArray = [...this.state.array];
newArray[2] = 'somethingElse';
this.setState({array: newArray});
```
The above example is using [Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
There are multiple ways to modify state, but all the ways should ensure that data is treated as immutable. You can read more about handling state in React [here](https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5)
|
18,410,997 |
I have two to three variables that I want to mix into strings and then place them all into a table, however I can't figure out how to make the variables mix.
What I have is
```
document.write('<table cellspacing="0" cellpadding="5">')
var a = ["String1", "String2"]
var n = ["string3", "String4"]
for(var i=0; i <a.length; i++){
document.write('<tr'>
document.write('td' + (a[i]) + (b[i]) +'</td>')
document.write('</td>')
}
document.write('</table>')
```
This does create the table I want however it doesn't perform the function I am looking for.
It creates a table that goes:
"string1" "string3"
"string2" "string4'
I'm looking for:
"string1" "string3"
"string1" "string4"
"string2" "string3"
"string2" "string4"
Hopefully that makes sense. I've tried searching through the internet and on Stack Overflow to no avail. How would I make this happen? Eventually the arrays should be able to grow to maybe a hundred each...
|
2013/08/23
|
[
"https://Stackoverflow.com/questions/18410997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014858/"
] |
You need an additional loop -
```
for(var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
document.write('<tr'>);
document.write('<td>' + a[i] + b[j] + '</td>');
document.write('</td>');
}
}
```
P.S.: Do you really need to create elements using `document.write`? It's OK if it's an example, but this style of element creation is strongly discouraged in real development code.
|
22,651,117 |
I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
```
|
2014/03/26
|
[
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] |
It looks like derby locking issue. you can temporarily fix this issue by deleting the lock file inside the directory `/var/lib/hive/metastore/metastore_db`. But this issue will also occur in future also
`sudo rm -rf /var/lib/hive/metastore/metastore_db/*.lck`
With default hive metastore embedded derby, it is not possible to start multiple instance of hive at the same time. By changing hive metastore to mysql or postgres server this issue can be solved.
See the following cloudera documentation for changing hive metastore
<http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH4/4.2.0/CDH4-Installation-Guide/cdh4ig_topic_18_4.html>
|
146,490 |
Is there a simple way to select only one radio button with the `<apex:selectRadio>` component? I searched for examples and found two posts on this topic that did not resolve the issue I'm having. I might be missing something simple.
|
2016/10/30
|
[
"https://salesforce.stackexchange.com/questions/146490",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/7528/"
] |
The reason you are having this issue is because it is not one Radio button. It is a list of radio buttons. While in each one you can only select one options. For every one you can choose one.
I don't think there is a very quick fix for this one. Either, you give up using apex repeat in this case and put all the opportunity roles in the option list. In that case, you will be able to select only one primary opportunity role. Or otherwise, if you still want the table structure, you will need to use Javascript to enhance the logic.
|
25,496,692 |
I'm trying to open multiple windows with JavaFX, I have an eventlistener that opens a new window when a button is clicked it looks like this:
```
@FXML
private void joinAction() {
Parent root;
try {
Stage stage = (Stage) joinButton.getScene().getWindow();
stage.close();
root = FXMLLoader.load(getClass().getResource("main.fxml"));
stage = new Stage();
stage.setTitle("TuneUs");
stage.setScene(new Scene(root));
stage.show();
} catch (IOException e) {e.printStackTrace();}
}
```
the first window opens and the new one opens, but my problem is getting events to work with my second window
in `main.fxml` I have this line:
```
<TextField id="chat_bar" onAction="#sendChat" layoutX="14.0" layoutY="106.0" prefHeight="22.0" prefWidth="403.0"/>
```
Then in my controller class I have this method:
```
@FXML
private void sendChat() {
System.out.println("test");
}
```
but Intellij is telling me that; no controller specified for top level element
So, my question is: Do I need to create multiple controller classes or can I use just one for multiple windows if so how?
|
2014/08/26
|
[
"https://Stackoverflow.com/questions/25496692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2292723/"
] |
The recommended approach is to define a controller for each FXML. Since controllers are very lightweight this shouldn't add much overhead. The controller for your main.fxml file might be as simple as
```
import javafx.fxml.FXML ;
public class MainController {
@FXML
private void sendChat() {
// ...
}
}
```
I have used this approach with fairly large numbers of FXML files and corresponding controllers in a single project, and have had no issues with managing the code etc. I recommend using a naming convention of the form `Main.fxml <-> MainController`.
If your controllers need to share data, use the techniques outlined in [Passing Parameters JavaFX FXML](https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml/14190310#14190310)
As @Vertex points out in the comments, there is an alternative approach provided by the `FXMLLoader.setController(...)` method. So in your example above, you could do
```
@FXML
private void joinAction() {
Parent root;
try {
Stage stage = (Stage) joinButton.getScene().getWindow();
stage.close();
FXMLLoader loader = new FXMLLoader (getClass().getResource("main.fxml"));
loader.setController(this);
root = loader.load();
stage = new Stage();
stage.setTitle("TuneUs");
stage.setScene(new Scene(root));
stage.show();
} catch (IOException e) {e.printStackTrace();}
}
@FXML
private void sendChat() {
// ...
}
```
This approach is fine if you are not setting any fields (controls) via FXML injection (i.e. with an `fx:id` attribute in the fxml and a corresponding `@FXML` annotation in the controller). If you are, it will be very difficult to keep track of when those fields have been set. Moreover, if your `joinAction` handler is invoked multiple times, you will have multiple instances of the node created by main.fxml, but all sharing a single controller instance (and consequently overwriting the same injected fields). Also note that with this approach, your `initialize()` method will be invoked *both* when the original fxml file is loaded, **and** when the main.fxml file is loaded, which will almost certainly cause undesired effects.
One last note: if you have many FXML files, and corresponding controllers, you might want to look at the [afterburner.fx framework](http://afterburner.adam-bien.com/). This is a very lightweight framework that mandates a naming convention on FXML files and their corresponding controllers, and also provides a (very) easy mechanism for sharing data between them.
|
62,521,767 |
I have variable from an HTML form that are currently being posted to one table in my database table.
I would like to post those same variables to other tables at the same time within the same function. Is this possible? Here is my current PHP function that is posting successfully to one table
```
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
// Database connection
$conn = new mysqli('localhost','user','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$execval = $stmt->execute();
echo $execval;
$stmt->close();
$conn->close();
}
?>
```
And I would like the following the variables to post to more than one table in the same database, so was thinking the following but it does not work -
```
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
// Database connection
$conn = new mysqli('localhost','user','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$stmt = $conn->prepare("insert into table2(var1) values(?)");
$stmt->bind_param("s", $var1);
$stmt = $conn->prepare("insert into table3(var2, var3) values(?, ?)");
$stmt->bind_param("ss", $var2, $var3);
$execval = $stmt->execute();
echo $execval;
$stmt->close();
$conn->close();
}
?>
```
|
2020/06/22
|
[
"https://Stackoverflow.com/questions/62521767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13794315/"
] |
Yes, it is possible. You can do what you are doing now, but you need to call `execute()` method after preparing each query. Apart from this, it would also be a good idea to wrap this in a transaction. Transactions help you make you sure that either all or none operations are successful. If one of them fails the others are not executed.
Your fixed code should look something like this:
```
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
// Database connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // switches error reporting on
$conn = new mysqli('localhost','user','password','database');
$conn->set_charset('utf8mb4'); // always set the charset
// Start transaction
$conn->begin_transaction();
$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$stmt->execute();
$stmt = $conn->prepare("insert into table2(var1) values(?)");
$stmt->bind_param("s", $var1);
$stmt->execute();
$stmt = $conn->prepare("insert into table3(var2, var3) values(?, ?)");
$stmt->bind_param("ss", $var2, $var3);
$stmt->execute();
// End transaction
$conn->commit();
```
|
33,728,977 |
If I have the file:
```
A pgm1
A pgm2
A pgm3
Z pgm4
Z pgm5
C pgm6
C pgm7
C pgm8
C pgm9
```
How can I create the list:
```
[['pgm1','pgm2','pgm3'],['pgm4','pgm5'],['pgm6','pgm7','pgm8','pgm9']]
```
I need to retain the original order from the load file. So [pgm4, pgm5] must be the 2nd sublist.
My preference is that the new sub-list is triggered when the grouping variable changes from the previous one, thus "A, Z, C". But I can accept if the grouping variable must be sequential, i.e. "1, 2, 3".
(This is to support running the programs in each sub-list concurrently, but waiting for all upstream programs to finish before proceeding to the next list.)
I'm on RHEL 2.6.32 using Python 2.6.6
|
2015/11/16
|
[
"https://Stackoverflow.com/questions/33728977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3735970/"
] |
Simply use [`collections.defaultdict()`](https://docs.python.org/3/library/collections.html#collections.defaultdict).
Code:
```
import collections
d = collections.defaultdict(list)
infile = 'filename'
with open(infile) as f:
a = [i.strip() for i in f]
a = [i.split() for i in a]
for key, value in a:
d[key].append(value)
l = list(d.values())
```
Demo:
```
>>> import collections
>>> d = collections.defaultdict(list)
>>> infile = 'filename'
>>> with open(infile) as f:
... a = [i.strip() for i in f]
>>> a = [i.split() for i in a]
>>> a
[['A', 'pgm1'], ['A', 'pgm2'], ['A', 'pgm3'], ['Z', 'pgm4'], ['Z', 'pgm5'], ['C', 'pgm6'], ['C', 'pgm7'], ['C', 'pgm8'], ['C', 'pgm9']]
>>> for key, value in a:
... d[key].append(value)
>>> d
defaultdict(<class 'list'>, {'A': ['pgm1', 'pgm2', 'pgm3'], 'C': ['pgm6', 'pgm7', 'pgm8', 'pgm9'], 'Z': ['pgm4', 'pgm5']})
>>> d.values()
dict_values([['pgm1', 'pgm2', 'pgm3'], ['pgm6', 'pgm7', 'pgm8', 'pgm9'], ['pgm4', 'pgm5']])
>>> list(d.values())
[['pgm1', 'pgm2', 'pgm3'], ['pgm6', 'pgm7', 'pgm8', 'pgm9'], ['pgm4', 'pgm5']]
>>>
```
---
The blow code do the same thing as the above code does, but keep the order:
```
infile = 'filename'
with open(infile) as f:
a = [i.strip() for i in f]
a = [i.split() for i in a]
def orderset(seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or seen_add(x))]
l = []
for i in orderset([i[0] for i in a]):
l.append([j[1] for j in a if j[0] == i])
```
|
11,088,343 |
Let's say I have a table with 1M rows and I need to add an index on it. What would be the process of doing so? Am I able to do `ALTER TABLE table ADD INDEX column (column)` directly on production? Or do I need to take other things into account to add the index.
How does one normally go about adding an index on a live production db?
|
2012/06/18
|
[
"https://Stackoverflow.com/questions/11088343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651174/"
] |
First, get the `GtkTextBuffer` from the `GtkTextView` using `gtk_text_view_get_buffer()`. Then get the start and end *GtkTextIters* from the buffer to use to get the text of the buffer. Finally, write that text to the file using the API of your choice, however, I would recommend `Gio`. Here's a snippet from my old tutorial:
```c
gtk_widget_set_sensitive (text_view, FALSE);
buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (editor->text_view));
gtk_text_buffer_get_start_iter (buffer, &start);
gtk_text_buffer_get_end_iter (buffer, &end);
text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
gtk_text_buffer_set_modified (buffer, FALSE);
gtk_widget_set_sensitive (editor->text_view, TRUE);
/* set the contents of the file to the text from the buffer */
if (filename != NULL)
result = g_file_set_contents (filename, text, -1, &err);
else
result = g_file_set_contents (editor->filename, text, -1, &err);
if (result == FALSE)
{
/* error saving file, show message to user */
error_message (err->message);
g_error_free (err);
}
g_free (text);
```
Check out the following API documentation:
1. <http://developer.gnome.org/gtk3/stable/GtkTextBuffer.html>
2. [http://developer.gnome.org/glib/stable/glib-File-Utilities.html](http://developer.gnome.org/gtk3/stable/GtkTextBuffer.html)
|
852,814 |
I'm trying to set up a VM network using vmbuilder. When setting it up using Ubuntu 12.04 there are no problems. However, when trying any of the newer LTS (14.04 or 16.04) i get the following error when I try to build my KVM:
```
Configuration file '/etc/sudoers'
==> Modified (by you or by a script) since installation.
==> Package distributor has shipped an updated version.
What would you like to do about it ? Your options are:
Y or I : install the package maintainer's version
N or O : keep your currently-installed version
D : show the differences between the versions
Z : start a shell to examine the situation
The default action is to keep your current version.
*** sudoers (Y/I/N/O/D/Z) [default=N] ? dpkg: error processing package sudo (--configure):
EOF on stdin at conffile prompt
Errors were encountered while processing:
sudo
E: Sub-process /usr/bin/dpkg returned an error code (1)
```
I have read a bunch of similar issues where the recommendation is more or less to blow out the whole system. This is however VERY undesirable in this case since we are running jobs on the computer each day. So please, if anyone knows a workaround??
FYI, this is how my VM.sh looks:
```
vmbuilder kvm ubuntu \
--dest=/home/pett/VM \
--overwrite \
--mem=15000\
--cpus=4 \
--rootsize=10240\
--swapsize=5000\
--addpkg=openssh-server \
--addpkg=vim \
--addpkg=cron \
--addpkg=acpid \
--arch=amd64 \
--suite=trusty\
--flavour virtual \
--components main,universe,restricted \
--hostname Buri \
--user pett \
--pass hello \
--libvirt qemu:///system ;
```
PS the following did NOT solve it:
```
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
```
|
2016/11/23
|
[
"https://askubuntu.com/questions/852814",
"https://askubuntu.com",
"https://askubuntu.com/users/622692/"
] |
I have exactly the same bug, on several fresh 1604 installations. I don't know why this doesn't get fixed, because it would come up if they ever tested this package.
The solution I found from another post is:
1. change the word 'dist-upgrade' to 'update' in
/usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py
2. delete /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.pyc
Annoying that the "solution" to a problem like this is to edit the installed package, but that's what it is.
|
5,307,678 |
how to pass an array containing urls as an image source to imageadapter of the grid view?
I have a working Image adapter. but the problem is the getView method of the adapter returns only one imageview. Can some one tell how to pass an array containing urls to the image adapter of the gridview ? the getview method is here
```
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
if (convertView == null) { // if it's not recycled, initialise some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
} else {
imageView = (ImageView) convertView;
}
// Bitmap bmp = loadBitmap(url[i]);
Bitmap bmp = loadBitmap("http://www.fgj.com/aero/planes/boeing/boeingf15.jpg");
System.out.println("in adapter :" + url[i]);
imageView.setImageBitmap(bmp);
//imageView.setImageResource(mThumbIds[position]);
//Bitmap bmp = loadBitmap("http://www.fgj.com/aero/planes/boeing/boeingf15.jpg");
return imageView;
}
```
|
2011/03/15
|
[
"https://Stackoverflow.com/questions/5307678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335997/"
] |
Unfortunately this is *much* harder than it needs to be. The overview of what you need to do is:
1. Collect the urls you need to fetch.
2. Create an AsyncTask to fetch each one in turn *or* use a pool of AsyncTasks in a thread-pool fashion to service the urls. Somewhere you need to keep track of which url belongs to which position in your `AdapterView` so you can selectively invalidate rows as their images come in.
3. Cache the images you get back to the SD card or in memory.
4. Invalidate rows as their images come in, causing them to reload from the cache.
Personally I think the framework should supply a "WebImage" widget that would make this a bit easier. I guess there are just too many moving parts that it makes sense for each app to implement this on its own.
**Edit** - *unless* you use a library and let someone else do the dirty work. Apparently [DroidFu](https://github.com/kaeppler/droid-fu/) has a solution for this problem: [ImageLoader](http://kaeppler.github.com/droid-fu/com/github/droidfu/imageloader/package-summary.html). I haven't used it, but it's probably less error prone than rolling one's own.
|
461,545 |
Какой вариант верный? Спасибо!
1. Слишком быстро они отнимают у маленького, едва покрытого перьями тельца, драгоценное тепло.
2. Слишком быстро они отнимают у маленького, едва покрытого перьями тельца драгоценное тепло.
|
2020/07/24
|
[
"https://rus.stackexchange.com/questions/461545",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/192143/"
] |
**О качестве ответа**
Как я себе представляю хороший ответ?
С одной стороны, мы отвечаем **конкретному**, а не абстрактному автору, поэтому желательно понять ход его мыслей.
С другой стороны, информационная часть ответа должна иметь **безотносительную ценность**, так как по большому счету каждый ответ влияет на качественный уровень и престижность ресурса.
**1. Почему автор задает подобный вопрос?** Об этом важно подумать при ответе, иначе он будет формальным.
Это проблема **«лишних запятых»**, которые ставятся на месте произносительных пауз. А причина такой паузы в данном случае – **неудачно построенное предложение**. Оно сложно читается и не сразу понимается, в том числе на слух.
Возможное редактирование: *Слишком быстро они отнимают **драгоценное тепло** у маленького, // едва покрытого перьями тельца.*
В этом варианте две фразы, запятая ставится на месте паузы. И порядок слов обоснованный: сначала прямое дополнение (отнимают что?), а потом косвенное (отнимают у кого?)
Сравним: *Слишком быстро они отнимают у маленького, // **едва покрытого перьями тельца драгоценное тепло**.*
Здесь тоже две фразы, но вторая фраза (после запятой) имеет **некорректную по сочетаемости структуру.**
Поэтому при ответе желательно обратить внимание на данный факт.
**2. О самом анализе**
Грамматика и структура предложения становятся ясными, если мы просто **уберем распространенное определение,** тогда получится:
*Слишком быстро они отнимают у (**маленького, едва покрытого перьями**) тельца драгоценное тепло.*
Предлог **У относится к существительному**, поэтому мы не можем разделить их запятой. Вот и всё доказательство. Он намного проще приведенного.
Кстати, однородность определений здесь **неочевидна**, значения разных признаков сближаются в данном тексте (маленький предмет с незащищенной поверхностью остывает быстрее).
|
56,223 |
I've noticed from titles of songs and poems, a definite article is used such as:
>
> 'An die Hoffnung'
>
> 'An die Freude'
>
> 'An die Musik'
>
>
>
A few websites give examples of the use of definite articles before nouns like
>
> 'Der Winter kommt'
>
>
>
rather than
>
> 'Winter kommt'
>
>
>
, but they don't explain why that's the case. I hope the question makes sense.
|
2020/01/30
|
[
"https://german.stackexchange.com/questions/56223",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/41488/"
] |
German word order is not as strict as English word order. You may place subjects and objects as you like. The case markers tell the reader if a noun is a subject or an object, and which type of object.
German has no case markers on nouns apart from some exceptions (genitive singular and dative plural of some declination classes). Instead, it puts the case markers on the words describing a noun further. Adjectives, pronouns, number words. The indefinite article in German is identical with the number word »one«.
If there is no such describing word in front of a noun, you still need a case marker most times. That's when German puts the definite article in front of it.
Whereas, in English the definite article is only put in front of a noun as a pointing finger —a small demonstrative—. This use does exist in German, too, but it's not the only use of the definite article.
|
26,153 |
I have a Channel Form set up which is working fine and inserting entries into a Channel with the default status.
Now there is a requirement to allow the status to be changed when creating the entry via the Channel Form but for the life of me I can't get it to work.
I have tried using the Channel Form {status} tags and also tried hardcoding the select drop down but no matter what I do the default status is applied.
Here's the EE tag version
```
<select id="status" name="status">
{statuses}
<option value="{status}"{selected}>{status}</option>
{/statuses}
</select>
```
And here's the HTML
```
<select name="status">
<option value="Pending">Pending</option>
<option value="Approved">Approved</option>
<option value="Declined">Declined</option>
</select>
```
The only thing I can think of is that I'm trying to set a custom status and not the normal "open" or "closed". Even using standard "open" and "closed" (via the EE generated drop down) doesn't work.
The site is using EE 2.9.0.
Has anyone run into this problem?
|
2014/10/10
|
[
"https://expressionengine.stackexchange.com/questions/26153",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/159/"
] |
I've encountered exactly the same problem with 2.10.1. No matter what I set the status to, it always writes as 'Open'. I'm sure I've got the proper group assigned and title-casing for 'Pending'... I can only conclude it's a system bug.
|
23,654 |
My neighbor who lives across the hall from me in my apartment building is clearly trying to extend an olive branch of friendship. We met at a community gathering for residents a little over a month ago and got along splendidly, but due to opposing work schedules we have not seen each other since. I gather he has some social or professional contact wherein he can get free tickets to sporting events, because for the second time since we exchanged numbers, I've had to politely decline an invitation to a football game. I travel a lot for work, so I legitimately was and will be out of town on the dates in question.
Having just moved here recently, I don't have any friends and would welcome the companionship. My problem is twofold:
1. I don't want him to think that I'm blowing him off. People who consistently refuse invites -- even with good excuses -- stop getting invitations after a while.
2. I have a non-obvious, hard-to-explain visual impairment that makes sporting events *in particular* a no-go for me. It's a neurological condition that affects motion tracking and object recognition, so playing or watching sports is nearly impossible for me to enjoy. Aside from that (or maybe because of it), I'm not much of a sports guy anyway.
I want to let him know I appreciate the overture, and I figure the best thing to do would be to make a counter-proposal. But I don't really know how to do that. Personality-wise I'm an ambivert, so I do well in social situations most of the time; I just don't know how to initiate them.
* I have a very spartan, bachelor-esque studio apartment, so inviting him across the hall is out. I don't have anywhere to entertain guests. I don't even own a TV; I work in IT for a living, so my computer provides all my entertainment needs.
* I don't know what his interests are. Sporting events are such a stereotypical "guy" thing, so no real insight there. He's a lawyer professionally, so I don't know how our social spheres would intersect.
* I'm a homebody by nature and a recent transplant to the area, so I don't know much about what there is to do around town. I've found a few bars and restaurants that I like, but one-on-one those options sound like a date and I don't want to make things awkward. I have no idea what his intentions are.
* I'm rarely available on weekends, so any get-together would likely need to happen in the evening during the week. That precludes most festivals or block party-type events as those typically happen on Friday or Saturday nights.
I don't really know how to ask people to do things with me. How can I reciprocate or otherwise display that I am interested?
Also, how do I respond if he invites me to a game again and I'm actually free to go?
|
2019/12/04
|
[
"https://interpersonal.stackexchange.com/questions/23654",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/284/"
] |
Honesty is the best policy here. He's only going to feel like you're "blowing him off" if your refusals are without reason. If you think more offers are forthcoming, your next response should be something like:
>
> Yes!
>
>
>
Or, if you can't, then:
>
> I'm sorry I keep turning down your invites, I really want to hang out but weekends are usually difficult for me. Can we do something on a weeknight instead?
>
>
>
As you are new in town and want to make friends, you should make an extra effort to take up this offer of friendship, no matter what the event. Unless being at a sports match is physically uncomfortable for you, why not just go along anyway and be honest - say something like "actually, I can't really follow sports because of a vision problem, but I appreciate the company". You can perhaps talk, have a few beers, and find something in common that you can bond over even if the sport doesn't hold any interest for you. In fact, most friendships/relationships rely on some give and take when it comes to choosing places to go, events to attend etc. If you are worried about the fact you've turned down his offers before, he might actually really appreciate it when he learns you came along to a sports match you can't watch properly just for the friendship.
Even if you don't think you're going to be best buddies with this guy because you have different interests, you'll soon meet other people through him, and you may get along better with them. That doesn't mean you're using him to meet people - if he attends things like the community event you met at and *still* wants to make new friends he sounds a pretty gregarious person that is welcoming you, not just into his life, but into his social group.
If you think you've already refused him too many times to get another invite, why not initiate contact and still say the above - that you'd like to hang, but weekends are difficult. See what happens. As he's contacted you several times with offers, he won't think it unusual that you've reached out to him.
If he suggests a one-to-one meeting rather than some social event, let him also suggest the venue - it's unlikely he will invite himself to your house, and if he suggests a bar or restaurant then it shouldn't be any place or setting that will make him feel weird. There are restaurants that feel like a date, but there are loads of places that are casual and normal places for platonic dates.
|
63,983,714 |
What would a piece of code look like which checks today's date, and if it's a particular date, it will print out a message?
The context is that I'm making a birthday cake for my son who codes and I want to write a themed Happy Birthday message on top correctly. (Sorry, not as clever or serious as a lot of the things on here!)
I'd like something which is basically:
```
johnsBirthday = 01/01/1998
johnsAge = todaysdate - johnsBirthday (in years)
if todays date == 01/01/XXXX then print("Happy Birthday John!" + johnsAge + " today!")
```
My knowledge of python is very limited (as I'm sure you can tell from the above) but I vaguely know how to do this in Excel, so I figure there must be a way to do it in python too?
I know could always just write out:
```
print("Happy Birthday, John!")
```
and he'd appreciate that, but I think it would really make him smile to go a little further than that!
|
2020/09/20
|
[
"https://Stackoverflow.com/questions/63983714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14311302/"
] |
```
# Import datetime class from datetime module
from datetime import datetime
birthday = "20/09/1998"
# Parses the string into a datetime object
birthday_obj = datetime.strptime(birthday, '%d/%m/%Y')
# Gets todays date
now = datetime.now()
# Checks the day and month to verify birthday status
if(birthday_obj.day == now.day and birthday_obj.month == now.month):
johns_age = str(now.year - birthday_obj.year)
print("Happy Birthday John! " + johns_age + " today!")
```
|
4,200,359 |
I want to “rank” [primitive] Pythagorean triples by some metric that could reasonably be referred to as “size”.
Naturally, there are a huge number of options: size of hypotenuse, size of smallest leg, perimeter, area, radius of incircle, etc. etc. etc. (Note: One thing I *don’t* want to use is the row index from the triple’s position in one of the infinite ternary trees.)
Is there a widely-accepted “sizing” of triples? What are the pros and cons of various metrics?
EDIT (inspired by Gerry Myerson’s comment): The “Holy Grail” in this investigation would be a strictly “linear” ordering of the Pythagorean triples. Does (or can) such a thing exist?
EDIT #2: Let $(p,q)$ be the Euclid generating pair for a primitive Pythagorean triple. Applying the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) with $p-q$ and $q$ gives a unique integer value for each triple, which *generally* correlates with “size”; and I have yet to find anything more compact (*e.g.,* in a set of $38$ of the “smallest” triples, the area-divided-by-6 range is $1–1820$, while the Cantor function for the same set has a range of $4–106$). What’s clearly missing is any obvious way to “descend” through this ordered set.
EDIT #3: The inradius is the most obvious “size” ranking, since the only gaps in the sequence are the powers of $2$. The issue here is the fact that inradius isn’t unique.
|
2021/07/16
|
[
"https://math.stackexchange.com/questions/4200359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93271/"
] |
Given that side-A is odd, side-B is even, and side-C is odd, they take the form of $A = (2x+1), B=4y, C=4z+1), x,y,z\in\mathbb{N}.\quad$ Finding them is a relatively easy but pick any of the three and the solution seems incomplete without the other two. Also, side-A is larger than side-B for half of all triples. (I can demonstrate this if you want.)
Here are some other ratings and methods of finding them. Beginning with Euclid's formula shown here as
$ \qquad A=m^2-k^2\qquad B=2mk \qquad C=m^2+k^2.\qquad$ Note: any m-value that yields an integer k-value yields a valid Pythagorean triple.
$\bullet\space$ Perimeter in sizes shown [here](https://oeis.org/A024364)
\begin{equation}
P=2m^2+2mk\implies k=\frac{P-2m^2}{2m}\\
\text{for} \quad \biggl\lfloor\frac{\sqrt{4P+1}+1}{4}\biggr\rfloor\le m \le \biggl\lfloor\frac{\sqrt{2P+1}-1}{2}\biggr\rfloor
\end{equation}
The lower limit ensures that $m>k$ and the upper limit insures that $k\ge1$.
$$P=286\implies \biggl\lfloor\frac{\sqrt{1144+1}+1}{4}\biggr\rfloor =8\le m \le \biggl\lfloor\frac{\sqrt{572+1}-1}{2}\biggr\rfloor=11\\
\land\quad m\in\{11\}\implies k\in\{2\}$$
$$F(11,2)=(117,44,125)\qquad P=(117+44+125)=286$$
$\bullet\space$ Area:perimeter ratio$\space$ (All are multiples of $\frac{1}{2}$ and here is a way to find them)
$$R=\frac{area}{perimeter}=\frac{AB}{2P}=\frac{2mk(m^2-k^2)}{2(2m^2+2mk)}=\frac{mk-k^2}{2}
$$
\begin{equation}
R=\frac{mk-k^2}{2}\quad\implies k=\frac{m\pm\sqrt{m^2-8R}}{2}\\\text{for}\quad \big\lceil\sqrt{8R}\big\rceil\le m \le (2R+1)
\end{equation}
The lower limit insures that $k\in \mathbb{N}$ and the upper limit ensures that $m> k$.
$$R=1\implies \lceil\sqrt{8}\rceil=3\le m \le (2+1)=3 \\\land\qquad m\in\{ 3\}\implies k\in\{ 2,1\}$$
$$F(3,2)=(5,12,13)\space\land\space \frac{30}{30}=1\qquad F(3,1)=(8,6,10)\space\land\space \frac{24}{24}=1$$
$\bullet\space$ Area (Sizes are multiples of $6$ listed in [this](https://oeis.org/A009112) series). Up to $3$ distinct triples can have the same area.
\begin{equation}
k\_0=\sqrt{\frac{4m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\cos^{-1}{\biggl(-\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}
\\ k\_1=\sqrt{\frac{4m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\cos^{-1}{\biggl(\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}
\\ k\_2=k\_1-k\_0
\\\qquad\text{ for }\quad\bigg\lfloor\sqrt[\LARGE{4}]{\frac{8D}{3}}\bigg\rfloor
\le m \le\big\lceil\sqrt[\LARGE{3}]{D}\big\rceil
\end{equation}
$$D=840\implies \lfloor\sqrt[\LARGE{4}]{2(840)}\rfloor=7 \le m \le \lceil\sqrt[\LARGE{3}]{840}\rceil=10\quad\text {and we find}$$
$$m\in \{7\}\implies k\in\{5,8,3\}\qquad\land\qquad m\in\{8\}\implies k\in\{7\}$$
$$\text{We find }\qquad S\_{mk}=\{(7,5), (7,8), (7,3), (8,7)\}$$
$$F(7,5)=(24,70,74)\quad F(7,8)=(-15,112,113)\\ F(7,3)=(40,42,58)\quad F(8,7)=(15,112,113)$$
$\bullet\space$ A,B,C product sizes seen [here](https://oeis.org/A057096)
( All are multiples of $60$. Finding them requires a more convoluted solution available on request.)
$\bullet\space B-A=1$ side difference.
An interesting solution to $B-A=1$ was provided by Wacław Sierpiński, $\textit{Pythagorean triangles}$,
THE SCRPTA MATHEMATICA STUDIES Number NINE, ,
GRADUATE SCHOOL OF SCIENCE YESHIVA UNIVERSITY, NEW YORK, 1962, pp. 17-22
with a formula that generates these triples $(T\_n)$ sequentially with a starting "seed" of $T\_0=(0,0,1)$.
\begin{equation}T\_{n+1}=3A\_n+2C\_n+1\qquad B\_{n+1}=3A\_n+2C\_n+2 \qquad C\_{n+1}=4A\_n+3C\_n+2\end{equation}
$$T\_1=(3,4,5)\qquad T\_2=(20,21,29)\qquad T\_3=(119,120,169)\qquad \textbf{ ...}$$
In casual testing, it appears that only the sums and products of A,B,C have unique solutions (only one triple per value) and Area/Perimeter ratio is a pleasing set
$\big(R=\big\{\frac{1}{2},\frac{2}{2},\frac{3}{2},\cdots\big\}\big)$
so perhaps one of these are the most "natural" series to pursue.
$\textbf{Update:}$ Gerry Myerson has shown below that perimeter does not map to a unique triple.
|
59,608,312 |
I am trying to set up the workspace for creating mods for Minecraft. I installed JRE, installed JDK 8. I installed eclipse. I downloaded the latest mdk file of minecraft forge. I setup the environment variables for JDK. I extracted the forge zip file. I opened powershell in the extracted forge folder. I ran the command `.\gradlew setupDecompWorkspace`. I am getting the following error:
```
> FAILURE: Build failed with an exception.
>
> * What went wrong: A problem occurred configuring root project 'First Mod'.
> > Could not resolve all files for configuration ':_compileJava_1'.
> > Could not resolve com.mojang:patchy:1.1.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve oshi-project:oshi-core:1.1.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.ibm.icu:icu4j-core-mojang:51.2.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:javabridge:1.0.22.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:brigadier:1.0.17.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:datafixerupper:2.0.24.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:authlib:1.5.25.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:text2speech:1.11.3.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
>
> * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
>
> * Get more help at https://help.gradle.org
>
> Deprecated Gradle features were used in this build, making it
> incompatible with Gradle 5.0. Use '--warning-mode all' to show the
> individual deprecation warnings. See
> https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
```
How do I fix this error? I even tried the other command that I found online. ".\gradlew genEclipseRuns` this gives the following error:
```
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'First Mod'.
> Could not resolve all files for configuration ':_compileJava_1'.
> Could not resolve com.mojang:patchy:1.1.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve oshi-project:oshi-core:1.1.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.ibm.icu:icu4j-core-mojang:51.2.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:javabridge:1.0.22.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:brigadier:1.0.17.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:datafixerupper:2.0.24.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:authlib:1.5.25.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:text2speech:1.11.3.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 44s
```
This is the gradle.build file present in the minecraft forge folder:
```
buildscript {
repositories {
maven { url = 'https://files.minecraftforge.net/maven' }
jcenter()
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true
}
}
apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
version = '1.0'
group = 'com.yourname.modid' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'modid'
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
minecraft {
// The mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD Snapshot are built nightly.
// stable_# Stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'snapshot', version: '20190719-1.14.3'
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
server {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/')
mods {
examplemod {
source sourceSets.main
}
}
}
}
}
dependencies {
// Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed
// that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.15.1-30.0.26'
// You may put jars on which you depend on in ./libs or you may define them like so..
// compile "some.group:artifact:version:classifier"
// compile "some.group:artifact:version"
// Real examples
// compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
// compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
// provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// These dependencies get remapped to your current MCP mappings
// deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest {
attributes([
"Specification-Title": "examplemod",
"Specification-Vendor": "examplemodsareus",
"Specification-Version": "1", // We are version 1 of ourselves
"Implementation-Title": project.name,
"Implementation-Version": "${version}",
"Implementation-Vendor" :"examplemodsareus",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
// Example configuration to allow publishing using the maven-publish task
// we define a custom artifact that is sourced from the reobfJar output task
// and then declare that to be published
// Note you'll need to add a repository here
def reobfFile = file("$buildDir/reobfJar/output.jar")
def reobfArtifact = artifacts.add('default', reobfFile) {
type 'jar'
builtBy 'reobfJar'
}
publishing {
publications {
mavenJava(MavenPublication) {
artifact reobfArtifact
}
}
repositories {
maven {
url "file:///${project.projectDir}/mcmodsrepo"
}
}
}
```
|
2020/01/06
|
[
"https://Stackoverflow.com/questions/59608312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10551333/"
] |
I think the gradle version you are using is too high.Youre currently using gradle 5.0 and you should try to use gradle 4.9.
|
55,665,395 |
I am supposed to solve Problem 25 from Projecteuler. Below is my code, I have no clue, why it is not working.
Can anyone help me?
```
n <- 0
a <- 1
b <- 1
c <- 0
while (nchar(a)<1000)
n <- n+1
c <- b
b <- a
a <- a + c
```
Thanks
|
2019/04/13
|
[
"https://Stackoverflow.com/questions/55665395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10432814/"
] |
Generation of non-repeatable numbers is not an easy task compared to a simple shuffling the array or a collection using [`Collections::shuffle`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#shuffle-java.util.List-).
```
final String[] fruitArray = new String[]{"apple", "orange", "pear", "banana",
"cherry", "blueberry", "papaya", "litchi"};
// SHUFFLE
final List<String> fruitList = Arrays.asList(fruitArray);
Collections.shuffle(fruitList);
// TEST IT
fruitList.stream()
.limit(4) // sets the count to 4
.forEach(System.out::println); // prints qualified random items without repetition
```
|
318,005 |
When you actually read what's written in the [Help Center](https://meta.stackexchange.com/help/referencing), it strongly implies that only *answers* need to give attribution (see added emphasis):
>
> Plagiarism - posting the work of others with no indication that it is not your own - is frowned on by our community, and may result in your **answer** being down-voted or deleted.
>
>
> When you find a useful resource that can help **answer** a question (from another site or in an answer on Stack Overflow) make sure you do all of the following
>
>
>
Can this be changed to be more inclusive of questions (and perhaps tag wikis)?
---
My best suggestion:
>
> Plagiarism - posting the work of others with no indication that it is not your own - is frowned on by our community, and may result in your **post** being down-voted or deleted.
>
>
> When you use a resource in your post (e.g. from another site or in an answer on Stack Overflow) make sure you do all of the following
>
>
>
|
2018/11/08
|
[
"https://meta.stackexchange.com/questions/318005",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/323179/"
] |
This was finally changed, though the help page still lives under the "answering" category. To quote (emphasis added):
>
> Plagiarism - posting the work of others with no indication that it is not your own - is frowned on by our community, and may result in your **content** being down-voted or deleted.
>
>
> If you copy (or closely rephrase/reword) content that you did not create into **something you post** on Meta Stack Exchange (e.g. from another site or elsewhere on Meta Stack Exchange) make sure you do all of the following
>
>
>
And since I must reference the author, [shoutout to Catija](https://meta.stackoverflow.com/a/416676/6083675).
|
14,884,516 |
I have a table formatted like the one below, i want to split it up so theres a column for month and year ie. January 2014 then another column for cost. So effectively each row would be split into 12 different rows, but i cant for the life of me figure out how to approach it. Any help would be greatly appreciated
```
CREATE TABLE dbo.Line14(
ItemID int IDENTITY(1,1) NOT NULL,
Detail nvarchar(max) NULL,
Type nvarchar(255) NULL,
Cat nvarchar(255) NULL,
Jan_14 money NULL,
Feb_14 money NULL,
Mar_14 money NULL,
Apr_14 money NULL,
May_14 money NULL,
Jun_14 money NULL,
Jul_14 money NULL,
Aug_14 money NULL,
Sep_14 money NULL,
Oct_14 money NULL,
Nov_14 money NULL,
Dec_14 money NULL
) ON PRIMARY TEXTIMAGE_ON PRIMARY
GO
```
|
2013/02/14
|
[
"https://Stackoverflow.com/questions/14884516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902540/"
] |
You should be able to use the [`UNPIVOT`](http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) function which converts the data from columns into rows:
```
select itemid,
detail,
type,
cat,
Month,
2014 as Year,
value
from Line14
unpivot
(
value
for Month in (Jan_14, Feb_14, Mar_14, Apr_14,
May_14, Jun_14, Jul_14, Aug_14,
Sep_14, Oct_14, Nov_14, Dec_14)
) unpiv
```
See [SQL Fiddle with Demo](http://www.sqlfiddle.com/#!6/b4b6a/1).
The result would be similar to this:
```
| ITEMID | DETAIL | TYPE | CAT | MONTH | YEAR | VALUE |
---------------------------------------------------------
| 1 | Test | C | blah | Jan_14 | 2014 | 10 |
| 1 | Test | C | blah | Feb_14 | 2014 | 12 |
| 1 | Test | C | blah | Mar_14 | 2014 | 45 |
| 1 | Test | C | blah | Apr_14 | 2014 | 56 |
| 1 | Test | C | blah | May_14 | 2014 | 89 |
| 1 | Test | C | blah | Jun_14 | 2014 | 78 |
| 1 | Test | C | blah | Jul_14 | 2014 | 96 |
| 1 | Test | C | blah | Aug_14 | 2014 | 35 |
| 1 | Test | C | blah | Sep_14 | 2014 | 55 |
| 1 | Test | C | blah | Oct_14 | 2014 | 30 |
| 1 | Test | C | blah | Nov_14 | 2014 | 99 |
| 1 | Test | C | blah | Dec_14 | 2014 | 120 |
```
|
7,328 |
I have a very High resolution image in illustrator, which leads to a very heavy eps file size, I'm asking for a batch tool or a script to compress the eps image , in other words reduce its resolution without affecting the width and height of the image.I don't want to export the image as a separated Jpg file
|
2012/05/08
|
[
"https://graphicdesign.stackexchange.com/questions/7328",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/4501/"
] |
Object > Rasterize and choose a lower resolution setting.
This will embed any linked image, however.
|
24,408,248 |
Recently I downloaded qemu, and ran configure, make and make install.
when I run
```
qemu-system-sparc linux-0.2.img
```
I just see a message below
>
> VNC server running on `::1:5900'
>
>
>
At this state, when I open vncviewer window by typing `vncviewer :5900`, then I see the window.
The window shows the emulated screen
>
> Welcome to OpenBIOS v1.1 build on Mar 10 2014 08:41
>
> Type 'help'
> for detailed information
>
> Trying disk...
>
> No valid state has been
> set by load or init-program
>
> 0>
>
>
>
How can I make the vnc window come up automatically? and how do I supply right linux image?
when I build my linux image, I can get sImage.elf or sImage.bin which contains the file system too.
|
2014/06/25
|
[
"https://Stackoverflow.com/questions/24408248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1511337/"
] |
I solved this problem by installing sdl-devel to my CentOS.
I reran ./configure --target-list=sparc-softmmu --enable-sdl
and did make, make install
and the problem is gone!
|
46,877 |
I'm trying to enable my polystrips addon but I receive this error every time I try to check the enable addon box.[](https://i.stack.imgur.com/04VOC.png)
|
2016/02/13
|
[
"https://blender.stackexchange.com/questions/46877",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/21819/"
] |
It appears you need to grab the code from here <https://github.com/CGCookie/retopology-lib> and put the source files (ie `__init__.py, common_utilities.py, common_drawing.py, common_classes.py`) into the empty retopology-polystrips-master/lib folder
|
336,692 |
I'm having a lot of trouble to find lore.
I exhausted the bookstore, the auction, Mansur until the Stag door and the expeditions I could find. Where else can I find lore?
|
2018/07/28
|
[
"https://gaming.stackexchange.com/questions/336692",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/116230/"
] |
This is the way I see to be the quickest path to acquire Lore:
1. Keep buying everything from Morland's Shop. It will keep bringing books to study that will become Lore.
2. When Morland's shop closes, start buying books at Oriflamme's Auction House until it doesn't have any more books to sell. Oriflamme can also be found by a believer **Exploring**.
3. If you **Explore** with Secret Histories Lore, they will convert into Aspect: Location+Vault. Those might bring back more Lore. [Here is](https://steamcommunity.com/sharedfiles/filedetails/?id=1402554171) a comprehensive description and requirements for all expeditions.
4. **Dream** with Passion and in the slot add a Lantern or Knock Lore. It will bring you **Way: The wood**. [This guide](https://www.reddit.com/r/weatherfactory/comments/8ohdsw/a_mostly_comprehensive_guide_to_cultist_simulator/) at *The Mansus* section has a great explanation on how to open each location further and what you will find there. The idea here is to grab all the Secret Histories you can find and transform them into expeditions (as commented above). Expeditions bring a lot of Lore.
5. If you already made/have all the expeditions of a certain level (they start to repeat the location), start to "merge" the same Secret Histories to get advanced levels of them.
6. Some Lore books need to be translated. Some Patrons can translate those books if you pay them with Spintria. Patrons pays their commissions with Spintria or you can get it from expeditions. [You will have to summon](https://cultistsimulator.gamepedia.com/Spirits) Teresa, King Crucible and Ezeem to learn Fucine, Deep Mandaic and Phrygian respectively.
|
9,561,093 |
I have an XML column with this value
```
<sso_links>
<linktype>mytype</linktype>
<url>http://mydomain.com</url>
<linktype>mytype2</linktype>
<url>http://somedomain.com</url>
</sso_links>
```
I've tried using SQL to query this by value but this only returns scalar type
```
SELECT XMLCOLUMN.value('//linktype[1]', varchar(max)),
XMLCOLUMN.value('//url[1]', varchar(max))
from table
where someid = '1'
```
This produced 2 rows from the XML. How can I output all values?
|
2012/03/05
|
[
"https://Stackoverflow.com/questions/9561093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248945/"
] |
Oftentimes such patterns are evaluated in order, with the first prefix matching being the one chosen.
Try moving your most general regex to the end:
```
application = webapp.WSGIApplication([
('/(\w+)',MainMain)],
('/', MainMain),
debug=True)
```
|
65,441,773 |
Here's the workflow:
Get a https link --> write to filesystem --> read from filesystem --> Get the sha256 hash.
*It works all good on my local machine running node 10.15.3 But when i initiate a lambda function on AWS, the output is null.* Some problem may lie with the readable stream. Here's the code. You can run it directly on your local machine. It will output a sha256 hash as required. If you wish to run on AWS Lambda, Comment/Uncomment as marked.
```
//Reference: https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries
var https = require('https');
var fs = require('fs');
var crypto = require('crypto')
const url = "https://upload.wikimedia.org/wikipedia/commons/a/a8/TEIDE.JPG"
const dest = "/tmp/doc";
let hexData;
async function writeit(){
var file = fs.createWriteStream(dest);
return new Promise((resolve, reject) => {
var responseSent = false;
https.get(url, response => {
response.pipe(file);
file.on('finish', () =>{
file.close(() => {
if(responseSent) return;
responseSent = true;
resolve();
});
});
}).on('error', err => {
if(responseSent) return;
responseSent = true;
reject(err);
});
});
}
const readit = async () => {
await writeit();
var readandhex = fs.createReadStream(dest).pipe(crypto.createHash('sha256').setEncoding('hex'))
try {
readandhex.on('finish', function () { //MAY BE PROBLEM IS HERE.
console.log(this.read())
fs.unlink(dest, () => {});
})
}
catch (err) {
console.log(err);
return err;
}
}
const handler = async() =>{ //Comment this line to run the code on AWS Lambda
//exports.handler = async (event) => { //UNComment this line to run the code on AWS Lambda
try {
hexData = readit();
}
catch (err) {
console.log(err);
return err;
}
return hexData;
};
handler() //Comment this line to run the code on AWS Lambda
```
|
2020/12/24
|
[
"https://Stackoverflow.com/questions/65441773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10845323/"
] |
I'm not sure why std::map is necessary, but this should do what you want.
```
for (const auto& s : synonyms) {
auto object = s.begin();
if (object->first == word || object->second == word) {
++amount;
}
}
```
Since each element in your set `s` is a map of size 1, you can access its element by using an iterator on its beginning.
|
20,388,634 |
I want to print doubles so that the decimals line up. For example:
```
1.2345
12.3456
```
should result in
```
1.2345
12.3456
```
I have looked everywhere, and the top recommendation is to use the following method (the 5s can be anything):
```
printf(%5.5f\n");
```
I have tried this with the following (very) simple program:
```
#include <stdio.h>
int main() {
printf("%10.10f\n", 0.523431);
printf("%10.10f\n", 10.43454);
return 0;
}
```
My output is:
```
0.5234310000
10.4345400000
```
Why doesn't this work?
|
2013/12/04
|
[
"https://Stackoverflow.com/questions/20388634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813111/"
] |
The number before the `.` is minimum characters *total*, not just before the radix point.
```
printf("%21.10f\n", 0.523431);
```
|
725,261 |
I have a word doc where when you look at the file preview in the Finder window on a mac (osx), it shows the first page and on the upper right corner of the page, theres a Qlikview logo (im guessing Qlikview contributed to the creation of the document). However when you open the document itself, the logo is not there and the document is in the correct/desired formatting.
I've tried
-saving it as a new file
-saving it as a .doc instead of .docx
-converting to google doc then downloading as .docx but the formatting is affected
-changing security settings on MS Word to "remove personal information from this file upon saving"
-checking for water marks/settings
-copy/pasting entire doc onto a new doc and saving
and none of these got rid of the mark.
Anyone know how to fix this or get around it? Or how to disable doc preview for this file only? Any help would be appreciated. Thanks!
|
2014/03/06
|
[
"https://superuser.com/questions/725261",
"https://superuser.com",
"https://superuser.com/users/305427/"
] |
I found this page after having the same issue. Solution:
Click into your header /footer. Click > Different First Page.
The logo and header will come up from an old source.
Delete it, and then unselect Different First Page.
Problem solved!
|
109,677 |
On a site that I operate I use several layers of protection for our subscription content. Among the other protections, each content item is placed into a folder with a randomly generated 19-character name. That name can include numbers, lowercase letters, and uppercase letters.
While it will not really lower the benefit provided by this layer of protection for a second file to end up in a folder, I am curious about the chances of that happening. That leads me to two related questions:
1. Assuming that we have 2500 files/folders, what is the chance that the next folder we generate will be a repeat?
2. How many folders must exist for the chance of repetition to rise above 1%?
|
2012/02/15
|
[
"https://math.stackexchange.com/questions/109677",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/25055/"
] |
Let's say you generate $K$-character folder names from an alphabet consisting of $A$ different symbols, and you currently have $N$ *distinctly named* folders.
The chance of a particular folder name being generated is $1 / A^K$. The chance that your next folder name matches one that already exists therefore $N/A^K$.
For this to be above a particular value $p$, you need $N > pA^K$.
For you, you have $K=19$, $A=62$ and $N=2500$, so the chance of a repeat is $2500/62^{19}$, whcih is around 1 part in $5\times 10^{30}$, i.e. vanishingly small.
For there to be a greater than 1% chance of a collision, you need $N > 0.01 \times 62^{19} = 10^{32}$ folders.
Note that since each folder name takes up around 20 bytes (19 characters plus a null character), you would need in excess of $10^{24}$ GB of disk space just to store the names of this many folders, never mind their contents.
|
9,253,662 |
So I am going to be doing some work with R soon, and I need to learn how to use it. I figured a good exercise would be to try to write a program that takes a payoff matrix and does iterated elimination of dominated strategies (if you don't know what I'm talking about, it's very simple game theory stuff and not really important to the question). The first step was to write a function that takes a matrix and returns a summary of all strategies that are dominated, but something is going wrong.
```
strictdomlist <- function(m) {
# takes a matrix, determines if row player has strictly
# dominated strategies
strategies <- dim(m)[1]
dominatingstrategies <- list()
for (i in 1:strategies) {
dstrat <- 0
for (j in 1:strategies) {
if (i != j) {
if (all(m[i, ]<m[j, ])) dstrat <- c(dstrat,j)
}
}
dominatingstrategies[i] <- dstrat
}
return(dominatingstrategies)
}
```
All (I wish) it's doing is checking each row to see if there is a row which has entries that are all greater. If there is, it should put the number of that row in a vector, and then at the end, assign that vector to the i-th position in dominatingstrategies. If I give it this matrix:
```
[,1] [,2] [,3] [,4]
[1,] 1 4 2 10
[2,] 2 5 9 11
[3,] 0 1 1 1
[4,] 16 7 10 12
```
I want it to give me back:
```
[[1]]
[1] 2 4
[[2]]
[1] 4
[[3]]
[1] 1 2 4
[[4]]
[1] 0
```
But what it's giving me is:
```
> strictdomlist(m2)
[[1]]
[1] 4
[[2]]
[1] 4
[[3]]
[1] 4
[[4]]
[1] 0
Warning messages:
1: In dominatingstrategies[i] <- dstrat :
number of items to replace is not a multiple of replacement length
2: In dominatingstrategies[i] <- dstrat :
number of items to replace is not a multiple of replacement length
3: In dominatingstrategies[i] <- dstrat :
number of items to replace is not a multiple of replacement length
```
Can anyone see what I'm doing wrong? And, if there's a better way of doing this in R, can you help?
Thank you!
|
2012/02/12
|
[
"https://Stackoverflow.com/questions/9253662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205762/"
] |
It's your list assignment:
```
dominatingstrategies[i] <- dstrat
```
To assign into a list, you have to use double square brackets:
```
dominatingstrategies[[i]] <- dstrat
```
When you use single brackets, you extract the *list* containing the vector contained in `dominatingstrategies[i]`, not the vctor itself.
Also, since you start your `dstrat` at 0, you get this matrix out (with the above error fixed):
```
> strictdomlist(m)
[[1]]
[1] 0 2 4
[[2]]
[1] 0 4
[[3]]
[1] 0 1 2 4
[[4]]
[1] 0
```
i.e., you get a `0` out in every element, including ones which have greater rows.
If you don't want this, you can initialise `dstrat` as `dstrat <- c()`, and then at the end do something like
```
if (length(dstrat)==0)
dominatingstrategies[[i]] <- 0
else
dominatingstrategies[[i]] <- dstrat
```
|
29,820,214 |
I need to test a JavaScript project. There are described several modules but when I try to load them something goes wrong.
```
define([
'core/BaseModel'
],
function (BaseModel) {
var MessageModel = BaseModel.extend({
defaults: {
messageType: "Advertisment",
receiver: "me",
title: "Title",
heading_1: "Heading1",
heading_2: "Heading2"
},
url: function () {
var base = this.apipath + '/companies/';
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
}
});
return MessageModel;
});
```
To load the module I do this:
```
var message;
beforeAll(function(done){
require(['../../../public/js/app/models/Message'], function(Message){
message = Message;
done();
});
});
```
Now message is not undefined but when I test if message.defaults or message.url is defined this fails. what is wrong there?
|
2015/04/23
|
[
"https://Stackoverflow.com/questions/29820214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2818992/"
] |
Given that ***../../../public/js/app/models/Message*** corresponds to the `MessageModel`, what you want to do is:
`var Message = require('../../../public/js/app/models/Message');`
and to create a new instance: `var m = new Message();`
Hope this helps.
|
381,611 |
Multiple questions on meta indicate, that code-only answers, if they are self-explanatory and, what's more important, correct, do not fall into *low quality*: [1](https://meta.stackoverflow.com/questions/303772/failed-audit-when-commenting-on-code-only-answer), [2](https://meta.stackoverflow.com/a/258676/7606764).
Meanwhile I failed the audit when I accepted a code-only answer:
[](https://i.stack.imgur.com/5mIm3.png)
What is wrong with that?
Edit: I think this question is more specific, than duplicate candidate as it limits itself to code-only answers.
|
2019/03/21
|
[
"https://meta.stackoverflow.com/questions/381611",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/7606764/"
] |
>
> *"if they are self-explanatory"*.
>
>
>
That answer is not self-explanatory.
It's a code dump where the OP has to figure out what changed, and more importantly: *why*. It doesn't explain why the changes make the code work.
Answers like that *are* of low quality. Maybe not enough to flag or delete them, but they definitely don't look "Ok". (I usually downvote cases like that)
When in doubt, `Skip` the review.
|
52,305,729 |
I'm new to React JS and am trying to implement something similar to the Angular sample application.
I have a table of customers and want to seen the selected customer at the bottom of the table.
I tried the following with react-router-dom:
```
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
// App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
import Customers from './components/customers';
import Customer from './components/customer';
export default class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
<Customers />
<Route path={`/customer/:id`} component={Customer} />
</React.Fragment>
);
}
}
// customers.jsx
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Customers extends Component {
state = {
customers: []
};
render() {
return (
<React.Fragment>
<header className="jumbotron"><h1>Customer List</h1></header>
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.customers.map(c => (<tr key={c.id}><td><Link to={`/customer/${c.id}`}>{c.name}</Link></td><td>{c.address}</td></tr>))}
</tbody>
</table>
<hr />
</div>
<footer className="footer">© 2018</footer>
</React.Fragment>
);
}
async componentDidMount() {
const result = await fetch('http://api.com/customers');
const customers = await result.json();
this.setState({ customers });
console.log(this.state.customers);
}
}
// customer.jsx
import React, { Component } from 'react';
export default class Customer extends Component {
render() {
return (<p>Customer</p>);
};
}
```
The line in App.js that adds the Route (Route path={`/customer/:id`} component={Customer}) is causing the error. If I remove that line I can see the table of customers but as soon as I add this line, then I get that error message.
Did I miss something on how this router works?
Thank you.
**UPDATE**
Event changing App.js to this very simple version causes the error
```
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
export default class App extends Component {
state = {
};
render() {
return (
<div>
<Route exact path='/' render={() => (<h1>Hello</h1>)} />
<Route exact path='/customer' render={() => (<h1>Customer</h1>)} />
</div>
);
}
}
```
The full error message is:
**Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.**
|
2018/09/13
|
[
"https://Stackoverflow.com/questions/52305729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583658/"
] |
change this:
```
import {Route} from "react-router-dom/Route";
```
to this:
```
import Route from "react-router-dom/Route";
```
Route is a default export when you access it directly: `"react-router-dom/Route"`
You can use named exports when you import `Route` from base package
```
import {Route} from "react-router-dom";
```
But don't mix the two.
|
16,269,897 |
For the last month, we've had a bot scraping our site regularly, leading to a bunch of `ArgumentError: invalid %-encoding` errors because the URLs are malformed. I've looked at a bunch of issues in rack [here](https://github.com/rack/rack/issues/337) and [here](https://github.com/rack/rack/issues/225) and rails [here](https://github.com/rails/rails/issues/2622), and looked at [this SO thread](https://stackoverflow.com/questions/15769681/rails-rack-argumenterror-invalid-encoding-for-post-data) but there doesn't seem to be a definitive solution. Is there a correct solution for GET errors? Do I have to monkeypatch rack?
edit: And here's a backtrace:
```
/usr/local/lib/ruby/1.9.1/uri/common.rb:898:in `decode_www_form_component'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:41:in `unescape'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:94:in `block (2 levels) in parse_nested_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:94:in `map'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:94:in `block in parse_nested_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:93:in `each'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/utils.rb:93:in `parse_nested_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/request.rb:332:in `parse_query'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/request.rb:269:in `parse_query'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/request.rb:186:in `GET'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/request.rb:225:in `GET'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/parameters.rb:10:in `parameters'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/http/filter_parameters.rb:33:in `filtered_parameters'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal/instrumentation.rb:21:in `process_action'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
[GEM_ROOT]/gems/activerecord-3.2.12/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/abstract_controller/base.rb:121:in `process'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/abstract_controller/rendering.rb:45:in `process'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal.rb:203:in `dispatch'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_controller/metal.rb:246:in `block in action'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:73:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:36:in `call'
[GEM_ROOT]/gems/journey-1.0.4/lib/journey/router.rb:68:in `block in call'
[GEM_ROOT]/gems/journey-1.0.4/lib/journey/router.rb:56:in `each'
[GEM_ROOT]/gems/journey-1.0.4/lib/journey/router.rb:56:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:601:in `call'
[GEM_ROOT]/gems/omniauth-1.1.1/lib/omniauth/strategy.rb:177:in `call!'
[GEM_ROOT]/gems/omniauth-1.1.1/lib/omniauth/strategy.rb:157:in `call'
[GEM_ROOT]/gems/sass-3.2.7/lib/sass/plugin/rack.rb:54:in `call'
[GEM_ROOT]/gems/warden-1.2.1/lib/warden/manager.rb:35:in `block in call'
[GEM_ROOT]/gems/warden-1.2.1/lib/warden/manager.rb:34:in `catch'
[GEM_ROOT]/gems/warden-1.2.1/lib/warden/manager.rb:34:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/etag.rb:23:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/conditionalget.rb:25:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/head.rb:14:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/params_parser.rb:21:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/flash.rb:242:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:210:in `context'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:205:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/cookies.rb:341:in `call'
[GEM_ROOT]/gems/activerecord-3.2.12/lib/active_record/query_cache.rb:64:in `call'
[GEM_ROOT]/gems/activerecord-3.2.12/lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:405:in `_run__497203393471184793__call__4495106819278994598__callbacks'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:405:in `__run_callback'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/callbacks.rb:81:in `run_callbacks'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/rack/logger.rb:32:in `call_app'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/rack/logger.rb:16:in `block in call'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/tagged_logging.rb:22:in `tagged'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/rack/logger.rb:16:in `call'
[GEM_ROOT]/gems/actionpack-3.2.12/lib/action_dispatch/middleware/request_id.rb:22:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/methodoverride.rb:21:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/runtime.rb:17:in `call'
[GEM_ROOT]/gems/activesupport-3.2.12/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
[GEM_ROOT]/gems/rack-1.4.5/lib/rack/lock.rb:15:in `call'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:136:in `forward'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:143:in `pass'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:172:in `rescue in lookup'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:168:in `lookup'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:66:in `call!'
[GEM_ROOT]/gems/rack-cache-1.2/lib/rack/cache/context.rb:51:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/engine.rb:479:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/application.rb:223:in `call'
[GEM_ROOT]/gems/railties-3.2.12/lib/rails/railtie/configurable.rb:30:in `method_missing'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/request_handler.rb:96:in `process_request'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_request_handler.rb:516:in `accept_and_process_next_request'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_request_handler.rb:274:in `main_loop'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:206:in `start_request_handler'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:171:in `block in handle_spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/utils.rb:479:in `safe_fork'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:166:in `handle_spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:180:in `start'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/rack/application_spawner.rb:129:in `start'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:253:in `block (2 levels) in spawn_rack_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:246:in `block in spawn_rack_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server_collection.rb:82:in `block in synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:244:in `spawn_rack_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:137:in `spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
/usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.13/helper-scripts/passenger-spawn-server:99:in `<main>'
```
|
2013/04/29
|
[
"https://Stackoverflow.com/questions/16269897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/703019/"
] |
Java is case-sensitive. The `static` keyword must be lowercase. Your code does not have `static` in all-lowercase; therefore, the compiler interprets `Static` as a return type, interprets the actual return type as the name, and then chokes on the actual name.
To fix this, simply change `Static` to `static` everywhere.
|
74,767 |
In using the SerialTransfer.h / pySerialTransfer libraries to send commands between my laptop and an Arduino Mega, I am sending multiple sequential strings between the devices. However, I'm having trouble "clearing" the receiving buffer on the Arduino side - it never shrinks, despite a few different attempts to clear the string (memset; a for loop).
I'm sending a string to the Arduino of the format , where there are anywhere from 1 to 5 asterisks. Then the Arduino is simply sending the exact same string back, without any processing (as of yet). And in the python terminal, I'm printing it all out; this is what I get:
```
SENT (17 bytes): <rand_len_str=**>
RECD (17 bytes): <rand_len_str=**>
SENT (18 bytes): <rand_len_str=***>
RECD (18 bytes): <rand_len_str=***>
SENT (19 bytes): <rand_len_str=****>
RECD (19 bytes): <rand_len_str=****>
SENT (17 bytes): <rand_len_str=**>
RECD (19 bytes): <rand_len_str=**>*>
SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>
SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>
```
As long as the string is growing, all is well - but see the error in the 4th pair, with the extra \*> characters, etc.
The following is my Arduino code; I've tried to reset the receiving string using memset, but this seems not to be working.
```
#include "SerialTransfer.h"
SerialTransfer myTransfer;
const int CMD_LEN = 200;
char buff[CMD_LEN];
char received_str[CMD_LEN];
void setup()
{
Serial.begin(115200);
myTransfer.begin(Serial);
}
void loop()
{
if(myTransfer.available())
{
//////////////////////////////////////////////
// handle call from Python
memset(received_str, '\0', CMD_LEN*sizeof(char));
myTransfer.rxObj(received_str, CMD_LEN);
sprintf(buff, "%s", received_str);
//////////////////////////////////////////////
//////////////////////////////////////////////
// send response
myTransfer.txObj(buff, strlen(buff));
myTransfer.sendData(strlen(buff));
//////////////////////////////////////////////
}
else if(myTransfer.status < 0)
{
Serial.print("ERROR: ");
if(myTransfer.status == -1)
Serial.println(F("CRC_ERROR"));
else if(myTransfer.status == -2)
Serial.println(F("PAYLOAD_ERROR"));
else if(myTransfer.status == -3)
Serial.println(F("STOP_BYTE_ERROR"));
}
}
```
I didn't see anything in SerialTransfer.h about clearing the rxObj; I can always just use the first terminating > character to parse the command - but I imagine there is a cleaner / better solution in clearing the buffer, or at least, I'd like to understand what's going on! Thanks in advance.
|
2020/04/09
|
[
"https://arduino.stackexchange.com/questions/74767",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/65355/"
] |
Instead of clearing your buffers, make use of the bytesRead property. Have a look at how they print the received string in the example code from the library using a for loop. I don't know that it is null terminated or anything.
Example from the library's github page:
```
#include "SerialTransfer.h"
SerialTransfer myTransfer;
void setup()
{
Serial.begin(115200);
Serial1.begin(115200);
myTransfer.begin(Serial1);
}
void loop()
{
if(myTransfer.available())
{
Serial.println("New Data");
for(byte i = 0; i < myTransfer.bytesRead; i++)
Serial.write(myTransfer.rxBuff[i]);
Serial.println();
}
else if(myTransfer.status < 0)
{
Serial.print("ERROR: ");
if(myTransfer.status == -1)
Serial.println(F("CRC_ERROR"));
else if(myTransfer.status == -2)
Serial.println(F("PAYLOAD_ERROR"));
else if(myTransfer.status == -3)
Serial.println(F("STOP_BYTE_ERROR"));
}
```
|
80,990 |
There doesn't seem to be a weight limit on [teleport](https://www.dndbeyond.com/spells/teleport) anymore but, for the purposes of looting a dungeon, what is an object?
I can see how you can fill a chest and then teleport the chest and its contents. It is container and so all its contents are also teleported.
How about a 10' long table stacked with gear? Is the table also a container in the same way or would teleporting a table not teleport the tablecloth?
|
2016/05/31
|
[
"https://rpg.stackexchange.com/questions/80990",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/26539/"
] |
### By RAW, an object is a single designated thing that isn't alive. In my opinion RAI extends to obvious containers.
The teleport spell states (emphasis mine):
>
> This spell instantly transports you and up to eight willing creatures of your choice that you can see within range, or a single object that you can see within range, to a destination you select. If you target **an object**, it must be able to fit entirely inside a 10-foot cube, and it can’t be held or carried by an unwilling creature.
>
>
>
This wording indicates it only applies to a single object since it does not say all objects. It also makes no exceptions for containers and their contents.
For example, if you could transport anything in a container all you would have to do is build a makeshift 10 X 10 X 10 wooden cage and call it a large box. Then you could teleport 1000 cubic feet of whatever you want because you targeted the container.
Personally, I would allow transporting obvious containers like chests, bags of holding, boxes, jars, etc because that seems in keeping with the intent of the game mechanics. It also avoids the unnecessary confusion and ceaseless arguing over just how many separate objects make up a single carriage.
I would say that common sense needs to prevail. If the contents of a table would fit in a standard chest, there's no real reason to prevent players from designating the table or shelf as a container for the purpose of transport. Especially if you're willing to let them just throw it in a Santa Claus bag and transport that anyways.
Now, if the players were trying to be deliberately game breaking with it, you can always have fun. Let's say they stack the treasure eight feet tall on a small bench and transport it. When they arrive, the mound of treasures topples, and riches are scattered everywhere. Small street urchins, poor folk, homeless beggars and Paul's girlfriend are all seen sprinting in to scoop up as much as possible. The player's are able to recover X % of the treasure before the rest disappears, and the guards come by and fine/imprison them for starting a riot.
That's just my opinion though. I don't mind people bending the rules a bit to do some ridiculous stuff, but I bend back a bit to show them I'll be just as ridiculous in response.
|
36,015,250 |
I have many to many relation between `users` and `projects` through `user_project`. I know I could simply add `has_many :projects` in User Serializer (and vice versa in project serializer) to nest projects inside users.
But I also have a few additional fields in `user_projects` table (eg. start and end dates for user's participation in a corresponding project) and I have no idea what is the correct way to include them in the returned json. Should I create a special serializer for projects that are returned inside user with `start_date` included as a project's attribute or there's another way to do that?
|
2016/03/15
|
[
"https://Stackoverflow.com/questions/36015250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5679283/"
] |
The best way to do this would be to establish a `'has-many-through'` (HMT) relationship between the `user` and `project` models and create a serializer for relationship's model.
```
class UserProjectSerializer < ActiveModel::Serializer
...
end
```
This will then be used in the `UserSerializer` via:
```
has_many :users_projects
```
The reason is that the relationship between the models contains additional data.
To implement the HMT, you'll need to create the `user_projects` model and define the HMT relationship in the related models:
**users\_project.rb**
```
class UserProjects < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
```
**user.rb**
```
class User < ActiveRecord::Base
has_many: users_projects
has_many: projects, through: :user_projects
end
```
**project.rb**
```
class Project < ActiveRecord::Base
has_many: users_projects
has_many: users, through: :user_projects
end
```
|
48,481,492 |
I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class `Foo` like so
```
class Foo:
bar = True
```
`Foo` is then directly accessible, such as `print(Foo)` or `print(Foo.bar)`
However, if I dynamically create create a class and **don't set it to a variable** like so
```
type('Foo',(),{'bar':True})
```
If done in the interpreter it shows `<class '__main__.Foo'>`. However, when I try to print `Foo` it's undefined...`NameError: name 'Foo' is not defined`
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
```
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
```
If so, then why doesn't python also create a variable named `Foo` set to class Foo when using `type()` to create it?
|
2018/01/27
|
[
"https://Stackoverflow.com/questions/48481492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104854/"
] |
let's compare your problem with function statements and lambdas (because they play the same role here), consider this function `f` :
```
def f ():
return 1
```
the above snippet of code is not an expression at all, it is a python statement that creates a function named `f` returning `1` upon calling it.
let's now do the same thing, but in a different way :
```
f = lambda : 1
```
the above snippet of code is a python expression (an assignment) that assigns the symbol `f` to the lambda expression (which is our function) `lambda : 1`. if we didn't do the assignment, the lambda expression would be lost, it is the same as writing `>>> 1` in the python REPL and then trying after that to reference it.
|
48,204 |
My website is in PHP, running on Apache.
One of my users is on a WAN with 2 IPs and his connection gets routed to our server by any one of them.
PHP seems to log out the user out, if it detects change in IP.
It is an open source app and I think some common popular file must have been used.
Any way to prevent it?
|
2009/07/30
|
[
"https://serverfault.com/questions/48204",
"https://serverfault.com",
"https://serverfault.com/users/15055/"
] |
I don't think apache has anything to do with that. The problem is most likely in php session although I don't think php checks the client ip by default. Are you sure there's nothing in your code checking the ip for a session?
|
30,401,920 |
I am trying to copy files, folders, sub folders, zip files etc from a given location to another location. I used the code below.
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyDirectoryExample
{
public static void main(String[] args)
{
File srcFolder = new File("C:\\Users\\Yohan\\Documents");
File destFolder = new File("D:\\Test");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
```
Now, I used the above code to take a copy of "My Documents". But unfortunatly, it ended up with `NullPointerException` after running for a while.
The reason for the error is it tried to take a copy of "My Music" folder, which is not even inside of the "My Documents" folder. I tested this code in 2 different machines running windows 7, got the same error in both.
A windows specific solution is fine for me, as I am targeting windows machines at the moment. What have I done wrong?
The error I am getting is below
```
Directory copied from C:\Users\Yohan\Documents\My Music to D:\Test\My Music
Exception in thread "main" java.lang.NullPointerException
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:51)
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:56)
at CopyDirectoryExample.main(CopyDirectoryExample.java:25)
```
|
2015/05/22
|
[
"https://Stackoverflow.com/questions/30401920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] |
The reason this isn't working is because "My Music", "My Pictures" (or Images) and other directories are just symbolic links. See this post on how to detect symbolic links: [Java 1.6 - determine symbolic links](https://stackoverflow.com/questions/813710/java-1-6-determine-symbolic-links)
|
36,093,126 |
The error is at `script, first, second, third = argv`. I would like to understand why I am getting the error and how to fix it.
```
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
```
|
2016/03/18
|
[
"https://Stackoverflow.com/questions/36093126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084339/"
] |
`argv` variable contains command line arguments. In your code you expected 4 arguments, but got only 1 (first argument always script name). You could configure arguments in `pycharm`. Go to `Run` -> `Edit Configurations`. Then create a new python configuration. And there you could specify `Script parameters` field. Or you could run your script from command line as mentioned by dnit13.
|
17,322,583 |
I'm trying to to install my rails app on a second computer. But when I run `bundle install` I get an error with the json gem:
```
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.0), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.0'` succeeds before bundling.
```
The computer runs Mac OS X 10.8.4 with Xcode 4.6.3 and the latest command line tools.
I installed the latest ruby using rvm:
```
$ rvm -v
rvm 1.21.2 (stable) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
$ ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-darwin12.4.0]
$ gem -v
2.0.3
```
When I try to install the json gem using `gem install json` I get almost the same error:
```
Building native extensions. This could take a while...
ERROR: Error installing json:
ERROR: Failed to build gem native extension.
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0 for inspection.
Results logged to /Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out
```
Trying to install using `sudo` does not change anything.
I uninstalled and reinstalled homebrew, rvm, ruby & the command line tools but nothing helps.
**Update**
Contentent of `/Users/feuerball/.rvm/gems/ruby-2.0.0-p195/gems/json-1.8.0/ext/json/ext/generator/gem_make.out`:
```
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby extconf.rb
/Users/feuerball/.rvm/rubies/ruby-2.0.0-p195/bin/ruby: invalid option -D (-h will show valid options) (RuntimeError)
```
GCC Version:
```
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin11
Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure --disable-checking --enable-werror --prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
```
**Update 2**
I did a fresh install of OS X, Xcode, Command Line Tools, Homebrew, rvm and Ruby. Ruby is now patch level 247 and the damn problem is still there. What a waste of time... If it is important: rvm installed json 1.7.7 together with ruby
**Update 3**
Seems that my machine fails on all native extensions. `gem install bcrypt-ruby` gives the same error message.
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17322583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1183192/"
] |
The problem was that my home folder is on a separate volume which contained a space in its name. Because of the space the second part of the name was interpreted as an option. The volumes name was something like `My Data` and thus I got the message`invalid option -D`.
I just renamed this volume and now everything installs fine.
|
94,644 |
Excluding vocabulary items which are entirely new or have fallen into disuse, what are some ways in which Japanese syntax itself has changed between the 1950s and today?
(I would also like to exclude phenomena such as the semi-productivity of terms like ググる, since I'd argue these are new vocabulary and not fully productive ways of deriving new words.)
|
2022/05/23
|
[
"https://japanese.stackexchange.com/questions/94644",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/816/"
] |
[言文一致](https://en.wikipedia.org/wiki/Genbun_itchi) and the shift to modern kana orthography (1946) happened shortly before this period, and they were undoubtedly much more fundamental than anything that happened after 1950. But I'll focus on the change of modern 口語 here. The list is far from complete; I just wrote down things that came to mind.
* Decline of ましょう as a way to express future inference.
>
> 明日は雨が降りましょう。
>
>
>
This was common in weather forecast until the 1970's, but we never hear this today. See: <https://ameblo.jp/heppokomental/entry-12527905042.html>
* Decline of some "heavy" keigo patterns (でございます, でありました, くださいませ, ...)
* Continued decline of ぬ as a negation marker (ありませぬ, 分からぬ, ...)
* Decline of many gender-specific sentence endings (かしら, だわ, ...), although many remain in fictional works as part of お嬢様言葉
* Decline of most iteration marks (ゝ, [〱](https://japanese.stackexchange.com/q/40805/5010), ...) except 々. (If I understand correctly, these symbols have never been officially standardized nor banned by the government.)
* Increased acceptance of ら抜き of ichidan potential forms (食べれる, 見れる, ...)
* Increased acceptance of `i-adjective + です` (嬉しいです, よかったです, ...) and the decline of ~うございます. See: [Conjugating present and past negative i-adjectives](https://japanese.stackexchange.com/q/68964/5010)
|
30,208,595 |
I am building a form where I need to programmatically set bindings and the dataset (as it is variable and different documents can be loaded in to it). I've managed to get the form to load any information in to a `DataGridView` and also load that information from the `DataGridView` in to some TextBoxes for structured editing:

However I am struggling to get the edited information to save back to the database. It won't even update the `DataGridView` with anything. Here's the code I'm currently using:
```
Imports System.Data.SqlClient
Imports System.Data.OleDb
Module DataGridView_Setup
Public Sub Set_Datasource(mode As Integer)
Dim connString As String = My.Settings.Database_String
Dim myConnection As OleDbConnection = New OleDbConnection
myConnection.ConnectionString = connString
' create a data adapter
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT ID, [Name Of Person], [SAP Job Number], [Site Name], [Asset Description], [Spares Supplier], [Supplier Contact Name], [Supplier Contact Phone Number], [Supplier Contact Email], [Spares Description], [Part Number], [Quantity To Order], Cost, [Request Date], [Date Ordered], [Ordered By], [Invoice Received], [Invoice Paid], [Method Of Payment], [Date Item Received], [Additional Comments], [Quote Attatchment] FROM Spares", myConnection)
' create a new dataset
Dim ds As DataSet = New DataSet
' fill dataset
da.Fill(ds, "Spares")
Main.DataGridView1.DataSource = ds.Tables(0)
Main.DataGridView1.AllowUserToAddRows = False
'Set Site Listbox
Dim SiteString = My.Settings.SETTINGS_SiteNames
Dim SiteBox = Main.VIEW_Site.Items
SiteBox.Clear()
Do Until SiteString = ""
Dim ActiveSiteName = Left(SiteString, InStr(SiteString, "¦"))
ActiveSiteName = ActiveSiteName.Remove(ActiveSiteName.Length - 1)
With SiteBox
.Add(ActiveSiteName)
End With
SiteString = Replace(SiteString, ActiveSiteName + "¦", "")
Loop
'Set DataBindings
Main.VIEW_Ref.DataBindings.Clear()
Main.VIEW_Ref.DataBindings.Add(New Binding("Text", ds, "Spares.ID", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_NameOfPerson.DataBindings.Clear()
Main.VIEW_NameOfPerson.DataBindings.Add(New Binding("Text", ds, "Spares.Name Of Person", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SAPJobNo.DataBindings.Clear()
Main.VIEW_SAPJobNo.DataBindings.Add(New Binding("Text", ds, "Spares.SAP Job Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_Site.DataBindings.Clear()
Main.VIEW_Site.DataBindings.Add(New Binding("Text", ds, "Spares.Site Name", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_AssetDesc.DataBindings.Clear()
Main.VIEW_AssetDesc.DataBindings.Add(New Binding("Text", ds, "Spares.Asset Description", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SparesSupplier.DataBindings.Clear()
Main.VIEW_SparesSupplier.DataBindings.Add(New Binding("Text", ds, "Spares.Spares Supplier", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactName.DataBindings.Clear()
Main.VIEW_SupplierContactName.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Name", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactNumber.DataBindings.Clear()
Main.VIEW_SupplierContactNumber.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Phone Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactNumber.DataBindings.Clear()
Main.VIEW_SupplierContactNumber.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Phone Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SupplierContactEmail.DataBindings.Clear()
Main.VIEW_SupplierContactEmail.DataBindings.Add(New Binding("Text", ds, "Spares.Supplier Contact Email", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_SparesDesc.DataBindings.Clear()
Main.VIEW_SparesDesc.DataBindings.Add(New Binding("Text", ds, "Spares.Spares Description", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_PartNumber.DataBindings.Clear()
Main.VIEW_PartNumber.DataBindings.Add(New Binding("Text", ds, "Spares.Part Number", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_QuantityToOrder.DataBindings.Clear()
Main.VIEW_QuantityToOrder.DataBindings.Add(New Binding("Text", ds, "Spares.Quantity To Order", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_CostEach.DataBindings.Clear()
Main.VIEW_CostEach.DataBindings.Add(New Binding("Text", ds, "Spares.Cost", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_DateRequested.DataBindings.Clear()
Main.VIEW_DateRequested.DataBindings.Add(New Binding("Text", ds, "Spares.Request Date", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_DateOrdered.DataBindings.Clear()
Main.VIEW_DateOrdered.DataBindings.Add(New Binding("Text", ds, "Spares.Date Ordered", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_OrderedBy.DataBindings.Clear()
Main.VIEW_OrderedBy.DataBindings.Add(New Binding("Text", ds, "Spares.Ordered By", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_InvoiceReceivedDate.DataBindings.Clear()
Main.VIEW_InvoiceReceivedDate.DataBindings.Add(New Binding("Text", ds, "Spares.Invoice Received", False, DataSourceUpdateMode.OnPropertyChanged))
Main.VIEW_InvoicePaidDate.DataBindings.Clear()
Main.VIEW_InvoicePaidDate.DataBindings.Add(New Binding("Text", ds, "Spares.Invoice Paid", False, DataSourceUpdateMode.OnPropertyChanged))
DataGridView_Setup.BindingUpdates()
End Sub
Public Sub BindingUpdates()
Dim curr As DataGridViewRow = Main.DataGridView1.CurrentRow
Main.VIEW_Ref.Text = curr.Cells("ID").Value
Main.VIEW_NameOfPerson.Text = curr.Cells("Name Of Person").Value
Main.VIEW_SAPJobNo.Text = curr.Cells("SAP Job Number").Value
Main.VIEW_Site.Text = curr.Cells("Site Name").Value
Main.VIEW_AssetDesc.Text = curr.Cells("Asset Description").Value
Main.VIEW_SparesSupplier.Text = curr.Cells("Spares Supplier").Value
Main.VIEW_SupplierContactName.Text = curr.Cells("Supplier Contact Name").Value
Main.VIEW_SupplierContactNumber.Text = curr.Cells("Supplier Contact Phone Number").Value
Main.VIEW_SupplierContactEmail.Text = curr.Cells("Supplier Contact Email").Value
Main.VIEW_SparesDesc.Text = curr.Cells("Spares Description").Value
Main.VIEW_PartNumber.Text = curr.Cells("Part Number").Value
Main.VIEW_QuantityToOrder.Text = curr.Cells("Quantity To Order").Value
Main.VIEW_CostEach.Text = "£" + CStr(curr.Cells("Cost").Value)
Main.VIEW_DateRequested.Text = curr.Cells("Request Date").Value
'Handle DBNULL From now on
If IsDBNull(curr.Cells("Date Ordered").Value) = True Then
With Main.VIEW_DateOrdered
.Text = "Not Ordered Yet"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_DateOrdered
.Text = curr.Cells("Date Ordered").Value
.BackColor = Color.White
End With
End If
If IsDBNull(curr.Cells("Ordered By").Value) = True Then
With Main.VIEW_OrderedBy
.Text = "Not Ordered Yet"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_OrderedBy
.Text = curr.Cells("Ordered By").Value
.BackColor = Color.White
End With
End If
If IsDBNull(curr.Cells("Invoice Received").Value) = True Then
With Main.VIEW_InvoiceReceivedDate
.Text = "No Invoice"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_InvoiceReceivedDate
.Text = curr.Cells("Invoice Received").Value
.BackColor = Color.White
End With
End If
If IsDBNull(curr.Cells("Invoice Paid").Value) = True Then
With Main.VIEW_InvoicePaidDate
.Text = "Not Paid"
.BackColor = Color.LightPink
End With
Else
With Main.VIEW_InvoicePaidDate
.Text = curr.Cells("Invoice Paid").Value
.BackColor = Color.White
End With
End If
End Sub
End Module
```
I have set `DataSourceUpdateMode.OnPropertyChanged` and assumed that this means when the textbox's are changed, it will update the datasource (being the database). I'm guessing this isn't the case as it doesn't work.
What I'd really like is to be able to edit multiple fields on one data row (via the textboxes) and then click the "Save Changes" button to update the Database.
Thanks
**UPDATE 1**
I've done a bit more research following some comments and answers and have written this code in to my `Save` button:
```
Public Sub Save()
Dim myCon = New OleDbConnection(My.Settings.Database_String)
myCon.Open()
Dim sqr = "UPDATE [Spares] SET [Name Of Person] = '" & Main.VIEW_NameOfPerson.Text & "', [SAP Job Number] = '" & CInt(Main.VIEW_SAPJobNo.Text) & "', " & _
"[Site Name] = '" & Main.VIEW_Site.Text & "', [Asset Description] = '" & Main.VIEW_AssetDesc.Text & "', " & _
"[Spares Supplier] = '" & Main.VIEW_SparesSupplier.Text & "', [Supplier Contact Name] = '" & Main.VIEW_SupplierContactName.Text & "', " & _
"[Supplier Contact Phone Number] = '" & Main.VIEW_SupplierContactNumber.Text & "', " & _
"[Supplier Contact Email] = '" & Main.VIEW_SupplierContactEmail.Text & "', [Spares Description] = '" & Main.VIEW_SparesDesc.Text & "', " & _
"[Part Number] = '" & Main.VIEW_PartNumber.Text & "', [Quantity To Order] = '" & CInt(Main.VIEW_QuantityToOrder.Text) & "', " & _
"[Cost] = '" & CDbl(Main.VIEW_CostEach.Text) & "', [Request Date] = '" & CDate(Main.VIEW_DateRequested.Text) & "' WHERE [ID] = '" & CInt(Main.VIEW_Ref.Text) & "'"
Dim Command = New OleDbCommand(sqr, myCon)
Command.ExecuteNonQuery()
myCon.Close()
End Sub
```
When the `Command.ExecuteNonQuery` line attempts to execute I get an error that states the following:
>
> An unhandled exception of type 'System.Data.OleDb.OleDbException'
> occurred in System.Data.dll
>
>
> Additional information: Data type mismatch
> in criteria expression.
>
>
>
**NB:** The string that is produced in `sqr` is:
```
UPDATE [Spares] SET [Name Of Person] = 'Name', [SAP Job Number] = '2', [Site Name] = 'Site', [Asset Description] = 'Asset', [Spares Supplier] = 'Spares Supplier', [Supplier Contact Name] = 'Contact Name', [Supplier Contact Phone Number] = 'Contact Email', [Supplier Contact Email] = 'Contact Number', [Spares Description] = 'Spare Desc', [Part Number] = 'Part Number', [Quantity To Order] = '1', [Cost] = '1', [Request Date] = '12/02/02' WHERE [ID] = '5'"
```
I am obviously using dummy information
I can't be too far away now surely!
|
2015/05/13
|
[
"https://Stackoverflow.com/questions/30208595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925536/"
] |
`svcState` should be provider rather than service. Because service/factory won't be accessible inside config phase. You need to change the implementation of `svcState` to provider so that it will be available in config block of angular.
After provider implementation you could inject that provider using `svcStateProvider` in config block.
```
.config(function($routeProvider, svcStateProvider, cApp){
$routeProvider
.when('/home', {
templateUrl: "partials/home"
})
.when('/info', {
templateUrl: "partials/info"
})
.otherwise({
redirectTo: svcStateProvider.getState() //<--change herer
})
})
```
Look at [**this answer**](https://stackoverflow.com/a/28262966/2435473) to know more about provider
|
28,859 |
When designing an advertisement campaign how should one balance dignity and respect for offensiveness?
Nobody remembers the latest ad for McDonald's or Foldger's but I can tell you all about the "[black face Dunkin Donuts](http://www.adweek.com/adfreak/dunkin-donuts-apologizes-blackface-ad-not-everyone-sorry-152172)" ad or the "[Pearl Izumi run until your dog collapses](http://www.adweek.com/adfreak/running-shoes-magazine-ad-dead-dog-just-makes-people-really-sad-152336)" ad.
As a designer, who will undoubtedly take the blame for it - for example [the McDonald's You're Not Alone ad](http://www.adweek.com/adfreak/mcdonalds-apologizes-mental-health-parody-ad-it-says-it-didnt-approve-148498).
When is it okay? How do future employers view this? On the one hand it is in a sense marketing genius --- no publicity is bad publicity. On the other hand it is often highly offensive or at the very least seen as tasteless. So as a designer when is it okay, what is the calculation? Particularly, if you're the one making the decision *(Answering when the client wants it, is not a complete answer)*.
|
2014/03/31
|
[
"https://graphicdesign.stackexchange.com/questions/28859",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2611/"
] |
*De gustibus non est disputandum* applies. What is tasteless, like what is humorous (or not), varies with culture, fashion, sensitivities and the prevailing political climate. It is also a personal matter, so my answer is personal.
Like anyone, I have my own views on what is acceptable. This isn't a matter of being snobbish; it's that I want to hang onto my enthusiasm. In marketing, as in anything, working hard to produce stuff that is actively harmful (and spreading upset *is* harmful) is a fast route to burnout. On the other hand, I won't hold back on an effective and worthwhile message just because someone, somewhere might get hurt feelings.
As Emilie says, it's almost a certainty that someone will be offended by anything one puts out. (The mayor of a city I lived in used to talk about a "group" he called C.A.V.E. -- Citizens Against Virtually Everything -- who could be guaranteed to object to any project, regardless of how it would improve things.) But sometimes an ad has to be provocative to get a point across.
As to the calculation, it starts with enough research or knowledge to understand who might take offense, and why. That's balanced against the importance and the validity of the message. If there's a good chance that someone's going to be in a snit, is there a better way to design the message that will get the point across just as effectively? Am I just being lazy in going with the first idea that came along, whether mine or the client's?
If the answer to both of these is "No," I tend to apply the "Give me a break" test: Is this negative reaction actually sensible? The Dunkin' Donuts ad in Thailand is a great example: some people on the other side of the world, in a completely different culture, raised an objection to a *highly successful* (and perfectly tasteful, from a Thai point of view) ad. That's a forehead-smacking moment, right there. The inane reaction from some quarters to Coca-Cola's Super Bowl 2014 diversity ad is another.
I've my own experiences along this line: in one case, the key image in a billboard design, which perfectly communicated the intended message when we surveyed it, was rejected by a client's Board (a non-profit in the Black community) because "the Black kid is too light-skinned." The client's marketing director and I *both* reacted with "Give me a break!"
As for future employers, if the HR people are self-appointed guardians of Political Correctness or they have other hot-issue buttons, you may find you stomped on them. In the end, though, it is yourself that you have to live with. Trying to please all the people, all the time winds up in a bland, inconsequential place of no value to anyone.
Ultimately, it comes down to your own judgment and integrity. You can't expect to get it right 100% of the time, but you can certainly try.
|
56,071,682 |
I have two DF's, DF A and DF B. Both have identical schema.
DF A's column C have a different value and DF B's column C have a different value, other data is exactly same. Now, If I want to combine both tables DF C, how to do it in spark? I tried to do join operation, but it is creating duplicate columns.
For example:
DF A:
`+---+----+
| k| v|
+---+----+
| 1| |
| 2|bar1|
+---+----+`
DF B:
`+---+----+
| k| v|
+---+----+
| 1|foo1|
| 2| |
+---+----+`
Expected result:
`+---+----+
| k| v|
+---+----+
| 1|foo1|
| 2|bar1|
+---+----+`
|
2019/05/10
|
[
"https://Stackoverflow.com/questions/56071682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176086/"
] |
The system is looking for a main class `restaurantclient.RestaurantClient`, so a class `RestaurantClient` in package `restaurantClient`, but your class `RestaurantClient` seems to be in the default package.
|
25,755,297 |
```
std::string Concatenate(const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5)
{
return s1 + s2 + s3 + s4 + s5;
}
```
By default, `return s1 + s2 + s3 + s4 + s5;` may be equivalent to the following code:
```
auto t1 = s1 + s2; // Allocation 1
auto t2 = t1 + s3; // Allocation 2
auto t3 = t2 + s4; // Allocation 3
return t3 + s5; // Allocation 4
```
Is there an elegant way to reduce the allocation times to 1? I mean keeping `return s1 + s2 + s3 + s4 + s5;` not changed, but the efficiency is improved automatically. If it is possible, it can also avoid the programmer misusing `std::string::operator +`.
Does **ref-qualifier** member functions help?
|
2014/09/09
|
[
"https://Stackoverflow.com/questions/25755297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508343/"
] |
The premise of the question that:
```
s1 + s2 + s3 + s4 + s5 + ... + sn
```
will require n allocations is incorrect.
Instead it will require O(Log(n)) allocations. The first `s1 + s1` will generate a temporary. Subsequently a temporary (rvalue) will be the left argument to all subsequent `+` operations. The standard specifies that when the lhs of a `string +` is an rvalue, that the implementation simply append to that temporary and move it out:
```
operator+(basic_string<charT,traits,Allocator>&& lhs,
const basic_string<charT,traits,Allocator>& rhs);
Returns: std::move(lhs.append(rhs))
```
The standard also specifies that the capacity of the string will grow geometrically (a factor between 1.5 and 2 is common). So on every allocation, capacity will grow geometrically, and that capacity is propagated down the chain of `+` operations. More specifically, the original code:
```
s = s1 + s2 + s3 + s4 + s5 + ... + sn;
```
is *actually* equivalent to:
```
s = s1 + s2;
s += s3;
s += s4;
s += s5;
// ...
s += sn;
```
When geometric capacity growth is combined with the short string optimization, the value of "pre-reserving" the correct capacity is limited. I would only bother doing that if such code actually shows up as a hot spot in your performance testing.
|
42,295,298 |
My application calls some functions which are placed in an external static library. I link the external static library to my application and everything works (in this case I'm using GCC).
Nevertheless, the locations (addresses) of text, .data and .bss sections of the library are chosen by the linker. I can choose/change their locations by modifying the linker script, but it's tedious as I have to specify all the functions, variables, etc. of the library. What I mean it's something like:
```
. = 0x1000; /* new location */
KEEP(*(.text.library_function1));
KEEP(*(.text.library_function2));
[...]
```
An alternative solution is to build the external library by placing a *section attribute* for each function/variable, and then modifying the linker by re-locating the whole section. Something like:
```
/* C source file */
unsigned char __attribute__((section (".myLibrarySection"))) variable1[10];
unsigned char __attribute__((section (".myLibrarySection"))) variable2[10];
/* Linker script */
. = 0x1000;
KEEP(*(.myLibrarySection))
```
However, I'd like to be able to relocate entire .text, .data and .bss segments of an external static library without the need of using these tricks.
I'd like something like this (in linker script):
```
. = 0x1000;
KEEP(*(.text.library_file_name))
```
Is it possible using GCC toolchain?
Is it possible using other toolchains (IAR, Keil, etc.)?
|
2017/02/17
|
[
"https://Stackoverflow.com/questions/42295298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447290/"
] |
You can use the [`archive:filename`](https://sourceware.org/binutils/docs/ld/Input-Section-Basics.html) syntax in ld.
First place all the `.o` files from your external library into a static library `.a` file, if they aren't already. That is the normal way static library binaries are distributed.
Then in the linker script, specify:
```
.text.special : {
. = 0x1000;
*libspecial.a:*(.text .text.*)
}
.text {
*(.text .text.*)
}
```
The wildcard will pick all the files coming from `libspecial.a` and place them in the first section. The later wildcard will then pick anything left over. If there is a need to place the `.text.special` section after the normal section, you can use `EXCLUDE_FILE` directive in a similar way.
|
73,863,765 |
I am a beginner in Unity and I am currently making a simple game. I have a problem where the button should reappear on the object I am getting contact with. It only shows on the first object that I put the script on.
What I wanted to do is to have a recyclable button that will appear whenever I have contact with objects like the "view" button in most of the games. What keeps happening in my project is that the collision is triggered but the position of the object is in the first object where I put the script to set it active and set the position. I put it in another object because I want the button to show in that object but it keeps appearing in the first object.
This is the script I used:
```
using UnityEngine;
using UnityEngine.UI;
public class InteractNPC : MonoBehaviour
{
//public Button UI;
[SerializeField] GameObject uiUse, nameBtn, dialogBox;
[SerializeField] TextAsset characterData;
// [SerializeField] UnityEngine.UI.Text dialogMessage;
private Transform head;
private Vector3 offset = new Vector3(0, 1.0f, 0);
// Start is called before the first frame update
void Start()
{
//uiUse = Instantiate(UI, FindObjectOfType<Canvas>().transform).GetComponent<Button>();
uiUse.gameObject.SetActive(true);
head = this.transform.GetChild(0);
uiUse.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.GetComponent<Button>().onClick.AddListener(onNameClick);
}
// Update is called once per frame
void Update()
{
uiUse.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
//Character characterJson = JsonUtility.FromJson<Character>(characterData.text);
nameBtn.gameObject.SetActive(true);
// Text lbl = nameBtn.gameObject.GetComponentInChildren(typeof(Text), true) as Text;
// lbl.text = "BOBO";
// nameBtn.GetComponent<Button>().GetComponentInChildren<Text>().text = characterJson.name;
}
}
private void OnTriggerExit(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.gameObject.SetActive(false);
}
}
// DIALOGUE SYSTEM
public void onNameClick()
{
Text dialogMessage, dialogName;
if (dialogBox.gameObject.activeInHierarchy)
{
dialogName = GameObject.Find("Canvas/DialogBox/DialogueName").GetComponent<Text>();
dialogMessage = GameObject.Find("Canvas/DialogBox/Dialogue").GetComponent<Text>();
if (dialogMessage != null && dialogName != null)
{
loadCharacterData(dialogMessage, dialogName);
Debug.Log("not null dialog message");
}
else
{
Debug.Log("null dialog message");
}
}
}
public void loadCharacterData(Text dialogMessage, Text dialogName)
{
Character characterJson = JsonUtility.FromJson<Character>(characterData.text);
dialogName.text = characterJson.name;
dialogMessage.text = characterJson.dialogs[0].choices[1];
}
}
```
|
2022/09/27
|
[
"https://Stackoverflow.com/questions/73863765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11050464/"
] |
Well your issue is that each and every instnce of your scrip will all the time overwrite
```
void Update()
{
uiUse.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
nameBtn.transform.position = Camera.main.WorldToScreenPoint(head.position + offset);
}
```
**every frame**.
What you want is set it only **once** in
```
[SerializeField] private Button nameBtn;
pivate Character character;
private void Start()
{
...
// do this only once!
character = JsonUtility.FromJson<Character>(characterData.text);
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.gameObject.SetActive(true);
var lbl = nameBtn.gameObject.GetComponentInChildren<Text>(true);
lbl.text = characterJson.name;
var position = Camera.main.WorldToScreenPoint(head.position + offset);
uiUse.transform.position = position;
nameBtn.transform.position = position;
}
}
```
---
Further you will have another issue: Each and every instance of your script attaches a callback
```
nameBtn.GetComponent<Button>().onClick.AddListener(onNameClick);
```
that is not good! Now whenever you click the button once, the allback is fired for each and every instance of your script.
You would rather do this only if the click was actually invoked for the current object.
For this you could attach the listener only add-hoc when needed like e.g.
```
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
...
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.onClick.AddListener(onNameClick);
}
}
private void OnTriggerExit(Collider other)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.gameObject.SetActive(false);
}
}
```
---
ok we didn't know before your objects move
so well you will need to go back to what you had before and update the position continuously, **BUT** only while you are the current active object so e.g.
```
private static InteractNPC buttonOwner;
private Camera mainCamera;
void Update()
{
if(buttonOwner != this) return;
if(!mainCamera) mainCamera = Camera.main;
var position = mainCamera.WorldToScreenPoint(head.position + offset);
uiUse.transform.position = position;
nameBtn.transform.position = position;
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player") && !buttonOwner)
{
...
buttonOwner = this;
}
}
private void OnTriggerExit(Collider other)
{
if (collisionInfo.CompareTag("Player") && buttonOwner == this)
{
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.gameObject.SetActive(false);
buttonOwner = null;
}
}
```
|
56,134,100 |
I'm new to f# and want to use it to alter the format of a propositional logic formula string:
I want to replace "aX" by the string "next(a)", with 'a' being an element of [a..z] and 'X' being the capital X' character.
All sources i found, e.g. <https://www.dotnetperls.com/replace-fs> either replace a string by another string,
```
let s = "a & b & c & aX & !bX"
let sReplaced = s.Replace("X", "next()") // val it : string = "a & b & c & anext() & !bnext()"
```
in which case you can not put the original character in between or if they work characterwise, as eg.
```
let sArray = s.ToCharArray()
for c in 0 .. sArray.Length - 1 do
if sArray.[c] = 'X' then
sArray.[c-2] <- '('
sArray.[c] <- ')'
let sArrayResult = new string(sArray) // val sArrayResult : string = "a & b & c &(a) & (b)"
```
only allow the same length for the output string.
"a & b & c & aX & !bX"
should be replaced with
"a & b & c & next(a) & !next(b)"
Is there some convinient way to handle this problem? Thanks in advance.
|
2019/05/14
|
[
"https://Stackoverflow.com/questions/56134100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499357/"
] |
You could use a [`MatchEvaluator`](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.matchevaluator?view=netframework-4.8):
```
open System.Text.RegularExpressions
let s = "a & b & c & aX & !bX"
Regex.Replace(s, "([a-z]X)", fun m -> "next(" + m.Value.TrimEnd('X') + ")")
- ;;
val it : string = "a & b & c & next(a) & !next(b)"
```
|
54,221,366 |
I'm trying to test off route detection in mapbox navigation and it is not working. I've traced through and the OffRouteDetector.isUserOffRouteWith *is* getting called, but the status.getRouteState() is only ever returning "INITIALIZED" (which is not the expected RouteState.OFFROUTE)
I suspect there's an edge case I'm hitting as I'm using a trip with a start and end that are very far away from my current location. As such, it never "gets going". However, this *is* a valid scenario in my application (it involves stored routes that are immutable due to public safety concerns).
I've made an issue (that was closed) on github, but for background, it is [here](https://github.com/mapbox/mapbox-navigation-android/issues/1680)
EDIT:
Here is some code to get closer to what I'm trying to do. This is from the onCreate of the MainActivity of a default android studio project:
```
String jsonRoute = "{\"routes\":[{\"legs\":[{\"steps\":[{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[0,90],\"location\":[-71.45082724993496,43.070903929852619],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[27,90],\"location\":[-71.444301000091471,43.023085298378462],\"in\":0}],\"driving_side\":\"right\",\"weight\":7560.0,\"geometry\":\"mbxcqArekhgCoG{B}HmGuHaLaGiT{@mPHs[bJggEUqYiA_KgCcJyKyVyGgJ\",\"maneuver\":{\"bearing_after\":90,\"type\":\"depart\",\"modifier\":\"\",\"bearing_before\":0,\"location\":[-71.45082724993496,43.070903929852619],\"instruction\":\"Travel on NO NAME\"},\"duration\":0.0,\"distance\":547.06000000000006,\"name\":\"NO NAME\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":547.06000000000006,\"announcement\":\"Travel on NO NAME, then Turn right onto US-3 [NH-28], [HOOKSETT RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Travel on NO NAME, then Turn right onto US-3 [NH-28], [HOOKSETT RD]</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Turn right onto US-3 [NH-28], [HOOKSETT RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Turn right onto US-3 [NH-28], [HOOKSETT RD]</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":547.06000000000006,\"primary\":{\"text\":\"US-3 / NH-28 / HOOKSETT RD\",\"type\":\"turn\",\"modifier\":\"right\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"US-3\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"NH-28\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"HOOKSETT RD\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[27,90],\"location\":[-71.444301000091471,43.023085298378462],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[197,211],\"location\":[-71.444535949177578,43.0230007289918],\"in\":0}],\"driving_side\":\"right\",\"weight\":6677.0,\"geometry\":\"}yycqAzk_hgCpLqOrNaNhTqMlfAsm@|\\\\eSb`@{ZvoBinBrKkJ~t@cg@r\\\\wQvrHimDv}Asz@xz@gd@n\\\\}PrpAil@prCmvAhgBa_A|m@qZvPcJlx@{]l_@iN~GuC~VgFpO}@bGEd[zBvo@jJ|cAeHvoCsWn]eJzuAkf@p`@aQ|sBypAzSkKrMsExPmDlUgAzNx@~OrC|NjFvaBp|@h]dMtmAbZb`Bv`@h\\\\fOxpCvtB|SjSrKxNjO`\\\\~FtNzKp_@xI|NrI`JvlHdmG\",\"maneuver\":{\"bearing_after\":90,\"type\":\"turn\",\"modifier\":\"right\",\"bearing_before\":27,\"location\":[-71.444301000091471,43.023085298378462],\"instruction\":\"Turn right onto US-3 [NH-28], [HOOKSETT RD]\"},\"duration\":186.0,\"distance\":5921.12,\"name\":\"US-3\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":5792.4000000000005,\"announcement\":\"In 3.6miles, I-93 SB ON RAMP\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 3.6miles, I-93 SB ON RAMP</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"I-93 SB ON RAMP\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">I-93 SB ON RAMP</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":5921.12,\"primary\":{\"text\":\"I-93 NB EXIT 9 OFF RAMP\",\"type\":\"turn\",\"modifier\":\"straight\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"I-93 NB EXIT 9 OFF RAMP\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[197,211],\"location\":[-71.444535949177578,43.0230007289918],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[126,135],\"location\":[-71.2864750743811,42.81703500887609],\"in\":0}],\"driving_side\":\"right\",\"weight\":838.0,\"geometry\":\"im|`qA~srggCfe@`l@lGlLtDpZ]~LoDpReEfJoHbIw`Ajt@mPlEiIQyNcGuFkG_HmUq@}QV{EfB_MfAqDpIaOxtAetA\",\"maneuver\":{\"bearing_after\":211,\"type\":\"turn\",\"modifier\":\"straight\",\"bearing_before\":197,\"location\":[-71.444535949177578,43.0230007289918],\"instruction\":\"I-93 SB ON RAMP\"},\"duration\":23.0,\"distance\":788.41,\"name\":\"I-93 NB EXIT 9 OFF RAMP\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":643.6,\"announcement\":\"In 0.4miles, Continue straight on I-93 SOUTH\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 0.4miles, Continue straight on I-93 SOUTH</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Continue straight on I-93 SOUTH\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Continue straight on I-93 SOUTH</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":788.41,\"primary\":{\"text\":\"I-93 SOUTH\",\"type\":\"turn\",\"modifier\":\"straight\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"I-93 SOUTH\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[126,135],\"location\":[-71.2864750743811,42.81703500887609],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[136,140],\"location\":[-71.275545391600389,42.809408142172572],\"in\":0}],\"driving_side\":\"right\",\"weight\":27322.0,\"geometry\":\"_h|`qAtbsggCbE}C~FgGbxK_zIloDguC|i@w`@j\\\\mSn\\\\}Pf]aOf`AmYx`@aIjdGmz@nrCqb@rb@}Irs@uSzo@s^x]{ZvZ}_@hO}TzV}f@lMy\\\\tJsZfu@auCxdA}gE`W_z@b_@}zApO_h@pHsRnIoQ`JiQbJ{NpXq]`[sXn\\\\cT`_@eO|c@mMxp@kN|]gIpiAyVho@oLjcBeR`wBmIb{DiQpq@cFl~BuZvmDcf@|a@eF|u@sGdQk@xPgAvc@w@|uDaHz}CsIv{@}Gvr@kR`k@sWvpB{eAjfAij@`o@cZf}@}XvkB{_@ft@_Qtp@qYbXoRzZiZbXm^x`Ak{A`^mk@na@_k@|m@k~@zDsEvF}HzYm[~KqLlLsKrPoLlzAajAx]yZz\\\\c_@xN}Q~MyS~s@{hAzd@ov@hrKetP~n@caA`NyS|J_M|\\\\gb@l\\\\{\\\\n^k[z_@gYfr@ua@bo@sWr_@_Od|Aif@lrAoc@~cCsw@blA}`@riBql@tk@}T`_A_e@pyDgaCvpUauNhlAyp@b}B{fAv`@}TlwH}zCzjK}dEphAki@dj@{[viAuu@l}@ut@xgAifAfpIg~JjcFwbGhSgTh_@s\\\\r]yVfb@wVld@yRxWsJlM{D`tW}kHhvBwo@nl@qXnr@cc@|pAqhAto@g{@tj@k_AlWyi@lUeh@~^sgAr\\\\usAl`@abC~]qxBvU_wAvYoyAnJqb@fT}v@j]ghAd]q{@xSqe@ls@{tAlWoc@dTy[hv@qeAd]o`@nm@{l@r}UouSt}@u{@~z@w_AdcDkfEtmBkfCvZy_@p^sa@l^u]d_@y[haAup@vp@q\\\\|cAgf@|wA_n@xi@w\\\\xm@sYtlHcgDdnAek@nvAko@v~@ic@lx@of@\",\"maneuver\":{\"bearing_after\":135,\"type\":\"turn\",\"modifier\":\"straight\",\"bearing_before\":126,\"location\":[-71.2864750743811,42.81703500887609],\"instruction\":\"Continue straight on I-93 SOUTH\"},\"duration\":803.0,\"distance\":27320.82,\"name\":\"I-93 SOUTH\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":25744.0,\"announcement\":\"In 16miles, I-93 SB EXIT 3 OFF RAMP TO NH-111\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 16miles, I-93 SB EXIT 3 OFF RAMP TO NH-111</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"I-93 SB EXIT 3 OFF RAMP TO NH-111\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">I-93 SB EXIT 3 OFF RAMP TO NH-111</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[136,140],\"location\":[-71.275545391600389,42.809408142172572],\"in\":0},{\"out\":1,\"entry\":[false,true],\"bearings\":[90,0],\"location\":[-71.408027396106363,42.771592398141067],\"in\":0}],\"driving_side\":\"right\",\"weight\":1481.0,\"geometry\":\"c_jtpAzk~}fC`o@c]br@}o@~f@eo@n\\\\uh@`e@{_AdZyw@dW_}@lnAcnEz^yrAnBaHhM_\\\\lJgPfKmN|O{KbIgCzQ_D`FpAxC|CjBjKpCn`@\",\"maneuver\":{\"bearing_after\":140,\"type\":\"turn\",\"modifier\":\"straight\",\"bearing_before\":136,\"location\":[-71.275545391600389,42.809408142172572],\"instruction\":\"I-93 SB EXIT 3 OFF RAMP TO NH-111\"},\"duration\":41.0,\"distance\":1383.74,\"name\":\"I-93 I93 S OFF RAMP\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":1287.2,\"announcement\":\"In 0.8miles, Merge onto NH-111 [INDIAN ROCK RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 0.8miles, Merge onto NH-111 [INDIAN ROCK RD]</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Merge onto NH-111 [INDIAN ROCK RD]\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Merge onto NH-111 [INDIAN ROCK RD]</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":1383.74,\"primary\":{\"text\":\"NH-111 / INDIAN ROCK RD\",\"type\":\"turn\",\"modifier\":\"straight\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"NH-111\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"INDIAN ROCK RD\",\"delimiter\":false}]},\"secondary\":null}]},{\"intersections\":[{\"out\":1,\"entry\":[false,true],\"bearings\":[90,0],\"location\":[-71.408027396106363,42.771592398141067],\"in\":0}],\"driving_side\":\"right\",\"weight\":20698.0,\"geometry\":\"mb{spAx`i}fCLhi@~CvvAzj@laHlN|u@dyAnwFpIh\\\\tLvo@jM`gAjJ~|Afb@`gHhDfn@rDz`@rH`g@zObt@~Vns@~`@pu@lv@pdAxbBjuBxUj^vIfUtOhc@zSzw@vC`SnIt}@v@lfAuBbj@gDb`@urAlhNcWtlB}dA`rGiuBjjM_UxxA_OtcBuCfl@iB|bACxu@pCdpAl_AfnMzNjoBzIxu@hJfm@`UncApT~p@dc@fbAph@n{@ds@nfAhuBphDhtAnuBthC`eEr{AnnCfkAvwBdwBvvDz[bf@pqA~bBdwB|rCpe@~o@vg@py@f_@zx@h~G~vPhTti@ba@xoAvMnj@ppAbgG~\\\\p|At]zxAt]`pA`f@n}Ap\\\\p`ArdBduEro@|dB`cChrG\",\"maneuver\":{\"bearing_after\":0,\"type\":\"arrive\",\"modifier\":\"\",\"bearing_before\":90,\"location\":[-71.408027396106363,42.771592398141067],\"instruction\":\"Merge onto NH-111 [INDIAN ROCK RD]\"},\"duration\":503.0,\"distance\":12421.48,\"name\":\"NH-111\",\"mode\":\"driving\",\"voiceInstructions\":[{\"distanceAlongGeometry\":12389.300000000001,\"announcement\":\"In 7.7miles, Arrive at destination.\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">In 7.7miles, Arrive at destination.</prosody></amazon:effect></speak>\"},{\"distanceAlongGeometry\":90.0,\"announcement\":\"Arrive at destination.\",\"ssmlAnnouncement\":\"<speak><amazon:effect name=\\\"drc\\\"><prosody rate=\\\"1.08\\\">Arrive at destination.</prosody></amazon:effect></speak>\"}],\"bannerInstructions\":[{\"distanceAlongGeometry\":12421.48,\"primary\":{\"text\":\"NH-111 / CENTRAL ST\",\"type\":\"arrive\",\"modifier\":\"\",\"degrees\":0,\"components\":[{\"type\":\"text\",\"text\":\"NH-111\",\"delimiter\":false},{\"type\":\"delimiter\",\"text\":\"/\",\"delimiter\":true},{\"type\":\"text\",\"text\":\"CENTRAL ST\",\"delimiter\":false}]},\"secondary\":null}]}],\"summary\":\"NO NAME, 1.4mi S of Hooksett - NH-111, 3.1mi NE of Nashua\",\"duration\":1556.0,\"distance\":48366.5390625,\"weight\":66578.0}],\"geometry\":\"mbxcqArekhgCoG{BcOoNyEyKwDgTQif@bJggEUqYiA_KcI{UwNiVdUkX~EgEv{Ae|@`w@yh@`aAu~@tt@{t@rKkJ~t@cg@vr@m^b|BceAze@uTzV{KlhDydB|`Aei@nVyLnuAyp@huHowDhWcN~VqLzt@mZxZeKdP}CtWcAd[zBta@lHvU|@~kEy`@ni@mO|bBin@vPaJ|_Awl@tQcL`WwOzSkKrMsExPmDbPw@hDOzNx@rWjFj_@dQlq@v_@bh@vVb{Ax_@b`Bv`@h\\\\fOzaCbhBr[rXzRdVpIjPxRnh@zElQlOvUxgH`iG|HjGhk@xs@rC`KlBdTkAlT}EfQ{FtIueA|x@mPlEcToCuKqK{EiNwBuRXgLfB_MtDmJfKoNjyAiwAjn@wh@j|JyaIf`DmhC|i@w`@j\\\\mSn\\\\}Pf]aOd_@yLhOyEvOyDx`@aIr\\\\wErlKq|AzdAiYzo@s^x]{ZhLaNvf@it@nV_k@tXs|@zsA}kF~]i{A`W_z@vWofAnNmh@lG_SpHsRnIoQ`JiQdWs_@nKyL`[sXfMwIfNkIbOoG|NuF|c@mMzx@_Q`iA_Wp}@sQnlBoTlZe@nxHk_@ffAiK~hAuPvmDcf@zs@eI~c@sD~b@sBvrHqMtXeCzhBsJvr@kRlcG}{CxO_Hr^_Mr]}Jt_@kIbpBoa@~^_Ln_@mQtK}Gth@_f@|o@_`A`hAgfBrvAorBhn@mq@lLsKt|@_q@jn@qe@hv@ct@~J}LrnHgiLvuE}kH`~@}uAzh@gp@l\\\\{\\\\n^k[z_@gYfr@ua@bo@sWr_@_OroDyjAv{HcgCtk@}T`_A_e@|hOcjJl_D{nBd_CswA~a@oXlWwNhe@mZtn@e^flAsm@vb@mSnkAkl@dhMccFh`HyqCxz@cd@zdAcq@`uAifAv}Ae~AthOirQhi@al@h_@s\\\\r]yVfb@wVld@yRxWsJriRskFx_AaWtdDu~@thAe^nl@qX`i@g\\\\|a@yZlw@ss@vWe\\\\zr@}eAd_@ws@pl@exAfj@cpBd[uiBl[qqBx`@caCnH}`@rTaeAxTa}@rY{`Ap\\\\g~@zUkj@lPg]zj@mfAlWoc@fl@s{@`m@qv@z|@q}@feP_oNluA_nA|`BovAt}@u{@~z@w_Axc@{j@j~BozCd}A}rBnOmRtE{Frs@qz@ln@uk@dOyMhaAup@tuBycA|wA_n@xi@w\\\\xmBg|@~dNcqGrWoO|MgJ`o@c]br@}o@zu@ecAn^}o@db@c`AlZ}~@jxAoiFjb@{{AdCsHbIkRrDgG`QmWhKyHvRmHzL{A`FpAxC|CjBjKpCn`@Lhi@~CvvA`b@foFxGdq@lN|u@lv@`xCrZjjAtPjp@nE`VjPpfApNdwBfb@`gH|IbpA~CzWlMdo@`FbSzM`a@bHlQpSna@~]dj@nhAtxAd_AbjAxUj^lDvI~Txn@zSzw@`H|f@xFfbAPx_@cChx@kTjbCqbAdfKqg@zoDyV`|Aab@tgCox@p`Fsp@xzDyZ|pBeGnl@oKlcBuBzyAhAbpA`F~eAzz@dgLzNjoBzIxu@hJfm@`UncApT~p@dc@fbAjsG|eKhlCdgEp[xj@~iCjyEziCxsEz[bf@||@~iAjeDhlEfTpZn_@rn@f_@zx@jmH`uQlM|\\\\|Xn~@zW~iAj`@`lBjXppA|z@bzDbk@jvBhs@v{B|tBnxFzmA~eDbOr`@ds@djBlPvb@fz@~~Bgi@e|A\",\"duration\":1556.0,\"distance\":48366.54,\"weight\":66578.0,\"weight_name\":\"routability\",\"voiceLocale\":\"en-US\"}],\"waypoints\":[{\"name\":\"NO NAME, 1.4mi S of Hooksett\",\"location\":[-71.45688,43.07003]},{\"name\":\"NH-111, 3.1mi NE of Nashua\",\"location\":[-71.40803,42.77159]}],\"code\":\"Ok\",\"uuid\":\"cjqsavmw70crz3po391gqh3mp\"}";
DirectionsResponse directions = DirectionsResponse.fromJson(jsonRoute);
DirectionsRoute route = directions.routes().get(0);
ArrayList<Point> wpPoints = new ArrayList<Point>();
for(DirectionsWaypoint w : directions.waypoints())
wpPoints.add((w.location()));
RouteOptions newRO = RouteOptions.builder()
.profile(DirectionsCriteria.PROFILE_DRIVING)
.coordinates(wpPoints)
.user("mapbox")
.geometries(DirectionsCriteria.GEOMETRY_POLYLINE6)
.accessToken(accessToken)
.requestUuid(directions.uuid())
.baseUrl("https://api.mapbox.com")
.waypointNames("")
.continueStraight(true)
.annotations("distance")
.approaches("")
.bearings(";")
.alternatives(false)
.language("en")
.radiuses("")
.voiceInstructions(true)
.bannerInstructions(true)
.roundaboutExits(true)
.overview("full")
.steps(true)
.voiceUnits("imperial")
.exclude("")
.waypointTargets("")
.build();
route = route.toBuilder().routeOptions(newRO).build();
boolean simulateRoute = false;
// Create a NavigationLauncherOptions object to package everything together
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(this, options);
```
|
2019/01/16
|
[
"https://Stackoverflow.com/questions/54221366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6542610/"
] |
@Troy Berg Let me take a quick second to explain how the route following code works internally when a fresh route is loaded.
Upon loading a new route, if the route json is valid, the `MapboxNavigator` will start in the `INITIALIZED` state. From there it will attempt to gain confidence that the GPS locations being passed in are actually the location where the user is. To establish this trust it needs to receive at least a few location updates and those must be consequtively coherent in both time and space. While it's in the process of establishing this trust it will report the `INITIALIZED` state.
Once trust of the users current stream of location updates has been established, the `MapboxNavigator` will attempt to measure the user's progress along the currently loaded route. If the user's location is found to be unreasonably far from the route itself, the state is flipped to the `OFFROUTE` state.
If the user's current location is within a reasonable distance from the currently loaded route but not close enough to be considered on-route (`TRACKING`) we will continue to return the `INITIALIZED` state and wait for the user to make their way to the route. We call this corraling. Corraling allows a user, in his/her driveway or a store's parking lot for example, to load up a route and not immediately get marked as `OFFROUTE`. While corraling, if the user continually makes progress away from the route they will eventually be marked `OFFROUTE`.
|
63,142,638 |
I m using GooglePlacesAutocomplete where while typing getting the list of places but some places text containing more than that,so I wanted to wrap the text there.
```
<GooglePlacesAutocomplete
placeholder='Where To ?'
minLength={4}
autoFocus={true}
listViewDisplayed="auto"
returnKeyType={'search'}
fetchDetails={true}
onPress={(data, details = null) => {
props.notifyChange(details.geometry.location,data);
}}
query={{
key: 'chghgdhgfhgfjhdhklkl',
language: 'en',
}}
nearbyPlacesAPI= 'GooglePlacesSearch'
debounce={200}
styles={ styles }>
</GooglePlacesAutocomplete>
```
and my styles for that is as follows
```
const styles = StyleSheet.create({
textInputContainer:{
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth:0,
zIndex:999,
width:'90%',
},
textInput: {
marginLeft: 0,
marginRight: 0,
height: 45,
color: '#5d5d5d',
fontSize: 16,
borderWidth:1,
zIndex:999,
},
predefinedPlacesDescription: {
color: '#1faadb'
},
listView:{
top:45.5,
zIndex:10,
position: 'absolute',
color: 'black',
backgroundColor:"white",
width:'89%',
},
separator:{
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: 'blue',
},
description:{
flexDirection:"row",
flexWrap:"wrap",
fontSize:14,
maxWidth:'89%',
},
```
});
refer this link <https://reactnativeexample.com/customizable-google-places-autocomplete-component-for-ios-and-android-react-native-apps/>
but not able to find the solution.help would be appreciated
|
2020/07/28
|
[
"https://Stackoverflow.com/questions/63142638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2714229/"
] |
The width of the ListView showing the results has its width hardcoded to window.with. That is why you wrapping the text isn't working.
There is a potential workaround, and that would be to split the description into multiple lines. You can do this with the [`renderRow`](https://github.com/FaridSafi/react-native-google-places-autocomplete#props) prop. Styling would need to be adjusted for your specific use case.
```
<GooglePlacesAutocomplete
placeholder='Where To ?'
minLength={4}
autoFocus={true}
listViewDisplayed="auto"
returnKeyType={'search'}
fetchDetails={true}
onPress={(data, details = null) => {
props.notifyChange(details.geometry.location,data);
}}
query={{
key: 'chghgdhgfhgfjhdhklkl',
language: 'en',
}}
nearbyPlacesAPI= 'GooglePlacesSearch'
debounce={200}
renderRow={(rowData) => {
const title = rowData.structured_formatting.main_text;
const address = rowData.structured_formatting.secondary_text;
return (
<View>
<Text style={{ fontSize: 14 }}>{title}</Text>
<Text style={{ fontSize: 14 }}>{address}</Text>
</View>
);
}}
styles={ styles }>
</GooglePlacesAutocomplete>
```
You would need to add `row` to your styles and you can `description` from styles, because it is being overwritten by `renderRow`
```
row: {
height: "100%",
},
```
Disclosure: I am the maintainer of this package.
|
56,710,146 |
I have some issues to convert jQuery code to JavaScript code.
For example, I have this piece of code :
```
$(document).ready(function() {
doing some stuff
});
```
I tried to code like this :
```
document.getElementById("canvas").onload = function () {
doing some stuff
};
```
but it's not working.
Here is bigger code I'm trying to convert :
```
$(document).ready(function() {
var color = "#000000";
var sign = false;
var begin_sign = false;
var width_line = 5;
var canvas = $("#canvas");
var cursorX, cursorY;
var context = canvas[0].getContext('2d');
context.lineJoin = 'round';
context.lineCap = 'round';
$(this).mousedown(function(e) {
sign = true;
cursorX = (e.pageX - this.offsetLeft);
cursorY = (e.pageY - this.offsetTop);
});
$(this).mouseup(function() {
sign = false;
begin_sign = false;
});
```
For information, I want to get this result, in JavaScript:
<http://p4547.phpnet.org/bikes/canvas.html>
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56710146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11624270/"
] |
Continuing on from the partial solution you provided, since you changing from jQuery element to a DOM node, you have to access a few properties differently as outlined below.
```
document.addEventListener("DOMContentLoaded", function(event) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d'); // <--- remove [0] index
canvas.addEventListener('mousemove', function(e) { ... ))
function clear_canvas() {
// offsetWidth and offsetHeight instead of Height() and Width()
context.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
}
});
```
|
42,146 |
I am teaching myself the very basics of design using [Affinity Designer](https://affinity.serif.com/) - and I haven't been able to figure out how to create a single shape from multiple vectors.
For instance, if I am creating a basic outline of a car and need to start and stop lines - when I use the `join lines tool` it doesn't join two unrelated lines together - rather it completes the "circle" (path) of one line only.
If I use the `join shapes tool` it completes all the unconnected lines, and fills in those spaces too - so I lose the shape I am after.
AD's help index is not very helpful to someone with my near non-existent skills - so I'd be thrilled if someone on this forum can help.
|
2014/11/13
|
[
"https://graphicdesign.stackexchange.com/questions/42146",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/33522/"
] |
You can indeed join two separate nodes from unrelated vector lines.
Do this by :
1. Select both lines using the Move Tool.
2. Using the Node Tool select both end nodes you want to join (hold down Shift to select them both).
3. Choose 'Join Curves' from the Action section of the Node context toolbar.
|
1,444,552 |
I know that the derivative of $\sec(x)$ is $\sec(x)\tan(x)$, so what is the derivative of $sec^2(x)$?
I want to know what derivative rules you use to derive it.
|
2015/09/21
|
[
"https://math.stackexchange.com/questions/1444552",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272658/"
] |
Let $1\_{E\_k}$ be the characteristic function of $E\_k$ and let $f=\sum\_{k=1}^n 1\_{E\_k}$. What can you say about the integral of $f$?
|
22,950,053 |
```
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
event.setName(parser.getValue(e, NODE_NAME));
event.setDate(parser.getValue(e, NODE_DATE));
event.setLocation(parser.getValue(e, NODE_LOC));
Log.d("Thisworks!:", event.getName());
eventsList.addLast(event);
}
for (Event curevent : eventsList) {
Log.d("ThisDoesnt!?:", curevent.getName());
}
```
Output should be:
```
name1
name1
name1
name2
name2
name3
name3
```
Thisworks! outputs different values every time, as expected.
But when i loop through the list and output, it only outputs:
```
name3
name3
name3
name3
name3
name3
name3
```
Am i missing something completely obvious here?
|
2014/04/08
|
[
"https://Stackoverflow.com/questions/22950053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2859891/"
] |
You should be adding a new `Event` to the `eventsList` each time through the loop, not setting the values of the same `event`.
`eventsList.addLast(event)` does *not* make a copy, it just adds a reference to `event` to the list. So there is only ever one `event` object, which you keep overwriting.
|
46,573,113 |
[Image of Description](https://i.stack.imgur.com/Kc9Ke.png)
The aim is to have the user select a shape (Square, Triangle or Circle) and then enter a boundary length. Once this information has been input I can then calculate the perimeter and area of their choice.
The problem is I don't want to create new variables for the length and area in each class if I don't have to and would rather have the variables declared and then passed into the classes if I can.
Basically I don't want to do it like this,
```
class square {
double bLength;
double area;
}
class triangle {
double bLength;
double area;
}
class circle {
double bLength;
double area;
}
```
Can I declare them outside of the classes and then have the classes use/inherit them or anything?
I must apologise for such a basic question, I am quite new to Java and I can't really think around this one.
|
2017/10/04
|
[
"https://Stackoverflow.com/questions/46573113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7921329/"
] |
The classic solution is to use inheritance:
```
class Shape {
double bLength;
double area;
Shape(double bLength, double area) {
this.bLength = bLength;
this.area = area;
}
}
class Square extends Shape {
Square(double bLength, double area) {
super(bLength, area);
}
// additional field, methods...
}
// same for the other shapes
```
|
16,001,999 |
I have a couple media queries in my stylesheet, each modifying some styles, but not others. I'm using the `max-width` query:
```
@media screen and (max-width: 1024px) {
#header .span6 { width: 60%; margin-left: 200px; }
#error .span6 { width: 60%; margin-left: 200px; }
#timer-block { width: 60%; margin-left: 200px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 200px; }
.control { width: 297px; margin-top: 0; }
#footer { width: 60%; margin-left: 200px; }
}
@media screen and (max-width: 768px) {
#header .span6 { width: 80%; margin-left: 75px; }
#error .span6 { width: 80; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px;}
#timer { font-size: 5em; }
#start-pause { margin-left: 75px; }
.control { width: 300px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 800px) {
#header .span6 { width: 80%; margin-left: 75px; }
h1 { font-size: 3.5em; margin-bottom: 0px;}
#error .span6 { width: 80%; margin-left: 75px; }
#timer-block { width: 80%; margin-left: 75px; }
#timer { font-size: 5em; }
.little { font-size: 0.5em; }
#start-pause { margin-left: 75px; }
.control { width: 312px; margin-top: -5px; }
#footer { width: 80%; margin-left: 75px; }
}
@media screen and (max-width: 600px) {
#header .span6 { width: 90%; margin-left: 25px; }
#error .span6 { width: 90%; margin-left: 30px; }
#timer-block { width: 90%; margin-left: 30px;}
#start-pause { margin-left: 30px; }
.control { width: 264px; margin-top: -5px; }
#footer { width: 90%; margin-left: 25px; }
}
@media screen and (max-width: 480px) {
#header { margin-top: -10px; }
#header .span6 { width: 90%; margin-left: 25px; }
h1 { font-size: 3em; margin-left: -15px; padding-left: 10px; }
#interval { width: 150px; height: 40px; font-size: 2em; margin-bottom: 20px; width: 150px; }
#error .span6 { width: 90%; margin-left: 25px; }
#timer-block { width: 90%; margin-left: 24px; height: 100px; padding: 10px; }
#start-pause { margin-left: 25px; }
.control { margin-top: -5px; width: 210px; }
#footer { width: 100%; margin-top: -20px; margin-left: 0; }
}
@media screen and (max-width: 320px) {
#timer-block { width: 90%; margin-left: 15px; padding: 10px; font-size: 0.8em; }
#header { margin-top: 0px; }
#header .span6 { margin-left: 37px; }
#interval { margin-top: -45px; margin-left: 20px; }
#error .span6 { width: 90%; margin-left: 15px; }
.control { width: 141px; margin-top: -10px; }
#start-pause { margin-left: 15px; }
#footer { width: 95%; margin-left: 10px; }
}
```
Is there a way I can change what I'm doing to make there be no collisions? This is the first time I use media queries so I may be missing something entirely.
|
2013/04/14
|
[
"https://Stackoverflow.com/questions/16001999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Instead of
```
@media screen and (max-width: 480px)
```
You can use
```
@media screen and (max-width: 480px) and (min-width: 321px)
```
This way it will look only at screen sizes between 320 and 481;
instead of 0 and 481
|
56,011,201 |
What i'm trying to do is to create a dropdown with all my "Stations" from database and when choosing one to zoom on it on map.
I have just created a controller called AdminMapController with this code:
```
public class AdminMapController : Controller
{
private readonly ApplicationDbContext _context;
public AdminMapController(ApplicationDbContext context)
{
_context = context;
}
public ActionResult GetListOfStations()
{
ViewBag.ListOfDropdown = _context.Stations.ToList();
return View("~/Areas/Identity/Pages/Account/AdminMap.cshtml");
}
public JsonResult GetAllLocation()
{
var data = _context.Stations.ToList();
return Json(data);
}
```
and the View ( only the drop down test ):
```
</style>
<br/><br/>
<div>
<select class="form-control">
<option>--Select--</option>
@foreach (var item in ViewBag.ListOfDropdown)
{
<option value ="@item.Id">@item.Name</option>
}
</select>
</div>
<br/>
```
Funny thing that `GetAllLocation` method works properly, but `GetListOfStations` throws me the error `NullReferenceException: Object reference not set to an instance of an object.` with these being the "problems": `@foreach (var item in ViewBag.ListOfDropdown)` and `ViewData["Title"] = "Admin Map";`
Any idea how can i fix this?
|
2019/05/06
|
[
"https://Stackoverflow.com/questions/56011201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I think you should use this one in return Action:
```
var model = _context.Stations.ToList();
return View("~/Areas/Identity/Pages/Account/AdminMap.cshtml", model);
```
View:
```
@model List<Stations>
<div>
<select class="form-control">
<option>--Select--</option>
@foreach (var item in Model)
{
<option value ="@item.Id">@item.Name</option>
}
</select>
</div>
```
|
19,005,570 |
We recently developed a website that essentially has 2 modes, mobile and a tablet + desktop one. The css file is laid out with mobile rules first, then there is a breakpoint for any sizes above 640px, so we could show the desktop version to the 7" tablets when on landspace.
However, although it is working great for all iphones, my galaxy s4, even the windows phone and of course for the ipad and desktop, some mobile phones pick up the desktop styles, essentially showing the desktop version, namely the galaxy s2 and the galaxy s3 among others.
As i said, my css code is built mobile first, so all mobiles with a width of less than 640px (pretty much all) should not pick up the desktop styles, the media query is as follows:
```
@media all and (min-width: 641px) { .... }
```
So i do not really understand why.. any ideas?
edit: I forgot to add we have added a conditional that will check whether the size of the device is larger than 640, in which case it sets the viewport size to the full width of the website so it scales down on tablets, or else it just sets it to device-width.
```
<meta id="testViewport" name="viewport" content="width=device-width, maximum-scale=1">
<script>
if (screen.width > 640) {
var mvp = document.getElementById('testViewport');
mvp.setAttribute('content','width=1000');
}
</script>
```
|
2013/09/25
|
[
"https://Stackoverflow.com/questions/19005570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171878/"
] |
You can use `.trigger` and target your buttons ID:
```
$("#idOfButton").trigger("click");
```
Or the shorthand, just call a `click()` on your target
```
$("#idOfButton").click();
```
|
711,425 |
I'm very new to Ubuntu 14.04 and want to install and run Teamviewer on my PC.
I have to maintain someone else's PC in another country who has Ubuntu installed.
I've installed it from the "Files and Folders" but can't find the application saved anywhere.
I've followed the instructions give by others to install and it seemed to work.
Where do I look for the teamviewer application and how to I run it?
Thank you
|
2015/12/20
|
[
"https://askubuntu.com/questions/711425",
"https://askubuntu.com",
"https://askubuntu.com/users/484270/"
] |
run:
```
sudo teamviewer --daemon enable
```
and then open teamviewer from the GUI
|
5,485,790 |
I am setting up CKAN, a pylons application according to these instructions:
<http://packages.python.org/ckan/deployment.html>
But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded.
here is my mod\_wsgi script:
```
import os
instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br'
config_file = 'ckan.emap.fgv.br.ini'
pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin')
activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from paste.deploy import loadapp
config_filepath = os.path.join(instance_dir, config_file)
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)
application = loadapp('config:%s' % config_filepath)
```
here is my virtual host configuration:
```
<VirtualHost *:80>
ServerName dck093
ServerAlias dck093
WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py
# pass authorization info on (needed for rest api)
WSGIPassAuthorization On
ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log
CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined
<Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
```
I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log:
```
sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response)
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a "
[Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment
```
Can anyone point out what am I missing?
|
2011/03/30
|
[
"https://Stackoverflow.com/questions/5485790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34747/"
] |
Since you're deploying on apache, ensure that you are not in interactive debug mode - which uses EvalException. In your Pylons config file (ckan.emap.fgv.br.ini) ensure you have this:
```
[app:main]
set debug = false
```
|
34,879,281 |
Lets say I have two lists of colors and I need to compare them. I have a function of comparing colors but I'm a little bit confused of types which function gets. How to cast them?
```
public bool AreColorsSimilar(Color c1, Color c2, int tolerance)
{
return Math.Abs(c1.R - c2.R) < tolerance &&
Math.Abs(c1.G - c2.G) < tolerance &&
Math.Abs(c1.B - c2.B) < tolerance;
}
```
Here is my first list:
```
public static List<Color> PaletteOfSeasons()
{
List<Color> springColors = new List<Color>();
springColors.Add(ColorTranslator.FromHtml("#80a44c"));
springColors.Add(ColorTranslator.FromHtml("#b4cc3a"));
return springColors;
}
```
And in another list I'm pulling pixels from image:
```
public static IEnumerable<Color> GetPixels(Bitmap bitmap)
{
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
Color pixel = bitmap.GetPixel(x, y);
yield return pixel;
}
}
}
```
And question is, how can I compare this colors ?
|
2016/01/19
|
[
"https://Stackoverflow.com/questions/34879281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5787061/"
] |
If I understand you right:
```
var springColors = null;
springColors = PaletteOfSeasons(springColors);
var similarColors = GetPixels(bitmap).Intersect(springColors, new ColorComparer(tolerance));
```
And you need this class:
```
public class ColorComparer : IEqualityComparer<Color>
{
private _tolerance;
public ColorComparer(int tolerance)
{
_tolerance = tolerance;
}
public bool Equals(Color x, Color y)
{
return AreColorsSimilar(x, y, _tolerance);
}
public int GetHashCode(Foo x)
{
return 0;
}
private bool AreColorsSimilar(Color c1, Color c2, int tolerance)
{
return Math.Abs(c1.R - c2.R) < tolerance &&
Math.Abs(c1.G - c2.G) < tolerance &&
Math.Abs(c1.B - c2.B) < tolerance;
}
}
```
P.S. Your method PaletteOfSeasons is a little confusing. Passing list to method foolishly.
P.P.S. Use Bitmap.LockBits() to increase code performance.
P.P.P.S. Such implementation of GetHashCode isn't good. But in our situation it is OK.
|
10,777,714 |
On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.
I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.
The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.
Could you please show me how?
**Edit:**
The application is a console one. And please show me example code. Thanks!
**Update:**
So after I read some of the suggestions here, I searched for some answers here and found this [one](https://stackoverflow.com/questions/10715555/settimer-in-vc) which was helpful.
I then wrote the below code, which works, but not as it's supposed to be:
```
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
HANDLE g_hExitEvent = NULL;
bool doneInTime = false;
string name;
bool inputWords();
//The below function will be called when the timer ends
void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
if(!doneInTime)
{
cout << "\nOut of time ... try again ..." << endl;
name = "";
doneInTime = inputWords();
}
SetEvent(g_hExitEvent);
}
bool inputWords()
{
/* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
callback is called, executes some processing and sets event to allow exit */
HANDLE hNewTimer = NULL;
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
cout << "Input your name in 5 seconds .. " << endl;
std::getline(cin, name);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return true;
}
int main()
{
doneInTime = inputWords();
cout << "Hello, " << name << "! You're done in time" << endl;
//WaitForSingleObject(g_hExitEvent, 15000);
system("pause");
return 0;
}
```
The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10777714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397057/"
] |
Here's an example that works with the Windows API:
```
#include <windows.h>
#include <iostream>
DWORD WINAPI threadProc()
{
for (int i = 0; ; ++i)
{
std::cout << i << '\n';
Sleep (1000);
}
return 0;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int iCmdShow)
{
CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)threadProc, NULL, 0, NULL);
int i;
std::cin >> i;
return ERROR_SUCCESS;
}
```
Basically the main function creates a thread that executes using the procedure `threadProc`. You can think of `threadProc` as the thread. Once it ends, the thread ends.
`threadProc` just outputs a running count every second or so, while the main function waits for a blocking input. Once an input is given, the whole thing ends.
Also be aware that `CreateThread` was used with minimal arguments. It returns a handle to the thread that you can use in functions like `WaitForSingleObject`, and the last argument can receive the thread id.
|
27,633,093 |
I am able to successfully run the WordCount example using DataflowPipelineRunner with the maven exec:java command shown in the docs.
However, when I attempt to run it in my own 1.8 VM, it doesn't work. I am using these args (on Windows):
```
--project=highfive-metrics-service \
--stagingLocation=gs://highfive-dataflow-test/staging \
--runner=BlockingDataflowPipelineRunner \
--gCloudPath=C:/Progra~1/Google/CloudS~1/google-cloud-sdk/bin/gcloud.cmd
```
I get the following error:
```
2014-12-24T04:53:34.849Z: (5eada047929dcead): Workflow failed. Causes: (5eada047929dce2e): There was a problem creating the GCE VMs or starting Dataflow on the VMs so no data was processed. Possible causes:
1. A failure in user code on in the worker.
2. A failure in the Dataflow code.
Next Steps:
1. Check the GCE serial console for possible errors in the logs.
2. Look for similar issues on http://stackoverflow.com/questions/tagged/google-cloud-dataflow.
```
Prior to the subsequent cleanup, I observed three harness instances on GCE as expected. Looking at the serial console for the first one, wordcount-jroy-1224043800-12232038-8cfa-harness-0, I see "normal" (comparing to what I see when running with Maven) looking output that ends with:
```
Dec 24 04:38:45 [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.438005] IPv6: ADDRCONF(NETDEV_CHANGE): veth30b3796: link becomes ready
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.439395] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.440262] docker0: port 1(veth30b3796) entered forwarding state
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 kernel: [ 16.443484] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 12898 100 12898 0 0 2009k 0 --:--:-- --:--:-- --:--:-- 3148k
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: {"attributes":{"config":"{\"alsologtostderr\":true,\"base_task_dir\":\"/tmp/tasks/\",\"commandlines_file_name\":\"commandlines.txt\",\"continue_on_exception\":true,\"dataflow_api_endpoint\":\"https://www.googleapis.com/\",\"dataflow_api_version\":\"v1beta1\",\"log_dir\":\"/dataflow/logs/taskrunner/harness\",\"log_to_gcs\":true,\"log_to_serialconsole\":true,\"parallel_worker_flags\":{\"job_id\":\"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588\",\"project_id\":\"highfive-metrics-service\",\"reporting_enabled\":true,\"root_url\":\"https://www.googleapis.com/\",\"service_path\":\"dataflow/v1b3/projects/\",\"temp_gcs_directory\":\"gs://highfive-dataflow-test/staging\",\"worker_id\":\"wordcount-jroy-1224043800-12232038-8cfa-harness-0\"},\"project_id\":\"highfive-metrics-service\",\"python_harness_cmd\":\"python_harness_main\",\"scopes\":[\"https://www.googleapis.com/auth/devstorage.full_control\",\"https://www.googleapis.com/auth/cloud-platform\"],\"task_group\":\"nogroup\",\"task_user\":\"nobody\",\"temp_g
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 goo[ 16.494163] device veth29b6136 entered promiscuous mode
gle: cs_directory\":\"gs://highfive-dataflow-test/staging\",\"vm_id\":\"wordcoun[ 16.505311] IPv6: ADDRCONF(NETDEV_UP): veth29b6136: link is not ready
[ 16.507623] docker0: port 2(veth29b6136) entered forwarding state
t-jroy-122404380[ 16.507633] docker0: port 2(veth29b6136) entered forwarding state
0-12232038-8cfa-harness-0\"}","google-container-manifest":"\ncontainers:\n-\n env:\n -\n name: GCS_BUCKET\n value: dataflow-docker-images\n image: google/docker-registry\n imagePullPolicy: PullNever\n name: repository\n ports:\n -\n containerPort: 5000\n hostPort: 5000\n name: registry\n-\n image: localhost:5000/dataflow/taskrunner:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: taskrunner\n volumeMounts:\n -\n mountPath: /dataflow/logs/taskrunner/harness\n name: dataflowlogs-harness\n-\n env:\n -\n name: LOG_DIR\n value: /dataflow/logs\n image: localhost:5000/dataflow/shuffle:20141217-rc00 \n imagePullPolicy: PullIfNotPresent\n name: shuffle\n ports:\n -\n containerPort: 12345\n hostPort: 12345\n name: shuffle1\n -\n containerPort: 22349\n hostPort: 22349\n name: shuffle2\n volumeMounts:\n -\n mountPath: /var/shuffle\n name: dataflow-shuffle\n -\n mountPath: /dataflow/logs\n name: dataflow-logs\nversion: v1
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: beta2\nvolumes:\n-\n name: dataflowlogs-harness\n source:\n hostDir:\n path: /var/log/dataflow/taskrunner/harness\n-\n name: dataflow-shuffle\n source:\n hostDir:\n path: /dataflow/shuffle\n-\n name: dataflow-logs\n source:\n hostDir:\n path: /var/log/dataflow/shuffle\n","job_id":"2014-12-23_20_38_16.593375-08_10.48.106.68_-469744588","packages":"gs://dataflow-releases-prod/worker_packages/NOTICES.shuffle|NOTICES.shuffler|gs://highfive-dataflow-test/staging/access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|access-bridge-64-fE-vq3Wgxy5FvnwmA5YdzQ.jar|gs://highfive-dataflow-test/staging/avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|avro-1.7.7-dTlef6huetK-4IFERNhcqA.jar|gs://highfive-dataflow-test/staging/charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|charsets-7HC8Y2_U4k8yfkY6e4lxnw.jar|gs://highfive-dataflow-test/staging/cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|cldrdata-A4PVsm4mesLVUWOTKV5dhQ.jar|gs://highfive-dataflow-test/staging/commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|commons-codec-1.3-2I5AW2KkklMQs3emwoFU5Q.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|commons-compress-1.4.1-uyvcB16Wfp4wnt8X1Uqi4w.jar|gs://highfive-dataflow-test/staging/commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|commons-logging-1.1.1-blBISC6STJhwBOT8Ksr3NQ.jar|gs://highfive-dataflow-test/staging/dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|dataflow-test-YIJKUxARCp14MLdWzNdBdQ.zip|gs://highfive-dataflow-test/staging/deploy-eLnif2izXW_mrleXudK0Eg.jar|deploy-eLnif2izXW_mrleXudK0Eg.jar|gs://highfive-dataflow-test/staging/dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|dnsns-hmxeUSrhtJou0Wo-UoCjTw.jar|gs://highfive-dataflow-test/staging/google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|google-api-client-1.19.0-YgeHY_Y9dPd2PwGBWwvmmw.jar|gs://highfive-dataflow-test/staging/google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|google-api-services-bigquery-v2-rev167-1.19.0-mNojB6wqlFqAd2G9Zo7o5w.jar|gs://highfive-dataflow-test/staging/google-api-services-compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|google-api-services
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -compute-v1-rev34-1.19.0-yR5ItN9uOowLPyMiTckyCA.jar|gs://highfive-dataflow-test/staging/google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|google-api-services-dataflow-v1beta3-rev1-1.19.0-Cg8Pyd4F0t7yqSE4E7v7Rg.jar|gs://highfive-dataflow-test/staging/google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|google-api-services-datastore-protobuf-v1beta2-rev1-2.1.0-UxLefoYWxF5K1EpQjKMJ4w.jar|gs://highfive-dataflow-test/staging/google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|google-api-services-pubsub-v1beta1-rev9-1.19.0-7E1jg5ZyfaqZBCHY18fPkQ.jar|gs://highfive-dataflow-test/staging/google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|google-api-services-storage-v1-rev11-1.19.0-8roIrNilTlO2ZqfGfOaqkg.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|google-cloud-dataflow-java-examples-all-manual_build-A9j6W_hzOlq6PBrg1oSIAQ.jar|gs://highfive-dataf
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: low-test/staging/google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|google-cloud-dataflow-java-examples-all-manual_build-tests-iIdI-AhKWiVKTuJzU5JxcQ.jar|gs://highfive-dataflow-test/staging/google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|google-cloud-dataflow-java-sdk-all-alpha-PqdZNVZwhs6ixh6de6vM7A.jar|gs://highfive-dataflow-test/staging/google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|google-http-client-1.19.0-1Vc3U5mogjNLbpTK7NVwDg.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|google-http-client-jackson-1.15.0-rc-oW6nFU6Gme53SYGJ9KlNbA.jar|gs://highfive-dataflow-test/staging/google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|google-http-client-jackson2-1.19.0-AOUP2FfuHtACTs_0sul54A.jar|gs://highfive-dataflow-test/staging/google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|google-http-client-protobuf-1.15.0-rc-xYoprQdNcvzuQGZXvJ3ZaQ.jar|gs://highfive-dataflow-test/st
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: aging/google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|google-oauth-client-1.19.0-b3S5WqgD7iWrwg38pfg3Xg.jar|gs://highfive-dataflow-test/staging/google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|google-oauth-client-java6-1.19.0-cP8xzICJnsNlhTfaS0egcg.jar|gs://highfive-dataflow-test/staging/guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|guava-18.0-HtxcCcuUqPt4QL79yZSvag.jar|gs://highfive-dataflow-test/staging/hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|hamcrest-all-1.3-n3_QBeS4s5a8ffbBPQIpFQ.jar|gs://highfive-dataflow-test/staging/hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|hamcrest-core-1.3-DvCZoZPq_3EWA4TcZlVL6g.jar|gs://highfive-dataflow-test/staging/httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|httpclient-4.0.1-sfocsPjEBE7ppkUpSIJZkA.jar|gs://highfive-dataflow-test/staging/httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|httpcore-4.0.1-_SGEPUOMREqA8u_h7qy9_w.jar|gs://highfive-dataflow-test/staging/idea_rt-6II88e1BKUeCOQqcrZht-w.jar|idea_rt-6II88e1BKUeCOQqcrZht-w.jar|gs://highfive-dataflow-test/staging/jacce
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: ss-laKenN34W6jKKivkBUzVcA.jar|jaccess-laKenN34W6jKKivkBUzVcA.jar|gs://highfive-dataflow-test/staging/jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|jackson-annotations-2.4.2-7cAfM1zz0nmoSOC_NlRIcw.jar|gs://highfive-dataflow-test/staging/jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|jackson-core-2.4.2-3CV4j5-qI7Y-1EADAiakmw.jar|gs://highfive-dataflow-test/staging/jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|jackson-core-asl-1.9.13-Ht2i1DaJ57v29KlMROpA4Q.jar|gs://highfive-dataflow-test/staging/jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|jackson-databind-2.4.2-M7rkZKQCfOO3vWkOyf9BKg.jar|gs://highfive-dataflow-test/staging/jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|jackson-mapper-asl-1.9.13-eoeZFbovPzo033HQKy6x_Q.jar|gs://highfive-dataflow-test/staging/javaws-O8JqID6BpsXsCSRRkhii3w.jar|javaws-O8JqID6BpsXsCSRRkhii3w.jar|gs://highfive-dataflow-test/staging/jce-eMjjWzdqQh30yNZ9HMuXMA.jar|jce-eMjjWzdqQh30yNZ9HMuXMA.jar|gs://highfive-dataflow-test/staging/jfr-xDzacRGMQeIR4SdPe69o1A.jar|jfr
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -xDzacRGMQeIR4SdPe69o1A.jar|gs://highfive-dataflow-test/staging/jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|jfxrt-5aSYnU7M458Xy_hx5zXF8w.jar|gs://highfive-dataflow-test/staging/jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|jfxswt-X8I_DFy9gs_6LMLp6_LFPA.jar|gs://highfive-dataflow-test/staging/joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|joda-time-2.4-EIO48_0LMn2_imYqUT5jxA.jar|gs://highfive-dataflow-test/staging/jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|jsr305-1.3.9-ntb9Wy3-_ccJ7t2jV2Tb3g.jar|gs://highfive-dataflow-test/staging/jsse-HOItnWzBlT4hG5HPmlF56w.jar|jsse-HOItnWzBlT4hG5HPmlF56w.jar|gs://highfive-dataflow-test/staging/junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|junit-4.11-lCgz3FeSwzD13Q_KNW4MuQ.jar|gs://highfive-dataflow-test/staging/localedata-R9ei3T8qar8cibFNN0X7Qg.jar|localedata-R9ei3T8qar8cibFNN0X7Qg.jar|gs://highfive-dataflow-test/staging/management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|management-agent-kiuGeHiVpYKGCDNexcQPIg.jar|gs://highfive-dataflow-test/staging/mockito-all-1.9.5-_T4jPTp05rc7PhcOO34Saw.jar|mockito-all-1.9.5-_T4jPTp0
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: 5rc7PhcOO34Saw.jar|gs://highfive-dataflow-test/staging/nashorn-x8si6abt-U04QaVUHvl_bg.jar|nashorn-x8si6abt-U04QaVUHvl_bg.jar|gs://highfive-dataflow-test/staging/paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|paranamer-2.3-rdmhSrp7GRPVm0JexWjzzg.jar|gs://highfive-dataflow-test/staging/plugin-TG6U30mOzKi8yMGKYd7ong.jar|plugin-TG6U30mOzKi8yMGKYd7ong.jar|gs://highfive-dataflow-test/staging/protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|protobuf-java-2.5.0-g0LcHblB4cg-bZEbNj3log.jar|gs://highfive-dataflow-test/staging/resources-RavNZwakZf55HEtrC9KyCw.jar|resources-RavNZwakZf55HEtrC9KyCw.jar|gs://highfive-dataflow-test/staging/rt-Z2kDZdIt-eG8CCtFIinW1g.jar|rt-Z2kDZdIt-eG8CCtFIinW1g.jar|gs://highfive-dataflow-test/staging/slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|slf4j-api-1.7.7-M8fOZEWF4TcHiUbfZmJY7A.jar|gs://highfive-dataflow-test/staging/slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|slf4j-jdk14-1.7.7-hDm19oG8Vzi6jVY9pLtr_g.jar|gs://highfive-dataflow-test/staging/snappy-java-1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|snappy-java
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: -1.0.5-WxwEQNTeXiDmEGBuY9O3Og.jar|gs://highfive-dataflow-test/staging/sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|sunec-ffsdkJzKsC8XbuZa-XHp3Q.jar|gs://highfive-dataflow-test/staging/sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|sunjce_provider-4x9-ynTri_pg6Hhk2Zj9Ow.jar|gs://highfive-dataflow-test/staging/sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|sunmscapi-5TwnMDAci3Hf47yMZYmN1g.jar|gs://highfive-dataflow-test/staging/sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|sunpkcs11-vCiFLLKN99XBpHW2JTkOBw.jar|gs://highfive-dataflow-test/staging/xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|xz-1.0-6m1HjeacPsPpniZtMte8kw.jar|gs://highfive-dataflow-test/staging/zipfs-SIKQJJIhpGOgSa4tT6nStA.jar|zipfs-SIKQJJIhpGOgSa4tT6nStA.jar"},"description":"GCE Instance created for Dataflow","disks":[{"deviceName":"persistent-disk-0","index":0,"mode":"READ_WRITE","type":"PERSISTENT"}],"hostname":"wordcount-jroy-1224043800-12232038-8cfa-harness-0.c.highfive-metrics-service.internal","id":8960015560553137779,"image":"","machineType":"projects/537312487774/machineTypes/n1-stan
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: dard-4","maintenanceEvent":"NONE","networkInterfaces":[{"accessConfigs":[{"externalIp":"130.211.184.44","type":"ONE_TO_ONE_NAT"}],"forwardedIps":[],"ip":"10.240.173.213","network":"projects/537312487774/networks/default"}],"scheduling":{"automaticRestart":"TRUE","onHostMaintenance":"MIGRATE"},"serviceAccounts":{"[email protected]":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.googleapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]},"default":{"aliases":["default"],"email":"[email protected]","scopes":["https://www.goog
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: leapis.com/auth/any-api","https://www.googleapis.com/auth/bigquery","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/datastore","https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/ndev.cloudman","https://www.googleapis.com/auth/pubsub","https://www.googleapis.com/auth/userinfo.email"]}},"tags":["dataflow"],"zone":"projects/537312487774/zones/us-central1-a"}
Dec 24 04:38:45 wordcount-jroy-1224043800-12232038-8cfa-harness-0 google: No startup script found in metadata.
```
Not sure what I should be looking for, but this seems to reliably fail for me in this manner. I see the same problem when I try to run a custom pipeline of my own (i.e. not WordCount), and also when I run the WordCount example on Linux.
I saved off a file where I recorded:
* The complete output from the WordCount main class
* The metadata field values set on the GCE instance
* The complete serial console output
It is available [here](https://docs.google.com/uc?id=0B5K6jhTgGQohVTZhSUFYdFRZMTA&export=download).
Things I've tried so far, without success:
* Forcing the language level of the compiled classes to 1.7 (am using 1.8 JRE)
* Modifying DataflowPipelineRunner::detectClassPathResourcesToStage to not emit JRE jar files (this is a difference I noticed in the log compared to Maven; when running under Maven the JRE jars are not staged).
* EDIT: Attempting to set the classpath to EXACTLY the same as what Maven ends up using (removing all of our projects' dependencies). This seemed to change the behavior a bit and I got to a `java.lang.ClassNotFoundException: com.google.cloud.dataflow.examples.WordCount$ExtractWordsFn` in the worker output.
Strongly suspicious that the problem lies with the staged classpath, but without more specific error messages, I'm shooting in the dark. Would appreciate ideas of where to look next or other things to try.
|
2014/12/24
|
[
"https://Stackoverflow.com/questions/27633093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390587/"
] |
When running pipelines using `[Blocking]DataflowPipelineRunner` from the Cloud Dataflow Java SDK, the runner automatically copies everything from your local Java class path to a staging location in Google Cloud Storage, which is being accessed by workers on-demand.
`ClassNotFoundException` in the Cloud Dataflow worker environment is an indication that required dependencies for your pipeline are not properly staged in a Google Cloud Storage bucket. This likely root cause can be confirmed by looking at the contents of your staging bucket in Google Developers Console and the console output of `BlockingDataflowPipelineRunner`.
Now, the problem can be fixed by bundling all dependencies into a single, monolithic jar. In Maven, the following command can be used to create such a jar as long as the bundle plugin is properly configured to embed all transitive dependencies:
```
mvn bundle:bundle
```
Then, the bundled jar can be executed normally, such as:
```
java -cp <bundled jar> <main class> --project=<project> ...
```
Alternatively, the problem can be fixed by manually adding dependencies to your local class path. For example, the following command may be helpful when running an unbundled jar:
```
java -cp <unbundled jar>:<dep1>:<dep2>:...:<depN> <main class> --project=<project> ...
```
where `dep1` to `depN` are all the dependencies needed for execution of the program. This is clearly error prone, and we don't endorse it. Our documentation recommends using `mvn exec:java` because that sets the execution class path automatically from the dependencies listed in the POM file. Specifically, to run WordCount example, use:
```
mvn exec:java -pl examples \
-Dexec.mainClass=com.google.cloud.dataflow.examples.WordCount \
-Dexec.args="--project=<YOUR GCP PROJECT NAME> --stagingLocation=<YOUR GCS LOCATION> --runner=BlockingDataflowPipelineRunner"
```
The main difference between bundled and unbundled version is in the upload activity before pipeline submission. Unbundled version has an advantage that it can automatically use unchanged dependencies that may have been uploaded in previous submissions.
To summarize, use `mvn exec:java` when running an unbundled jar, or bundle the dependencies into a monolithic jar. We'll try to clarify this in the documentation.
|
2,228,430 |
I know that this code works on another site I've got but it's not playing ball today.
I get three warnings:
>
> Warning: mysqli\_stmt\_bind\_param() expects parameter 1 to be mysqli\_stmt, boolean given in /homepages/14/d248783986/htdocs/subdomains/clients.bionic-comms.co.uk/httpdocs/carefree/process.php on line 33
>
>
> Warning: mysqli\_execute() expects parameter 1 to be mysqli\_stmt, boolean given in /homepages/14/d248783986/htdocs/subdomains/clients.bionic-comms.co.uk/httpdocs/carefree/process.php on line 34
>
>
> Warning: mysqli\_stmt\_affected\_rows() expects parameter 1 to be mysqli\_stmt, boolean given in /homepages/14/d248783986/htdocs/subdomains/clients.bionic-comms.co.uk/httpdocs/carefree/process.php on line 35
>
>
>
Can someone help me figure this out?
I am having to use htaccess to upgrade to PHP5 if this helps.
```
$connection = mysqli_connect($hostname, $username, $password, $dbname);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
$query = "INSERT INTO entries (name, dob, school, postcode, date) VALUES (?,?,?,?,?)";
$stmt1 = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt1, 'sssss',$name,$dob,$school,$postcode,$date);
mysqli_execute($stmt1);
if(mysqli_stmt_affected_rows($stmt1) != 1)
die("issues");
mysqli_stmt_close($stmt1);
return "new";
```
EDIT
After some investigation it transpires that the prepare statement doesn't play ball with mysql4. I have created a new mysql5 database but I now get this error when I try to connect:
>
> Warning: mysqli\_connect() [function.mysqli-connect]: (HY000/2005): Unknown MySQL server host 'localhost:/tmp/mysql5.sock' (1)
>
>
>
Does anyone have any idea as to why this is happening?
|
2010/02/09
|
[
"https://Stackoverflow.com/questions/2228430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
Add more error handling.
When the connection fails, [mysqli\_connect\_error()](http://docs.php.net/mysqli_connect_error) can tell you more details.
When preparing the statement fails [mysqli\_error()](http://docs.php.net/mysqli_error) has more infos about the error.
When executing the statement fails, ask [mysqli\_stmt\_error()](http://docs.php.net/mysqli-stmt.error). And so on and on...
Any time a function/method of the mysqli module returns false to indicate an error, a) handle that error and b) decide whether it makes sense or not to continue. E.g. it doesn't make sense to continue with database operations when the connection failed. But it may make sense to continue inserting data when just one insertion failed (may make sense, may not).
For testing you can use something like this:
```
$connection = mysqli_connect(...);
if ( !$connection ) {
die( 'connect error: '.mysqli_connect_error() );
}
$query = "INSERT INTO entries (name, dob, school, postcode, date) VALUES (?,?,?,?,?)";
$stmt1 = mysqli_prepare($connection, $query);
if ( !$stmt1 ) {
die('mysqli error: '.mysqli_error($connection);
}
mysqli_stmt_bind_param($stmt1, 'sssss',$name,$dob,$school,$postcode,$date);
if ( !mysqli_execute($stmt1) ) {
die( 'stmt error: '.mysqli_stmt_error($stmt1) );
}
...
```
For a real production environment this approach is to talkative and dies to easily ;-)
|
17,744 |
For a 3D scanning project I need to capture a video/snapshots of an object and a projector image that is projected on the object. The projector works (only) with a framerate of 60Hz, the camera supports rates in {3.75,7.5,15,30,60} Hz. I have to work in Matlab, and since it's an IEEE 1394 camera, I can only use the [CMU 1394 Camera driver](http://www.cs.cmu.edu/~iwan/1394/) since other drivers are not supported by matlab.
Now, my problem is, that the framerates of the camera (driver) seem to have a tiny non-zero phase-offset that adds up over time such that the captured image gets darker and darker until it reaches some minimum and becomes brighter and brighter again and so on. This is annoying. There are sample applications for 3D scanners that are able to work with different drivers. There, the problem does not exist, so I am pretty sure that it's the driver's fault.
Fortunately, the driver is open source, so putting a little offset somewhere in it and trying to solve the problem by trying out different times, could work. There is, however, one additional idea I had: The camera supports triggering. Is there any way that I can trigger it using the output of the projector? If that would work, that would be much easier and more elegant than fiddling around with that driver. The projector uses VGA. Do you know of any possibility to capture the signal and use it as a trigger? If possible without lot's of additional hardware.
|
2011/08/03
|
[
"https://electronics.stackexchange.com/questions/17744",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/5235/"
] |
(1) You mention 60 Hz for both **frame and capture rates** so the following should not be an issue, and it's obvious enough, but I mention it "just in case" as such things can trip you up.
I'd have expected that if your frame capture lasted exactly "one frame" that brightness variation would not be a major issue. If capture time is less than frame time then location of your capture window affects result. If capture time is > frame time you get a whole image and then part of another. Both arrangements can (will) affect image quality.
(2) **Frame sync signal:**
Camera synchronisation to the VGA signal **should** be easy.
The VGA signal set includes a Vsync (Vertical Synchronisation) signal that allows the start of the frame to be detected.
This is on pin 14 on a PC (DB15) video connector and on pin 12 on a Macintosh video connector.

The above diagram is from [Javier Valcarce's Personal Website - VGA Video Signal Format and Timing](http://www.javiervalcarce.eu/wiki/VGA_Video_Signal_Format_and_Timing_Specifications)
To add to the fun the polarity of the sync signal varies with resolution,but that's liable to not worry you once you work out which of he two possibilities applies in your case.
Assuming that you can synchronise the camera triggering to this signal (**seems** likely to be simple enough). Worst case you may have to add a fixed delay to move the picture phase into the correct location for you operation.
---
**VGA timing:**

Polarity is inverted for some resolutions.
From [VGA video signal generation](http://www.scribd.com/doc/4559939/VGA-Video-Signal-Generation)
|
15,823,756 |
I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance.
Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once.
The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem.
jQuery Code:
```
$(document).ready(function(){
$('.form_error').hide();
$('a.launch-1').click(function() {
var launcher = $(this).attr('id'),
launcher = launcher.split('_');
launcher, launcher[1], $('td .'+launcher[1]);
$('.'+launcher[1]).each(function(){
var field = $(this).attr('data-name'),
fieldValue = $(this).html();
if(field === 'InvoiceID'){
$("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() {
$("#previouspaymentsloader").hide();
});
} else if(field === 'InvoiceNumber'){
$("#addinvoicenum").html(fieldValue);
}
$('#'+field).val(fieldValue);
});
});
$("#addpayment_submit").click(function(event) {
$('.form_error').hide();
var amount = $("input#amount").val();
if (amount == "") {
$("#amount_error").show();
$("input#amount").focus();
return false;
}
date = $("input#date").val();
if (date == "") {
$("#date_error").show();
$("input#date").focus();
return false;
}
credit = $("input#credit").val();
invoiceID = $("input#InvoiceID").val();
by = $("input#by").val();
dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by;
$.ajax({
type: "POST",
url: "functions/invoicing_payments_make.php",
data: dataString,
success: function(result) {
if(result == 1){
$('#payment_window_message_success').fadeIn(300);
$('#payment_window_message_success').delay(5000).fadeOut(700);
return false;
} else {
$('#payment_window_message_error_mes').html(result);
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
return false;
}
},
error: function() {
$('#payment_window_message_error_mes').html("An error occured, form was not submitted");
$('#payment_window_message_error').fadeIn(300);
$('#payment_window_message_error').delay(5000).fadeOut(700);
}
});
return false;
});
});
```
Here is the html form:
```
<div id="makepayment_form">
<form name="payment" id="payment" class="halfboxform">
<input type="hidden" name="InvoiceID" id="InvoiceID" />
<input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" />
<fieldset>
<label for="amount" class="label">Amount:</label>
<input type="text" id="amount" name="amount" value="0.00" />
<p class="form_error clearb red input" id="amount_error">This field is required.</p>
<label for="credit" class="label">Credit:</label>
<input type="text" id="credit" name="credit" />
<label for="amount" class="label">Date:</label>
<input type="text" id="date" name="date" />
<p class="form_error clearb red input" id="date_error">This field is required.</p>
</fieldset>
<input type="submit" class="submit" value="Add Payment" id="addpayment_submit">
</form>
</div>
```
Hope someone can help as its driving me crazy. Thanks.
|
2013/04/04
|
[
"https://Stackoverflow.com/questions/15823756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513473/"
] |
Some times you have to not only prevent the default behauviour for handling the event, but also to prevent executing any downstream chain of event handlers.
This can be done by calling [`event.stopImmediatePropagation()`](https://api.jquery.com/event.stopimmediatepropagation/) in addition to [`event.preventDefault()`](https://api.jquery.com/event.preventDefault/).
Example code:
```
$("#addpayment_submit").on('submit', function(event) {
event.preventDefault();
event.stopImmediatePropagation();
});
```
|