qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
39,217,812 | I have a simple form with a text box, a command button and a couple of timers. The only purpose of the form is to advise the user what is happening. The program executes all the code as required **EXCEPT for the textbox changes**. I know the code to implement the textbox changes is executed because the form and the command button properties change as required.
I have added this.refresh and this.textbox1.refresh to no avail.
I am new to C# and most of the time I do not have Visual Studios available, so your assistance would be most appreciated. I have read other posts on this topic and probably the answer has already been given, but I have not understood the solution.
The simplified code is given below:
```
//PROGRAM.CS
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using WindowsFormsApplication1;
namespace PostBinaryFile
{
static class Program
{
/// The main entry point for the application.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
}
}
//FORM1.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string sUrl;
string sFileName;
string sCorNo;
public Form1(string[] args)
{
sUrl = args[0];
sFileName = args[1];
sCorNo = args[2];
InitializeComponent();
timer1.Enabled = true;
timer1.Start();
timer2.Enabled = true;
timer2.Start();
}
public void PostCode()
{
InitializeComponent();
string sToken;
string sPath;
const string boundary = "----WebKitFormBoundaryePkpFF7tjBAqx29L";
try
{
//Do all general code work here.
//Alter form to show successful post to web
this.button1.Visible = true;
this.button1.Enabled = true;
this.BackColor = System.Drawing.Color.FromArgb(189,194,241);
this.textBox1.Text = sCorNo + " Outlook file saved to FuseDMS."; // this code is executed but is not reflected on the Form
this.textBox1.BackColor= System.Drawing.Color.FromArgb(189,194,241); // this code is executed but is not reflected on the Form
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
timer1.Enabled = false;
PostCode();
}
private void timer2_Tick(object sender, EventArgs e)
{
timer2.Stop();
timer2.Enabled = false;
this.textBox1.Text = "Saving Message " + sCorNo + ".";
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
``` | 2016/08/30 | [
"https://Stackoverflow.com/questions/39217812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4031078/"
] | The order of "-v" parameter passed was incorrect.
Instead of going to docker command "-v" options it going to mongo container. Hence reorder the command as shown below
```
docker run -p 27018:27017 -v /Users/<user>/data:/data --name mongo2_001 -d mongo
```
On windows
```
docker run -p 27017:27017 -v /c/Users/<user>/data:/data --name mongo2_001 -d mongo
``` |
71,140,858 | I am using Symbolics.jl and I want to make a mathematical summation, equivalent to the function Sum from Sympy (<https://docs.sympy.org/latest/modules/concrete.html>)
The documentation of Symbolics.jl suggests that it is possible:
>
> * Discrete math (representations of summations, products, binomial coefficients, etc.)
>
>
>
However, in the frequently asked questions, the opposite is suggested:
>
> Loops are allowed, but the amount of loop iterations should not require that you know the value of the symbol x.
>
>
> | 2022/02/16 | [
"https://Stackoverflow.com/questions/71140858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18222706/"
] | You can use `+(x...)` for a summation for a vector of symbols.
```
julia> @variables x[1:5]
1-element Vector{Symbolics.Arr{Num, 1}}:
x[1:5]
julia> +(x...)
x[1] + x[2] + x[3] + x[4] + x[5]
julia> Symbolics.derivative(+(x...), x[2])
1
```
Beware of `sum(x)` as it seems to be not expanded and yields incorrect results:
```
julia> sum(x)
Symbolics._mapreduce(identity, +, x, Colon(), (:init => false,))
julia> Symbolics.derivative(sum(x), x[2])
0
```
Last but not least, make another step and define the summation symbol to get a nice experience:
```
julia> ∑(v) = +(v...)
∑ (generic function with 1 method)
julia> ∑(x)
x[1] + x[2] + x[3] + x[4] + x[5]
julia> Symbolics.derivative(100∑(x), x[2])
100
``` |
22,433,325 | I would like to implement the below SQL query in `RetriveMultiple` plug-in on `contact` entity.
```
SELECT contactid, restricted, sensitive, fullname
FROM contact
JOIN RelationsTeam ON contactid = RelationsTeamId
WHERE membersystemuserid = 'XXXXX'
UNION
SELECT contactid, restricted, sensitive, fullname
FROM contact
WHERE restricted = 1
```
Relations are like this: 1-N from `contact` to `RelationsTeam` and N-1 from `RelationsTeam` to `SystemUser` entities.
The requirement is: I need to get all the contacts who are flagged as Restricted when the logged in user is having restricted access privileges or belongs to relations team of contact.
Thanks in advance. | 2014/03/16 | [
"https://Stackoverflow.com/questions/22433325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3424888/"
] | The reason it stops counting is because scanf reads one word at a time. It's reading the first word and then halting, ignoring the rest of the line.
Instead, use [fgets](http://www.cplusplus.com/reference/cstdio/fgets/):
>
> Reads characters from stream and stores them as a C string into str
> until (num-1) characters have been read or either a newline or the
> end-of-file is reached, whichever happens first.
>
>
>
You can read from standard input like so:
```
fgets(phrase, 256, stdin);
```
Have you considered using [strlen](http://www.cplusplus.com/reference/cstring/strlen/) to measure the length of your input?
Finally, you should get into the habit of initialising variables when you declare them:
```
int i = 0,j = 0, size = 0;
```
When a variable is declared its value is 'whatever was in memory', until you set its value. In your example 'length' is never initialised, which will lead to unexpected behaviour. Initialising variables is a good way to avoid unexpected behaviour and time wasted tracking down bugs. |
3,009,253 | First time here -- thought I'd field a question on behalf of a coworker.
Somebody in my lab is doing a content analysis (e.g. reading an article or transcript line by line and identifying relevant themes) of the web presences of various privatized neuroimaging centers (e.g. <http://www.canmagnetic.com/>). She's been c/ping entire site maps by hand, and I know I *could* slap something together with Python to follow links and dump full text (with line numbers) for her, but I've never actually done anything quite like this. Any ideas for how I'd get started?
Cheers,
-alex | 2010/06/09 | [
"https://Stackoverflow.com/questions/3009253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362808/"
] | Here is pretty much everything you need to get started. Read the section "Listing 7. Simple Python Web site crawler". The examples are even written in python.
<http://www.ibm.com/developerworks/linux/library/l-spider/>
Good luck! |
53,254,043 | I have a data frame like:
```
user_name started_at session_time_min task_completed timediff
ABC 2018-03-02 18:00:00 1 3 NA
ABC 2018-03-02 19:00:00 1036 18 1
ABC 2018-03-03 12:00:00 6 10 17
ABC 2018-03-04 21:00:00 0 1 33
ABC 2018-03-05 16:00:00 143 61 19
ABC 2018-03-05 18:00:00 12 18 2
ABC 2018-03-05 19:00:00 60 94 1
ABC 2018-03-05 20:00:00 20 46 1
ABC 2018-03-09 15:00:00 0 1 91
```
I want to sum session\_time\_min and task\_completed with previous row if timediff = 1
Want output like:
```
user_name started_at session_time_min task_completed
ABC 2018-03-02 18:00:00 1037 21
ABC 2018-03-03 12:00:00 6 10
ABC 2018-03-04 21:00:00 0 1
ABC 2018-03-05 16:00:00 143 61
ABC 2018-03-05 18:00:00 92 158
ABC 2018-03-09 15:00:00 0 1
```
Any help will highly be appricated. | 2018/11/11 | [
"https://Stackoverflow.com/questions/53254043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7851425/"
] | `componentDidMount`
-------------------
Pass an empty array as the second argument to `useEffect()` to run only the callback on mount only.
```js
function ComponentDidMount() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('componentDidMount');
}, []);
return (
<div>
<p>componentDidMount: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<div>
<ComponentDidMount />
</div>,
document.querySelector("#app")
);
```
```html
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
```
`componentDidUpdate`
--------------------
`componentDidUpdate()` is invoked immediately after updating occurs. This method is not called for the initial render. `useEffect` runs on every render including the first. So if you want to have a strict equivalent as `componentDidUpdate`, you have to use `useRef` to determine if the component has been mounted once. If you want to be even stricter, use `useLayoutEffect()`, but it fires synchronously. In most cases, `useEffect()` should be sufficient.
This [answer is inspired by Tholle](https://stackoverflow.com/a/53254028/1751946), all credit goes to him.
```js
function ComponentDidUpdate() {
const [count, setCount] = React.useState(0);
const isFirstUpdate = React.useRef(true);
React.useEffect(() => {
if (isFirstUpdate.current) {
isFirstUpdate.current = false;
return;
}
console.log('componentDidUpdate');
});
return (
<div>
<p>componentDidUpdate: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<ComponentDidUpdate />,
document.getElementById("app")
);
```
```html
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
```
`componentWillUnmount`
----------------------
Return a callback in useEffect's callback argument and it will be called before unmounting.
```js
function ComponentWillUnmount() {
function ComponentWillUnmountInner(props) {
React.useEffect(() => {
return () => {
console.log('componentWillUnmount');
};
}, []);
return (
<div>
<p>componentWillUnmount</p>
</div>
);
}
const [count, setCount] = React.useState(0);
return (
<div>
{count % 2 === 0 ? (
<ComponentWillUnmountInner count={count} />
) : (
<p>No component</p>
)}
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<div>
<ComponentWillUnmount />
</div>,
document.querySelector("#app")
);
```
```html
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
``` |
68,506,099 | Where can I find the source code and instructions for building libcurl-gnutls.so?
I'm working on a project that needs libcurl-gnutls.so. I am required to build it from source code - I am not allowed to simply install it with "apt-get install libcurl". Unfortunately, my google-fu is failing me and I can't find a source code repository or instructions to build libcurl-gnutls.so anywhere.
Here's what I have found:
Linux-from-scratch has well-documented instructions for building libcurl.so, here: <https://www.linuxfromscratch.org/blfs/view/svn/basicnet/curl.html>. That lets me build libcurl.so with gnutls, but not libcurl-gnutls.so.
The curl website (curl.se), has detailed instructions on its various options here: <https://curl.se/docs/install.html>. Those show me how to build libcurl with gnutls, but the end product is still libcurl.so, not libcurl-gnutls.so.
When I run ldd -r on my project, it identifies the functions it needs (curl\_easy\_init, curl\_easy\_setopt, curl\_easy\_perform, and curl\_easy\_cleanup). I can find those symbols in both libcurl.so and a pre-built libcurl-gnutls.so. This leads me to suspect that libcurl-gnutls.so **is** libcurl.so, published under a different name. However, renaming libcurl.so to libcurl-gnutls.so is not sufficient to meet the dependency requirements. I could try altering the libcurl project to set its name and version to libcurl-gnutls (not that I know how to do it - I would poke around until I figure it out), but I don't know how appropriate that would be.
I found one other question on Stack Overflow about libcurl-gnutls ([How to create lib curl-gnutls.so.4](https://stackoverflow.com/questions/37012612/how-to-create-lib-curl-gnutls-so-4/37013062)), but the answers to that are to install a pre-built version via apt-get install, which I am not allowed to do. | 2021/07/24 | [
"https://Stackoverflow.com/questions/68506099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3149991/"
] | tl;dr
=====
```java
input
.codePoints()
.mapToObj( this :: wordForCodePoint )
.toList()
```
And, that `wordForCodePoint` method:
```java
if ( codePoint >= 65 && codePoint <= 90 ) { // US-ASCII for A-Z (uppercase) characters are code points 65 to 90.
return NatoConverter.natoWords.get( codePoint - 65 ); // Annoying zero-based index counting.
} else if ( codePoint >= 97 && codePoint <= 122 ) { // US-ASCII for a-z (lowercase) characters are code points 97 to 122.
return NatoConverter.natoWords.get( codePoint - 97 ); // Annoying zero-based index counting.
} else {
return "INVALID CODE POINT: " + codePoint;
}
```
Details
=======
Apparently you want to produce a series of [NATO phonetic alphabet words](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet), one word for each letter of an input string.
`List.of`
---------
An array would work. But I prefer using a [`List`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html).
In Java 9 and later, we can make an [unmodifiable list](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#unmodifiable) by calling [`List.of`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#of(E...)).
```java
List< String > natoWords = List.of( "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "Xray", "Yankee", "Zulu" ) ;
```
Code point, not `char`
----------------------
The `char` type in Java is obsolete, unable to represent even half of the [Unicode](https://en.wikipedia.org/wiki/Unicode) characters supported by Java. So I suggest you make a habit of using Unicode [code point](https://en.wikipedia.org/wiki/Codepoint) integer numbers instead.
We need the code point number for each letter in your input. In the following code we get an [`IntStream`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/IntStream.html) (a series of `int` numbers, one after another) of each letter’s code point. We convert that stream to a [`List`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html).
```java
List < Integer > codePoints = codePointsStream.boxed().toList();
```
The `.boxed()` call converts `int` primitives to `Integer` objects. Not really important here; come back to this point another day if you are unfamiliar.
Before Java 16, replace `.toList()` with: `.collect( Collectors.toList () )`.
```java
List < Integer > codePoints = codePointsStream.boxed().collect( Collectors.toList () );
```
We need a collection of our resulting words. We make an empty list, pre-sized to the number of Unicode characters in our input.
```java
List < String > result = new ArrayList <>( codePoints.size() );
```
Loop our input of code points. For each, test if that code point is an uppercase US-ASCII letter A-Z or a lowercase a-z. If neither, we throw an exception as a way of signaling an error condition.
From code point to index number
-------------------------------
For each code point, we can cleverly convert that number to an index number we need to retrieve from our master list of NATO words. The index numbers for a `List` use the annoying zero-based counting. So we need zero for the first, one for the second, and so on. We get such a number by subtracting the code point number for `A` or `a`, either 65 or 97. For example:
* For `A`, we subtract 65 from 65 to get `0`, the index we need to get "Alpha" from the list.
* For `B`, we subtract 65 from 66 to get `1`, the index we need to get "Bravo" from the list.
```java
for ( Integer codePoint : codePoints ) {
if ( codePoint >= 65 && codePoint <= 90 ) { // US-ASCII for A-Z (uppercase) characters are code points 65 to 90.
String word = NatoConverter.natoWords.get( codePoint - 65 ); // Annoying zero-based index counting.
result.add( word );
} else if ( codePoint >= 97 && codePoint <= 122 ) { // US-ASCII for a-z (lowercase) characters are code points 97 to 122.
String word = NatoConverter.natoWords.get( codePoint - 97 ); // Annoying zero-based index counting.
result.add( word );
} else {
throw new IllegalStateException( "Encountered non-ASCII code point: " + codePoint );
}
}
```
Lastly, we return an unmodifiable list of our resulting NATO words. We call [`List.copyOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#copyOf(java.util.Collection)) to produce a copy of our modifiable list.
```
return List.copyOf( result ); // Return unmodifiable list.
```
Pull that code all together.
```java
package work.basil.example;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class NatoConverter {
private static List < String > natoWords = List.of( "Alpha" , "Bravo" , "Charlie" , "Delta" , "Echo" , "Foxtrot" , "Golf" , "Hotel" , "India" , "Juliett" , "Kilo" , "Lima" , "Mike" , "November" , "Oscar" , "Papa" , "Quebec" , "Romeo" , "Sierra" , "Tango" , "Uniform" , "Victor" , "Whiskey" , "Xray" , "Yankee" , "Zulu" );
public List < String > convert ( String input ) {
IntStream codePointsStream = input.codePoints();
List < Integer > codePoints = codePointsStream.boxed().toList(); // Before Java 16, replace `.toList()` with: .collect( Collectors.toList () )
List < String > result = new ArrayList <>( codePoints.size() );
for ( Integer codePoint : codePoints ) {
if ( codePoint >= 65 && codePoint <= 90 ) { // US-ASCII for A-Z (uppercase) characters are code points 65 to 90.
String word = NatoConverter.natoWords.get( codePoint - 65 ); // Annoying zero-based index counting.
result.add( word );
} else if ( codePoint >= 97 && codePoint <= 122 ) { // US-ASCII for a-z (lowercase) characters are code points 97 to 122.
String word = NatoConverter.natoWords.get( codePoint - 97 ); // Annoying zero-based index counting.
result.add( word );
} else {
throw new IllegalStateException( "Encountered non-ASCII code point: " + codePoint );
}
}
return List.copyOf( result ); // Return unmodifiable list.
}
}
```
Write a little app to call that code.
```java
package work.basil.example;
import java.util.List;
public class App2 {
public static void main ( String[] args ) {
NatoConverter natoConverter = new NatoConverter();
List < String > result = natoConverter.convert( "Basil" );
System.out.println( result );
}
}
```
Or, more compactly.
```java
package work.basil.example;
public class App2 {
public static void main ( String[] args ) {
System.out.println(
new NatoConverter().convert( "Basil" )
);
}
}
```
We get these results:
>
> [Bravo, Alpha, Sierra, India, Lima]
>
>
>
Streams, lambdas, & method references
-------------------------------------
After you become familiar with streams, lambdas, and method references, you could rewrite that converter class to something like this.
```java
package work.basil.example;
import java.util.List;
public class NatoConverter {
private static List < String > natoWords = List.of( "Alpha" , "Bravo" , "Charlie" , "Delta" , "Echo" , "Foxtrot" , "Golf" , "Hotel" , "India" , "Juliett" , "Kilo" , "Lima" , "Mike" , "November" , "Oscar" , "Papa" , "Quebec" , "Romeo" , "Sierra" , "Tango" , "Uniform" , "Victor" , "Whiskey" , "Xray" , "Yankee" , "Zulu" );
public List < String > convert ( String input ) {
return List.copyOf(
input
.codePoints()
.mapToObj( this :: wordForCodePoint )
.toList()
);
}
public String wordForCodePoint ( int codePoint ) {
if ( codePoint >= 65 && codePoint <= 90 ) { // US-ASCII for A-Z (uppercase) characters are code points 65 to 90.
return NatoConverter.natoWords.get( codePoint - 65 ); // Annoying zero-based index counting.
} else if ( codePoint >= 97 && codePoint <= 122 ) { // US-ASCII for a-z (lowercase) characters are code points 97 to 122.
return NatoConverter.natoWords.get( codePoint - 97 ); // Annoying zero-based index counting.
} else {
return "INVALID CODE POINT: " + codePoint;
}
}
}
```
See this [code run live at IdeOne.com](https://ideone.com/eiqQP8).
>
> [Bravo, Alpha, Sierra, India, Lima]
>
>
> |
2,897,864 | I am just trying to fiddle around what is the best and shortest way to describe two simple instructions with C-like pseudo code. The extract instruction is defined as follows:
```
extract rd, rs, imm
```
This instruction extracts the appropriate byte from the 32-bit source register rs and
right justifies it in the destination register. The byte is specified by imm and thus
can take the values 0 (for the least-significant byte) and 3 (for the most-significant byte).
```
rd = 0x0; // zero-extend result, ie to make sure bits 31 to 8 are set to zero in the result
rd = (rs && (0xff << imm)) >> imm; // this extracts the approriate byte and stores it in rd
```
The insert instruction can be regarded as the inverse operation and it takes a right justified byte from the source register rs and deposits it in the appropriate byte of the
destination register rd; again, this byte is determined by the value of imm
```
tmp = 0x0 XOR (rs << imm)) // shift the byte to the appropriate byte determined by imm
rd = (rd && (0x00 << imm)) // set appropriate byte to zero in rd
rd = rd XOR tmp // XOR the byte into the destination register
```
This looks all a bit horrible, so I wonder if there is a little bit a more elegant way to
describe this bahaviour in C-like style ;)
Many thanks,
Claus | 2010/05/24 | [
"https://Stackoverflow.com/questions/2897864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349053/"
] | Extract:
```
rd = (rs >> (imm * 8)) & 0xff
```
Insert:
```
rd = (rd & ~(0xff << (imm * 8))) | ((rs & 0xff) << (imm * 8))
``` |
104,203 | How do I remove the Author textfield from the Comments form. I added a couple new fields:
* First Name
* Last Name
But now in addition to asking for First Name and Last Name, there is a 'Your Name' field which is confusing.
So it looks like this:
* Add New Comments
* First Name (text box)
* Last Name (text box)
* Your name (text box)
* Subject (text box)
* Comment (text box)
I'd like to remove the 'Your name (text box) from all comments since it is a repeating field.
This is the code I am using.
```
function onviasupport_preprocess_page(&$vars) {
//modify taxonomy pages breadcrumbs
if (!empty($vars['template_files'][0]['page-taxonomy'])){
//pull term id from variable templates list
foreach($vars['template_files'] as $key => $value){
if(substr_count($value, 'page-taxonomy-term-') > 0){
$tid = explode('-', $value);
$tid = $tid[3];
}
}
if (!empty($tid)){
//We're on a taxonomy term page.
$term = taxonomy_get_term($tid);
$link = getLinkByPath();
$bc = '<div class="breadcrumb"><a href="/">Home</a> › '.$link;
$vars['breadcrumb'] = $bc. ' › '. $term->name .'</div>';
}
}
//var_dump($vars['page']['content']['system_main']['nodes']);
if (!empty($vars['node'])){
// If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
$vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
$vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type.'__'.$vars['node']->nid;
//modify resource page & article breadcrumbs..
//$lnk = getLinkByType($vars['node']->type);
$lnk = getLinkByPath();
$bc = '<div class="breadcrumb"><a href="/">Home</a>';
if ($lnk) { $bc .= ' › '.$lnk;}
//add the first taxonomy term associated with this node
$tid = _get_node_taxonomy_tid($vars['node']);
$term = taxonomy_term_load($tid);
if(!empty($term)) {
$bc .= ' › '.l($term->name, drupal_get_path_alias('taxonomy/term/'.$tid));
}
$vars['breadcrumb'] = $bc . ' › '.$vars['node']->title .'</div>';
//insert the title emphasis
//$vars['head_title'] = cleanTitle($vars['head_title']);
$vars['title'] = lowerG(insertEmTrig($vars['node']->title));
//$vars['node']->title = insertEmTrig($vars['head_title']);
if ($vars['node']->type == 'primary_landing' || $vars['node']->type == 'resource_landing'){
$vars['title'] = lowerG(insertEmTrig($vars['node']->title, '<br />'));
}
}
}
//given a node, return the first taxonomy tid assigned
function _get_node_taxonomy_tid($node) {
$tkeys = array();
foreach($node as $key => $val) {
if(substr_count($key, 'taxonomy')) {
$tkeys[] = $key;
}
}
foreach($tkeys as $tvoc){
if(!empty($node->$tvoc)) {
$tx = $node->$tvoc;
return $tx['und'][0]['tid'];
}
}
}
//create a list of clickable letters to glossary pages.
function glossary_letters($term = array(), $nodeTx = array()){
$output = '';
/*
//if we're on a node, grab the term id
if(!empty($nodeTx)){
foreach($nodeTx as $nt){
if($nt->vid == "5"){ //the glossary
$tid = $nt->tid;
break;
}
}
}
*/
//make sure this is a term in the glossary vocabulary
if ($term->vid == "5") {
//search through the nodes assigned to this term, and strip off the letter from their title.
//$sql = taxonomy_select_nodes(array($tid),'or', 0, false, 'n.title DESC');
// - not working well due to it's running db_query_range(), fine for a limited range but not this.
$result = db_query('SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n
INNER JOIN taxonomy_index tn ON n.nid = tn.nid
WHERE tn.tid = :tid AND n.status = 1', array(':tid' => $term->tid));
$nodes = array();
foreach ($result as $node){
$ltr = explode(' - ', $node->title);
$ltr = strtoupper($ltr[1]);
$nodes[$ltr] = $node->nid; //letter is now matched to the nid
}
if(!empty($nodes)) {
$output .= '<div class="clr letters">';
foreach(range('A','Z') as $letter){
if(array_key_exists($letter, $nodes)){
$path = url('node/'.$nodes[$letter]);
$output .= '<a href="'.$path.'">'.$letter.'</a> ';
} else {
$output .= $letter.' ';
}
}
$output .= '</div>';
}
}
return $output;
}
//given a vocabulary object, return the link to the correct primary page
function getVocabLink($voc){
$link = '';
if(is_array($voc->nodes)){
foreach($voc->nodes as $key => $val){
if (empty($link)) {
$link = getLinkByType($key);
}
}
}
return $link;
}
function getLinkByPath() {
$link = '';
$pth = drupal_get_path_alias();
if (substr_count($pth, 'product-guide') > 0){
$link = l('Product Guide','product-guide');
}
if (substr_count($pth, 'resources') > 0){
$link = l('Resources','resources');
}
if (substr_count($pth, 'your-account') > 0){
$link = l('Your Account','your-account');
}
return $link;
}
function getLinkByType($type){
if ($type == 'product_guide_page'){
$link = l('Product Guide','product-guide');
}
if ($type == 'resource_page'){
$link = l('Resources','resources');
}
if ($type == 'your_account_page'){
$link = l('Your Account','your-account');
}
if ($type == 'user_guide'){
$link = l('Product Guide','user-guides');
}
return $link;
}
function swapTitle($title){
//now change the default Drupal page title, put brand at beginning
$t = str_replace(' | Onvia', '',$title);
return 'ONVIA | '.$t;
}
/* function to force lowercase "g" on gBusiness */
function lowerG($gtext){
//Don't lowercase the content, as that could be bad for IDs and classes, so I test for all variances.
$gtext = str_replace('GBUSINESS','<span class="g">g</span>BUSINESS', $gtext);
$gtext = str_replace('GBusiness','<span class="g">g</span>Business', $gtext);
$gtext = str_replace('gBusiness','<span class="g">g</span>Business', $gtext);
$gtext = str_replace('gBUSINESS','<span class="g">g</span>BUSINESS', $gtext);
return $gtext;
}
function onviasupport_breadcrumb($vars){
if (!empty($vars)) {
$crumbs = '<div class="breadcrumb">'.implode(' › ', $vars['breadcrumb']).'</div>';
$crumbs = str_replace('^','', $crumbs);
return $crumbs;
}
}
/**
* insert the <em> tag into title using trigger ^
*/
function insertEmTrig($title, $tag=''){
$title = explode('^',$title);
if(count($title) > 1) {
return $title[0].$tag.' <em>'.$title[1].'</em>';
} else {
return $title[0];
}
}
/**
* clear the trigger ^ for head title
*/
function cleanTitle($title){
$title = str_replace('^','', $title);
return $title;
}
/**
* insert the <em> tag half-way through the title, auto = no trigger
*/
function insertEmAuto($title, $tag = ''){
$title = explode(' ',$title);
$half = (floor(count($title) / 2));
array_splice($title, $half, 0, $tag.'<em>');
$title = implode(' ',$title). '</em>';
return $title;
}
//return a list of node titles as links from array of nodes. Used in articles.
function get_title_list($rel_nodes){
if (empty($rel_nodes[0]['nid'])){
return '';
} else {
$filter = '';
foreach($rel_nodes as $item){
if (strpos($filter, 'AND') > 0){
$filter .= ' OR nid = '.$item['nid'];
} else {
$filter .= ' AND nid = '.$item['nid'];
}
}
$query = db_query('SELECT nid, title FROM {node} WHERE status = 1 '.$filter.' ORDER BY created DESC');
$list = '';
while ($result = db_fetch_object($query)){
$itemtitle = cleanTitle($result->title);
$list .= '<dd>'.l($itemtitle, 'node/'.$result->nid).'</dd>';
}
return $list;
}
}
/**
* This is a theme override of the theme_table function from Drupal's theme.inc file.
* Only thing I'm doing here is stripping out any ^ symbols
*/
function onviasupport_table($variables) {
$header = $variables['header'];
$rows = $variables['rows'];
$attributes = $variables['attributes'];
$caption = $variables['caption'];
$colgroups = $variables['colgroups'];
$sticky = $variables['sticky'];
$empty = $variables['empty'];
// Add sticky headers, if applicable.
if (count($header) && $sticky) {
drupal_add_js('misc/tableheader.js');
// Add 'sticky-enabled' class to the table to identify it for JS.
// This is needed to target tables constructed by this function.
$attributes['class'][] = 'sticky-enabled';
}
$output = '<table' . drupal_attributes($attributes) . ">\n";
if (isset($caption)) {
$output .= '<caption>' . $caption . "</caption>\n";
}
// Format the table columns:
if (count($colgroups)) {
foreach ($colgroups as $number => $colgroup) {
$attributes = array();
// Check if we're dealing with a simple or complex column
if (isset($colgroup['data'])) {
foreach ($colgroup as $key => $value) {
if ($key == 'data') {
$cols = $value;
}
else {
$attributes[$key] = $value;
}
}
}
else {
$cols = $colgroup;
}
// Build colgroup
if (is_array($cols) && count($cols)) {
$output .= ' <colgroup' . drupal_attributes($attributes) . '>';
$i = 0;
foreach ($cols as $col) {
$output .= ' <col' . drupal_attributes($col) . ' />';
}
$output .= " </colgroup>\n";
}
else {
$output .= ' <colgroup' . drupal_attributes($attributes) . " />\n";
}
}
}
// Add the 'empty' row message if available.
if (!count($rows) && $empty) {
$header_count = 0;
foreach ($header as $header_cell) {
if (is_array($header_cell)) {
$header_count += isset($header_cell['colspan']) ? $header_cell['colspan'] : 1;
}
else {
$header_count++;
}
}
$rows[] = array(array('data' => $empty, 'colspan' => $header_count, 'class' => array('empty', 'message')));
}
// Format the table header:
if (count($header)) {
$ts = tablesort_init($header);
// HTML requires that the thead tag has tr tags in it followed by tbody
// tags. Using ternary operator to check and see if we have any rows.
$output .= (count($rows) ? ' <thead><tr>' : ' <tr>');
foreach ($header as $cell) {
$cell = tablesort_header($cell, $header, $ts);
$output .= _theme_table_cell($cell, TRUE);
}
// Using ternary operator to close the tags based on whether or not there are rows
$output .= (count($rows) ? " </tr></thead>\n" : "</tr>\n");
}
else {
$ts = array();
}
// Format the table rows:
if (count($rows)) {
$output .= "<tbody>\n";
$flip = array('even' => 'odd', 'odd' => 'even');
$class = 'even';
foreach ($rows as $number => $row) {
// Check if we're dealing with a simple or complex row
if (isset($row['data'])) {
$cells = $row['data'];
$no_striping = isset($row['no_striping']) ? $row['no_striping'] : FALSE;
// Set the attributes array and exclude 'data' and 'no_striping'.
$attributes = $row;
unset($attributes['data']);
unset($attributes['no_striping']);
}
else {
$cells = $row;
$attributes = array();
$no_striping = FALSE;
}
if (count($cells)) {
// Add odd/even class
if (!$no_striping) {
$class = $flip[$class];
$attributes['class'][] = $class;
}
// Build row
$output .= ' <tr' . drupal_attributes($attributes) . '>';
$i = 0;
foreach ($cells as $cell) {
$cell = tablesort_cell($cell, $header, $ts, $i++);
$output .= _theme_table_cell(cleanTitle($cell));
}
$output .= " </tr>\n";
}
}
$output .= "</tbody>\n";
}
$output .= "</table>\n";
return $output;
}
``` | 2014/02/21 | [
"https://drupal.stackexchange.com/questions/104203",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/26391/"
] | You could do use a [hook\_form\_alter()](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7), eg, something like this:
```
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
global $user;
if (!$user->uid) {
unset($form['author']['name']);
}
}
```
to remove that field for anonymous users. If you want that field gone for everyone, then just remove the `if` :)
Note: you could also `unset()` the whole `$form['author']` but then you would not be able to allow other contact information, eg, the homepage and email address, when you use:
![enter image description here](https://i.stack.imgur.com/rsGsP.png) |
38,320,927 | Why does attempting to output a `TCHAR[]` from an iterator cause an access violation and how can I remedy this and still use iterators? I don't understand what is going wrong?
```
struct FileInfo
{
TCHAR path[MAX_PATH];
};
void iter()
{
std::vector<FileInfo> v;
for (int i = 0; i < 5; i++)
v.push_back({ _T("abc") });
for (int i = 0; i < v.size(); i++) {
OutputDebugString(_T("Ok "));
OutputDebugString(v[i].path);
OutputDebugString(_T("\n"));
}
for (auto it = v.begin(); it != v.end(); it++){
OutputDebugString(_T("Bad "));
OutputDebugString((LPTSTR)*it->path); // CAUSES runtime error here
OutputDebugString(_T("\n"));
}
}
``` | 2016/07/12 | [
"https://Stackoverflow.com/questions/38320927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6366191/"
] | `*it->path` evaluates to a `TCHAR`, not a `TCHAR*`.
Casting a `TCHAR` to `LPTSTR` is not right. Casting a `TCHAR*` to `LPTSTR` is OK.
You can use:
```
OutputDebugString((LPTSTR)it->path);
```
or
```
OutputDebugString((LPTSTR)(*it).path));
``` |
1,707,584 | I've read a lot of Zend controller testing tutorials but I can't find one that explains how to test a controller that uses models and mocking those models.
I have the following controller action:-
```
function indexAction(){
// Get the cache used by the application
$cache = $this->getCache();
// Get the index service client and model
$indexServiceClient = new IndexServiceClient($this->getConfig());
$indexModel = $this->_helper->ModelLoader->load('admin_indexmodel', $cache);
$indexModel->setIndexServiceClient($indexServiceClient);
// Load all the indexes
$indexes = $indexModel->loadIndexes();
$this->view->assign('indexes', $indexes);
}
```
At the moment I have a very basic test case:-
```
public function testIndexActionRoute() {
$this->dispatch( '/admin/index' );
$this->assertModule('admin', 'Incorrect module used');
$this->assertController('index', 'Incorrect controller used');
$this->assertAction('index', 'Incorrect action used');
}
```
This test works but it's calling the real models and services, which sometimes means it times out and fails on the test environment. In order to properly unit test just the controller I need to have mocks and expectations for IndexServiceClient and IndexModel - how is this done? | 2009/11/10 | [
"https://Stackoverflow.com/questions/1707584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187415/"
] | Well, since not many replies I am seeing here, I'll try to add my 2cents(potentially arguable).
Answer written below is my IHMO and very subjective(and I think not very useful, but here we go anyway)
I think controllers are not a good fit unit testing. Your business logic layer, models etc. is what is unitestable.
Controllers are connected with UI and bring system together so to speak - hence to me they are a better fit for integration and UI testing - something that packages such as Selenium are used for.
To my mind testing should be easy enough to implement such that total effort for testing implementation is adequate to the returns of it. Wiring up all dependencies for a controller seems to me(with my limited knowledge of course) a bit too much of a task.
The other way to think about it is - what is actually going on in your controllers. Again IHMO it supposed to be primarily a glue level between your business logic and your UI. If you're putting a lot of business logic into controller it will have an adverse effect(for instance it won't be easily unitestable..).
This is all sort of theory of course. Hopefully someone can provide a better answer and actually show how to easily wire up a controller for unit tests! |
70,491,784 | i have a book for flutter beginner programmer. At the first section it show me how to create splash screen, but the problem is that splash screen is doesn't show, just a blank black screen and after that the apps is showing.
This is my splash\_screen.dart
```
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wisata_yogya/main.dart';
void main() =>runApp(SplashScreen());
// ignore: use_key_in_widget_constructors
class SplashScreen extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
home: _SplashScreenBody(),
);
}
}
class _SplashScreenBody extends StatefulWidget{
@override
State<StatefulWidget> createState(){
return _SplashScreenBodyState();
}
}
class _SplashScreenBodyState extends State<_SplashScreenBody>{
@override
Widget build(BuildContext context){
Future.delayed(const Duration(seconds: 3), (){
Navigator.pushAndRemoveUntil(context,
// ignore: prefer_const_constructors
MaterialPageRoute(builder: (context) => MyApp()), (Route route) => false);
});
return const Scaffold(
body: Center(
child: Image(
image: AssetImage("graphics/logo.png"),
height: 75,
width: 75,
)
)
);
}
}
```
And there's no error in the code. | 2021/12/27 | [
"https://Stackoverflow.com/questions/70491784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925180/"
] | This error throws in [useNavigate](https://github.com/remix-run/react-router/blob/v6.2.2/packages/react-router/index.tsx#L512). [useInRouterContext](https://github.com/remix-run/react-router/blob/v6.2.2/packages/react-router/index.tsx#L386) will check if the component(which uses `useNavigate` hook) is a descendant of a `<Router>`.
Here's the source code to explain why you can't use `useNavigate`, `useLocation` outside of the `Router` component:
>
> `useNavigate` uses `useLocation` underly, `useLocation` will get the [location](https://github.com/remix-run/react-router/blob/dc37beb049e883e0e33c77a3897d4ca0891dd565/packages/react-router/index.tsx#L408) from [LocationContext](https://github.com/remix-run/react-router/blob/dc37beb049e883e0e33c77a3897d4ca0891dd565/packages/react-router/index.tsx#L84) provider. If you want to get the react context, you should render the component as the descendant of a context provider.
> `Router` component use the [LocationContext.Provider](https://github.com/remix-run/react-router/blob/dc37beb049e883e0e33c77a3897d4ca0891dd565/packages/react-router/index.tsx#L321) and [NavigationContext.Provider](https://github.com/remix-run/react-router/blob/dc37beb049e883e0e33c77a3897d4ca0891dd565/packages/react-router/index.tsx#L320). That's why you need to render the component as the [children](https://github.com/remix-run/react-router/blob/dc37beb049e883e0e33c77a3897d4ca0891dd565/packages/react-router/index.tsx#L322), so that `useNavigate` hook can get the context data from `NavigationContext` and `LocationContext` providers.
>
>
>
Your environment is browser, so you need to use `BrowserRouter`. `BrowserRouter` is built based on `Router`.
Refactor to this:
`App.jsx`:
```
function App() {
const navigate = useNavigate();
return (
<div>
<button onClick={() => navigate(-1)}>go back</button>
<Nav/>
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route exact path="/home" element={<Home/>}/>
<Route exact path="/upcoming/:user" element={<Upcoming/>}/>
<Route exact path="/record/:user" element={<Record/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</div>
);
}
```
`index.jsx`:
```
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App/>
</BrowserRouter>,
document.getElementById('root')
)
``` |
49,508,437 | I have this HTML form with an input field.
I want only numeric values to be inputted.
Problem is, when I hover the mouse over the input field, a scroll bar appears on the right. How to avoid this?
```html
<html>
<body>
<div class="form-group">
<br/>
<label class="control-label">Hours spent :</label>
<input type="number" id="hours" name="hours" placeholder="Please input total number of hours spent on this job." class="form-control">
</div>
</body>
</html>
``` | 2018/03/27 | [
"https://Stackoverflow.com/questions/49508437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7124778/"
] | You can remove them with CSS, assuming you mean the input spinners.
```
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: textfield;
}
```
<https://css-tricks.com/snippets/css/turn-off-number-input-spinners/> |
89,008 | [Season 43, Episode 19 of Saturday Night Live](https://www.imdb.com/title/tt8283202/?ref_=tt_eps_pr_n) was billed as Guest Host: Donald Glover and Musical Guest: Childish Gambino. But Donald Glover **is** Childish Gambino. Or at the very least, he's the lead singer of it and everyone else is backup.
Has this happened before? I would settle for "Paul McCartney was the host and the Beatles were the musical guest" but ideally it would be "Reg Dwight was the host and Elton John was the musical guest" -- the very same person. And to be clear "Paul Simon was the host and the musical guest" does not count because he uses the same name for both roles. | 2018/05/14 | [
"https://movies.stackexchange.com/questions/89008",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/8842/"
] | [On season 25, episode 5](https://www.imdb.com/title/tt0694782/?ref_=ttep_ep5), Garth Brooks played on SNL as [Chris Gaines](https://www.rollingstone.com/music/news/flashback-garth-brooks-hosts-saturday-night-live-and-performs-as-chris-gaines-20141113). At the time, there were plans to make a Chris Gaines movie starring Garth Brooks which fell through. He was still the host and musical guest of SNL as two different alter egos.
EDIT: [Here is a link to the NBC page which has some clips.](http://www.nbc.com/saturday-night-live/season-25/episode/5-garth-brooks-with-chris-gaines-62551) |
21,873,545 | This will be an additional question to my previous question: [Storing password for an offline app](https://stackoverflow.com/questions/21849131/storing-password-for-an-offline-app)
If I store my password in a file in external storage and it's encrypted, is the file editable?
I'm just thinking for example, I set a pass `"hello"` and stored it in a file. Then to login, I will call that encrypted string.
What if you open the file where your password is stored and edit that encrypted string and save it and you try to login again in your app, will the `"hello"` still work?
Sorry, I'm kinda new to this thing. | 2014/02/19 | [
"https://Stackoverflow.com/questions/21873545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3322594/"
] | Why don't you use `SharedPreference` for this kind of data saving. If your data is not quite big you can use SharedPreference for that. Save the data in `SharedPreference` so it wont be editable explicitly. And the data is only editable by your app. Documentation for [SharedPreferences](http://developer.android.com/guide/topics/data/data-storage.html#pref)
>
> The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
>
>
> |
5,114,352 | I have a segemented control with three choices, each choice does a different calculations. The calculations are doing manipulating strings.
I notice that when I first start the app, the strings are nil, btw. If I touch all three options on the segmented control, the app will crash, and here is the stack trace.
I've searched everywhere but can't find the problem still.
```
[Session started at 2011-02-25 01:21:03 -0500.]
2011-02-25 01:21:07.075 tipApp[2184:207] -[_UIStretchableImage isEqualToString:]: unrecognized selector sent to instance 0x4b5c0a0
2011-02-25 01:21:07.078 tipApp[2184:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIStretchableImage isEqualToString:]: unrecognized selector sent to instance 0x4b5c0a0'
*** Call stack at first throw:
(
0 CoreFoundation 0x00db7be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f0c5c2 objc_exception_throw + 47
2 CoreFoundation 0x00db96fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d29366 ___forwarding___ + 966
4 CoreFoundation 0x00d28f22 _CF_forwarding_prep_0 + 50
5 tipApp 0x00006f13 -[tipAppViewController exact] + 56
6 tipApp 0x00006ed3 -[tipAppViewController mirror] + 4772
7 tipApp 0x000057f2 -[tipAppViewController segmentedControlIndexChanged] + 104
8 UIKit 0x002c0a6e -[UIApplication sendAction:to:from:forEvent:] + 119
9 UIKit 0x0034f1b5 -[UIControl sendAction:to:forEvent:] + 67
10 UIKit 0x00351647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
11 UIKit 0x0034f16c -[UIControl sendActionsForControlEvents:] + 49
12 UIKit 0x0038e6b2 -[UISegmentedControl setSelectedSegmentIndex:] + 574
13 UIKit 0x0039317e -[UISegmentedControl touchesBegan:withEvent:] + 971
14 UIKit 0x002e5025 -[UIWindow _sendTouchesForEvent:] + 395
15 UIKit 0x002c637a -[UIApplication sendEvent:] + 447
16 UIKit 0x002cb732 _UIApplicationHandleEvent + 7576
17 GraphicsServices 0x016eda36 PurpleEventCallback + 1550
18 CoreFoundation 0x00d99064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
19 CoreFoundation 0x00cf96f7 __CFRunLoopDoSource1 + 215
20 CoreFoundation 0x00cf6983 __CFRunLoopRun + 979
21 CoreFoundation 0x00cf6240 CFRunLoopRunSpecific + 208
22 CoreFoundation 0x00cf6161 CFRunLoopRunInMode + 97
23 GraphicsServices 0x016ec268 GSEventRunModal + 217
24 GraphicsServices 0x016ec32d GSEventRun + 115
25 UIKit 0x002cf42e UIApplicationMain + 1160
26 tipApp 0x00002888 main + 102
27 tipApp 0x00002819 start + 53
)
terminate called after throwing an instance of 'NSException'
[Session started at 2011-02-25 01:26:59 -0500.]
``` | 2011/02/25 | [
"https://Stackoverflow.com/questions/5114352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597775/"
] | It looks like in your `-[tipAppViewController exact]` method you are sending the `isEqualToString:` selector to an object that does not handle it.
If that's not helpful, maybe post the code for the `exact` method. |
52,392,380 | I'm trying to make a Login screen I've made in Android Studio to work with Kotlin but I'm having troubles making a class that will "attach" the Basic Authentication to all the requests. To do this I am using Retrofit2 and OkHttp3.
These are the relevant classes in my code:
**GET\_LOGIN.kt**
```
package com.joaomartins.srodkitrwale
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Headers
interface GET_LOGIN {
@GET("login")
fun getAccessToken() : Call<String>
}
```
**RetrofitClient.kt**
```
package com.joaomartins.srodkitrwale
import android.app.Application
import android.util.Base64
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.Interceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
val username = Login().userTxt.text
val password = Login().passTxt.text
val credentials = username + ":" + password
val AUTH = "Basic " + Base64.encodeToString(credentials.toByteArray(Charsets.UTF_8), Base64.DEFAULT).replace("\n", "")
val retrofit = RetrofitClient().init()
//.getBytes(), Base64.DEFAULT).replace("\n", "")
//val AUTH2 = java.util.Base64.getEncoder().encode((username + ":" + password).toByteArray()).toString(Charsets.UTF_8)
class RetrofitClient {
// Initializing Retrofit
fun init() : Retrofit{
// Creating the instance of an Interceptor
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
// Creating the OkHttp Builder
val client = OkHttpClient().newBuilder()
// Creating the custom Interceptor with Headers
val interceptor = Interceptor { chain ->
val request = chain?.request()?.newBuilder()?.addHeader("Authorization", AUTH)?.build()
chain?.proceed(request)
}
client.addInterceptor(interceptor) // Attaching the Interceptor
// Creating the instance of a Builder
return Retrofit.Builder()
.baseUrl("https://srodki.herokuapp.com/") // The API server
.client(client.build()) // Adding Http Client
.addConverterFactory(GsonConverterFactory.create()) // Object Converter
.build()
}
fun providesGetLogin(): GET_LOGIN = retrofit.create(GET_LOGIN::class.java)
}
```
**Login.kt**
```
package com.joaomartins.srodkitrwale
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.util.Base64
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_login.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
class Login : AppCompatActivity() {
val apiLogin = RetrofitClient().providesGetLogin().getAccessToken()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
loginBtn.setOnClickListener {
val user = userTxt.text
val pass = passTxt.text
if (validateLogin(user, pass)){
login(user, pass)
}
}
}
fun validateLogin(user: Editable, pass: Editable): Boolean {
if (user == null || user.trim().isEmpty()){
Toast.makeText(this, "Missing Username or Password", Toast.LENGTH_SHORT).show()
return false
}
if (pass == null || pass.trim().isEmpty()){
Toast.makeText(this, "Missing Username or Password", Toast.LENGTH_SHORT).show()
return false
}
return true
}
fun login(user: Editable, pass: Editable) {
/*val intent = Intent(this, List_users::class.java)
startActivity(intent)*/
apiLogin.enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
Log.d("check", "Reached this place")
if(!response.isSuccessful)
Log.d("failed", "No Success")
Toast.makeText(this@Login, "Login Successful!", Toast.LENGTH_SHORT).show()
val intent = Intent(this@Login, List_users::class.java)
startActivity(intent)
}
override fun onFailure(call: Call<String>, t: Throwable) {
Toast.makeText(this@Login, "Login Failed.", Toast.LENGTH_SHORT).show()
}
})
}
}
```
The class that would be responsible for the creation of the request with the encrypted authentication is the *RetrofitClient* class.
I believe the error lies within the following lines of code:
```
val username = Login().userTxt.text
val password = Login().passTxt.text
val credentials = username + ":" + password
val AUTH = "Basic " + Base64.encodeToString(credentials.toByteArray(Charsets.UTF_8), Base64.DEFAULT).replace("\n", "")
```
There should be an easier way to do this but I am still learning Android and Kotlin. | 2018/09/18 | [
"https://Stackoverflow.com/questions/52392380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10381749/"
] | Use this:
```
val client = OkHttpClient()
val credential = Credentials.basic("username", "secret")
val request = Request.Builder()
.url("https://yourserver.com/api")
.addHeader("Authorization", credential)
.build()
client.newCall(request).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
TODO("Not yet implemented")
}
override fun onResponse(call: Call, response: Response) {
println(response.body()?.string())
}
})
``` |
34,758,780 | I have a Java parser code Im running in `Eclipse` to generate 1GB of data and put in `sstable` format. Once complete how do I load `sstables` into my `keyspace` and `cluster` from terminal on windows machine. My `cluster` is running on my local machine.
My terminal
```
path = C:\program files\datastaxcommunity\apache-cassandra\bin>
```
The command I attempt to run from terminal `path = sstableloader ip address> data\KeyspaceName\TableName`
The Error I receive: `"The system cannot find the file specified."`
Is my `sstableloader` statement correct?
Should I run `sstableloader` from a different path?
Any help is very much appreciated. | 2016/01/13 | [
"https://Stackoverflow.com/questions/34758780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5145969/"
] | The command line for `sstableloader` should be:
```
sstableloader -d <ip_address> <path to sstables>
```
It looks to me like you are missing the `-d` so the loader is trying to interpret your ip address as the sstable location. |
29,261,417 | I have a json file which the link is <https://gist.githubusercontent.com/Rajeun/b550fe17181610f5c0f0/raw/7ba82c6c1135d474e0bedc8b203d3cf16e196038/file.json>
i want to do a test on the boolean "sent". there is my xml file.
```
<http:request-config name="HTTP_Request_Configuration"
host="gist.githubusercontent.com" port="443" protocol="HTTPS"
doc:name="HTTP Request Configuration" />
<flow name="testFlow">
<poll doc:name="Poll">
<http:request config-ref="HTTP_Request_Configuration"
path="Rajeun/b550fe17181610f5c0f0/raw/7ba82c6c1135d474e0bedc8b203d3cf16e196038/file.json"
method="GET" doc:name="HTTP" />
</poll>
<json:json-to-object-transformer
returnClass="java.lang.Object" doc:name="JSON to Object" />
<choice doc:name="Choice">
<when expression="#[payload.sent] == true )">
<logger message="its ok" level="INFO" doc:name="Logger"/>
</when>
<otherwise>
<logger message="Error" level="INFO" doc:name="Logger"/>
</otherwise>
</choice>
</flow>
```
errors:
```
ERROR 2015-03-25 16:29:59,871 [[push1].testFlow.stage1.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Failed to transform from "json" to "java.lang.Object"
Code : MULE_ERROR-109
--------------------------------------------------------------------------------
Exception stack is:
1. Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries
at [Source: java.io.InputStreamReader@1a09a5b; line: 5, column: 4] (org.codehaus.jackson.JsonParseException)
org.codehaus.jackson.JsonParser:1433 (null)
2. Failed to transform from "json" to "java.lang.Object" (org.mule.api.transformer.TransformerException)
org.mule.module.json.transformers.JsonToObject:132 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
org.codehaus.jackson.JsonParseException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries
at [Source: java.io.InputStreamReader@1a09a5b; line: 5, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1433)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
```
i don't know what is the problem please any help !! | 2015/03/25 | [
"https://Stackoverflow.com/questions/29261417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4659336/"
] | The expression should be `<when expression="#[payload.sent == true ]">` and this is working for me ..
also as afelisatti mentioned, there should be a comma after **email** attribute in JSON payload |
8,170,325 | i want to create few Reports which picks data from few SQL tables, So instead of creating different report's i want to create (or use any Open source) reporting framework, I googled about it but still didn't find enough information to try one.
Following are my requirements:
```
Filters : Support for different types of Filtering mechanism for the End User
DataSource : SQL Table
UI : user Defined UI for every user (user specific information can be persisted in DB)
Number of concurrent users : 10 (Max)
server : tomcat
Support for graph/Charts
javascript support for customizable UI
```
i have heard about Jasper / birt framework but dont have working knowledge for any 1 of them so can some one suggest if there exists a opensource framework which i can use for the above mentioned requirements | 2011/11/17 | [
"https://Stackoverflow.com/questions/8170325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/537445/"
] | There are the tools around the JasperReports library like iReport and JasperServer all from [JasperSoft](http://www.jaspersoft.com/). The tools around [Eclipse Birt](http://eclipse.org/birt/). And then there are the tools from [Pentaho](http://www.pentaho.com/).
All three are very powerful and open source and can do what you need. There is plenty of tooling and documentation available and you can buy commercial support for them. Your decision will be based a bit around licensing and potential need for features that are only in the commercial version (e.g. of JasperServer). |
95,797 | I have a view whose query I want to completely change. I want to change the select statement, the joins and the where clause.
the original query is this:
```
SELECT node.nid AS nid, node.title AS node_title, field_data_field_location.field_location_tid AS field_data_field_location_field_location_tid, node.created AS node_created, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_entity_type} field_data_field_entity_type ON node.nid = field_data_field_entity_type.entity_id AND (field_data_field_entity_type.entity_type = :views_join_condition_0 AND field_data_field_entity_type.deleted = :views_join_condition_1)
LEFT JOIN {field_data_field_location} field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = :views_join_condition_2 AND field_data_field_location.deleted = :views_join_condition_3)
LEFT JOIN {node} node_1 ON node.nid = node_1.nid AND (node_1.language = 'bg' AND node.tnid != node.nid AND node.language = 'en')
WHERE (( (field_data_field_entity_type.field_entity_type_tid = :field_data_field_entity_type_field_entity_type_tid ) AND (field_data_field_location.field_location_tid = :field_data_field_location_field_location_tid ) )AND(( (node.status = :db_condition_placeholder_4) AND (node.type IN (:db_condition_placeholder_5)) AND (node.language IN (:db_condition_placeholder_6, :db_condition_placeholder_7)) )))
ORDER BY field_data_field_location_field_location_tid ASC, node_title ASC, node_created DESC
```
and the new query is this:
```
select CASE when b.node_title is not null then b.nid else a.nid end as nid,
CASE when b.node_title is null then a.node_title else b.node_title end as node_title,
CASE when b.node_title is not null then b.field_data_field_location_field_location_tid else a.field_data_field_location_field_location_tid end as field_data_field_location_field_location_tid,
CASE when b.node_title is not null then b.node_created else a.node_created end as node_created,
'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
from
(SELECT node.tnid, node.nid AS nid, node.title AS node_title, field_data_field_location.field_location_tid AS field_data_field_location_field_location_tid, node.created AS node_created, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
FROM
node node
LEFT JOIN field_data_field_entity_type field_data_field_entity_type ON node.nid = field_data_field_entity_type.entity_id AND (field_data_field_entity_type.entity_type = 'node' AND field_data_field_entity_type.deleted = '0')
LEFT JOIN field_data_field_location field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = 'node' AND field_data_field_location.deleted = '0')
WHERE field_data_field_entity_type.field_entity_type_tid = '818'
AND field_data_field_location.field_location_tid = '408'
AND node.status = '1'
AND node.type IN ('data_entity')
AND node.language = 'en') a LEFT OUTER JOIN
(SELECT node.tnid, node.nid AS nid, node.title AS node_title, field_data_field_location.field_location_tid AS field_data_field_location_field_location_tid, node.created AS node_created, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
FROM
node node
LEFT JOIN field_data_field_entity_type field_data_field_entity_type ON node.nid = field_data_field_entity_type.entity_id AND (field_data_field_entity_type.entity_type = 'node' AND field_data_field_entity_type.deleted = '0')
LEFT JOIN field_data_field_location field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = 'node' AND field_data_field_location.deleted = '0')
WHERE field_data_field_entity_type.field_entity_type_tid = '818'
AND field_data_field_location.field_location_tid = '408'
AND node.status = '1'
AND node.type IN ('data_entity')
AND node.language = 'bg') b
ON a.nid= b.tnid
```
I tried with views\_pre\_execute hook and with query\_alter view with no luck...
The first attemt is using <https://drupal.org/node/409808>
$view->build\_info['query'] = MY QUERY; which throws error:Call to a member function
addMetaData() on a non-object
The attempt with query alter is a dissaster...I cannot make it work.. | 2013/11/29 | [
"https://drupal.stackexchange.com/questions/95797",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/21321/"
] | As the others say you can use `hook_views_query_alter` in your custom module and this is Sample of using it :
```
function alterform_views_query_alter(&$view, &$query) {
switch($view->name) {
case 'myViewName':
echo 'test test'; // test
$query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";
$query->orderby[1] = "node_title ASC";
break;
}
}
``` |
7,310,678 | I'd like to know if with `HTML5` and `JavaScript` - and relative support in later browser versions, plus some server side technology `PHP` could I manage a dynamic video playlist.
I would like to play video1, video2, video3 (placed in a web server sub directory) and loop. I would like to then add a video (video4) and then system should play video1, video2, video3, video4 (loop).
With PHP I can easy add file video4 in sub directory but I don't know about a playlist loop in HTML5/ECMA/JavaScript.
It it possible and easy to implement?
Thank in advance. | 2011/09/05 | [
"https://Stackoverflow.com/questions/7310678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927143/"
] | I have experienced the same problems. The only thing which helps is to run devappserver with specified IP address of your computer instead of running it on localhost (which is default).
like this:
`google_appengine\dev_appserver.py --address=192.168.1.33 myapp`
Please can you confirm if it works? |
1,638,148 | Does `date +%a` output always the weekday in the system language?
No matter if in bash, sh or cronjob | 2021/03/30 | [
"https://superuser.com/questions/1638148",
"https://superuser.com",
"https://superuser.com/users/1291904/"
] | Yes, except it's not "system language" in general, but specifically the value of `LANG` or `LC_TIME` environment variables. Now, whether those variables are set or not *may* indeed depend on how the script is started.
For example, in some Linux distributions, the locale environment is set through pam\_env and will be present everywhere – local, SSH, cron, etc. But in some other distributions, the environment is set through /etc/profile which *only* applies to interactive sh/bash logins but not batch ones.
The most reliable option is to specify the desired locale directly within your script.
For example, if you run `env LC_TIME=en_US.UTF-8 date +%a` then you will always get English output, no matter what the global system language is. And if you run `env LC_TIME=de_DE.UTF-8 date +%a` then the output will be in German, and so on.
*(All locale-related functions first look at `LC_something`, e.g. LC\_TIME or LC\_MESSAGES, and if that's not set, they look at the general `LANG`.)*
Note that the locale has to be made available system-wide first, using `locale-gen` or similar tools. Use `locale -a` to check which ones are currently available. |
367,111 | A friend of mine keeps making nasty comments at people who are the same race as her and can't speak their mother tongue. Besides, she also believes some languages don't even matter. I'm looking for a word to call her the next time she does it | 2017/01/07 | [
"https://english.stackexchange.com/questions/367111",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/214083/"
] | This is precisely called as "**Linguistic Chauvinism**"
Linguistic chauvinism is the idea that one's language is superior to others. For a few examples, the Greeks called all non-Greek speakers barbarians, the French are only at home where French is spoken, and English speakers consider the ability to speak another language a social defect
Source of above text: wiki answers |
13,391,363 | As mentioned, how do i get the last element index , for example the position of 11 in this $a ?
```
$a[0][0] = 0;
$a[0][1] = 1;
$a[0][2] = 2;
$a[1][0] = 3;
$a[1][1] = 4;
$a[1][2] = 5;
$a[2][3] = 6;
$a[2][4] = 7;
$a[2][5] = 8;
$a[3][0] = 9;
$a[4][0] = 10;
$a[4][1] = 11;
enter code here
```
i will like to receive x = 1, y = 4 | 2012/11/15 | [
"https://Stackoverflow.com/questions/13391363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1611546/"
] | If you want to get last array value of `11` then you can simple use `end()` array function
```
echo end(end($a));
```
**Demo:** <http://codepad.org/fSsHJYTI>
**Full code:**
```
<?php
$a[0][0] = 0;
$a[0][1] = 1;
$a[0][2] = 2;
$a[1][0] = 3;
$a[1][1] = 4;
$a[1][2] = 5;
$a[2][3] = 6;
$a[2][4] = 7;
$a[2][5] = 8;
$a[3][0] = 9;
$a[4][0] = 10;
$a[4][1] = 11;
echo end(end($a));
?>
``` |
15,636,263 | Heyho. I'm writing an android client which is communicating between a [Hessian Servlet](http://www.caucho.com/resin-3.0/protocols/hessian.xtp) and [Hessdroid](https://code.google.com/p/hessdroid/). Everything went fine until i wanted to transmit this selfimplemented type:
* client & server are communicating between IUserService.java interface.
**SERVER-SIDE:**
***odtObject.java:***
```
import java.io.Serializable;
public class odtObject implements Serializable {
private String siteName;
private int siteId;
public odtObject(String siteName, int siteId) {
this.siteName = siteName;
this.siteId = siteId;
}
public String getSiteName() {
return siteName;
}
public int getSiteId() {
return siteId;
}
}
```
***UserService.java:***
```
public ArrayList<odtObject> getSiteList() {
ArrayList<odtObject> siteList = new ArrayList<odtObject>();
siteList.add(new odtObject("hello", 1));
System.out.println(siteList.get(0).getSiteName()); // out: hello
return siteList;
}
```
**CLIENT-SIDE**
***PageOne.java:***
```
IUserService con = new IUserService();
ArrayList<odtObject> siteList = new ArrayList<odtObject>();
siteList = con.getSiteList();
System.out.println(siteList.get(0).getSiteName()); // 87: Exception
```
***odtObject.java: ...***
***Exception:***
```
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testapp/com.testapp.PageOne}: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.testapp.odtObject
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.testapp.odtObject
at com.testapp.PageOne.onCreate(PageOne.java:87)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
```
Thank you for help! Just say it, if you want to see more code...
**Edit:**
RetrieveData calls IUserService function... PageOne code from above is kind of pseudo code to understand it easier.
```
protected void onCreate(Bundle savedInstanceState) {
Thread t = new Thread() {
public void run() {
Intent myIntent = getIntent();
String user = myIntent.getStringExtra("user");
String pass = myIntent.getStringExtra("pass");
RetrieveData r = new RetrieveData(context);
if(r.login(user, pass.toCharArray()) != null) {
siteList = r.getSiteList();
System.out.println("done");
} else {
System.out.println("error");
}
}
};
t.start();
super.onCreate(savedInstanceState);
setContentView(R.layout.page1);
inputSearch = (EditText) findViewById(R.id.inputSearch);
listView = (ListView) findViewById(R.id.mylist);
/* wait for networking thread */
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
System.out.println(siteList.get(0).getSiteName()); // 87: Exception
for (odtObject d : siteList) {
adapter.add(d.getSiteName());
}
listView.setAdapter(adapter);
...
}
```
maybe this could be relevant too:
```
public String login(String username, char[] password) {
HessianProxyFactory factory = new HessianProxyFactory();
String url = "http://192.168.56.1:8080/hessianServerX";
factory.setHessian2Reply(false); // avoid hessian reply error
try {
userCon = (IUserService) factory.create(IUserService.class,
url+"/IUserService");
sessionId = userCon.login(username, password);
secureCon = (ISecureService) factory.create(ISecureService.class,
url+"/restrictedArea/ISecureService;jsessionid="+sessionId);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return sessionId;
}
```
Edit:
I set DebugMode on the HessianProxyFactory and now i get this one:
```
03-26 16:07:06.909: W/SerializerFactory(6023): Hessian/Burlap: 'com.hessian.odtObject' is an unknown class in dalvik.system.PathClassLoader[dexPath=/data/app/tsch.serviceApp-1.apk,libraryPath=/data/app-lib/tsch.serviceApp-1]:
03-26 16:07:06.909: W/SerializerFactory(6023): java.lang.ClassNotFoundException: com.hessian.odtObject
03-26 16:07:06.909: W/dalvikvm(6023): threadid=10: thread exiting with uncaught exception (group=0x9e50d908)
03-26 16:07:06.909: E/AndroidRuntime(6023): FATAL EXCEPTION: Thread-527
03-26 16:07:06.909: E/AndroidRuntime(6023): java.lang.ClassCastException: java.util.HashMap cannot be cast to tsch.serviceApp.types.odtObject
03-26 16:07:06.909: E/AndroidRuntime(6023): at tsch.serviceApp.net.HessianConnect.<init>(HessianConnect.java:31)
03-26 16:07:06.909: E/AndroidRuntime(6023): at tsch.serviceApp.PageLogin$1.run(PageLogin.java:17)
``` | 2013/03/26 | [
"https://Stackoverflow.com/questions/15636263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2140082/"
] | Solved the problem by myself. I had to export the custom type class OdtObject.java as a jar and add it to the classpaths! |
10,333,934 | I'm going to enhance an application with a Swing UI, to allow the user to pick colors so they're not stuck with the default color choices.
It is common for other applications to have shaded rectangles drawn on each button that activates a color selector, with the rectangle's color changing accordingly when a new color is selected. I am trying to achieve the same effect by placing a small JPanel with the selected color on the button, but that results in a tiny square in the middle of the button, instead of filling most of the surface of the button.
I figure another way would be to dynamically generate rectangular icons with the colors and then add the appropriate icon to each button, but surely there must be a simpler way? | 2012/04/26 | [
"https://Stackoverflow.com/questions/10333934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383341/"
] | put there `JButton.setIcon` with expected `Rectangle`, for [example](https://stackoverflow.com/a/9300813/714968)
EDIT
>
> I am trying to achieve the same effect by placing a small JPanel with the selected color on the button, but that results in a tiny square in the middle of the button, instead of filling most of the surface of the button.
>
>
>
only `JFrame (BorderLayout)` and `JPanel (FlowLayout)` have got pre-implemented `LayoutManager`, for rest of `JComponents` (add one `JComponent` to the another `JComponent`) you have to define `LayoutManager`, [please read this thread](https://stackoverflow.com/a/10140922/714968) |
69,298,730 | I have a monorepo that includes both a front-end (CRA) React app and an Express API. They both use another package in the monorepo that is plain TS, but uses `import` statements. I use `tsc` to compile the TS -> JS for the React app, into a directory I call `tscompiled`, and for the Node app I further transpile the JS with babel to a directory called `lib`, so that all the `import` statements become `require`s.
So when I want to compile the React app, I need `package.json` for my dependency to use the `tscompiled` directory with its type definitions:
```
"main": "tscompiled/index.js",
```
And then when I want to compile the Express app, I need `package.json` for my dependency to use the `lib` directory:
```
"main": "lib/index.js",
```
This is a real kludge — can I get my Node Express app to handle `import` statements or transpile dependent packages within the monorepo automatically? | 2021/09/23 | [
"https://Stackoverflow.com/questions/69298730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351536/"
] | First idea is use lambda function with [`Series.str.len`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html) and `max`:
```
df = (df.groupby('source')['text_column']
.agg(lambda x: x.str.len().max())
.reset_index(name='something'))
print (df)
source something
0 a 9.0
1 b 14.0
2 c 9.0
```
Or you can first use [`Series.str.len`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html) and then aggregate `max`:
```
df = (df['text_column'].str.len()
.groupby(df['source'])
.max()
.reset_index(name='something'))
print (df)
```
Also if need integers first use [`DataFrame.dropna`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html):
```
df = (df.dropna(subset=['text_column'])
.assign(text_column=lambda x: x['text_column'].str.len())
.groupby('source', as_index=False)['text_column']
.max())
print (df)
source text_column
0 a 9
1 b 14
2 c 9
```
EDIT: for first and second top values use [`DataFrame.sort_values`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html) with [`GroupBy.head`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.head.html):
```
df1 = (df.dropna(subset=['text_column'])
.assign(something=lambda x: x['text_column'].str.len())
.sort_values(['source','something'], ascending=[True, False])
.groupby('source', as_index=False)
.head(2))
print (df1)
source text_column something
0 a abcdefghi 9
1 a abcde 5
7 b qazxswedcdcvfr 14
2 b qwertyiop 9
3 c plmnkoijb 9
5 c abcde 5
```
Alternative solution with [`SeriesGroupBy.nlargest`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.nlargest.html), obviously slowier:
```
df1 = (df.dropna(subset=['text_column'])
.assign(something=lambda x: x['text_column'].str.len())
.groupby('source')['something']
.nlargest(2)
.reset_index(level=1, drop=True)
.reset_index())
print (df1)
source something
0 a 9
1 a 5
2 b 14
3 b 9
4 c 9
5 c 5
```
Last solution for new columns by top1, top2:
```
df=df.dropna(subset=['text_column']).assign(something=lambda x: x['text_column'].str.len())
df = df.sort_values(['source','something'], ascending=[True, False])
df['g'] = df.groupby('source').cumcount().add(1)
df = (df[df['g'].le(2)].pivot('source','g','something')
.add_prefix('top')
.rename_axis(index=None, columns=None))
print (df)
top1 top2
a 9 5
b 14 9
c 9 5
``` |
42,694,264 | I've been starting to use VS2017 Community. This bugs me:
Below is normal getter setter from previous VS:
```
public string Name
{
get{ return _name;}
set{ _name = value;}
}
```
This is the new getter setter:
```
public string Name { get => _name; set => _name = value; }
```
Anyone can explain to me why the syntax is changed? | 2017/03/09 | [
"https://Stackoverflow.com/questions/42694264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7499325/"
] | I wouldn't say they changed it, I would say they gave us some new syntax options. You can still use the "old" way of declaring getters and setters, but there is now also a more functional programming style of doing it as well. In C#6 Microsoft already introduced using expressions for getter only properties doing:
```
public int SomeProp => someMethod();
```
C#7 enhanced this support allowing it to be used for getters AND setters. One nice feature of this is with the new "throw expressions" feature which allows us to make some concise syntax. For example, before you had to do.
```
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(Name));
_name = value;
}
}
```
We can now simplify this to:
```
private string _name;
public string Name {
get => _name;
set => _name = value ?? throw new ArgumentNullException(nameof(Name));
}
```
Granted, you could do the throw expression even without making the setter a lambda, but as you can see, for simple things, it makes the syntax very concise.
As with anything, use the syntax that makes the most sense to you and is most readable for the people who will be coding your application. Microsoft has been making a push to add more and more functional programming style features to C# and this is just another example of that. If you find it ugly/confusing/not needed, you can absolutely accomplish everything you need with the existing method. As another example, why do we have `while` and `do while` loops? I can honestly say I've used a `do while` loop maybe 5 times in my career. A `while` loop can do everything a `do while` can just with different syntax. However, there are sometimes where you realize that using a `do while` will make your code more readable, so why not use it if it makes things easier to follow? |
21,467,125 | Recently I updated CakePHP from 2.3.9 to 2.4.4. As far as I remember (I can't test now) `Timehelper::timeAgoInWords` was working well in old CakePHP. But after this update I get locale problem. I change language to English, but time ago still comes in Turkish.
In `core.php` i already set default language to Turkish:
```
Configure::write('Config.language', 'tur');
```
Inside my view file I use this:
```
$d = "2012-05-02 20:17:30"
$myString = $this->Time->timeAgoInWords($d, array('end' => '+10 year'));
```
I get result in Turkish like this:
```
1 yıl, 8 ay, 4 hafta önce
```
I want result like this:
```
1 year, 8 months, 4 weeks ago
```
My session variables like this:
```
[Config] => Array
(
[userAgent] => 35db889a82essb4e57b540d52e8a766d
[time] => 1391121684
[countdown] => 10
[language] => eng
)
```
Although I set my language as English, result cames in Turkish. How can I debug/fix this ?
**Edit:**
I checked for Configure-language values. Results like this:
```
echo Configure::read( 'Config.language' );
result: tur
```
But
```
echo $this->Session->read('Config.language');
result: eng
```
As I noted in the top of my question, I already setted Configure::language inside my `core.php` file. Does `core.php` overrides my session value ?
**Edit2:**
And strange thing is, although Config.language looks like both "tur" and "eng", other parts inside my view file works well. For example this works well:
```
__("string")
```
**Edit3:**
Regarding to this page: <http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html>
I added this:
```
class AppController extends Controller {
public function beforeFilter() {
if ($this->Session->check('Config.language')) {
Configure::write('Config.language', $this->Session->read('Config.language'));
}
}
}
```
After this change config language results like this:
```
echo Configure::read( 'Config.language' );
result: eng
echo $this->Session->read('Config.language');
result: eng
```
But I still see timeAgo result in Turkish..
Last week I migrated to new server, maybe some setting is missing for English or etc ? I can't understand why `timeAgo` doesn't work while `__("string")` works.
**Edit4:**
I even changed `core.php` like this:
```
Configure::write('Config.language', 'eng');
setlocale( LC_TIME, 'en_US.utf8', 'eng', 'en', 'en_US', 'en_UK' );
```
It seems like, in my configuration nothing changes `timeAgoInWords`'s language. I override in every beforeFilter to change Config.language is to english, but still words are Turkish. Note that in my `php.ini` timezone is like this:
```
date.timezone = Europe/Istanbul
```
**Edit5:**
It seems like there is a problem in the translations. I checked for source code of timeago, here is a copy: <https://github.com/cakephp/cakephp/blob/2.4.4/lib/Cake/Utility/CakeTime.php#L738>
It seems like this method uses \_\_d and \_\_dn so I checked the results in my code. "az önce" means "just now" in Turkish.
I'm sure that Config.language is "eng". So:
```
echo __d('cake', 'just now', 'just now'); // results: "az önce"
echo __('just now'); // results: "just now"
echo __('az önce'); // results: "az önce"
$days=12;
echo __dn('cake', '%d day', '%d days', $days, $days); // results: "12 gün"
echo __('gün'); // results: "days"
``` | 2014/01/30 | [
"https://Stackoverflow.com/questions/21467125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429938/"
] | To debug `echo Configure::read( 'Config.language' );` **right before** your `timeAgo` call. If you find it's not "eng" then you are setting the language to English *after* timeAgo was already called.
IF that does not work then you may have to call setlocale as well
I use this for english dates:
`setlocale( LC_TIME, 'en_US.utf8', 'eng', 'en', 'en_US', 'en_UK' );`
And I guess this would the call for Turkish
`setlocale(LC_TIME, 'tr_TR.UTF-8', 'tr_TR', 'tr', 'turkish');`
PS: Looking at the history of the TimeHelper nothing was changed to affect the locale, but may a dependency was changed. |
40,554,124 | I put this into my code:
```
import urllib
print(urllib.request("http://www.google.com"))
input()
```
I get an error saying:
```
Traceback (most recent call last):
File "C:\Users\David\Desktop\Interwebz.py", line 3, in <module>
print(urllib.request("http://www.google.com"))
AttributeError: module 'urllib' has no attribute 'request'
```
I have no idea what's wrong. I checked
```
C:/Users/David/AppData/Local/Programs/Python/Python35-32/Lib/urllib
```
but I see nothing wrong with the files.
Request seems to not exist in urllib. (even though I found a request.py file in the urllib folder) | 2016/11/11 | [
"https://Stackoverflow.com/questions/40554124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6727894/"
] | You don't actually say what you want to do but I assume you want to open a URL and read the response.
```
import urllib.request
with urllib.request.urlopen("http://www.google.com") as f:
print(f.read())
``` |
55,118,768 | Sorry for the double post (2 hours ago), but it's still not working.
I am using a table from Bootstrap 4 for creating a tournament generator. The last part is that I give numbers to the games.
The part at the top is the situation right now. I want the situation from the bottom part, with 1 number in front of it.
[Click for image](https://imgur.com/SyH9Gpk)
This is my code:
```
<table class="table table-bordered">
<thead>
<tr>
<th colspan="2">Quarter-finals</th>
<th colspan="2">Semi-finals</th>
<th colspan="2">Final</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2"><?php echo '<b>' . $player_1 . '</b><hr><b>' . $player_2 . '</b>' ;?></td>
<td colspan="2" class="vs-text">Winners game 1 & 2</td>
<td colspan="2" class="vs-text">Winners game 5 & 6</td>
</tr>
<tr>
<td colspan="2"><?php echo '<b>' . $player_3 . '</b><hr><b>' . $player_4 . '</b>' ;?></td>
<td colspan="2" class="vs-text">Winners game 3 & 4</td>
</tr>
<tr>
<td colspan="2"><?php echo '<b>' . $player_5 . '</b><hr><b>' . $player_6 . '</b>' ;?></td>
</tr>
<tr>
<td colspan="2"><?php echo '<b>' . $player_7 . '</b><hr><b>' . $player_8 . '</b>' ;?></td>
</tr>
</tbody>
</table>
```
And this is the CSS:
```
td, th {border: 1px solid black !important;}
hr {margin-top: 2px !important; margin-bottom: 2px !important;}
.vs-text{text-align: center; line-height: 45px; opacity:0.2;}
td{ padding: 1em; border: 1px solid; text-align: center;}
```
And this is how how the table looks like right now:
[Link to my table](https://imgur.com/a/e1jNU5V)
So, what I want is that there is a small number in a different small cell in front of every game. Anyone a solution? | 2019/03/12 | [
"https://Stackoverflow.com/questions/55118768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7263381/"
] | You could add another `td` and use percentage `widths` to define the widths, for a responsive table.
```css
table {
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr td:first-child {
width: 20%;
text-align: center;
}
tr td:last-child {
width: 80%;
}
hr {
background-color: #c7c7c7;
height: 1px;
border: 0;
width: 100%;
}
```
```html
<table>
<tr>
<td>1</td>
<td>2<hr> 3</td>
</tr>
</table>
```
[**JSFiddle Demo**](https://jsfiddle.net/ktLd136a/1) |
34,035,624 | I have simple .htaccess, which implements front controller pattern (i.e. redirects non static requests to index.php)
Rules for serve for page and news by url.
```
RewriteRule ^([a-z0-9_]+)/$ /index.php?action=page&url=$1
RewriteRule ^([a-z0-9_]+)/$ /index.php?action=news&url=$1
```
If there is no page with passed url (i.e. 404 error raises), I need serve news.
I want assign 2 rules to 1 regexp: if first rule returns 404, try second. I know alternative ways:
1. Use two rules with different regexp, as @Starkeen noted.
2. Deligate login to actual handler (in my case it's php).
May I achieve this behavior with `.htaccess/mod_rewrite`?
**P.S.** I decided don't overcomplicate things and to implement variant 1. | 2015/12/02 | [
"https://Stackoverflow.com/questions/34035624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203805/"
] | you are using same pattern for both rules, that is why the first is being processed and the second being ignored.
change pattern for both rules
```
RewriteRule ^page/([a-z0-9_]+)/?$ /index.php?action=page&url=$1 [NC,L]
RewriteRule ^news/([a-z0-9_]+)/?$ /index.php?action=news&url=$1 [NC,L]
```
Now you can use your urls as :
```
example.com/page/foo
example.com/news/foo
``` |
16,739,280 | I have a problem with the Manifest of my Application.
Clicking on a button on Main activity I want to start an other Activity, so I used this function:
```
public void startDatacenters() {
Intent intent = new Intent(context, Datacenters.class);
activity.startActivity(intent);}
```
The package of Datacenters.class is com.eco4cloud.activities.Datacenters
So my manifest is this:
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eco4cloud"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".activities.Main"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.Datacenters"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.eco4cloud.activities.DATACENTERS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
```
Android gave me this error i don't know why :(
>
> 05-24 18:01:32.622: D/AndroidRuntime(15404): Shutting down VM
> 05-24 18:01:32.622: W/dalvikvm(15404): threadid=1: thread exiting with uncaught exception (group=0x40a441f8)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): FATAL EXCEPTION: main
> 05-24 18:01:32.632: E/AndroidRuntime(15404): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eco4cloud/com.eco4cloud.activities.Main}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.eco4cloud/com.eco4cloud.activities.Datacenters}; have you declared this activity in your AndroidManifest.xml?
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2079)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.ActivityThread.access$600(ActivityThread.java:132)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.os.Handler.dispatchMessage(Handler.java:99)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.os.Looper.loop(Looper.java:137)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.ActivityThread.main(ActivityThread.java:4575)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at java.lang.reflect.Method.invokeNative(Native Method)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at java.lang.reflect.Method.invoke(Method.java:511)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at dalvik.system.NativeStart.main(Native Method)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.eco4cloud/com.eco4cloud.activities.Datacenters}; have you declared this activity in your AndroidManifest.xml?
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1508)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.Activity.startActivityForResult(Activity.java:3190)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.Activity.startActivity(Activity.java:3297)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at com.eco4cloud.controllers.MainController.startDatacenters(MainController.java:46)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at com.eco4cloud.activities.Main.verifyAndSignIn(Main.java:117)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at com.eco4cloud.activities.Main.onCreate(Main.java:53)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.Activity.performCreate(Activity.java:4465)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
> 05-24 18:01:32.632: E/AndroidRuntime(15404): ... 11 more
>
>
>
Someone can help me??
I don't know if the problem is with the package name or others things :( | 2013/05/24 | [
"https://Stackoverflow.com/questions/16739280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305094/"
] | I am not sure what you are trying to do.
But a couple of suggestions to try.
```
package="com.eco4cloud.activities"
// make sure package name is right.
// probably it should be as above.
```
Mention the package name as above
Since you have explicit intent you don't require a intent-filter
```
// use this assuming Datacenters is in package com.eco4cloud.activities
// also assuming package="com.eco4cloud.activities"
<activity
android:name=".Datacenters"
android:label="@string/app_name" >
</activity>
```
If package="com.eco4cloud" try the below
```
<activity
android:name="com.eco4cloud.activities.Datacenters"
android:label="@string/app_name" >
</activity>
```
If you are starting a activity in a non-activity class
```
public void startDatacenters() {
Intent intent = new Intent(context, Datacenters.class);
// assuming context is the activity content
context.startActivity(intent);
//in your case you have activity.startActivity(intent)
// not sure what activity is
}
``` |
6,407,374 | I have the following code in the **web.config** file for my ASP.NET C# app that's hosed on Azure:
```
<!-- Turn on Custom Errors -->
<!-- Switch the mode to RemoteOnly for Retail/Production -->
<!-- Switch the mode to On for to see error pages in the IDE during development -->
<customErrors mode="On" defaultRedirect="ErrorPage.aspx">
<error statusCode="403" redirect="ErrorPage403.aspx"/>
<error statusCode="404" redirect="ErrorPage404.aspx"/>
</customErrors>
```
This works great for errors when I'm hitting my site site natively (<http://ipredikt.com/ErrorPage.aspx>), but I also have a Facebook version of the app in which all of the pages use a different MasterPage and hence a different URL (<http://ipredikt.com/ErrorPageFB.aspx>).
Is it possible to **modify the customError redirect values at runtime** when I'm running in Facebook app mode, as if I had the following settings in web.config:
```
<customErrors mode="On" defaultRedirect="ErrorPageFB.aspx">
<error statusCode="403" redirect="ErrorPage403FB.apx"/>
<error statusCode="404" redirect="ErrorPage404FB.apx"/>
</customErrors>
```
I don't think I can set this at the Application scope since it's individual **pages** in my app that have knowledge of whether they are running in Facebook mode. | 2011/06/20 | [
"https://Stackoverflow.com/questions/6407374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371317/"
] | So here's a brute force solution. I'm using this on the page for the non-Facebook mode 404 errors:
```
protected override void OnInit(System.EventArgs e)
{
// If the user tries, for example, to navigate to" /fb/foo/bar
// then the Request.Url.Query will be as follows after the 404 error: ?aspxerrorpath=/fb/foo/bar
string queryString = Request.RequestContext.HttpContext.Request.Url.Query;
string[] str = queryString.Split('=');
if (str.Length > 0)
{
string[] str2 = str[1].Split('/');
if (str2.Length > 1)
{
string test = str2[1].ToLowerInvariant();
if (test == "fb")
{
string pathAndQuery = Request.RequestContext.HttpContext.Request.Url.PathAndQuery;
string absolutePath = Request.RequestContext.HttpContext.Request.Url.AbsolutePath;
string mungedVirtualPath = pathAndQuery.Replace(absolutePath, "/ErrorPage404FB.aspx");
Response.Redirect(mungedVirtualPath);
}
}
}
base.OnInit(e);
}
```
Hardly ideal, but it works. |
36,060,541 | I am looking to render SQL code on my webpage. I am making tutorials and i would like to display SQL snippets to my visitors. Are there some librairies out there or best practices to do that? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36060541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1162116/"
] | `DeserializeXmlNode()` doesn't really have a way to customize the way it does its JSON to XML conversion. To get the result you want using that method, you will either have to manipulate the JSON before converting it to XML, or manipulate the XML afterwards.
In this case, I think it might be easier to use Json.Net's [LINQ-to-JSON API](http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm) to build the XML directly from the JSON in the shape you want. You can do it like this:
```
var ja = JArray.Parse(jsonResult);
var xml = new XDocument(
new XElement("cars",
ja.Select(c =>
new XElement("car",
new XElement("features",
c["car"]["features"].Select(f =>
new XElement("feature",
new XElement("code", (string)f["code"])
)
)
)
)
)
)
);
Console.WriteLine(xml.ToString());
```
Fiddle: <https://dotnetfiddle.net/fxxQnL> |
28,944,635 | Why does this fail?
The way I read this code is "if either a or b or c equals three, then the statement is true". But apparently JavaScript disagrees. Why?
```
function test() {
var a = 'one';
var b = 'two';
var c = 'three';
return ( ( a || b || c ) === 'three' );
}
```
EDIT: am aware of the fact that i need to evaluate each expression separately, but was looking for a quicker way to write it. any suggestions will be welcome. | 2015/03/09 | [
"https://Stackoverflow.com/questions/28944635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1704673/"
] | Your reading of the code is incorrect. Translated to a different form:
```
if (a) {
return a === "three";
}
if (b) {
return b === "three";
}
if (c) {
return c === "three";
}
```
The subexpression `(a || b || c)` returns the first of `a`, `b`, or `c` that is not "falsy". That's `a`, because its value is `"one"`, so that's the overall value that's compared to `"three"`. |
68 | We have a lot of small CSS and JS files and enabling merging seems to be a good choice.
Many of the CSS and JS files are used on every page (home page, category page, product detail page).
Whenever we saw that a different merged file is loaded again on each page, even the contained CSS must be overlapping.
How can we avoid this and reuse more data? | 2013/01/23 | [
"https://magento.stackexchange.com/questions/68",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/81/"
] | **Short answer:** never enable Magento's JS/CSS merging function. Overall it's worse for performance throughout the lifecycle of a typical checkout than sending each asset individually.
**Long answer:** You should only be serving one CSS file to users. Multiple files block rendering until all CSS is downloaded. Unless you are serving a huge amount of CSS it's advantageous to send it all at once, then the browser has it cached. Using a pre-processor like Sass or LESS can bring this step into your build process instead of letting Magento do it inefficiently.
For JS, ideally you should not be combining these server-side. Client-side script loaders like AMD/RequireJS are better choices and help manage dependencies, which Magento's Layout XML does not. In the real world though Magento drops in scripts at several points in the checkout flow. You're still better off taking the initial page load hit of multiple requests and having separate but cached assets afterwards.
The Fooman Speedster Advanced extension is your best bet for intelligently combining assets without duplication (today).
You are somewhat limited by the Magento 1.x architecture which starts off with a heap of poor practices for frontend performance. It's not realistic to change the course of that ship. Contribute to Magento 2. |
93,186 | I have two custom objects, Question\_\_c and Response\_\_c. There is a lookup field named Related\_Question\_\_c on the Response\_\_c object to relate the two. In my VF controller I have two Lists, one for each object. My objective is to find all records in the Question List that do not have a match in the Response List (ie questions that haven't been answered yet).
I believe I need to use a map for this but am unsure of exactly how to accomplish this. Any advice would be appreciated. Thanks in advance.
Here's what I have so far to build the two Lists:
```
List <Question__c> questions = [select Id, Name From Question__c];
List <Response__c> questionResponses = [select Id, Name, Related_Question__c From Response__c Where Related_Question__c IN: questions};
``` | 2015/09/21 | [
"https://salesforce.stackexchange.com/questions/93186",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/16511/"
] | Can you try something like this ?
```
List<Id> l = new List<Id>();
Map<Id,Response__c> qr = new Map<Id,Response__c>();
for(Response__c r : questionResponses)
{
qr.put(r.Related_Question__r.Id,r);
}
for(Question__c q : questions)
{
if(qr.get(q.Id) == null)
{
l.add(q.Id);
}
}
System.debug('~~~ Non matching Ids '+ l);
``` |
8,017,858 | error I get when I try to run this simple script
```
RMAN> CMDFILE c:\oraclexe\app\oracle\admin\xe\scripts\rman1.rcv
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00558: error encountered while parsing input commands
RMAN-01009: syntax error: found "cmdfile": expecting one of: "allocate, alter, backup, beginline, blockrecover, catalog, change, connect, copy, convert, create, crosscheck, configure, duplicate, debug, delete, drop, exit, endinline, flashback, host, {, library, list, mount, open, print, quit, recover, register, release, replace, report, r
enormalize, reset, restore, resync, rman, run, rpctest, set, setlimit, sql, switch, spool, startup, shutdown, send, show, test, transport, upgrade, unregister, validate"
RMAN-01007: at line 1 column 1 file: standard input
```
The script is a simple one
```
connect target /;
backup database plus archivelog delete input;
```
Any ideas as to what I am doing wrong? | 2011/11/05 | [
"https://Stackoverflow.com/questions/8017858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008100/"
] | Try this:
```
RMAN> @c:\oraclexe\app\oracle\admin\xe\scripts\rman1.rcv
```
[Documented here.](http://download.oracle.com/docs/cd/B19306_01/backup.102/b14193/toc.htm#i773595) |
59,258,740 | Does the Python formatting tool Black have an option for undoing the formatting changes it made after it's been run? Or does it assume I'm using source control and making my own backups? This is as of December 2019 and Black version 19.3b0. | 2019/12/10 | [
"https://Stackoverflow.com/questions/59258740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1893164/"
] | No it does not. It does nothing more, but reformat the files it has been passed. It's simply a well behaved Unix tool and it expects you to handle your own version control.
Its `--diff` option is the best you can get:
>
> `--diff`
>
>
> Don't write the files back, just output a diff for each file on stdout.
>
>
>
Source: <https://github.com/psf/black#command-line-options> |
56,444,733 | I have a dropdown menu in my website which I want to be exactly in line with the "Resources" tab (which opens up the dropdown menu when I hover over it). I have tried adding margins to the `ul` inside the "Resources" `li`, but it isn't changing the styling the way I want it to. Am I entering the CSS in the wrong selector or even using the wrong properties?
Here is my HTML and CSS:
```css
* {
margin: 0;
padding: 0;
}
body {
background-color: orange;
}
nav {
width: 100%;
height: 60px;
background-color: black;
display: flex;
}
nav p {
text-align: center;
font-family: arial;
color: white;
font-size: 24px;
line-height: 55px;
float: left;
padding: 0px 20px;
flex: 1 0 auto;
}
nav ul {
position: absolute;
right: 0;
}
nav ul li {
float: left;
list-style: none;
position: relative; /* we can add absolute position in subcategories */
padding-right: 1em;
}
nav ul li a {
display: block;
font-family: arial;
color: white;
font-size: 14px;
padding: 22px 14px;
text-decoration: none;
}
nav ul li ul {
display: none;
position: absolute;
background-color: black;
padding: 5px; /* Spacing so that hover color does not take up entire chunk */
border-radius: 0px 0px 4px 4px;
}
nav ul li:hover ul {
/* This means when li is hovered, we want the unordered list inside list item to do something. */
display: block;
}
nav ul li ul li{
width: 130px; /* increases width so that all text can be fit */
border-radius: 4px;
}
nav ul li ul li a:hover {
background-color: #ADD8E6;
}
```
```html
<nav>
<p> The Novel Column </p>
<ul>
<li> <a href="#"> Resources </a>
<ul>
<li> <a href="#"> Book Reviews </a> </li>
<li> <a href="#"> Quotes and Principles </a> </li>
<li> <a href="#"> Community Aid </a> </li>
</ul>
</li>
<li> <a href="#"> About Us </a> </li>
</ul>
</nav>
``` | 2019/06/04 | [
"https://Stackoverflow.com/questions/56444733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10642528/"
] | Add
```
nav ul li ul {
left: 50%;
right: auto;
transform: translateX(-50%);
}
```
`left: 50%` positions the left edge of the dropdown in the center of its parent. Then `translateX(-50%)` moves it to the left by half of the dropdown's width. Lastly `right: auto` ensures that the dropdown's width doesn't get messed up.
Demo:
<https://jsfiddle.net/7Lzb8u6t/> |
5,030,150 | I have an application that contains a main Activity, which has a very simple screen with all application setup options and a few user selections. The main screen buttons start other Activities.
(1) I'm now implementing a bluetooth scanner into the application and i would like to be able to edit settings and establish a bluetooth connection on the main Activity and pass that connection (via Bundle or Parcelable perhaps?) to the other Activities.
I looked up Bundle as a way to pass the connection, but it appears to only accept primitive and basic types as values. I noticed Intent.putExtra(String, Parcelable) was available, but Parcel sort of confused me. What would be the best way to implement this, or is it even possible?
some relevant code:
```
//subclass definitions for the Runnables which start the applications in their own threads
private final Handler smsHandler = new Handler();
private final Handler smsOutHandler = new Handler();
private final Runnable smsIntentRunnable = new Runnable() {
public void run() {
Intent smsIntent = new Intent(smsMobile.this, smsActivity.class);
startActivity(smsIntent);
}
};
private final Runnable smsOutIntentRunnable = new Runnable() {
public void run() {
Intent smsOutIntent = new Intent(smsMobile.this, smsOutActivity.class);
startActivity(smsOutIntent);
}
};
//button listeners located in onCreate(), which start the Activities
newTicket.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
smsHandler.post(smsIntentRunnable);
}
});
updateTicket.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
smsOutHandler.post(smsOutIntentRunnable);
}
});
```
(2) Could I also pass a database connection? I understand that SQLiteOpenHelper must be subclassed, which could complicate IPC, but thought it might still be possible somehow? | 2011/02/17 | [
"https://Stackoverflow.com/questions/5030150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329993/"
] | There are several options to [share data between activities and services](http://developer.android.com/guide/appendix/faq/framework.html#3).
**Update:** to expand on your situation a little bit:
You only need IPC/Parcelable when code runs in separate processes. You have to specify in manifest to make code run in separate processes: <http://developer.android.com/guide/topics/fundamentals.html#procthread>
1. In your case I asume you activities run in the same process, so you can simply use custom Application class to store/share this data. Make sure it's `synchronized` if you access it from different threads. Alternatively you can use any other approach listed in the first link.
2. You can of course pass database connection within same process, as this is one java application. But you can not pass it via IPC between processes, because all [classes need to implement Parcelable in order to pass via IPC](http://developer.android.com/guide/developing/tools/aidl.html#parcelable) and, AFAIK, SQLiteDatabase does not implement parcelable (classes talking to native functions usually don't). |
21,029,401 | I'm likely overlooking something pretty core/obvious, but how can I create a task that will always be executed for every task/target?
I can do something like:
```
task someTask << {
println "I sometimes run"
}
println "I always run"
```
But it would be much more desirable to have the always running part in a task.
The closest I've come is:
```
task someTask << {
println "I sometimes run"
}
println "I always run"
void helloThing() {
println "I always run too. Hello?"
}
helloThing()
```
So, using a method is an 'ok' solution, but I was hoping there'd be a way to specifically designate/re-use a task.
Hopefully somebody has a way to do this. :) | 2014/01/09 | [
"https://Stackoverflow.com/questions/21029401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1161429/"
] | Assuming the goal is to print system information, you could either just always print the information in the configuration phase (outside a task declaration), and have a dummy task `systemStatus` that does nothing (because the information is printed anyway). Or you could implement it as a regular task, and make sure the task always gets run by adding `":systemStatus"` as the first item of `gradle.startParameter.taskNames` (a list of strings), which simulates someone always typing `gradle :systemStatus ...`. Or you could leverage a hook such as `gradle.projectsLoaded { ... }` to print the information there. |
14,960,947 | Is there a way to access a control's value/text using the base class?
Looking at [TextBox](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox%28v=vs.100%29.aspx) and [HiddenField](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield%28v=vs.100%29.aspx), System.Web.UI.Control is the most specific base class they share. Seems like a good candidate, but I don't see an obvious way to access the text/value.
I do see that both class definitions use the *ControlValuePropertyAttribute* to identify the property that holds their text/value... e.g. HiddenField is set to "Value", TextBox is set to "Text". Not sure how to use that info to retrieve the data, though.
**Background**
I have an extension method that takes the text of some web control (e.g., a TextBox) and converts it to a given type:
```vb
<Extension()> _
Public Function GetTextValue(Of resultType)(ByVal textControl As ITextControl, ByVal defaultValue As resultType) As resultType
Return ConvertValue(Of resultType)(textControl .Text, defaultValue)
End Function
```
Now, I need the value of a HiddenField (which does not implement the ITextControl interface). It would be easy enough to overload the function, but it would be awesome to just handle the base class and not have to deal with writing overloads anymore.
**Edit - additional info**
Here is an example of how the extension method is used
```vb
Dim myThing as Decimal = tbSomeWebControl.GetTextValue(Of Decimal)(0) ' Converts the textbox data to a decimal
Dim yourThang as Date = hdnSomeSecret.GetTextValue(Of Date)(Date.MinValue) ' Converts the hiddenfield data to a Date
```
Currently, this requires two overloads because data is accessed using the Value property in hiddenfields and the Text property in textboxes.
What's wrong with overloads? Nothing, except i'm writing nearly the same code over and over (just modifying the 1st parameter of the definition and the 1st argument of its call). | 2013/02/19 | [
"https://Stackoverflow.com/questions/14960947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54804/"
] | You cant use object-oriented approach to get the value, because they don't have common ancestor in inheritance tree from which you can fetch data. Solutions are so inelegant that you should just pass `WebControl` and check type dynamically.
Pardon my C#:
(note that this is notepad code, I didn't run any of it so you may need some tweaks)
---
**Solution 1: Get data directly from Request**
Downside: Not very ASP.NET-ish. Does the job however.
```
public string GetTextValue<ResultType>(WebControl control, ResultType defaultValue)
{
// If you only wish data from form, and not questy string or cookies
// use Request.Form[control.UniqueId] instead
string value = Request[control.UniqueId];
return ConvertValue<ResultType>(value, defaultValue);
}
```
---
**Solution 2: Check type dynamically**
Downside: you have to provide handling for multiple control types
```
public string GetTextValue<ResultType>(WebControl control, ResultType defaultValue)
{
if (control is ITextControl)
return ConvertValue<ResultType>((ITextControl)control.Text, defaultValue);
else if (control is HiddenField)
return ConvertValue<ResultType>((HiddenField)control.Value, defaultValue);
else if (anothertype)
return ConvertValue<ResultType>(another_retrieval_method, defaultValue);
}
```
---
**Solution 3: Use reflection**
Downside: reflection can be tricky, doesn't look elegant, and can be slow on many invocations
```
public string GetTextValue<ResultType>(WebControl control, ResultType defaultValue)
{
// Get actual control type
Type controlType = control.GetType();
// Get the attribute which gives away value property
Attribute attr = controlType.GetCustomAttribute<ControlValuePropertyAttribute>();
if (attr == null)
throw new InvalidOperationException("Control must be decorated with ControlValuePropertyAttribute");
ControlValuePropertyAttribute valueAttr = (ControlValuePropertyAttribute)attr;
// Get property name holding the value
string propertyName = valueAttr.Name;
// Get PropertyInfo describing the property
PropertyInfo propertyInfo = controlType.GetProperty(propertyName);
// Get actual value from the control object
object val = propertyInfo.GetValue(control);
if (val == null)
val = "";
return ConvertValue<ResultType>(val, defaultValue);
}
``` |
35,518,053 | I am trying to make my program so that an integer value entered in a JTextfield can be stored into a variable. Then, when a JButton is clicked, this variable can tell a JSlider to move it's head to that of the integer value stored in the variable. My class name is Camera.Java
Code is showing no errors, however if I click my JButton, nothing happens, instead I see this error in the console:
```
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Camera.main(Camera.java:67)
```
My code:
```
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
public class Camera {
static JButton addtolist;
static Scanner input = new Scanner(System.in);
static JSlider cam = new JSlider();
static JTextField enterval = new JTextField();
static int x ;
public static void main (String args[]){
JFrame myFrame = new JFrame ("Matthew Damon on Mars");
myFrame.setSize(300, 600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel userinp = new JLabel("Enter input: ");
cam = new JSlider(0, 15, 0);
cam.setPaintLabels(true);
enterval.setPreferredSize(new Dimension(100,80));
addtolist = new JButton("Enter");
addtolist.setPreferredSize(new Dimension(50,20));
JTextField enterval1 = new JTextField();
panel.add(addtolist);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(0, new JLabel("0"));
table.put(1, new JLabel("1"));
table.put(2, new JLabel("2"));
table.put(3, new JLabel("3"));
table.put(4, new JLabel("4"));
table.put(5, new JLabel("5"));
table.put(6, new JLabel("6"));
table.put(7, new JLabel("7"));
table.put(8, new JLabel("8"));
table.put(9, new JLabel("9"));
table.put(10, new JLabel("A"));
table.put(11, new JLabel("B"));
table.put(12, new JLabel("C"));
table.put(13, new JLabel("D"));
table.put(14, new JLabel("E"));
table.put(15, new JLabel("F"));
cam.setLabelTable(table);
myFrame.add(cam, BorderLayout.SOUTH);
myFrame.add(userinp, BorderLayout.NORTH);
myFrame.add(enterval1, BorderLayout.NORTH);
myFrame.add(panel, BorderLayout.CENTER);
myFrame.setVisible(true);
buttonAction();
}
public static void buttonAction() {
addtolist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
});
}
}
``` | 2016/02/20 | [
"https://Stackoverflow.com/questions/35518053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4490215/"
] | Your setting `x` on program creation before the user has had any chance to change its value. Get the text value from within the `actionPerformed` method which should be after the user has already selected a value, parse it into a number and set the slider with that value.
```
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
```
Then get rid of all that static nonsense. The only method that should be static here is main, and it should do nothing but create an instance and set it visible.
Note that better than using a `JTextField`, use a `JSpinner` or a `JFormattedTextField` or if you're really stuck, a `DocumentFilter` to limit what the user can enter |
53,990,888 | I have the following query:
```
SELECT table_1.id
FROM
table_1
LEFT JOIN table_2 ON (table_1.id = table_2.id)
WHERE
table_1.col_condition_1 = 0
AND table_1.col_condition_2 NOT IN (3, 4)
AND (table_2.id is NULL OR table_1.date_col > table_2.date_col)
LIMIT 5000;
```
And I have the following keys and indexes:
* table\_1.id primary key.
* index on table\_1.col\_condition\_1
* index on table\_1.col\_condition\_2
* composite index on table\_1.col\_condition\_1 and table\_1.col\_condition\_2
The correct indexes are getting picked up. Query explain:
```
+--+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------------+---------+------------+----------+-----------------------+--+
| | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | |
+--+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------------+---------+------------+----------+-----------------------+--+
| | 1 | SIMPLE | table_1 | range | "the composite index", col_condition_1 index ,col_condition_2 index | "the composite index" | 7 | | 11819433 | Using index condition | |
| | 1 | SIMPLE | table_2 | eq_ref | PRIMARY,id_UNIQUE | PRIMARY | 8 | table_1.id | 1 | Using where | |
+--+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------------+---------+------------+----------+-----------------------+--+
```
table\_1 has ~60 MM records, and table\_2 has ~4 MM records.
**The query takes 60 seconds to return a result.**
What's interesting is that:
```
SELECT table_1.id
FROM
table_1
LEFT JOIN table_2 ON (table_1.id = table_2.id)
WHERE
table_1.col_condition_1 = 0
AND table_1.col_condition_2 NOT IN (3, 4)
LIMIT 5000;
```
takes 145 ms to return a result and has the same indexes picked as the first query.
```
SELECT table_1.id
FROM
table_1
LEFT JOIN table_2 ON (table_1.id = table_2.id)
WHERE
table_1.col_condition_1 = 0
AND (table_2.id is NULL OR table_1.date_col > table_2.date_col)
LIMIT 5000;
```
takes 174 ms to return a result.
Query explain:
```
+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------+---------+------------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------+---------+------------+----------+-------------+
| 1 | SIMPLE | table_1 | ref | "the composite index", col_condition_1 index ,col_condition_2 index | col_condition_1 | 2 | const | 30381842 | NULL |
| 1 | SIMPLE | table_2 | eq_ref | PRIMARY,id_UNIQUE | PRIMARY | 8 | table_1.id | 1 | Using where |
+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------+---------+------------+----------+-------------+
```
And
```
SELECT table_1.id
FROM
table_1
LEFT JOIN table_2 ON (table_1.id = table_2.id)
WHERE
table_1.col_condition_2 NOT IN (3, 4)
AND (table_2.id is NULL OR table_1.date_col > table_2.date_col)
LIMIT 5000;
```
takes about 1 second to return a result.
Query explain:
```
+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------+---------+------------+----------+-----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------+---------+------------+----------+-----------------------+
| 1 | SIMPLE | table_1 | range | "the composite index", col_condition_1 index ,col_condition_2 index | col_condition_2 | 5 | | 36254294 | Using index condition |
| 1 | SIMPLE | table_2 | eq_ref | PRIMARY,id_UNIQUE | PRIMARY | 8 | table_1.id | 1 | Using where |
+----+-------------+---------+--------+---------------------------------------------------------------------+-----------------+---------+------------+----------+-----------------------+
```
Also when I use every where condition separately, the query returns a result in ~100 ms.
My question is why the query takes a significant amount of time (60 seconds) to return a result when using the three where conditions together even though it looks like the correct indexes are getting used and executing the query with any two of the three where conditions also returns a result in much less time.
Also, is there a way to optimize this query?
Thank you.
**EDIT:**
create tables:
table\_1:
```
CREATE TABLE `table_1` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`col_condition_1` tinyint(1) DEFAULT '0',
`col_condition_2` int(11) DEFAULT NULL,
`date_col` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `compositeidx` (`col_condition_1`,`col_condition_2`),
KEY `col_condition_1_idx` (`col_condition_1`),
KEY `col_condition_2_idx` (`col_condition_2`)
) ENGINE=InnoDB AUTO_INCREMENT=68272192 DEFAULT CHARSET=utf8
```
table\_2:
```
CREATE TABLE `table_2` (
`id` bigint(20) NOT NULL,
`date_col` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
``` | 2018/12/31 | [
"https://Stackoverflow.com/questions/53990888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123707/"
] | You could use pattern matching.
```
val myChars = "[bgjkqtz]".r //compiled once
def predicate(c :Char) :Boolean = c match {
case myChars() => true
case _ => false
}
```
But I don't know how performant it would be since this would also involve the underlying calls to `unapplySeq()` and `isEmpty()`. |
66,423,223 | I have a function which is f=x^4-8x^3+24^2-32x.
I need to find the turning points (i.e. the maximum or minimum of the curve) using the inbuilt command 'fsolve'.
Now, I know that the turning point is x=2 because I worked it out manually by finding the first derivative of f and making it equal to zero, but when I tried doing it on matlab using fsolve I didn't manage it. I did this:
```
x=sym('x');
f=x^4-8*x^3+24*x^2-32*x;
f1=diff(f,x,1)
```
and I don't know how to continue from there (my approach is most probably wrong as I've been viewing the problem from a mathematical point of view)
Anyone know how I can write the code please? | 2021/03/01 | [
"https://Stackoverflow.com/questions/66423223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15307405/"
] | You are using the *same* formula to calculate both the `lost_happiness` *and* new `happiness` values:
```cpp
int lost_happiness = happiness - (happiness%100); // Notice the similarity
happiness = happiness - (happiness%100); // in the two RHS codes?
```
This is incorrect, and the former should just be `happiness % 100`.
```cpp
if (happiness <= 100) {
happiness += 20;
cout<< "The festival goes well";
if (happiness > 100) {
int lost_happiness = happiness % 100; // DON'T subtract this from total
happiness -= lost_happiness; // No need to recalculate the "%"
cout << ", however, happiness has reached the cap of 100. The amount lost is " << lost_happiness;
}
}
```
Note that I have also used some techniques to make your code rather more succinct; please feel free to ask for further details and/or clarification. |
7,594,163 | have a look at this code:
```
#include<stdio.h>
#include <unistd.h>
int main()
{
int pipefd[2],n;
char buf[100];
if(pipe(pipefd)<0)
printf("Pipe error");
printf("\nRead fd:%d write fd:%d\n",pipefd[0],pipefd[1]);
if(write(pipefd[1],"Hello Dude!\n",12)!=12)
printf("Write error");
if((n=read(pipefd[0],buf,sizeof(buf)))<=0)
printf("Read error");
write(1,buf,n);
return 0;
}
```
I expect the printf to print Read fd and write fd before Hello Dude is read from the pipe. But thats not the case... see [here](http://www.ideone.com/XuF6u). When i tried the same program in our college computer lab my output was
```
Read fd:3 write fd:4
Hello Dude!
```
also few of our friends observed that, changing the printf statement to contain more number of `\n` characters changed the output order... for example..`printf("\nRead fd:%d\n write fd:%d\n",pipefd[0],pipefd[1]);` meant that Read fd is printed then the message `Hello Dude!` then the write fd is printed. What is this behaviour??
Note: Out lab uses a linux server on which we run terminals, i don't remember the compiler version though. | 2011/09/29 | [
"https://Stackoverflow.com/questions/7594163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522058/"
] | It's because `printf` to the standard output *stream* is buffered but `write` to the standard output *file descriptor* is not.
That means the behaviour can change based on what sort of buffering you have. In C, standard output is *line* buffered if it can be determined to be connected to an interactive device. Otherwise it's *fully* buffered (see [here](https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-string/4201325#4201325) for a treatise on why this is so).
Line buffered means it will flush to the file descriptor when it sees a newline. Fully buffered means it will only flush when the buffer fills (for example, 4K worth of data), or when the stream is closed (or when you `fflush`).
When you run it interactively, the flush happens before the `write` because `printf` encounters the `\n` and flushes automatically.
However, when you run it otherwise (such as by redirecting output to a file or in an online compiler/executor where it would probably do the very same thing to capture data for presentation), the flush happens *after* the `write` (because `printf` is not flushing after every line).
In fact, you don't need all that pipe stuff in there to see this in action, as per the following program:
```
#include <stdio.h>
#include <unistd.h>
int main (void) {
printf ("Hello\n");
write (1, "Goodbye\n", 8);
return 0;
}
```
When I execute `myprog ; echo === ; myprog >myprog.out ; cat myprog.out`, I get:
```
Hello
Goodbye
===
Goodbye
Hello
```
and you can see the difference that the different types of buffering makes.
If you want line buffering regardless of redirection, you can try:
```
setvbuf (stdin, NULL, _IOLBF, BUFSIZ);
```
early on in your program - it's implementation defined whether an implementation supports this so it may have no effect but I've not seen many where it doesn't work. |
100,546 | Tt the time before installing i had 322 MB free storage and was about to get Dead Trigger 2 but I didn't have enough space so it stopped and now I have only 77 MB free? Did it keep half the app on my phone still? | 2015/02/22 | [
"https://android.stackexchange.com/questions/100546",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/95400/"
] | It helped me to uncheck and check again the option "Back Up all" on the phone. It sort of restarts the process of backing up. But now they aggressively forced everyone to switch to Google Photos, so this will work differently. |
51,963,396 | What I Want, Summarized:
========================
I have a commit, such as `HEAD` or `111abc111`, and I want an elegant way to print all of the modified files and *only* the modified files along with their SHA-1 hashes. How can I do that?
Below is an idea using `git-cat-file` that *almost* works, but it either lists all files (including files that didn't change) or you must use it in batch mode. Using it in batch mode initially seems promising, but I cannot make it work. See below for things I have tried with `git-ls-tree` and so on.
For a note about my priorities, see below in this question, or see the answer I wrote myself (which I am not going to accept, but maybe you can refactor it).
Concrete Example:
=================
**Setting up the example:**
For background, let's see what my Git working tree looks like:
```
$ ls
alice.txt
bob.c
carol.h
main.c
$ git status -s
# Nothing prints, the working copy is clean and untouched.
```
I will now change *only* two files:
```
$ echo "Add one line." >> bob.c
$ echo "Add one line." >> carol.h
$ git add . # Add (stage) both changed files.
$ git status -s
M bob.c
M carol.h
$ git commit -m "Two changed files."
[master 111abc111] Two changed files.
2 files changed, 2 insertions(+), 0 deletions(-)
```
---
**This does ALMOST what I want:**
```
$ git cat-file -p 111abc111:./
100644 blob 99c2e88ad312f1eac63afc908f64c370fac9d947 .gitignore
100644 blob 607f8ea764981fb3f92a8d91abc2b154d99bc39c alice.txt
100755 blob 5a297bd6931c1a70abbcab919815324258c08b0f bob.c
100644 blob c6c2dfd18d26c1cf71b21e9d4c0892157dd6ec33 carol.h
100755 blob d0802cd238a3e83f186bc5c24be7e23dfc69205f main.c
```
The problem with the command above is that it lists everything at the specified path, which was `./` in this example, which is the current directory. It lists **every file**, not only the modified files. I only want it to show `bob.c` and `carol.h`.
A second problem is that using `111abc111:./` to specify the tree-ish object will only show files (blobs) in that one directory, it will not show files in subdirectories. Subdirectories will show up like this:
```
040000 tree b98f38763b689e8197c6129726d41169fceeaaa0 subdir
```
**Possible Ideas:**
I just deleted a few paragraphs with some things that I have tried.
I suspect the key will be using `git-diff` to make a list of "git objects" (including blobs) that have changed in the specified commit, and then pass that list of "git objects" in some format to `git-cat-file`. So a magic command like this might work:
```
$ git diff 111abc111^ 111abc111 --magic-options-go-here | git cat-file --batch-check='%(objectname) %(objectsize)'
```
The key is to find the value for `--magic-options-go-here`. I am also not convinced `git-cat-file` is what I want on the right side of the pipe character, I might want something else.
Thank you.
Edit: My Priorities
-------------------
I am more interested in "git objects", the entities stored within Git and identified by SHA-1 hashes, such as trees, blobs, commits, and maybe other things I have not thought of such as tags. I am far less interested in filenames and how things actually look in the filesystem if you do a checkout of the commit.
I want to see the SHA-1 hashes so that I can see "oh, this merge commit is pointing to the tree from *way over there* in a different branch." With branching and merging and rebasing in a large repository, each commit object contains a huge number of trees and blobs that have not changed and are just pointers (references), and the things they refer to may get very far away in a conceptual sense. This can become apparent when you change just one line, do a git-commit, then do a git-push and the amount of data pushed is 50 MiB. Internally, Git just had to dereference a ton of pointers and make new deltas and packfiles and stuff. Things that feel like small changes in the working directory (the filesystem) may actually represent a lot of data in the Git repository binary format. | 2018/08/22 | [
"https://Stackoverflow.com/questions/51963396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1286417/"
] | simple like that:
```
git show --stat --name-only 'YOUR_COMMIT_HASH'
``` |
11,763,376 | In linux, netstat command tells us information of active sockets in system.
I understand that `netstat` uses `/proc/net/tcp` to acquire the system network information.
Since `netstat` man page says that netstat is obsolete, so we should use 'ss'.
```
NOTE
This program is obsolete. Replacement for netstat is ss. Replacement
for netstat -r is ip route. Replacement for netstat -i is ip -s link.
Replacement for netstat -g is ip maddr.
```
I have discovered that `ss` performs similar functionality but it does not use
`/proc/net/tcp` to acquire system network information.
Now I am curious how `ss` gets system network socket information? | 2012/08/01 | [
"https://Stackoverflow.com/questions/11763376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1528889/"
] | It gets them from kernel space directly using [Netlink](http://en.wikipedia.org/wiki/Netlink) which uses the classic [sockets](http://www.linuxjournal.com/article/7356) API. |
4,813,282 | My question is pretty simple, was looking for a simpler answer, Why is C in CAP theorem not same as C in ACID?
Read [this](http://news.ycombinator.com/item?id=1192833) HN thread.
**Update**
[A Hitchhiker's Guide to NOSQL v1.0](http://www.slideshare.net/ksankar/nosql-4559402), slide 71 says: C in CAP = A+C (Atomic Consistency) | 2011/01/27 | [
"https://Stackoverflow.com/questions/4813282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231917/"
] | Both C's stand for consistency, but the notion of consistency in CAP means that "all nodes see the same data at the same time" and the notion of consistency in ACID means that "any transaction the database performs will take it from one consistent state to another". (From Wikipedia.) |
26,487,501 | I trying to compile program (I have previously ported it from `Cg` language). Fragment shader is
```
precision mediump float;
precision mediump int;
uniform float time;
uniform float aspect;
uniform sampler2D sampler_main;
varying vec4 v_texCoord;
void main()
{
vec3 ret;
vec2 uv = v_texCoord.xy;
float rad=sqrt((uv.x-0.5)*(uv.x-0.5)*4.0+(uv.y-0.5)*(uv.y-0.5)*4.0)*.7071067;
float ang=atan(((uv.y-0.5)*2.0),((uv.x-0.5)*2.0));
vec2 uv1 = (uv-0.5)*aspect.xy;
float rad1 = .1/(length(uv1) + .1)) ;
vec2 uv2 = vec2 (ang/3.14, rad1);
uv2.y = uv2.y +0.1*time;
uv2.x = uv2.x +.0*time;
vec2 uv3 = vec2 (ang/3.14, rad1*1.5);
uv3.y = uv3.y + 0.08*time ;
uv3.x = uv3.x + time/32;
vec3 crisp = 2*texture2D(sampler_main, uv2).xyz;
vec3 lay1 = vec3 (0,0,1)*uv.y*pow(1-rad,8);
crisp = 3*crisp * pow(rad,1);
float mask = saturate(1-4*rad);
ret = crisp + lay1*mask + mask * texture2D(sampler_main, uv).xyz;
gl_FragColor.xyz = ret;
gl_FragColor.w = 1.0;
}
```
I got error on line
```
uv3.x = uv3.x + time/32;
```
When I change it to
```
uv3.x = uv3.x + time/32.0;
```
Problem is solved, but I don't understand the root of the problem.
The same problem for the line
```
float mask = saturate(1-4*rad); => float mask = saturate(1.0-4.0*rad);
vec3 crisp = 2*texture2D(sampler_main, uv2).xyz; => vec3 crisp = 2.0*texture2D(sampler_main, uv2).xyz;
vec3 lay1 = vec3 (0,0,1)*uv.y*pow(1-rad,8); => vec3 lay1 = vec3 (0,0,1)*uv.y*pow(1.0-rad,8.0);
crisp = 3*crisp * pow(rad,1); => crisp = 3.0*crisp * pow(rad,1.0);
```
Could someone explain:
1. Why I cannot mix float and int constant in the same expression?
2. Is there any workaround that allow me to mix float and int constant? | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902217/"
] | Implicit casts are not allowed in early GLSL. So try an explicit cast:
```
uv3.x = uv3.x + time/float(32);
```
The [GLSL 1.1 Spec](https://www.opengl.org/registry/doc/GLSLangSpec.Full.1.10.59.pdf) says in Chapter 4 (page 16):
>
> The OpenGL Shading Language is type safe. There are no implicit conversions between types
>
>
>
Recent GLSL allows implicit type casts. The [GLSL 4.4 Spec](https://www.opengl.org/registry/doc/GLSLangSpec.4.40.diff.pdf) says in Chapter 4 (page 25):
>
> The OpenGL Shading Language is type safe. There are some implicit conversions between types.
> Exactly how and when this can occur is described in section 4.1.10 “Implicit Conversions” and as
> referenced by other sections in this specification.
>
>
>
And later on starting at page 39 there is a list of possible implicit conversions. |
20,578,987 | Use case: I've got a long string that is divided by linebreaks, and each line has two element separated by a comma.
Ideally, this should work
```
[(x, y) for line in lines.split() for x, y in line.split(',')]
```
But it doesn't, and yields a ValueError the same as below. So I tried to decompose the problem to figure out what's going on here
```
lines = \
"""a,b
c,d
e,f
g,h"""
lines = [line for line in lines.split()]
print(lines)
print(len(lines))
print([len(line) for line in lines])
print(all(',' in line for line in lines))
[(x, y) for l in lines for x,y in l.split(',')]
```
Yields:
```
/usr/bin/python3m /home/alex/PycharmProjects/test.py
['a,b', 'c,d', 'e,f', 'g,h']
4
[3, 3, 3, 3]
True
Traceback (most recent call last):
File "/home/alex/PycharmProjects/test.py", line 74, in <module>
...
File "/home/alex/PycharmProjects/test.py", line 63, in <listcomp>
[(x, y) for l in sines for x,y in l.split(',')]
ValueError: need more than 1 value to unpack
```
Yet if I replace the list comprehension in the last line with a classic for loop:
```
for line in lines:
x, y = line.split(',')
```
It executes successfully:
```
['a,b', 'c,d', 'e,f', 'g,h']
4
True
[3, 3, 3, 3]
a b
c d
e f
g h
```
This is driving me absolutely insane. If I further decompose it, I find that list, set, and generator comprehensions shit themselves trying to do this:
```
[(x,y) for x, y in "a,b".split(",")]
```
Anyone have an idea about why this occurs? | 2013/12/14 | [
"https://Stackoverflow.com/questions/20578987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2399953/"
] | This code:
```
for x, y in "a,b".split(",")
```
is looking for *two-item* iterables that are *inside* the iterable (list) returned by `"a,b".split(",")`.
However, all it finds is `'a'` and `'b'`:
```
>>> "a,b".split(",")
['a', 'b']
>>>
```
Since both of these are only *one-item* iterables (strings with one character), the code breaks.
---
Considering the above, watch what happens when an extra character is added to each side of the comma:
```
>>> "ax,by".split(",")
['ax', 'by']
>>> [(x,y) for x, y in "ax,by".split(",")]
[('a', 'x'), ('b', 'y')]
>>>
```
As you can see, the code now works.
This is because `"ax,by".split(",")` returns an iterable (list) that contains two-item iterables (strings with two characters). Furthermore, this is exactly what `for x, y in` is looking for.
---
However, you could also place the last part in a tuple:
```
>>> ("a,b".split(","),)
(['a', 'b'],)
>>> [(x,y) for x, y in ("a,b".split(","),)]
[('a', 'b')]
>>>
```
`("a,b".split(","),)` returns an iterable (tuple) that contains two-item iterables (a list with two strings). Once again, this is exactly what `for x, y in` is looking for, so the code works.
---
With all this in mind, the below should fix your problem:
```
[(x, y) for line in lines.split() for x, y in (line.split(','),)]
``` |
110,851 | How do I prevent exposing MySQL usernames and passwords in PHP code when establishing a connection? | 2016/01/16 | [
"https://security.stackexchange.com/questions/110851",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/97177/"
] | Hanky 웃 Panky brings up good points. However, I'd like to add to them:
1. You can mitigate damage by restricting connecting accounts by roles. Let's say you only allow searching on your website. Allowing only `SELECT` statements for that particular account will prevent anything else from running. This doesn't work if you have an account for each: `SELECT`, `UPDATE`, `INSERT`, `DELETE`, as an attacker could combine the privileges and cause serious damage.
2. You can also deny anyone except those with appropriate admin access to the website, whose login will likely be independent of the webhost. IP-based deny all, allow from , for example. Note that this won't completely protect you if you've been breached, **nor will it protect you if your web host is the one accessing the database.**
Only those with root/admin/shell access to your website can obtain the username and passwords, unless you improperly chmodded the files. If any of those are true, you have much bigger issues than having your MySQL user/pass known. |
57,852,306 | I created a custom loop for exclusion of sticky post from the flow. So in that loop no sticky post came, but the problem is when I went to `page/2/` or `page/3/` same posts are repeating.
```html
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$rest = new WP_Query(array(
'post__not_in' => get_option('sticky_posts'),
'paged' => $paged,
));
?>
<?php if($rest->have_posts()) { ?>
<?php while($rest->have_posts()) { ?>
<?php $rest->the_post(); ?>
<?php get_template_part('template/main/main-content'); ?>
<?php } ?>
<?php } else { ?>
<p> no post available </p>
<?php } ?>
<?php the_posts_pagination(); ?>
<?php wp_reset_query(); ?>
``` | 2019/09/09 | [
"https://Stackoverflow.com/questions/57852306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11931534/"
] | That image of the tennis ball that you linked reveals the problem. I'm glad you ultimately provided it.
[![enter image description here](https://i.stack.imgur.com/7lXSgs.jpg)](https://i.stack.imgur.com/7lXSg.jpg)
Your image is a four-channel PNG with transparency (Alpha channel). There are transparent pixels all around the outside of the yellow part of the ball that have (R,G,B,A) = (0, 0, 0, 0), so if you're ignoring the A channel then (R, G, B), will be (0, 0, 0) = black.
Here are just the Red, Green, and Blue (RGB) channels:
[![enter image description here](https://i.stack.imgur.com/z907sm.jpg)](https://i.stack.imgur.com/z907s.jpg)
And here is just the Alpha (A) channel.
[![enter image description here](https://i.stack.imgur.com/8wLtfm.png)](https://i.stack.imgur.com/8wLtf.png)
The important thing to notice is that the circle of the ball does not fill the square. There is a significant margin of 53 pixels of black from the extent of the ball to the edge of the texture. We can calculate the radius of the ball from this. Half the width is 1000 pixels, of which 53 pixels are not used. The ball's radius is 1000-53, which is 947 pixels. Or about 94.7% of the distance from the center to the edge of the texture. The remaining 5.3% of the distance is black.
>
> **Side note:** I also notice that your ball doesn't quite reach 100% opacity. The yellow part of the ball has an alpha channel value of 254 (of 255) Meaning 99.6% opaque. The white lines and the shiny hot spot do actually reach 100% opacity, giving it sort of a Death Star look. ;)
>
>
>
To fix your problem, there's the intuitive approach (which may not work) and then there are two things that you need to do that will work. Here are a few things you can do:
Intuitive Solution:
-------------------
***This won't quite get you 100% there.***
1) Resize the ball to fill the texture. Use image editing software to enlarge the ball to fill the texture, or to trim off the black pixels. This will just make more efficient use of pixels, for one, but it will ensure that there are useful pixels being sampled at the boundary. You'll probably want to expand the image to be slightly larger than 100%. I'll explain why below.
2) Remap your texture coordinates to only extend to 94.7% of the radius of the ball. (Similar to approach 1, but doesn't require image editing). This just uses coordinates that actually correspond to the image you provided. Your `x` and `y` coordinates need to be scaled about the center of the image and reduced to about 94.7%.
```
x2 = 0.5 + (x - 0.5) * 0.947;
y2 = 0.5 + (y - 0.5) * 0.947;
```
Suggested Solution:
-------------------
***This will ensure no more black.***
3) Fill the "black" portion of your ball texture with a less objectionable colour - probably the colour that is at the circumference of the tennis ball. This ensures that any texels that are sampled at exactly the edge of the ball won't be linearly combined with black to produce an unsightly dark-but-not-quite-black band, which is almost the problem you have right now anyway. You can do this in two ways. A) Image editing software. Remove the transparency from your image and matte it against a dark yellow colour. B) Use the shader to detect pixels that are outside the image and replace them with a border colour (this is clever, but probably more trouble than it's worth.)
Different Texture Coordinates
-----------------------------
The last thing you can do is avoid this degenerate texture mapping coordinate problem altogether. At the equator, you're not really sure which pixels to sample. The black (transparent) pixels or the coloured pixels of the ball. The discrete nature of square pixels, is fighting against the polar nature of your texture map. You'll never find the exact colour you need near the edge to produce a continuous, seamless map. Instead, you can use a different coordinate system. I hope you're not attached to how that ball looks, because let me introduce you to the *equirectangular projection*. It's the same projection that you can naively use to map the globe of the Earth to a typical rectangular map of the world you're likely familiar with where the north and south poles get all the distortion but the equatorial regions look pretty good.
Here's your image mapped to equirectangular coordinates:
[![enter image description here](https://i.stack.imgur.com/KdscTm.jpg)](https://i.stack.imgur.com/KdscT.jpg)
Notice that black bar at the bottom...we're onto something! That black bar is actually exactly what appears around the equator of your ball with your current texture mapping coordinate system. But with this coordinate system, you can see easily that if we just remapped the ball to fill the square we'd completely eliminate any transparent pixels at all.
It may be inconvenient to work in this coordinate system, but you can transform your image in Photoshop using Filter > Distort > Polar Coordinates... > Polar to Rectangular.
[Sigismondo's answer](https://stackoverflow.com/a/57856208/1563833) already suggests how to adjust your texture mapping coordinates do this.
And finally, here's a texture that is both enlarged to fill the texture space, and remapped to equirectangular coordinates. No black bars, minimal distortion. But you'll have to use Sigismondo's texture mapping coordinates. Again, this may not be for you, especially if you're attached to the idea of the direct projection for your texture (i.e.: if you don't want to manipulate your tennis ball image and you want to use that projection.) But if you're willing to remap your data, you can rest easy that all the black pixels will be gone!
[![enter image description here](https://i.stack.imgur.com/WBftlm.jpg)](https://i.stack.imgur.com/WBftl.jpg)
Good luck! Feel free to ask for clarifications. |
356,023 | Suppose I have a bivariate normal $(x,y)\sim \mathcal N(0,\Sigma)$ .
Is there an easy formula for the expectation $\mathrm E(x\mid y>0)$ ? | 2018/07/13 | [
"https://stats.stackexchange.com/questions/356023",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/205719/"
] | Let $\phi(\cdot)$ and $\Phi(\cdot)$ be the PDF and CDF of standard normal distribution, as usual.
Suppose $\Sigma=\left[\begin{matrix}\sigma\_1^2&\rho \sigma\_1\sigma\_2\\\rho\sigma\_1\sigma\_2&\sigma\_2^2\end{matrix}\right]$ is the dispersion matrix of $(X,Y)$.
By definition,
\begin{align}
E\left[X\mid a<Y<b\right]&=\frac{E\left[XI(a<Y<b)\right]}{P(a<Y<b)}
\\&=\frac1{P(a<Y<b)}\iint\_{\mathbb R^2} x \mathbf1\_{a<y<b}f\_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y
\\&=\frac1{P(a<Y<b)}\int\_a^b\int\_{-\infty}^{\infty} xf\_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y
\\&=\frac{1}{P(a<Y<b)}\int\_a^b \left\{\int\_{-\infty}^{\infty} xf\_{X\mid Y}(x\mid y)\,\mathrm{d}x \right\}f\_Y(y)\,\mathrm{d}y
\\&=\frac{1}{P(a<Y<b)}\int\_a^b E\left[X\mid Y=y\right]f\_Y(y)\,\mathrm{d}y
\end{align}
This of course is same as saying $$E\left[X\mid a<Y<b\right]=\int\_a^b E\left[X\mid Y=y\right]f\_{Y\mid a<Y<b}(y)\,\mathrm{d}y$$
Now $X$ conditioned on $Y=y$ has a $N\left(\frac{\rho\,\sigma\_1}{\sigma\_2}y,(1-\rho^2)\sigma\_1^2\right)$ distribution, so that
$$E\left[X\mid Y=y\right]=\frac{\rho\,\sigma\_1}{\sigma\_2}y$$
In this case, we thus have
\begin{align}
E\left[X\mid Y>0\right]&=\frac{\rho\,\sigma\_1}{\sigma\_2}\int\_0^\infty \frac{yf\_Y(y)}{P(Y>0)}\,\mathrm{d}y
\\&=\frac{\rho\,\sigma\_1}{\sigma\_2}E\left[Y\mid Y>0\right]
\end{align}
Finally,
\begin{align}
E\left[Y\mid Y>0\right]&=\frac{1}{P(Y>0)}\int\_0^\infty \frac{y}{\sigma\_2}\phi\left(\frac{y}{\sigma\_2}\right)\mathrm{d}y
\\&=2\sigma\_2\int\_0^\infty t\phi(t)\,\mathrm{d}t
\\&=2\sigma\_2\int\_0^\infty (-\phi'(t))\,\mathrm{d}t
\\&=2\sigma\_2\,\phi(0)
\\&=\sqrt{\frac{2}{\pi}}\sigma\_2
\end{align}
Hence for $(X,Y)\sim N(\mathbf 0,\Sigma)$, we have the simple formula
$$\boxed{E\left[X\mid Y>0\right]=\sqrt{\frac{2}{\pi}}\rho\,\sigma\_1}$$
A general formula where the means of $X$ and $Y$ are not zero, and $Y$ ranging from some $a$ to $b$ can also be found in a similar manner. That formula would involve $\phi$ and $\Phi$, whereas for the current one, we get the values at $\phi$ and $\Phi$ directly. |
29,573,913 | I am implementing a system in which the memory could be allocated in an offline manner, i.e. all allocation time, size and deallocation time are known beforehand, and I just need to figure out a static allocation that minimizes peak memory usage.
Google does not help much; most of the results are about dynamic allocators used in various systems. I heard that this problem is NP-Hard, but did not find good reference. I only find that memory insertion and compaction problem is NP-Hard (<http://epubs.siam.org/doi/pdf/10.1137/0213037> ), but it seems not equivalent to my situation.
So is there an optimal algorithm in polynomial time, or any good sub-optimal algorithms? Time complexity is not a major concern, as long it could finish in several seconds for thousands of allocations on a multi-core system (maybe O(n^4) is acceptable).
Thanks very much! | 2015/04/11 | [
"https://Stackoverflow.com/questions/29573913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1184354/"
] | This is called the offline dynamic storage allocation problem. Check out the papers cited by <https://epubs.siam.org/doi/abs/10.1137/S0097539703423941> for a good review of the literature. |
50,958,238 | The Flutter tutorial uses the word "Widget" everywhere. What is a widget in that context? The closest question I could find on this on SO is here: [What is a widget in Android?](https://stackoverflow.com/questions/3777637/what-is-a-widget-in-android)
But it is about Android and not Flutter (which builds for both Android and iOS, thus defines widget in both contexts) and the answers are a bit confusing. One person says a Widget is like a button (so I am thinking of a Ui-Component of some Ui-Package/framework), the other says it's like an app because it can run anywhere and take up the whole screen. So coming from WebDevelopment, can I assume a Widget is something like a WebComponent?
It is a piece of self-contained code that doesn't depend on other components but needs to be bootstrapped in an environment? Is this assumption true? For both Android and iOS? | 2018/06/20 | [
"https://Stackoverflow.com/questions/50958238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4125622/"
] | The [strict definition of WebComponent](https://www.webcomponents.org/introduction) differs a little bit wherever you look, but basically it boils down (in my own words) to "a set of standards which allow definition of custom, encapsulated, re-usable elements in the form of html tags".
Flutter's [strict definition of a widget](https://docs.flutter.io/flutter/widgets/Widget-class.html) is:
>
> Describes the configuration for an Element
>
>
>
and [Element is defined as](https://docs.flutter.io/flutter/widgets/Element-class.html):
>
> An instantiation of a Widget at a particular location in the tree
>
>
>
However, when you're speaking about WebComponents, you're probably thinking about the "custom, encapsulated, re-usable elements" rather than the strict definition.
When you start thinking about them this way, flutter's Widget becomes quite similar. When you define a widget (by extending one of the widget classes) you can allow for certain inputs, and you define how it will be displayed. You can more or less use a widget without knowing how it works internally, so long as you know the 'interface' you've been given to it. And when you instantiate it you create an instance of the widget that Flutter is choosing to call an Element. The Widget sounds eerily similar to a WebComponent Element!
Futhermore, when you create a `Widget` in Flutter, you can encapsulate other widgets so that you don't have to write the visual definition from scratch (Flutter uses RenderObject to represent the rendering whereas the WebComponents analogue would be writing plain html5 without other elements). Flutter includes many widgets such as Buttons, Lists, Containers, Grids, etc that are similar to what you would find in various WebComponent libraries (e.g. Polymer's iron set of components).
There are a few extra wrinkles to Flutter's definition of Widget - they have various types including `InheritedWidget`, `StatefulWidget`, `StatelessWidget` (and a few more specialized), each of which has their own usage; in some ways Flutter's components are actually closer to React's components than WebComponents (and in fact the design of flutter is based from the same reactive ideals). This 'reative'-ness is the biggest difference between flutter Widgets and WebComponent elemnts - they primarily work by passing state down the tree while WebComponent elements would be more likely to have methods that your widget can call on its sub-element, and changes are propagated down the tree by the way your widgets are defined rather than having to call functions.
Not every flutter Widget has to have a visual definition (not that all WebComponents have a visual definition either). InheritedWidget for example is used for essentially leap-frogging state down the tree of widgets without having to actually pass the information down through each layer - it's used for sharing the ThemeData throughout an app. And without getting too much into the gory details, flutter is optimized for primarily building immutable widgets when things change rather than re-using and modifying existing widgets.
The TLDR of this though is that yes, widgets in flutter 'something like' WebComponent elements, with some caveats. You will be writing your application mostly in the form of a set of widgets, some of which encapsulate other ones. And the way that Flutter works is that it uses its own cross-platform renderer (Skia) which lives in the corresponding visual container for android or iOS (Activity and I believe UIView *(controller?)*) - so you never switch from activity to activity or UIViewController to UIViewController on the native android/iOS side. |
45,604,130 | I am converting string of date/datetime to `OffsetDateTime` and I have datetime format which may have one of these values
```
yyyy-MM-dd, yyyy/MM/dd
```
Sometimes with and without time and I need to convert this into `OffsetDateTime`.
I have tried below code
```
// for format yyyy-MM-dd
DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
.toFormatter();
```
As it doesn't have time I am setting this to default values but when I try to parse
```
OffsetDateTime.parse("2016-06-06", DATE_FORMAT)
```
It is throwing error like
>
> Exception in thread "main" java.time.format.DateTimeParseException: Text '2016-06-06' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2016-06-06T00:00 of type java.time.format.Parsed
>
>
>
Can anyone help me how to solve this? | 2017/08/10 | [
"https://Stackoverflow.com/questions/45604130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4361808/"
] | To create an `OffsetDateTime`, you need the **date** (day, month and year), the **time** (hour, minute, second and nanosecond) and the [**offset**](https://en.wikipedia.org/wiki/UTC_offset) (the difference from [UTC](https://www.timeanddate.com/time/aboututc.html)).
Your input has only the date, so you'll have to build the rest, or assume default values for them.
To parse both formats (`yyyy-MM-dd` and `yyyy/MM/dd`), you can use a `DateTimeFormatter` with optional patterns (delimited by `[]`) and parse to a `LocalDate` (because you have only the date fields):
```
// parse yyyy-MM-dd or yyyy/MM/dd
DateTimeFormatter parser = DateTimeFormatter.ofPattern("[yyyy-MM-dd][yyyy/MM/dd]");
// parse yyyy-MM-dd
LocalDate dt = LocalDate.parse("2016-06-06", parser);
// or parse yyyy/MM/dd
LocalDate dt = LocalDate.parse("2016/06/06", parser);
```
You can also use this (a little bit more complicated, but it works the same way):
```
// year followed by - or /, followed by month, followed by - or /, followed by day
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy[-][/]MM[-][/]dd");
```
Then you can set the time to build a `LocalDateTime`:
```
// set time to midnight
LocalDateTime ldt = dt.atStartOfDay();
// set time to 2:30 PM
LocalDateTime ldt = dt.atTime(14, 30);
```
---
Optionally, you can also use `parseDefaulting`, as already explained in [@greg's answer](https://stackoverflow.com/a/45606640/7605325):
```
// parse yyyy-MM-dd or yyyy/MM/dd
DateTimeFormatter parser = new DateTimeFormatterBuilder().appendPattern("[yyyy-MM-dd][yyyy/MM/dd]")
// set hour to zero
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
// set minute to zero
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
// create formatter
.toFormatter();
// parse the LocalDateTime, time will be set to 00:00
LocalDateTime ldt = LocalDateTime.parse("2016-06-06", parser);
```
Note that I had to set hour and minute to zero. You can also set seconds (`ChronoField.SECOND_OF_MINUTE`) and nanoseconds (`ChronoField.NANO_OF_SECOND`) to zero, but setting the hour and minute are enough to set all the other fields to zero.
---
You told that you want to use the system's default offset. This is a little bit tricky.
The "system's default offset" will depend on the system's default timezone. And a timezone can have more than one offset, depending on **when** you are in the timeline.
I'll use my system's default timezone (`America/Sao_Paulo`) as an example. In the code below I'm using `ZoneId.systemDefault()`, but remember that this will be different in each system/environment. **For all the examples below, remember that `ZoneId.systemDefault()` returns the `America/Sao_Paulo` timezone. If you want to get a specific one, you should use `ZoneId.of("zone_name")` - actually this is prefered**.
First you must get the list of valid offsets for the `LocalDateTime`, at the specified timezone:
```
// using the parser with parseDefaulting
LocalDateTime ldt = LocalDateTime.parse("2016-06-06", parser);
// get all valid offsets for the date/time, in the specified timezone
List<ZoneOffset> validOffsets = ZoneId.systemDefault().getRules().getValidOffsets(ldt);
```
According to [javadoc](https://docs.oracle.com/javase/8/docs/api/java/time/zone/ZoneRules.html#getValidOffsets-java.time.LocalDateTime-), the `validOffsets` list size, for any given local date-time, can be zero, one or two.
For most cases, there will be just one valid offset. In this case, it's straighforward to get the `OffsetDateTime`:
```
// most common case: just one valid offset
OffsetDateTime odt = ldt.atOffset(validOffsets.get(0));
```
The other cases (zero or two valid offsets) occurs usually due to Daylight Saving Time changes (DST).
In São Paulo timezone, DST will start at October 15th 2017: at midnight, clocks shift forward to 1 AM and offset changes from `-03:00` to `-02:00`. This means that all local times from 00:00 to 00:59 don't exist - you can also think that clocks change from 23:59 directly to 01:00.
So, in São Paulo timezone, this date will have no valid offset:
```
// October 15th 2017 at midnight, DST starts in Sao Paulo
LocalDateTime ldt = LocalDateTime.parse("2017-10-15", parser);
// system's default timezone is America/Sao_Paulo
List<ZoneOffset> validOffsets = ZoneId.systemDefault().getRules().getValidOffsets(ldt);
System.out.println(validOffsets.size()); // zero
```
There are no valid offsets, so you must decide what to do in cases like this (use a "default" one? throw exception?).
Even if your timezone doesn't have DST today, it could've had in the past (and dates in the past can be in that case), or it can have in the future (because DST and offsets of any country are defined by governments and laws, and there's no guarantee that nobody will change in the future).
If you create a `ZonedDateTime`, though, the result will be different:
```
// October 15th 2017 at midnight, DST starts in Sao Paulo
LocalDateTime ldt = LocalDateTime.parse("2017-10-15", parser);
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
```
The `zdt` variable will be `2017-10-15T01:00-02:00[America/Sao_Paulo]` - the time and the offset are adjusted automatically to **1 AM at `-02:00` offset**.
---
And there are the case of two valid offsets. In São Paulo, DST will end at February 18th 2018: at midnight, clocks will shift 1 hour back to 11 PM of 17th, and the offset changes from `-02:00` to `-03:00`. This means that all local times between 23:00 and 23:59 will exist twice, in both offsets.
As I set the default time to midnight, there will be only one valid offset. **But suppose I decided to use a default time at 23:00**:
```
// parse yyyy-MM-dd or yyyy/MM/dd
parser = new DateTimeFormatterBuilder().appendPattern("[yyyy-MM-dd][yyyy/MM/dd]")
// *** set hour to 11 PM ***
.parseDefaulting(ChronoField.HOUR_OF_DAY, 23)
// set minute to zero
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
// create formatter
.toFormatter();
// February 18th 2018 at midnight, DST ends in Sao Paulo
// local times from 23:00 to 23:59 at 17th exist twice
LocalDateTime ldt = LocalDateTime.parse("2018-02-17", parser);
// system's default timezone is America/Sao_Paulo
List<ZoneOffset> validOffsets = ZoneId.systemDefault().getRules().getValidOffsets(ldt);
System.out.println(validOffsets.size()); // 2
```
There will be 2 valid offsets for the `LocalDateTime`. In this case, you must choose one of them:
```
// DST offset: 2018-02-17T23:00-02:00
OffsetDateTime dst = ldt.atOffset(validOffsets.get(0));
// non-DST offset: 2018-02-17T23:00-03:00
OffsetDateTime nondst = ldt.atOffset(validOffsets.get(1));
```
If you create a `ZonedDateTime`, though, it'll use the first offset as the default:
```
// February 18th 2018 at midnight, DST ends in Sao Paulo
LocalDateTime ldt = LocalDateTime.parse("2018-02-17", parser);
// system's default timezone is America/Sao_Paulo
List<ZoneOffset> validOffsets = ZoneId.systemDefault().getRules().getValidOffsets(ldt);
// by default it uses DST offset
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
```
`zdt` will be `2018-02-17T23:00-02:00[America/Sao_Paulo]` - note that it uses the DST offset (`-02:00`) by default.
If you want the offset after DST ends, you can do:
```
// get offset after DST ends
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault()).withLaterOffsetAtOverlap();
```
`zdt` will be `2018-02-17T23:00-03:00[America/Sao_Paulo]` - it uses the offset `-03:00` (after DST ends).
---
Just reminding that the system's default timezone can be changed even at runtime, and it's better to use a specific zone name (like `ZoneId.of("America/Sao_Paulo")`). You can get a list of available timezones (and choose the one that fits best your system) by calling `ZoneId.getAvailableZoneIds()`. |
20,699,961 | How it works? I got some code running in an IPython Notebook. Some iterative work.
Accidentally I closed the browser with the running Notebook, but going back to the IPython Dashboard I see that this particular Notebook hasn't Shutdown, so if I open the Notebook again I see the [\*] in front of my code that it was executing.
I even can hear my PC still running the code, but it doesn't return me any new output of the print statements.
Can I wait and eventually continue with the output, or my PC will still running my code, but it won't be accessible anymore? | 2013/12/20 | [
"https://Stackoverflow.com/questions/20699961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2459096/"
] | When you start up ipython, it is essentially creating a web server that is running on a separate process. The code itself is running on the web server, or kernel. The web browser is simply one of several front-ends that can view and edit the code on the kernel.
This design allows ipython to separate the evaluation of code from the viewing and editing of code -- for example, I could access the same kernel via the web interface (`ipython notebook`), the console (`ipython console`), or the qt console interface (`ipython qtconsole`).
Your PC will continue to run the code, though I believe that the output requested by one frontend will not show on any other frontends using the same kernel (I'm not 100% certain about this though).
You can find more information [here](http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Frontend-Kernel%20Model.ipynb). |
65,668,980 | In my AS ABAP 7.50 system, I have a table where the material length is 18 and I need to expose it via CDS as if the material length was 40 like in S/4. The material IDs in the system can be numeric (with leading zeros) or alphanumeric. The material field needs to be casted to MATNR40, and if the ID is numeric, the leading zeros need to be added up to the 40 characters.
First, I tried `lpad. But of course, it also adds the leading zeros to the alphanumeric values:
```
lpad( cast(matnr as matnr40), 40, '0' ) as material_long,
```
Then I added a `case` but I'm not able to make the condition work as I expect. As konstantin confirmed in the comments, it's not possible to use regex here as I attempted:
```
case when matnr like '%[^0-9.]%'
then lpad( cast(matnr as matnr40), 40, '0' )
else cast(matnr as matnr40)
end as material_long,
```
Is there a solution within the CDS itself to this problem?
Source table:
| MATNR18 | Description |
| --- | --- |
| 000000000000000142 | Numeric ID material |
| MATERIAL\_2 | Alphanumeric ID |
Expected result:
| MATNR40 | Description |
| --- | --- |
| 0000000000000000000000000000000000000142 | Numeric ID material |
| MATERIAL\_2 | Alphanumeric ID | | 2021/01/11 | [
"https://Stackoverflow.com/questions/65668980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385123/"
] | Due to the limited functionality in CDS syntax the only way I see is to nest 10 `REPLACE` functions to remove digits and compare the result with initial string. If it is initial, then you have only digits, so you can `LPAD` them with zeroes. If not - use the original value.
Here's my code:
```abap
@AbapCatalog.sqlViewName: 'Z_V_TEST'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Test'
define view Z_TEST as select from /bi0/mmaterial {
cast(
case replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(material,
'0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', '')
when ''
then lpad(material, 40, '0')
else material
end as abap.char(40)
) as MATERIAL_ALPHA,
material
}
```
And the result is:
```
REPORT Z_TEST.
select *
from Z_V_TEST
where material in ('LAMP', '000000000000454445')
into table @data(lt_res)
.
cl_demo_output=>display( lt_res ).
MATERIAL_ALPHA | MATERIAL
-----------------------------------------+-------------------
0000000000000000000000000000000000454445 | 000000000000454445
LAMP | LAMP
``` |
44,836,123 | I would like to use some R packages requiring R version 3.4 and above. I want to access these packages in python (3.6.1) through rpy2 (2.8).
I have R version 3.4 installed, and it is located in `/Library/Frameworks/R.framework/Resources` However, when I use `pip3 install rpy2` to install and use the python 3.6.1 in `/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6)` as my interpreter, I get the error:
>
> Traceback (most recent call last):
> File "/Users/vincentliu/PycharmProjects/magic/rpy2tester.py", line 1, in
> from rpy2 import robjects
> File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/robjects/**init**.py", line 16, in
> import rpy2.rinterface as rinterface
> File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/rinterface/**init**.py", line 92, in
> from rpy2.rinterface.\_rinterface import (baseenv,
> ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/rinterface/\_rinterface.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libiconv.2.dylib
> Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rpy2/rinterface/\_rinterface.cpython-36m-darwin.so
> Reason: Incompatible library version: \_rinterface.cpython-36m-darwin.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0
>
>
>
Which first seemed like a problem caused by Anaconda, and so I remove all Anaconda-related files but the problem persists.
I then uninstalled rpy2, reinstalled Anaconda and used `conda install rpy2` to install, which also installs R version 3.3.2 through Anaconda. I can then change the interpreter to `/anaconda/bin/python` and can use rpy2 fine, but I couldn't use the R packages I care about because they need R version 3.4 and higher. Apparently, the oldest version Anaconda can install is 3.3.2, so is there any way I can use rpy2 with R version 3.4?
I can see two general solutions to this problem. One is to install rpy2 through conda and then somehow change its depending R to the 3.4 one in the system. Another solution is to resolve the error
>
> Incompatible library version: \_rinterface.cpython-36m-darwin.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0
>
>
>
After much struggling, I've found no good result with either. | 2017/06/29 | [
"https://Stackoverflow.com/questions/44836123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173169/"
] | I uninstalled rpy2 and reinstalled with `--verborse`. I then found
>
> ld: warning: ignoring file /opt/local/lib/libpcre.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/libpcre.dylib
> ld: warning: ignoring file /opt/local/lib/liblzma.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/liblzma.dylib
> ld: warning: ignoring file /opt/local/lib/libbz2.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/libbz2.dylib
> ld: warning: ignoring file /opt/local/lib/libz.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/libz.dylib
> ld: warning: ignoring file /opt/local/lib/libiconv.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/libiconv.dylib
> ld: warning: ignoring file /opt/local/lib/libicuuc.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/libicuuc.dylib
> ld: warning: ignoring file /opt/local/lib/libicui18n.dylib, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/lib/libicui18n.dylib
> ld: warning: ignoring file /opt/local/Library/Frameworks/R.framework/R, file was built for x86\_64 which is not the architecture being linked (i386): /opt/local/Library/Frameworks/R.framework/R
>
>
>
So I supposed the reason is the architecture incompatibility of the libiconv in `opt/local`, causing make to fall back onto the outdate libiconv in `usr/lib`. This is strange because my machine should be running on x86\_64 not i386. I then tried `export ARCHFLAGS="-arch x86_64"` and reinstalled libiconv using port. This resolved the problem. |
45,683,877 | I just need to extract the part between ':' and '/' in the attribute "PointName".
Following is the sample XML:
```
<?xml version="1.0" encoding="utf-8"?>
<Trend xmlns="Data">
<tblPoint PointName="ABC:XYZ123/AAA.DDD-111.MMM.MV-3.PV" UOM="0">
<tblValue UTCDateTime="2017-07-18T05:07:47" val="3" />
<tblValue UTCDateTime="2017-07-18T05:08:27" val="0" />
</tblPoint>
<tblPoint PointName="BCD:XYZ234/AAA.DDD-222.MMM.MV-3.PV" UOM="0">
<tblValue UTCDateTime="2017-07-18T06:01:12" val="0" />
<tblValue UTCDateTime="2017-07-18T06:01:13" val="0" />
</tblPoint>
</Trend>
```
I'm currently using the following code:
```
var xdoc = XDocument.Load(xmlFilePath); // xmlFilePath - where the above XML file is located.
var ns = XNamespace.Get("Data");
var pointNames = xdoc.Root.Elements(ns + "tblPoint").Attributes("PointName").ToList();
```
I wish there was a way to populate the pointNames like this:
```
var pointNames = xdoc.Root.Elements(ns + "tblPoint").Attributes("PointName").StringBetween(':', '/').ToList();
```
I would hate to use a loop on pointNames because tblPoint nodes can be thousands in number in the XML. | 2017/08/14 | [
"https://Stackoverflow.com/questions/45683877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8464385/"
] | Using many different `Activity` instances that all duplicate the `BottomNavigationView` and its associated code (like the `OnNavigationItemSelectedListener` etc) is not recommended. Instead, you would generally use a single `Activity` that hosts the `BottomNavigationView` as well as multiple `Fragment` instances that are `.replace()`d into your content area as the user interacts with the `BottomNavigationView`.
That being said, let's see if we can solve your problem.
There are two pieces to this puzzle. The first is simple: you have to indicate which item in your `BottomNavigationView` should be selected. This can be achieved by calling `setSelectedItemId()`. Add something like this to your `onCreate()` method.
```
navigation.setSelectedItemId(R.id.navigation_settings);
```
The second is a little more complicated. When you call `setSelectedItemId()`, the system is going to behave as though a user had tapped on that item. In other words, your `OnNavigationItemSelectedListener` will be triggered.
Looking at your posted listener, I notice that you always `return false`. If you check the documentation for `onNavigationItemSelected()`, you will find
>
> **Returns**:
> `true` to display the item as the selected item and `false` if the item should not be selected
>
>
>
So the call to `setSelectedItemId()` won't work without also changing your listener to return `true`.
You could still solve the problem with just a `setSelectedItemId()` call if you place that call **before** your `setOnNavigationItemSelectedListener()` call, but that's just masking the problem. It'd be better to fix your listener to return `true` in cases where you want the tapped item to appear as selected. |
3,871,088 | At this point we are developing Sitecore websites and we are gaining experience every day. This means that we know how to adjust our approach to different types of customers and that we are able to build our applications quicker every project we do. Offcourse Sitecore is not the only W-CMS around and we have looked into other W-CMS's. What are the pro's and the con's for a company to offer solutions in different types of CMS's and what would this mean for the programmers that are working with this CMS? Would a choice to offer solutions in more CMS's automatically mean that the global experience per CMS will shrink relative? Hope there are some people around with experience in multiple big W-CMS's (Sitecore, KEntico, EPIServer, etc.. etc..). | 2010/10/06 | [
"https://Stackoverflow.com/questions/3871088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81892/"
] | If the domain remains the same, the first iframe will create the session and the second iframe will just pick it up after `session_start()`
You dont really need to pass the session in the URL for this or anything. The first iframe while writing the session data will lock the session data. However there is a problem, with iframes you can never be sure that the first iframe does load first, maybe cause of network congestion or something it is possible that the second iframe loads first. So maybe to counter this delay loading the second iframe a bit. |
18,880,511 | I'm getting a NullPointerException when trying to create a Timer. Obviously the TimerService is not getting set, but my question is, why? As far as I can tell I'm following the exact pattern used by another class in our application that *does* work.
**Note**: I'm new to EJB so explanation is helpful
```
@Stateless
public class MyClass implements SomeInterface
{
private static final Logger ourLogger = new Logger(MyClass.class);
private volatile Timer timer = null;
private volatile static MyClass instance = null;
@javax.annotation.Resource
TimerService timerService;
@Override
public synchronized void myMethod()
{
resetTimer();
//do other stuff
}
/**
* Creates the timer.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private synchronized void resetTimer()
{
if (timer != null)
{
timer.cancel();
timer = null;
}
//NullPointerException on next line:
timer = timerService.createTimer(30000, "My Note");
}
public static MyClass getInstance()
{//MDB calls this, then runs instance.myMethod
if (instance == null)
{
instance = new MyClass ();
}
return instance;
}
@Timeout
public synchronized void timeout()
{
//Do some stuff
instance = null;
}
}
``` | 2013/09/18 | [
"https://Stackoverflow.com/questions/18880511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036285/"
] | Additional code you posted adds one more thing to the list of wrong things with this code (which I started in first comment to your question.)
You're trying to implement a Singleton design pattern in SLSB. This is wrong on many levels.
If you need singleton - just use `@Singleton` EJB. If you're doing it like you posted - you're basically not instantiating an EJB but some regular Java class. No wonder why injection doesn't occur - container doesn't know anything about the instance you're creating in your method.
If you want to have an EJB - just give it a default constructor and use it from your MDB with `@EJB`. Then the container will instantiate it and give it the EJB nature (with all those management lifecycle, pooling, dependency injection, etc.)
To sum up you can find the list of wrong things in the code you've posted:
* you're holding a state in a **stateless** EJB,
* you're implementing a singleton pattern into **pooled-by-specification** EJB,
* you're synchronizing already **thread-safe (also by-specification)** EJB,
* you're adding `@TransactionAttribute` to **private method**; I'm not even sure if this have any sense. `@TransactionAttribute` is a sign that you're defining a business method. At the same time this method is private which means it cannot be a part of the business interface so it is not a business method.
Hope this will help you! |
126,862 | My probability textbook introduction just mentioned that Ohm's Law is not always precisely true at the microscopic level.
How is this possible? What is causing this to happen? | 2014/08/27 | [
"https://electronics.stackexchange.com/questions/126862",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/16840/"
] | Consider the rule that the volume of liquid in a vessel is equal to the height of the liquid times its horizontal cross sectional area. For vessels whose horizontal cross section is uniform from top to bottom, halving the height of the liquid will halve its volume. Doubling the amount of liquid, if there's room, will double the volume.
Suppose, however, one removes nearly all of the liquid from the vessel, leaving only two nanoliters. and then cuts the height of the liquid in half. Should one expect that exactly one nanoliter would remain?
The relationship between cross-sectional area, height, and volume remains true *by definition* at any scale, large or small, provided that those quantities are concretely defined numbers. At very small scales, however, concepts like "volume" become rather nebulous. If there are only a few hundred molecules bouncing around, it's unclear how much of the space outside each should count as part of the "volume" of liquid, and how much should be considered "empty space". In such cases, the relationship between height, volume, and cross sectional area doesn't "break down" so much as it becomes less and less meaningful, especially in cases where the cross-sectional area varies widely with height.
To put it another way, when quantities get very small, measurement uncertainties get very big. When quantities get so small that measurement uncertainties get to be as big as the measurements, Ohm's Law will still hold, but will cease to have much predictive value. |
2,360,764 | I'm using CMT in EJB3 state-less session beans. Also I've created my own Exception having the annotation "@ApplicationException (rollback=true)".
1. Do I have to use "context.setRollbackOnly()" when I want to rollback the transaction?
2. Can I just rollback the transaction by throwing an exception inside public method in the bean?
3. If so (the answer to Q#2 is yes) do I have to throw the exception out of the method by declaring the exception in the method or will it be sufficient to just throw an exception inside the method and handle it inside the same method itself? (I don't want to propagate the exception to the next level. I just want to rollback the exception.)
Thanks in advance. ;) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2360764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248857/"
] | First of all, there is no rollback of an exception, it's a rollback of a transaction.
1. If you throw your exception with `@ApplicationException(rollback=true)`, you don't have to rollback the transaction manually. `Context.setRollbackOnly()` forces the container to rollback the transaction, also if there is no exception.
2. A checked exception itself doesn't rollback a transaction. It needs to have the annotation `@ApplicationException(rollback=true)`. If the exception is a `RuntimeException` and the exception isn't caught, it forces the container to rollback the transaction. But watch out, the container will in this case discard the EJB instance.
3. As mentioned in 2.), if you throw a `RuntimeException`, the transaction will be rolled back automatically. If you catch an checked exception inside the code, you have to use `setRollbackOnly` to rollback the transaction.
For further information, check out the free book [Mastering EJB](http://www.theserverside.com/news/1369778/Free-Book-Mastering-Enterprise-JavaBeans-30). It describes the rollback scenarios very well and is free for [download](https://media.techtarget.com/tss/static/books/wiley/masteringEJB/downloads/MasteringEJB3rdEd.pdf). |
58,189,432 | My name is Laurenz and my question is how to delay the color changing of my sprites in Unity with c#.
Right now I have a random generator which choses a color based on a number, but this happens every frame. So now the real challenge is how to delay it so that it changes less often.
```
public class colorchange : MonoBehaviour
{
public int color;
public bool stop = true;
void Start()
{
}
void Update()
{
Debug.Log("Hello");
color = Random.Range(1, 5);
if (color == 2)
{
gameObject.GetComponent<SpriteRenderer>().color = Color.blue;
}
if (color == 3)
{
gameObject.GetComponent<SpriteRenderer>().color = Color.red;
}
if (color == 4)
{
gameObject.GetComponent<SpriteRenderer>().color = Color.yellow;
}
}
}
``` | 2019/10/01 | [
"https://Stackoverflow.com/questions/58189432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can put your code in a loop in a [**Coroutine**](https://docs.unity3d.com/ScriptReference/Coroutine.html) that iterates once every number of seconds:
```
public class colorchange : MonoBehaviour
{
public int color;
public float delaySeconds = 1f;
IEnumerator changeColorCoroutine;
SpriteRenderer mySprite;
public bool doChangeColor;
void Start()
{
// cache result of expensive GetComponent call
mySprite = GetComponent<SpriteRenderer>();
// initialize flag
doChangeColor = true;
// create coroutine
changeColorCoroutine = ChangeColor();
// start coroutine
StartCoroutine(changeColorCoroutine);
}
void OnMouseDown()
{
// toggle doChangeColor
doChangeColor = !doChangeColor;
}
IEnumerator ChangeColor()
{
WaitUntil waitForFlag = new WaitUntil( () => doChangeColor);
while (true)
{
yield return waitForFlag;
Debug.Log("Hello");
color = Random.Range(1, 5);
// switch for neater code
switch (color)
{
case 2:
mySprite.color = Color.blue;
break;
case 3:
mySprite.color = Color.red;
break;
case 4:
mySprite.color = Color.yellow;
break;
}
yield return new WaitForSeconds(delaySeconds);
}
}
}
``` |
38,739,314 | Is there any way in JavaScript to determine the clicked position within the element or distance from left, right or center? I am not able to determine the position (left, center or right) of clicked area.
[![enter image description here](https://i.stack.imgur.com/8bpwe.png)](https://i.stack.imgur.com/8bpwe.png)
I have following table -
```
<tr id="ing-117">
<td style="width: 15%; vertical-align: middle; display: none;"><img src="arrow-left.png" class="arrow left hidden"></td>
<td style="width: 70%; text-align: left;" class="txt center lefted"><div class="in"></div>2 cups ice</td>
<td style="width: 15%; vertical-align: middle;"><img src="arrow-right.png" class="arrow right hidden"></td>
</tr>
```
and here is my js code -
```
$('.arrow').unbind('click')
.bind('click', function(event, is_triggered){
var th = $(this);
var x = event.clientX;
var y = event.clientY;
console.log(x , y);
```
but when I click on 2nd `<td>` it prints `undefined undefined` in console
Please help, Thanks. | 2016/08/03 | [
"https://Stackoverflow.com/questions/38739314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311999/"
] | You can retrieve the `offsetX` and `offsetY` properties from the click event that's passed to the click handler. Try this:
```js
$('div').click(function(e) {
var clickX = e.offsetX;
var clickY = e.offsetY;
$('span').text(clickX + ', ' + clickY);
});
```
```css
div {
width: 150px;
height: 25px;
border: 1px solid #000;
background-color: #EEF;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<span></span>
```
---
*Update*
The edited code in your question should work fine (even though you should be using `off()` and `on()` instead of `unbind()` and `bind()`). Have you checked the console for errors?
```js
$('.arrow').off('click').on('click', function(e) {
var th = $(this);
var x = e.clientX;
var y = e.clientY;
console.log(x, y);
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="ing-117">
<td style="width: 15%; vertical-align: middle; display: none;">
<img src="arrow-left.png" class="arrow left hidden">
</td>
<td style="width: 70%; text-align: left;" class="txt center lefted">
<div class="in"></div>
2 cups ice
</td>
<td style="width: 15%; vertical-align: middle;">
<img src="arrow-right.png" class="arrow right hidden">
</td>
</tr>
</table>
``` |
16,302,627 | I'm trying to get geolocation inside a webview in a Chrome Packaged App, in order to run my application properly. I've tried several ways to get the permission in manifest.json and injecting scripts, but it doesn't work and doesn't show any error message.
Could someone give me a light or a solution to get permission and show my geolocation? | 2013/04/30 | [
"https://Stackoverflow.com/questions/16302627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2336264/"
] | Some features that usually require permissions in a normal web page are also available in a webview. However, instead of the normal popup "the website xyz.com wants to know your physical location - allow / deny", the app that contains the webview needs to explicitly authorize it. Here is how it works:
* No need to change the web page inside the webview;
* In the app, you listen for `permissionrequest` events on the `<webview>` element:
```js
webview.addEventListener('permissionrequest', function(e) {
if ( e.permission === 'geolocation' ) {
e.request.allow();
} else {
console.log('Denied permission '+e.permission+' requested by webview');
e.request.deny();
}
});
```
One thing to note is that the request doesn't need to be handled immediately. You can do whatever you need to do before allowing or denying, as long as you call `preventDefault` in the permissionrequest event and keep the event object from being garbage collected. This is useful if you need to do any async operation, like going to a storage to check if the URL requesting a permission should be allowed or not.
For example:
```js
webview.addEventListener('permissionrequest', function(e) {
if ( e.permission === 'geolocation' ) {
// Calling e.preventDefault() is necessary to delay the response.
// If the default is not prevented then the default action is to
// deny the permission request.
e.preventDefault();
setTimeout(function() { decidePermission(e); }, 0);
}
});
var decidePermission = function(e) {
if (e.url == 'http://www.google.com') {
e.request.allow();
}
// Calling e.request.deny() explicitly is not absolutely necessary because
// the request object is managed by the Javascript garbage collector.
// Once collected, the request will automatically be denied.
// If you wish to deny immediately call e.request.deny();
}
```
* Also note that your app needs to also request the respective permission:
```json
"permissions": ["geolocation"],
```
The [webview sample](https://github.com/GoogleChrome/chrome-app-samples/blob/master/webview/index.js#L61-L72) has more code for other permissions, like pointerLock and media capture. |
1,765,171 | I know that you are supposed to use `0` instead of NULL in c++ (even though `NULL` is defined as `0` in C++ most of the time).
Recently I came across some code where `0x0` was used instead, though.
What is the difference? | 2009/11/19 | [
"https://Stackoverflow.com/questions/1765171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199637/"
] | `0x0` is just `0` written in hexadecimal notation. There is no difference between the two:
>
> 016 = 010 :)
>
>
>
`NULL` is usually `#define`d to `0` somewhere and does the same thing. |
22,012 | How can I create a photo that would blur the layers behind it in Photoshop? I need this for my website and I'll explain it a bit more below...
So lets say that I've got a background layer in Photoshop of Mario.
I create a new layer and create an image that will blur the background of Mario.
How can I create that "blur-image"?
Thanks! | 2012/04/02 | [
"https://photo.stackexchange.com/questions/22012",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/9259/"
] | I would like to question your description: "just went there, saw the scene, clicked the photo and returned home". You could describe this way every possible human activity, and it also has a literary value (Caesar's "Veni, vidi, vici") but reality is a bit different.
To just "go there" he had to walk around, in search, spending maybe hours. One cannot simply study the travel directions from google maps or whatever, get up from the computer and go straight to the point.
Regarding "seeing the scene": that's the whole point of photography. You visualize and capture something, and maybe a lot of people had seen the same thing a lot of times but didn't think/were able to capture it. Consider the title of Freeman's books: "The photographer's eye", "The photographer's mind"... how many times a mundane subject becomes a great photo? He had to find a good point of view (For example I am always left with the feeling that I have missed something, that it was possible to do better, to be more incisive...)
Regarding "clicking the photo": he had to find the right balance to achieve what he wished. And maybe he was carring a tripod all along in his walk in the trees.
So, it's not at all so easy. Your question seems to imply that since nature is so beautiful, taking a beautiful shot is "easy". But taking a shot always requires your point of view (and your opinion about picking one subject rather than another). And it requires your photographic skills, just like other (maybe much more controlled, e.g. in studio) kinds of photography. |
11,356,525 | I am new to Ruby and just can't figure out how you take input for an array from a user and display it.If anyone could clear that I can add my logic to find the biggest number.
```
#!/usr/bin/ruby
puts "Enter the size of the array"
n = gets.chomp.to_i
puts "enter the array elements"
variable1=Array.new(n)
for i in (0..n)
variable1[i]=gets.chomp.to_i
end
for i in (0..n)
puts variable1
end
``` | 2012/07/06 | [
"https://Stackoverflow.com/questions/11356525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337742/"
] | How about capturing the array in one line?
```
#!/usr/bin/ruby
puts "Enter a list of numbers"
list = gets # Input something like "1 2 3 4" or "3, 5, 6, 1"
max = list.split.map(&:to_i).max
puts "The largest number is: #{max}"
``` |
46,224,609 | Here, I have initialized array like this :
```
#include <stdio.h>
int main()
{
int a[10] = {1, 2, 3, [7] = 4, 8, 9};
printf("a[7] = %d\na[8] = %d\na[9] = %d\n", a[7], a[8], a[9]);
return 0;
}
```
**Output :**
```
a[7] = 4
a[8] = 8
a[9] = 9
```
Here, I have selected array index `7` as a `a[7] = 4` and thereafter added some elements. Then print array elements of index `7`, `8` and `9` and print correctly.
So, Is it correct output of index `8` and `9` without explicitly defined it?
Why sequence does not start from index `3`? | 2017/09/14 | [
"https://Stackoverflow.com/questions/46224609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> *Why sequence does not start from index 3?*
>
>
>
because, that's not how it works!!
Quoting `C11`, chapter §6.7.9 for *designated initializer* (*emphasis mine*)
>
> Each brace-enclosed initializer list has an associated current object. When no
> designations are present, subobjects of the current object are initialized in order according
> to the type of the current object: array elements in increasing subscript order, structure
> members in declaration order, and the first named member of a union.148) . In contrast, a
> designation causes the following initializer to begin initialization of the subobject
> described by the designator. **Initialization then continues forward in order, beginning
> with the next subobject after that described by the designator.**149)
>
>
>
Thus, in your case, after the designator `[7]`, the remaining two elements in the brace enclosed list will be used to initialize the next sub-objects, array elements in index `8` and `9`.
Just to add a little more relevant info,
>
> If a designator has the form
>
>
>
> ```
> [ constant-expression ]
>
> ```
>
> then the current object (defined below) shall have array type and the expression shall be
> an integer constant expression. [...]
>
>
> |
39,586,769 | How to recover the forgotten password through Firebase?I'm creating an app by suing Firebase and I am getting the problem to recover the password. | 2016/09/20 | [
"https://Stackoverflow.com/questions/39586769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5474261/"
] | Send a password reset email
You can send a password reset email to a user with the sendPasswordResetEmail method. For example:
```
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = "user@example.com";
auth.sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
```
You can customize the email template that is used in Authentication section of the Firebase console, on the Email Templates page. See Email Templates in Firebase Help Center.
You can also send password rest emails from the Firebase console. |
10,230,796 | i tried to use the most of the correct answers suggested by the users to adjust the brightness of the iphone (ie `[[UIScreen mainScreen]setBrightness:0.0];`) but the simulator didn't change its brightness. Is iphone simulator's brightness adjustable? | 2012/04/19 | [
"https://Stackoverflow.com/questions/10230796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344237/"
] | The iPhone simulator brightness is not adjustable, you have to try in a real device! |
18,242,058 | I have the following CSS code which is suppose to display one CSS if the browser is IE and display another CSS if the browser is !IE:
```
<!--[if !IE]-->
<style>
.img404 {
display:none;
}
#textd {
font-size: 14pt;
color: #ffffff;
text-shadow: 0 1px 0 #ccc,
0 2px 0 #c9c9c9,
0 3px 0 #bbb,
0 4px 0 #b9b9b9,
0 5px 0 #aaa,
0 6px 1px rgba(0,0,0,.1),
0 0 5px rgba(0,0,0,.1),
0 1px 3px rgba(0,0,0,.3),
0 3px 5px rgba(0,0,0,.2),
0 5px 10px rgba(0,0,0,.25),
0 10px 10px rgba(0,0,0,.2),
0 20px 20px rgba(0,0,0,.15);
}
</style>
<!--[endif]-->
<!--[if IE]>
<style>
.img404 {
display:none;
}
#textd {
font-size: 14pt;
}
</style>
<![endif]-->
```
Only the IE one works. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18242058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2654679/"
] | If you want the non-IE css to be used, you need to stop it from being commented out:
```
<!--[if !IE]-->
Non-IE CSS
<!--<![endif]-->
<!--[if IE]>
IE only CSS
<![endif]-->
```
Notice that `<!--[if IE]>` doesn't have a trailing pair of dashes - to any browsers except IE, this will be interpreted as the opening of a comment, which is then closed later by `<![endif]-->`.
Conversely, `<!--[if !IE]-->` is a standard, self-closing comment (as is `<!--<![endif]-->`). Any code between these lines will be processed by any browser except IE. |
14,508 | Say I have a matrix of:
```
tmp1 = 5;
tmp2 = 5;
tmp3 = RandomChoice[{0, 1, 2, 3, 4, 5}, {tmp1, tmp2}];
MatrixForm[tmp3]
```
How to do a conditional operation of elements - 1 if non-zero, else do nothing, as in the attached:![enter image description here](https://i.stack.imgur.com/Q94EO.png). Maybe using Positive? | 2012/11/13 | [
"https://mathematica.stackexchange.com/questions/14508",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/4319/"
] | You have lots of options. Among them `Replace`:
```
Replace[tmp3, x : Except[0] :> x - 1, {2}]
```
And numerically for the entire matrix:
```
tmp3 - Unitize[tmp3]
``` |
131,214 | I've noticed my Sims seem to earn a *lot* more money when gardening than they do at their day jobs. After crunching the numbers, I found out this wasn't just an illusion - depending on the crop of choice, a Sim can earn money two to three times faster with gardening than they can at an entry-level day job with roughly the same amount of player effort. If the player has time to devote to constantly refreshing crops that have shorter growing cycles, much higher rates are easily possible!
Of course, the Sims do advance in their careers and so can earn more money with their day jobs. But, by the time that's achieved, the player can just as quickly have reached a level where even higher-yield low-effort crops are available.
So, where's the real incentive for the Sims to get a job? Is it just a matter of player preference and role-play, or are there other benefits in the game's mechanics that I'm just not seeing yet? | 2013/09/18 | [
"https://gaming.stackexchange.com/questions/131214",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/6274/"
] | You are correct in that past updates of the game gardening, baking and certain hobbies were much more efficient in payout rate than careers. However, with the most current update (version 5.12.0) after all of the milestone quests and challenges, careers finally make as much, if not more, money. Here are the numbers to back this up.
Here are the rates for gardening and baking, sorted by highest to lowest rate per minute. This is assuming you purchase seeds and ingredients at the grocery store to procure the lowest price.
**Gardening**
Bell Pepper: §8.00 / minute
Carrots: §5.80 / minute
Corn: §4.50 / minute
Watermelons: §2.53 / minute
Potato: §2.17 / minute
Zucchini: §1.75 / minute
Onions: §1.61 / minute
Beans: §1.36 / minute
Hamburger: §0.63 / minute
Garlic: §0.36 / minute
Pumpkin: §0.35 / minute
Chilli Pepper: §0.18 / minute
**Baking**
Hot Cross Buns: §1.50 / minute
Cookies: §1.00 / minute
Heart-Shaped Chocolates: §0.75 / minute
Pancakes: §0.60 / minute
Apple Pie: §0.45 / minute
Muffins: §0.43 / minute
Choc Pudding: §0.25 / minute
Cheesecake: §0.17 / minute
Gingerbread Sims: §0.14 / minute
Caramel Slice: §0.12 / minute
Croissants: §0.10 / minute
Danish: §0.10 / minute
Turkey: §0.08 / minute
Pumpkin Pie: §0.03 / minute
This doesn't include transgenic crops or bakery items, which have a failure rate of somewhere around 50%, so in the long run those don't necessarily pay off. The quickest crops and baked goods in general have the best rate.
At the highest level (5), here are the equivalent rates for working at a career, sorted by highest to lowest pay rate.
**Careers**
Actor: (5 hours) §6.20 / minute
Real Estate Agent: (5 hours) §5.08 / minute
Athlete: (6 hours) §5.00 / minute
Musician: (7 hours) §4.17 / minute
Teacher: (5 hours) §3.48 / minute
Politician: (6 hours) §3.39 / minute
Artist: (7 hours) §3.00 / minute
Scientist: (8 hours) §3.00 / minute
Fire Fighter: (9 hours) §2.78 / minute
The added benefit to having a career comes when there are particular goals that are career related (such as, send 5 Sims to work, or start a career as a politician) or in order to fulfill life-dreams for orbs. In the case of orbs, career life-dreams are much more efficient than many of the other life-dreams, and still enable your Sim to have time to partake in other hobbies and/or gardening or baking when they're not at work.
As you can see, the careers aren’t necessarily much more time-efficient than gardening, however, unless you want to spend 30-second intervals gardening, you are better off having your sims go to a career. They will also make more money at a career while you’re sleeping than doing a several hour gardening task.
**All of this information is subject to change with future game updates.** |
46,129 | I have a pretty bad ant infestation. I think the little critters are Argentine ants. I've used a couple of bottles of Terro (I usually put down about a quarter bottle at a time). It does slow them down, but they come right back not after not too long.
I have been thinking about using an aerosol insecticide. The stuff I have has imiprothrin and cypermethrin as active ingredients. The are supposed to be good enough that I can just spray on their trails, and they'll die if they walk over the sprayed areas.
The problem is the location of the trail. They're coming out from a space between the baseboard heater and the wall's outer finish.
Can I spray the baseboard heater? I'm not worried about fires, but I'd really hate for the insecticide to start outgassing when the heaters get turned on this winter. | 2014/07/13 | [
"https://diy.stackexchange.com/questions/46129",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/21348/"
] | You should lay a bait down. I recommend Advion, which is a product from DuPont or MaxForce, which uses fipronil. You can do a search on Amazon or a similar site for "Advion ant" or "MaxForce ant". The bait comes in a plunger that you can use to apply in small places. Find out where they are trailing and put a few drops down. You can put the drops on paper if you are worried about your finish. Every day (or couple of hours if you have a bad infestation) check to see if the bait's gone and reapply. It may take a couple of weeks to kill them all.
As far as Terro goes, I haven't had much luck with it either. The attractant in Terro's all sugar-based from my understanding. The ants may be feeding on Protein now. |
29,540,765 | Google sends many people to my website using the translator. It is not needed. Therefore, when someone arrives, it looks like this:
```
http://translate.google.com/translate?hl=en&sl=de&u=http://stackoverflow.com
```
The site functions OK but not 100% like it should.
I would prefer to have an `index.php` (or HTML) file that is a redirect to the main URL. It should target and replace the entire window (removing any reference to Google Translate).
I tried different variations of the below but it did not work.
```
<META http-equiv="refresh" content="0;URL=http://www.domain.com" target="_new">
```
\_parent and \_top were tried.
Can you please help with this? | 2015/04/09 | [
"https://Stackoverflow.com/questions/29540765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333291/"
] | This should redirect to example.com if it accessed via iframe, which is how translator do it.
```
<script type="application/javascript">
if (window.parent && window.parent !== window) {
window.parent.location = '//example.com';
}
</script>
``` |
100 | As you all know, Help Center will be a general guidance to all current and future users.
[What topics can I ask about here?](https://korean.stackexchange.com/help/on-topic) in Help Center needs filling in. I think the linked question should be basis for our guidance on on-topic questions. [What should be on-topic here?](https://korean.meta.stackexchange.com/questions/9/what-should-be-on-topic-here)
Japanese SE, [What topics can I ask about here?](https://japanese.stackexchange.com/help/on-topic)
English Language and Usage SE, [What topics can I ask about here?](https://english.stackexchange.com/help/on-topic)
Portuguese Language Beta SE, [What topics can I ask about here?](https://portuguese.stackexchange.com/help/on-topic)
Portuguese SE is the newest language site on SE and I think it has an excellent page for on-topic questions.
I think we can get some ideas and start to draft it here until the page is completed. Any thought or suggestions? | 2016/09/23 | [
"https://korean.meta.stackexchange.com/questions/100",
"https://korean.meta.stackexchange.com",
"https://korean.meta.stackexchange.com/users/-1/"
] | Version 2
---------
>
> What topics can I ask about here?
> ---------------------------------
>
>
> * Word choice and usage, grammar, and pronunciation, including dialect differences
> * Korean linguistics, orthography (spelling, punctuation) or etymology
> * Specific problems encountered by people learning Korean
> * The meanings of words or expressions in context (if not clear from their dictionary definitions)
> * Questions on Korean culture that are relevant to language and communication
> * Help with usage of language in real-life contexts, such as asking about the meaning of a difficult Korean sentence, or how to express a
> specific idea in idiomatic Korean
>
>
> Please make your question as clear as possible, with any necessary
> **context, examples and references**, and any **research already done.**
>
>
> Is there anything I should not ask?
> -----------------------------------
>
>
> **Please avoid the following types of questions**, which are outside the scope of this site:
>
>
> * Simple general reference questions and character recognition requests that can be answered by a resource such as a dictionary
> (although requests for help and clarification *after* consulting a
> resource may be acceptable)
> * Requests for translation and proofreading that contain no particular question about the Korean language
> * Questions about Korean Culture that do not concern the Korean language itself
> * Questions that ignore the advice on the [don't ask](https://korean.stackexchange.com/help/dont-ask) page
>
>
> Should I write in Korean or English?
> ------------------------------------
>
>
> Both languages are accepted. When answering a question, we encourage you to answer in the language of the question, if you are able. Don't
> worry about making a few mistakes: other community members can help
> with corrections if you are not as strong in that language.
>
>
> All [tags](https://korean.stackexchange.com/tags) should be in English unless there is no English
> equivalent for a concept; in those cases, Korean is accepted.
>
>
> |
40,543,929 | I have an table which is filled with values using ng-repeat. I need to color the rows of table alternatively with green and yellow color. I tried it out the following way without ng-repeat and it works.
```css
.table-striped>tbody>tr:nth-of-type(odd)
{
background: yellow !important;
}
.table-striped>tbody>tr:nth-of-type(even)
{
background: green !important;
}
```
```html
<html>
<div><table class="table table-striped">
<thead style="border: 1px solid">
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{value.val1}}</td>
</tr>
<tr>
<td>{{value.val2}}</td>
</tr>
<tr>
<td>{{value.val3}}</td>
</tr>
</tbody>
</table>
</div>
<html>
```
But it is not working while using ng-repeat as follows(all rows are in yellow itself). Please help.Thanks in advance.
```css
.table-striped>tbody>tr:nth-of-type(odd)
{
background: yellow !important;
}
.table-striped>tbody>tr:nth-of-type(even)
{
background: green !important;
}
```
```html
<html>
<div><table class="table table-striped">
<thead style="border: 1px solid">
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody ng-repeat="value in values">
<tr>
<td>{{value.val1}}</td>
</tr>
</tbody>
</table>
</div>
<html>
``` | 2016/11/11 | [
"https://Stackoverflow.com/questions/40543929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5702263/"
] | You can add a class to your rows dynamically and then give the style you want.
```
<tr class="myrow">
$(".myrow:odd").addClass("odditem");
$(".myrow:even").addClass("evenitem");
``` |
9,969,202 | I am having trouble creating an entity using inout ports. I tried writing the following code where A is an input and B is an output and it works fine. But as soon as I change A to an inout port, it implements but it won't simulate. Can anyone tell me what the problem is?
```
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity Problem2 is
Port ( A : inout integer;
B : out integer
);
end Problem2;
architecture Behavioral of Problem2 is
procedure change (signal A: inout integer; signal B: out integer) is
begin
B<=A after 20 ns;
end change;
begin
change(A=>A, B=>B);
end Behavioral;
``` | 2012/04/01 | [
"https://Stackoverflow.com/questions/9969202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212426/"
] | The procedure "change" is a driver on A, but doesn't explicitly drive anything, so A will be driven to 'U'. Try this change which should do what you seem to expect:
```
procedure change (signal A: inout integer; signal B: out integer) is
begin
A <= 'Z';
B <= A after 20 ns;
end change;
``` |
5,623,624 | ```
package com.owen.quartergames.dao;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import com.owen.quartergames.R;
import com.owen.quartergames.domain.LogEntry;
public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
FishLoggerDao {
private static final String DB_NAME = "fishingLog";
private static final String TABLE_NAME = "LogEntries";
private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";
private static final String FIND_LOG_ENTRY_SQL = "SELECT _id, Longitude, Latitude FROM LogEntries WHERE _id = ?";
private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";
private static final String[] NO_ARGS = {};
private Context context;
private final SQLiteDatabase db = getWritableDatabase();
public SqlLiteFishLoggerDao(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
@Override
public void deleteLogEntry(String id) {
id = "0";
db.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
// int deleted = db.delete(TABLE_NAME, "_id = ?",
// new String[] { id.trim() });
// Log.i("fishlogger", String.format("Delete %d rows", deleted));
db.close();
}
@Override
public LogEntry findEntry(String id) {
Cursor cursor = db.rawQuery(FIND_LOG_ENTRY_SQL, new String[] { id });
if (!cursor.moveToFirst()) {
return null;
}
LogEntry entry = new LogEntry();
entry.setId(id);
entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
entry
.setLongitude(cursor.getDouble(cursor
.getColumnIndex("Longitude")));
cursor.close();
db.close();
return entry;
}
@Override
public void insertLogEntry(LogEntry entry) {
ContentValues values = new ContentValues();
values.put("Latitude", entry.getLatitude());
values.put("Longitude", entry.getLongitude());
values.put("PictureURL", entry.getPictureUrl());
values.put("SizeOrWeight", entry.getSizeOrWeight());
values.put("CreateDate", entry.getEntryDate());
values.put("Species", entry.getSpecies());
db.insertOrThrow("LogEntries", null, values);
db.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
String s;
try {
Toast.makeText(context, "1", 2000).show();
InputStream in = context.getResources().openRawResource(R.raw.sql);
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in, null);
NodeList statements = doc.getElementsByTagName("statement");
for (int i = 0; i < statements.getLength(); i++) {
s = statements.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
} catch (Throwable t) {
Toast.makeText(context, t.toString(), 50000).show();
}
Log.e("DB", "DB Created");
}
@Override
public List<LogEntry> findAllEntries() {
List<LogEntry> entries = new ArrayList<LogEntry>();
Cursor cursor = db.rawQuery(FIND_ALL_ENTRIES_SQL, NO_ARGS);
int entryDateCol = cursor.getColumnIndex("CreateDate");
int speciesCol = cursor.getColumnIndex("Species");
int sizeCol = cursor.getColumnIndex("SizeOrWeight");
int latCol = cursor.getColumnIndex("Latitude");
if (cursor.moveToFirst()) {
do {
LogEntry entry = new LogEntry();
entry.setEntryDate(cursor.getString(entryDateCol));
entry.setSpecies(cursor.getString(speciesCol));
entry.setSizeOrWeight(cursor.getString(sizeCol));
entry.setLatitude(cursor.getDouble(latCol));
if (entry.getSpecies() == null) {
entry.setSpecies("Not Entered");
}
if (entry.getSizeOrWeight() == null) {
entry.setSizeOrWeight("Not entered");
}
entries.add(entry);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return entries;
}
@Override
public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(getWritableDatabase());
}
}
```
basically the delete doesnt work however i think the problems stems from the findAllEntries() method. the reason i say that is that i get "leak found" errors in log cat saying the db was created but never closed. i have throughly searched the internet and have asked friends who code but no luck in solving the problem. all my cursors are closed and from what i can tell this is how a sqlliteopenhelper should generally look like.
thanks for any responses | 2011/04/11 | [
"https://Stackoverflow.com/questions/5623624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/530933/"
] | Your `getReadableDatabase()` opens a DB for read. To avoid leaks, you need to close it after your work is done.
```
final db = getReadableDatabase();
//do the things
db.close();
```
The same with `getWritableDatabase()`. |
45,501,245 | I'm looking for a way to inject a custom script into the `_Layout.cshtml` purely from code. `_Layout.cshtml` cannot know anything about it. Just like [Browser Link](https://learn.microsoft.com/en-us/aspnet/core/client-side/using-browserlink) does it.
You simple write this:
```
app.UseBrowserLink();
```
And this gets injected into the body at runtime.
```
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"requestId":"a717d5a07c1741949a7cefd6fa2bad08","requestMappingFromServer":false}
</script>
<script type="text/javascript" src="http://localhost:54139/b6e36e429d034f578ebccd6a79bf19bf/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
```
There is no sign of it in `_Layout.cshtml`.
Unfortunately Browser Link isn't open source so I can't see how they have implemented it. [Browser Link source now available](https://github.com/aspnet/BrowserLink)
So I was wondering how it was done? | 2017/08/04 | [
"https://Stackoverflow.com/questions/45501245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220627/"
] | It's not open source, but you can easily decompile it to see how it works.
From a comment in the source code:
>
> This stream implementation is a passthrough filter. It's job is to add links to the Browser Link connection scripts at the end of HTML content. It does this using a connection to the host, where the actual filtering work is done. If anything goes wrong with the host connection, or if the content being written is not actually HTML, then the filter goes into passthrough mode and returns all content to the output stream unchanged.
>
>
>
The entire thing seems pretty involved, but doesn't seem to use anything not available out of the box, so I guess it can be possible to code a similar thing. |
30,138,707 | My program reads a text file and lists the frequencies of each word in the file. What I need to do next, is ignore certain words such as 'the','an' when reading the file. I have a created a list of these words but not sure how to implement it in the while loop. Thanks.
```
public static String [] ConnectingWords = {"and", "it", "you"};
public static void readWordFile(LinkedHashMap<String, Integer> wordcount) {
// FileReader fileReader = null;
Scanner wordFile;
String word; // A word read from the file
Integer count; // The number of occurrences of the word
// LinkedHashMap <String, Integer> wordcount = new LinkedHashMap<String, Integer> ();
try {
wordFile = new Scanner(new FileReader("/Applications/text.txt"));
wordFile.useDelimiter(" ");
} catch (FileNotFoundException e) {
System.err.println(e);
return;
}
while (wordFile.hasNext()) {
word = wordFile.next();
word = word.toLowerCase();
if (word.contains("the")) {
count = getCount(word, wordcount) + 0;
wordcount.put(word, count);
}
// Get the current count of this word, add one, and then store the
// new count:
count = getCount(word, wordcount) + 1;
wordcount.put(word, count);
}
}
``` | 2015/05/09 | [
"https://Stackoverflow.com/questions/30138707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4879722/"
] | Create one list which will have list of word need to ignore as:
```
List<String> ignoreAll= Arrays.asList("and","it", "you");
```
then in while loop add one condition that will ignore the word contains these words as
```
if(ignoreAll.contains(word)){
continue;
}
``` |
57,744,030 | How is the accuracy calculated when the problem is a regression one?
I'm working on a regression problem to predict how much electricity each user USES each day,I use keras build a LSTM model to do this time series prediction. At the beginning, I use the 'accuracy' as the metrics, and when run
```
model.fit(...,verbose=2,...)
```
`val_acc` has a value after every epoch. And in my result, the value doesn't change, it's always the same value.
Then I realized that the regression problem was that there was no concept of accuracy, and then I started to wonder, how is that accuracy calculated?
I have a guess that when metrics is 'accuracy' in the regression question, accuracy is also calculated in a similar way to the classification problem: the number of predicted values equal to true values divided by the total sample size.
Am I right? | 2019/09/01 | [
"https://Stackoverflow.com/questions/57744030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7827820/"
] | Only enabling authentication would not solve the problem, as a crawler, or worse a malicious port scanner, would still deduct that `{"error":{"root_cause":[{"type":"security_exception...",` is a response from an Elasticsearch cluster and could still exploit well-known [Elasticsearch security vulnerabilities](https://www.cvedetails.com/vulnerability-list/vendor_id-13554/Elasticsearch.html).
If I was to create a malicious port scanner, I would not only query `/` but also very well known [API endpoints](https://www.elastic.co/guide/en/elasticsearch/reference/current/rest-apis.html).
So in order to achieve what you need, you need both:
* **authentication**: to prevent anyone from freely accessing your cluster and doing any damage to your data
* **a reverse proxy solution**: to return whatever Elastic-agnostic response content you want to trump whoever is trying to reach your cluster |
4,292,758 | How can I specify the auto-increment value of a primay key column? I would like to initialize it to 18. | 2010/11/27 | [
"https://Stackoverflow.com/questions/4292758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417798/"
] | You can change the value of AUTO\_INCREMENT:
```
ALTER TABLE tbl AUTO_INCREMENT = 18;
```
It can also be set to an initial value in the table create statement.
```
CREATE TABLE test1
(
x INT PRIMARY KEY AUTO_INCREMENT,
y VARCHAR(100)
)
AUTO_INCREMENT = 18;
```
See the documentation for [CREATE TABLE](http://dev.mysql.com/doc/refman/5.1/en/create-table.html) and [ALTER TABLE](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html). |
9,359,401 | As of jQuery 1.7 `.live` has been deprecated and replaced with `.on`. However, I am having difficulty getting jQuery `.on` to work with `event.preventDefault();`. In the below example, clicking the anchor tag takes me to the linked page instead of preventing the default browser action of following the link.
```
jQuery('.link-container a').on('click', function(event) {
event.preventDefault();
//do something
});
```
However, the same code with `.live` works without any hiccups.
```
jQuery('.link-container a').live('click', function(event) {
event.preventDefault();
//do something
});
```
I am using jQuery version 1.7.1 that ships with Wordpress 3.3.1 currently. What have I got wrong here? | 2012/02/20 | [
"https://Stackoverflow.com/questions/9359401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213627/"
] | You're not binding it correctly. The `.on()`-method works like a `.delegate()` when doing what you want to do. Here's an example of proper usage:
```
$('.link-container').on('click', 'a', function(event){
event.preventDefault();
})
```
This is assuming that .link-container is there on page load, and isn't dynamically loaded. You need to bind the delegate method to the closest ancestor that's statically there, and in the second argument, in this case `'a'`, specify what items the delegate method applies to.
Just using `$('selector').on('click', function() { })` gives exactly the same result as using `$('selector').click(function(){ })`
Here's an example on jsfiddle: <http://jsfiddle.net/gTZXp/> |
13,765 | I currently have a paper submitted to [*PNAS*](http://www.pnas.org). We had two rounds of revisions, and following detailed suggestions from one reviewer, we have improved our proposed algorithm a lot: its complexity is now significantly lower, and the idea he suggested makes the overall method more robust in handling noisy signal.
I feel that this reviewer's contribution extend far beyond his original role, so much that I feel it would be ethically honest to have him as a co-author. To be crystal-clear: if he was not a reviewer, but a colleague with whom I had discussed this before submitting the paper, he would clearly be entitled to authorship, no question.
But… he *is* a reviewer, so I am wondering how (if at all) we should ask him to join as co-author. Right now, I am ready to submit the twice-revised manuscript, and I have no doubt that it will be accepted (second review was “minor revisions”). The options I can see are:
* In my cover letter for the revised manuscript, explain the situation to the editor and ask him if he could (with the reviewer's agreement) lift anonymity and allow the authors' list change.
* Wait for the manuscript to be formally approved, and only then write to the editor asking for the same thing.
* Do nothing, for example because it is frowned upon. This would pain me greatly, because the reviewer really contributed very significantly to the algorithm, and I believe he should be able to claim authorship for this contribution (if he sees it fit).
So, what are accepted practices? How should I handle this matter? | 2013/10/31 | [
"https://academia.stackexchange.com/questions/13765",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/2700/"
] | Seconding other comments and answers: surely no one would be *offended* if you tried to make such an offer...
However, as already noted, if your offer is made prior to final acceptance, it might be misinterpreted, as your trying to clinch acceptance.
And that possibility surely has to be systematically excluded, so a foresightful editor and/or journal would surely not want to set such a *precedent*. A journal would not want authors to (be able to) solicit reviewers as co-authors, since this would create a conflict-of-interest situation, and cast doubt on the general validity and impartiality of their refereeing process!
That is, while it would be weird and awkward to publicly state such a policy, I would anticipate that the journal/editor would object *as a matter of principle*, to putting the reviewer on as a co-author.
Sensible reviewers would also understand this situation, for similar reasons, and *in advance* would expect no reward beyond "job well done". Even the anonymity of the referee should be maintained, as a matter of principle. Thus, we do often find effusive thanks to "the anonymous referee"... |
70,134,882 | Why my component didn't do the render again when I setState inside my useEffect ? I read on google that the component is render another time if I setState inside the useEffect
My code :
```
export default function CarouselMusicGenres() {
const [musicGenres, setMusicGenres] = useState(null)
const setAllMusicGenres = () => {
MusicGenresAPI.getAll()
.then((response) => {
if (response.status === 200) {
setMusicGenres(response.data.musicGenres)
}
})
.catch((error) => {
console.log(error)
})
}
const displayAllMusicGenres = () => {
if (musicGenres && musicGenres.length > 0) {
musicGenres.forEach((musicGenre) => {
return (
<SwiperSlide>
<Col
className="genre"
style={{
backgroundImage: `url(/assets/images/music-genres/${musicGenre.image_background_url})`,
}}
>
<span>{musicGenre.genre}</span>
<div className="transparent-background"></div>
</Col>
</SwiperSlide>
)
})
}
}
useEffect(() => {
setAllMusicGenres()
}, [])
return (
<Row className="carousel-genres">
<Swiper spaceBetween={10} slidesPerView={6}>
{displayAllMusicGenres()}
</Swiper>
</Row>
)
}
```
I try someting like that instead useEffect but still don't work
```
if (!musicGenres) {
setAllMusicGenres()
}
```
**Problem Fixed**
I need to use map instead foreach to get the array returned and add return before my musicGenres.map | 2021/11/27 | [
"https://Stackoverflow.com/questions/70134882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12938865/"
] | Considering that you're `going to have maybe another 5 environments eventually`, I tried to write something that will scale well:
```kotlin
enum class Env { Test, Sit }
data class ImageVersions(val apiName: String, val versions: Map<Env, String?>)
fun String.getNameAndVersion() = substringBefore(':') to substringAfter(':')
fun getVersions(envMap: Map<Env, List<String>>): List<ImageVersions> {
val envApiNameMap = envMap.mapValues { it.value.associate(String::getNameAndVersion) }
val allApiNames = envApiNameMap.flatMap { it.value.keys }.distinct()
return allApiNames.map { apiName ->
ImageVersions(apiName, envApiNameMap.mapValues { it.value[apiName] })
}
}
```
[Playground example](https://pl.kotl.in/GBjmCKuPp)
* So instead of separate `val testPodVersion: String, val sitPodVersion: String`, here you have a map. Now the structure of `ImageVersions` always remains the same irrespective of how many environments you have.
* `getNameAndVersion` is a helper function to extract apiName and version from the original string.
* `getVersions` accepts a list of versions corresponding to each environment and returns a list of `ImageVersions`
* `envApiNameMap` is same as `envMap` just that the list is now a map of apiName and its version.
* `allApiNames` contains all the available apiNames from all environments.
* Then for every `apiName`, we take all the versions of that `apiName` from all the environments.
In future, if your have another environment, just add it in the `Env` enum and pass an extra map entry in the `envMap` of `getVersions`. You need not modify this function every time you have a new environment. |
57,512 | Why must a יולדת bring a sin offering? What does she need כפרה for?
As it says in Vayikra 12:6-7:
>
> וּבִמְלֹאת יְמֵי טָהֳרָהּ לְבֵן אוֹ לְבַת תָּבִיא כֶּבֶשׂ בֶּן שְׁנָתוֹ לְעֹלָה וּבֶן יוֹנָה אוֹ תֹר לְחַטָּאת אֶל פֶּתַח
> אֹהֶל מוֹעֵד אֶל הַכֹּהֵן
>
>
> 6 And when the days of her purification have been completed, whether for a son or for a daughter, she shall bring a sheep in its first year as a burnt offering, and a young dove or a turtle dove as a sin offering, to the entrance of the Tent of Meeting, to the kohen.
>
>
> וְהִקְרִיבוֹ לִפְנֵי יְהֹוָה וְכִפֶּר עָלֶיהָ וְטָהֲרָה מִמְּקֹר דָּמֶיהָ זֹאת תּוֹרַת הַיֹּלֶדֶת לַזָּכָר אוֹ לַנְּקֵבָה
>
>
> 7 And he shall offer it up before the Lord and effect atonement for her, and thus, she will be purified from the source of her blood. This is the law of a woman who gives birth to a male or to a female.
>
>
>
If you quote a commentary please explain what it means if you can. Thanks! | 2015/04/21 | [
"https://judaism.stackexchange.com/questions/57512",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/161/"
] | Firstly the Bartenura already explains that it doesn't mean that it fills the entire house. Rather (as opposed to other cases in the Chapter) **it means that the entire beehive is in the house, and it reaches from the floor to the roof**. Not that it fills the entire house from wall to wall:
>
> **הָיְתָה מְמַלְּאָה אֶת כָּל הַבַּיִת**. שֶׁכֻּלָּהּ בְּתוֹךְ הַבַּיִת לִפְנִים וְיוֹשֶׁבֶת עַל שׁוּלֶיהָ וּפִיהָ מַגִּיעַ לִשְׁמֵי קוֹרָה, שֶׁאֵין בֵּינָהּ לַתִּקְרָה פּוֹתֵחַ טֶפַח:
>
>
>
(In other cases the beehive is half inside and half outside, and the Din changes depending on which side its opening is, amongst other factors.)
Secondly, as the section you quoted already says, there is some space (but less than a Tefach) between the beehive and the roof. Enough space to get in a Kezayit of a corpse and introduce Tuma.
>
> וְאֵין בֵּינָהּ לְבֵין הַקּוֹרוֹת פּוֹתֵחַ טֶפַח
>
>
>
Thirdly, it's possible that the beehive was brought into the house with the Tuma already inside it. |
907,899 | Given two topological spaces $\left\langle X,\tau\right\rangle $, $\left\langle Y,\sigma\right\rangle$ and a function $X\overset{f}\longrightarrow Y$. Would someone please sketch a proof that
(1) $\quad$ For all sets $M\subset Y$, it holds that $x\in \overline{f^{-1}(M)}\Rightarrow f(x)\in \overline{M}$
is equivalent with that $f$ is continuous? | 2014/08/24 | [
"https://math.stackexchange.com/questions/907899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/171248/"
] | Assume that $f$ is continuous. We will argue by contradiction. Suppose $f(x)\notin \overline{M}.$ Then there exists an open set $V$ in $Y$ such that $f(x)\in V$ and $V\cap M=\emptyset.$ Since $f$ is continuous we have that $f^{-1}(V)$ is open. Moreover, $x\in f^{-1}(V)$ and $f^{-1}(V)\cap f^{-1}(M)=\emptyset.$ So, $x\notin \overline{f^{-1}(M)}.$
Conversely, assume that for any set $M\subset Y$ it is $x\in \overline{f^{-1}(M)}\Rightarrow f(x)\in \overline{M}.$ To show continuity it is enough to show that $\overline{f^{-1}(M)}$ is closed if $M$ is closed. So, assume $M$ is closed, that is, $M=\overline{M}.$ If $\overline{f^{-1}(M)}$ is not closed, then there exists $x\in \overline{f^{-1}(M)}$ such that $x\notin f^{-1}(M).$ But this is impossible since $f(x)\in \overline{M}=M.$ |
5,525,141 | I know this can be accomplished by Javascript, and I am learning so please tell me, when I click an update button I want the text from a textbox to be copied into another one. | 2011/04/02 | [
"https://Stackoverflow.com/questions/5525141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643660/"
] | ```
jQuery solution - check it out (jQuery that is)
$('#button').click(function(e) {
e.preventDefault();
$('#totextarea').val($('#fromtextarea').val());
...then submit the form if you wish to or whatever...
$('#theform').submit();
});
``` |
533,118 | I use `\setlist{wide}` with the package `enumitem` to unindent a subsequent line in an item in vertical (normal) lists. This no indentation rule is a publisher guideline that I cannot change.
The problem is when I write an *inline* list extra space between the label and the content of an item sometimes emerges. (Please see the MWE: there is apparent extra space between "1." and "The first thing...".)
How can I get rid of this extra space?
MWE:
[![extra space example](https://i.stack.imgur.com/BJHv1.jpg)](https://i.stack.imgur.com/BJHv1.jpg)
```
\documentclass{article}
\usepackage[inline]{enumitem}
\setlist{wide}
\begin{document}
This is an inline enumeration.
\begin{enumerate*}
\item The first thing to enumerate. There should not be excessive space
between the number and the content.
\item The second thing to enumerate.
\item The third thing to enumerate.
\end{enumerate*}
\end{document}
``` | 2020/03/18 | [
"https://tex.stackexchange.com/questions/533118",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9789/"
] | Following [Javier Bezos](https://tex.stackexchange.com/users/5735/javier-bezos)'s comment, I put together the following solution (see the MWE below). The `wide` list option is only applied to `enumerate` and `itemize`. Two inline lists, `inlineenum` and `inlineitem` are defined.
MWE:
[![solution](https://i.stack.imgur.com/Ofcg5.png)](https://i.stack.imgur.com/Ofcg5.png)
```
\documentclass{article}
\usepackage{enumitem}
\newlist{inlineenum}{enumerate*}{1}
\setlist*[inlineenum]{mode=unboxed,label=(\arabic*)}
\newlist{inlineitem}{itemize*}{1}
\setlist*[inlineitem]{label=\textbullet}
\setlist[enumerate,itemize]{wide}
\begin{document}
This is an inline enumeration.
\begin{inlineenum}
\item The first thing to enumerate. There should not be excessive space
between the number and the content.
\item The second thing to enumerate.
\item The third thing to enumerate.
\end{inlineenum}
And this is an inline itemization.
\begin{inlineitem}
\item The first thing to itemize. There should not be excessive space
between the number and the content.
\item The second thing to itemize.
\item The third thing to itemize.
\end{inlineitem}
\end{document}
```
*Remark.* If you use a document class that already implements "wide" vertical lists by default and you do not need the extensive features of `enumitem`, you may just use the `paralist` package to implement the inline lists `inparaenum` and `inparaitem` with
>
> `\usepackage[olditem, oldenum]{paralist}`
>
>
> |
13,527,894 | I'm trying to convert a SVG to PNG which has a flowroot element in it. Inkscape does it fine, when I convert using Cairo or imagemagick the flowroot elements appear as an opaque box rather than rendering the text within it.
I'm thinking this is because flowroots are a part of SVG 1.2. Does anyone know of any other gems/libraries that might help? | 2012/11/23 | [
"https://Stackoverflow.com/questions/13527894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383851/"
] | Why not just export it to PNG from inkscape then?
You'll find that flowRoot isn't supported anywhere except inkscape. It's defined in an old working draft of SVG 1.2 Full, and if you look at the last published [SVG 1.2 Full working draft](http://www.w3.org/TR/SVG12/) you'll find this:
>
> Notable changes to the feature set that readers can expect to see in
> the next draft include:
>
>
> * Replacement of the previous flowing text proposal with a superset of the SVG 1.2 Tiny textArea feature.
>
>
>
That said, the SVG WG is working on [SVG2](https://svgwg.org/svg2-draft/) instead, so you should probably look there if you want to know where things are headed. |
10,914 | A while ago I did read on the web a page whose topic was more or less:
*Real men write [insert lowest level language here]*
(a similar page would be [this Reddit thread](https://www.reddit.com/r/ProgrammerHumor/comments/89pu1f/real_men_use_assembler/))
If we quickly tour some of the rudimentary methods:
* assembly, yes
* machine code and binary, certainly
* punch cards and mechanical switches, yes
I can't find anything more rudimentary than mechanical switches but I don't know in the end.
**What is the most rudimentary input method a platform has ever been programmed in?**
Clarification:
I am asking about what used to be the most tedious way to program a machine, whether it would be a programming language difficult to read for human beings, a physical approach such as using punch cards, or even at the electrical level such as directly connecting cables or soldering. | 2019/04/30 | [
"https://retrocomputing.stackexchange.com/questions/10914",
"https://retrocomputing.stackexchange.com",
"https://retrocomputing.stackexchange.com/users/3282/"
] | [ENIAC](https://en.wikipedia.org/wiki/ENIAC) was programmed by physically wiring the "program" on a plugboard:
[![enter image description here](https://i.stack.imgur.com/9pukp.jpg)](https://i.stack.imgur.com/9pukp.jpg)
(picture from Wikipedia: <https://upload.wikimedia.org/wikipedia/commons/7/7e/Eniac_Aberdeen.jpg>)
And since the question is not limited to digital computing, analog(ue) computers were often purpose-built; there is probably nothing more rudimentary than *directly building* your machine to perform whatever it is you need it to perform.
Or, if they were "programmable", you "programmed" (speaking about electronic ones) them by connecting and adjusting parameters of electronic components, amplifiers etc; often (but not necessarily) using a plugboard:
[![enter image description here](https://i.stack.imgur.com/tmbX9.jpg)](https://i.stack.imgur.com/tmbX9.jpg)
(picture from Wikipedia: <https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/EAI_580_analog_computer_plugboard_at_CHM.jpg/249px-EAI_580_analog_computer_plugboard_at_CHM.jpg>) |
12,629 | >
> Paraître / sembler : employé avec un adjectif, paraître décrit **de manière neutre** l’aspect, l’apparence : il paraît jeune (et il l’est, pour autant qu’on sache). Sembler laisse entendre que la réalité pourrait ne pas correspondre à l’apparence : il semble jeune (mais peut-être est-il plus vieux qu’il ne paraît).
>
>
> from the Larousse
>
>
>
I ask myself what's the difference between "de manière" and "d'une manière". I really think there is one.
Could it have been "d'une manière neutre"?
I look forward to your replies!
### PS:
Upon reflection, there is an analogy in the situation of adjectives too.
For example:
*une voiture de sport* = *a sports car*
(but you don't normally say "une voiture sportive").
Another example in English:
* a logical error = an error made logically (which sounds a bit strange)
* a logic error = an error which involves logic
So my guess is that the difference between “de manière” and “d'une manière” is something along these lines. | 2014/12/20 | [
"https://french.stackexchange.com/questions/12629",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/-1/"
] | ***de** manière* neutre : *manière* est utilisée dans son acception générale, manière est ici la façon, la forme utilisée pour accomplir cette action : on a utilisé la *manière neutre*, *le principe* de neutralité (pas d'article non plus devant *neutralité*, on reste dans les définitions générales).
***d'une** manière* neutre : ici on utilise une façon *particulière* pour accomplir une action, mais on aurait pu en envisager une autre : on a utilisé *une manière neutre*, *l'outil* de la neutralité (l'article est aussi devant *neutralité*, on précise la définition et son application précise).
On pourrait insister en précisant : *De la manière la plus neutre possible*.
>
> "C'est une *voiture de sport*".
>
>
>
... est tout à fait correct et conseillé pour l'écrit et les contextes soutenus. Mais le langage sportif ou mercantile utilise souvent :
>
> "C'est une *voiture sportive*" pour dire que la conduite de cette voiture peut être sportive,
>
>
>
et carrément, lorsqu'on est en face de l'objet (peut-être par anthropomorphisme):
>
> "C'est une sportive !".
>
>
>
Pour ce qui concerne la logique :
>
> * *Une erreur logique* est une erreur qui découle logiquement de la situation.
> * *Une erreur **de** logique*, est une erreur qui découle du raisonnement employé.
>
>
>
Du point de vue francophone, il n'y a pas vraiment de logique ou de cohésion entre les trois situations que vous présentez :
* *Manière* : le *de* différencie ce qui est d'ordre général et d'ordre particulier,
* *Voiture* : le *de* est correct mais peut s'éliminer dans le langage courant par facilité ou pour suivre les expressions à la mode,
* *Logique* : le *de* (ou son omission) est un pivot du raisonnement qui déplace l'origine de l'erreur. |