Find the coordinates of center for the composition of two rotations

Question: The combination of a clockwise rotation about $(0, 0)$ by $120◦$
followed by a clockwise rotation
about $(4, 0)$ by $60◦$
is a rotation. Find the coordinates of its center and its angle of rotation.
Here is my work so far:
$120◦+60◦=180◦$ which is not a multiple of $360◦$. As a result, the composition of these two rotations is another rotation $R_{x,\alpha}$ with the center $x$ and angle of rotation $\alpha$.
To find $\alpha$ then I divide each angle by 2, add them and multiply by 2. Therefore, $\alpha=180$
So my angle of rotation is 180 and we have $R_{x,180}$
Meanwhile, I am having a hard time finding the coordinates of its center $x$, can anyone guide me?
Answer: HINT: Since $\alpha=180^\circ$, the centre of the rotation must be the midpoint of any line segment joining a point to its image under the rotation. For instance, if $O$ is the origin, and $P$ is where it ends up after the composite rotation, the centre must be at the midpoint of $\overline{OP}$. It's not hard to calculate $P$ and then find the midpoint of $\overline{OP}$.
Comment: Oh alright! I can find the midpoint but how would I be able to find P?
Comment: @Mark: You know that the origin isn't moved by the first rotation, so you need only see where the second takes it. Look at $\triangle OPC$, where $C$ is the centre of the second rotation: it's a very nice triangle.
Comment: So I drew a triangle which I shall update above, if I am right I can find the sides and angles using the law of sines but I'm not seeing how that can get me the center.
Comment: @Mark: That's the wrong triangle. In the one that I described you have $|OC|=|PC|$, since you're rotating around $C$, and you have $\angle OCP=60^\circ$. From this you should be able to find the coordinates of $P$ and then those of the midpoint of $\overline{OP}$, which is the centre of the composite rotation.
Answer: What you wrote about the angle is a bit strange, you are saying that $a/2+b/2=(a+b)/2$... It's better to say something like , what would the tranformation look like far far away from these two points...
Of course this assumes that you know this theorem that a composition of two rotations is always a rotation. However, many books do teach that first, since you can characterize a rotation by what it does on arbitrary segments. Then the composition of two rotations behaves similarly, etc...
Now, for the center you just have to find the fixed point of the composition. This point should be reflected across the segment $(0,0)-(4,0)$ because of the first rotation and then back to its starting place by the second. This should be enough to tell you the angles that it defines with respect to $(0,0)-(4,0)$ and hence its coordinates...
A more straightforward way is to find the action on two particular points $A, B$. Now if $A$ is mapped to $A'$ and $B$ to $B'$, then the center should be the intersection of the perpendicular bisectors of $AA'$ and $BB'$.
Now a good choice for $A$ and $B$ involves making the actio of the composition easier... That is I would definitely have $A=(0,0)$ since the first rotation fixes it... What would be a good choice for $B$?
Comment: so for B,  once it is rotated, its image would be (4,0) ?
Comment: Correct, so $B$ should be the _preimage_ of $(4,0)$ under the first rotation...
Comment: First rotation would be 120?
Comment: Yes, so the preimage of $(4,0)$ would be the point that we get after we rotate $(4,0)$ by -120 degrees around $(0,0)$...


Function to translate from two 90 deg shifted triangle waves to a rotation angle?

Question: I have a dual output endless rotary encoder that varies it's analogue outputs as two triangle wave with a 90 degree phase shift between A and B (see graph below). Can anybody suggest an appropriate transform/function

f(a,b)=angle
Comment: I don't understand. What are the requirements for this function? You say "f(a,b) = angle", but what angle?
Comment: If you want a function that looks something like the A graph, for example, you could try something like
$$
f(x) = 90-\left| (x \mod{180}) - 90 \right|
$$
This doesn't give exactly the graph in the picture, but you can tweak the numerical values.
Comment: a,b both range between 0 and 100% (left axis of graph) and the two of them together uniquely encode the angle of rotation (bottom axis)
Answer: Assuming $a,b \in [0,1]$:
$$f(a,b) = \begin{cases} 180a &\text{if }b \geq \frac{1}{2}\\  180(2-a)&\text{if }b < \frac{1}{2}\end{cases}$$
(Alternatively, note that you can parametrically plot $\langle a(t), b(t)\rangle$ in two dimensions; it will make a diamond shape. You can recover the angle using trigonometry, though this is more work.)
Comment: thanks, it's going inside a micro controller interrupt handler so the non trig solution is much preferable...


How do I embed a dreemgl widget outside the server framework?

Question: I'd like to use the DreemGL framework (in particular the widgets, a very nice set of GL widgets) in my frontend code, but I'd rather not use the backend server pieces. How can I embed and use just the widgets, without using the server on the backend? Is there any example of this?
Answer: That's currently not possible with DreemGL. You can only run compositions with the backend server active.


fazer o javascript escutar um elemento html e manipular o valor da propriedade de outro elemento se houver click

Question: Preciso escutar um elemento html de id="hamburger", se o usuário clicar, o javascript verifica qual o valor da propriedade display de outro elemento, no caso id="OverlayNav", e altera o valor, caso display="none" transforma em "block" e vice versa.
tá dando erro de sintaxe, alguém pode exemplificar como faço isso acontecer?
gostaria de tornar todo o box do meu OverlayNav sensível ao click, para caso o usuário clicar em qualquer área de tela onde não houver um
, o display do OverlayNav se torne "none" tbm

Answer: Se código tinha alguns erros, o primeiro é que vc não declarou a variável pro OverlayNav depois que vc colocou a variável status = OverlayNav.style.display = '' como um valor = '' e vc pode simplesmente colocar a variável como OverlayNav.style.display e deixa pra setar o none ou block na condição if/else

E se vc quer que clicando no OverlayNav ele suma vc coloca outro listener com uma função de clique nele para caso seja clicado ele fique com display:none

var OverlayNav = document.getElementById("OverlayNav");

OverlayNav.addEventListener('click', function() {
  this.style.display = 'none';
})

document.getElementById("hamburger").addEventListener("click", function() {

  var status = OverlayNav.style.display;

  if (status == 'none') {
      OverlayNav.style.display = 'block';
  } else {
      OverlayNav.style.display = 'none';
  }

});

hamburger

OverlayNav

Comment: boa recomendação, baixando aqui :)
Comment: perfeito, tudo funcionando de acordo
Comment: como vc comentou, nem precisaria criar uma nova `var status` onde está mudando o `display` do elemento, ficaria até melhor :)
Comment: @RicardoPontual vdd, na verdade é que como parti do código dele nem me atendei aos detalhes
Comment: eu entendi. aliás acho muito legal esse gifs animados
Comment: @RicardoPontual é um programinha de 3MB chama ScreenToGif, super leve e fácil de usar, recomendo
Comment: legal, funcionou =D
outro detalhe, existe um script que muda a classe do botão hamburger quando clicado, this.classList.toggle("is-active");
quando clica na box do overlay, ele some mas o botão continua com a classe ("is-active") como volto a classe do botão caso o overlay seja display:none ?
Comment: @NicholasAffonso na função que vc clica no overlay vc coloca dentro para remover a classe is-active do hamburger, ficaria assim por exemplo `document.getElementById("hamburger").classList.remove('is-active');`, vc tem que executar isso quando clicar no overlay


Distribution of sales to generate numbers from that distribution

Question: I have a set of data referring to the sales that a company had in the past 90 days.I need to determine the distribution that this data may come from in order to use it in R. If I know the distribution, I can use different functions to generate numbers that respect that distribution (for example, rrnorm or rrpois) and to simulate the stocks(how many products of that type) that this company will own in the future, after a certain amount of time. My data looks like this:

day 1:30
day 2:32
day 3:35
day 4:37
day 5:36
day 6:32
day 7:28
day 8:35
day 9:33
day 10:30

And so on.
More specifically, I need to find what  theoretical distribution  the sales follow and use that as my demand distribution in a stock.inventory management simulation.
I only need the way that I could do this, not the actual result, because I cannot give you all the data I have, because it`s confidential.
Could someone please help me?
Answer: In general, to simulate from data, you don't necessarily need to/should try to find an approximating parameterised distribution. There might none exist. Even if the data is generated from a closed-form distribution (I mean one that could be explicitly written down if somebody knew what it was), I'm not sure that there exists an exhaustive list of all described probability distributions that you could use to search for it.
One can use random sampling with replacement from the actual data (i.e. taking the empirical distribution as visualised by the histogram as the underlying distribution), bootstrapping.
Answer: Capturing seasonality in multiple regression for daily data would be a good place to start. Essentially when you form a predictive model you can forecast/simulate future periods. The simulation is based upon a monte-carlo ... bootstrap using the model residuals to give you  a distribution of values for each period in the future.
Simple method of forecasting number of guests given current and historical data contains a discussion of simulation/forecasting of daily data ( the number of people having lunch )
With 90 days of data your model might be quite simple incorporating ARIMA , daily effects , outliers , level shifts etc.
Comment: The "distribution" that you are looking for may depend on the day-of-the-week THUS there would be a family if distributions ..one for each day of the week. Care would have to be taken when generating these distributions/conditional forecasts to reflect anomalies and level shifts et al
Comment: I do not need to forecast it, I need to generate those numbers that  follow the certain distribution and this distribution is the one I need to find.
Comment: That is precisely what a forecast is . It is a simulation into the future, If you create 90 values I will demonstrate this.
Comment: I will simulate the stock, the number of products that remain in stock after they sell the products based on the distribution of the demand (I assume the demand follows the same distribution of the sales).
Comment: I made a simulation model of stock/inventory mangement in which I use a Poisson distribution to see the total cost, but now I need the real distribution of my data set.
Comment: The distribution of the composite would be useless if there is auto-correlation in the data of any form.


Using Google Books API in Android

Question: Hi I'm new to Android and using web APIs. I'm currently writing an application that can scan a barcode from a book and then search Google Books for it.
So far I implemented Scandit into my application and I registered and got the API key from Google API console for Books API. From there I do not know how to continue and start coding it. So far from my understanding it requires me make a request data via uri but I'm stuck on how to actually code it. I'm wondering if anyone could point me to the right direction or provide a sample code that shows how to fetch data using URI.
I also downloaded the zipped Book API Jar libraries do I need to make use of this? I ask this because from a question on Google Places API on this website, one of the answer said that all you need is to use Google API as the build target and it doesn't require any Jar files but does this apply to Books API as well?
Also I'm using Eclipse, should I set my build target to be Google APIs 16? I'm guessing this is right since I plan to use Google Maps in future with this app.
Thanks this is first time I asked a question on here.
Comment: This open source app does that, so it might help as a pointer (warning though, the code there is pretty old and hasn't been updated in a long time, so it might not be optimal in terms of latest best practices): http://code.google.com/p/and-bookworm/source/browse/trunk/src/com/totsp/bookworm/data/GoogleBookDataSource.java
Answer: I just finished doing this myself. This is how I implemented it using an HttpURLConnection and an AsyncTask (I just call "https://www.googleapis.com/books/v1/volumes?q=isbn:"+yourISBN and parse the JSON):
// Received ISBN from Barcode Scanner. Send to GoogleBooks to obtain book information.
class GoogleApiRequest extends AsyncTask<String, Object, JSONObject>{

    @Override
    protected void onPreExecute() {
        // Check network connection.
        if(isNetworkConnected() == false){
            // Cancel request.
            Log.i(getClass().getName(), "Not connected to the internet");
            cancel(true);
            return;
        }
    }
    @Override
    protected JSONObject doInBackground(String... isbns) {
        // Stop if cancelled
        if(isCancelled()){
            return null;
        }

        String apiUrlString = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbns[0];
        try{
            HttpURLConnection connection = null;
            // Build Connection.
            try{
                URL url = new URL(apiUrlString);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(5000); // 5 seconds
                connection.setConnectTimeout(5000); // 5 seconds
            } catch (MalformedURLException e) {
                // Impossible: The only two URLs used in the app are taken from string resources.
                e.printStackTrace();
            } catch (ProtocolException e) {
                // Impossible: "GET" is a perfectly valid request method.
                e.printStackTrace();
            }
            int responseCode = connection.getResponseCode();
            if(responseCode != 200){
                Log.w(getClass().getName(), "GoogleBooksAPI request failed. Response Code: " + responseCode);
                connection.disconnect();
                return null;
            }

            // Read data from response.
            StringBuilder builder = new StringBuilder();
            BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = responseReader.readLine();
            while (line != null){
                builder.append(line);
                line = responseReader.readLine();
            }
            String responseString = builder.toString();
            Log.d(getClass().getName(), "Response String: " + responseString);
            JSONObject responseJson = new JSONObject(responseString);
            // Close connection and return response code.
            connection.disconnect();
            return responseJson;
        } catch (SocketTimeoutException e) {
            Log.w(getClass().getName(), "Connection timed out. Returning null");
            return null;
        } catch(IOException e){
            Log.d(getClass().getName(), "IOException when connecting to Google Books API.");
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            Log.d(getClass().getName(), "JSONException when connecting to Google Books API.");
            e.printStackTrace();
            return null;
        }
    }
    @Override
    protected void onPostExecute(JSONObject responseJson) {
        if(isCancelled()){
            // Request was cancelled due to no network connection.
            showNetworkDialog();
        } else if(responseJson == null){
            showSimpleDialog(getResources().getString(R.string.dialog_null_response));
        }
        else{
            // All went well. Do something with your new JSONObject.
        }
    }
}

protected boolean isNetworkConnected(){

    // Instantiate mConnectivityManager if necessary
    if(mConnectivityManager == null){
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    }
    // Is device connected to the Internet?
    NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
    if(networkInfo != null && networkInfo.isConnected()){
        return true;
    } else {
        return false;
    }
}

I've omitted the code for my dialog methods as they are not relevant. Hope this helps.
Comment: You don't need a key, just the URI. Try it in your browser: [https://www.googleapis.com/books/v1/volumes?q=isbn:0307432866](https://www.googleapis.com/books/v1/volumes?q=isbn:0307432866)
Comment: Though, you should be using the API key, see [this question](http://stackoverflow.com/questions/19548866/google-books-api-and-the-neccesity-of-an-api-key/19985888).
Comment: If you're getting title, thumbnail, authors etc do you need to use the API key?
Comment: Since you aren't requesting private user data, you only need the API key and do NOT need to do the Oauth. Here's how to get started: [link](https://developers.google.com/books/docs/v1/getting_started)
Comment: This API does not return Image of the book, instead in Preview it returns an HTML
Answer: To access Google Books API or any other  REST APIs directly at HTTP level, you can use Volley if you are willing to write asynchronous code, or OkHttp for simpler synchronous requests. And there's also Android Asynchronous Http Client.
But what's even better, you can use Feign or Retrofit that abstract away the HTTP-level implementation details and provide fluent typesafe APIs on top of auto-generated implementation. Retrofit is the most used network library in Android, but Feign is used more in the wider Java ecosystem.
Here's an example using Feign for Google Books API, Retrofit is very similar.
API interface, implementation is auto-generated by Feign:
public interface GoogleBooksApi {

    @RequestLine("GET /books/v1/volumes")
    Results findBookByISBN(@QueryMap Map<String, Object> queryParameters);

}

API client code:
public class BookLookupService {

    public Book fetchBookByISBN(String isbn) throws BookLookupException {
        final GoogleBooksApi googleBooksApi = connect();
        final Map<String, Object> queryParameters = new HashMap<>();
        queryParameters.put("q", "isbn:" + isbn);
        final Results apiResponse = googleBooksApi.findBookByISBN(queryParameters);
        if (apiResponse == null || apiResponse.getTotalItems() < 1) {
            throw new BookLookupException("No books found for ISBN " + isbn);
        }
        final List<Result> results = apiResponse.getItems();
        if (results == null || results.size() < 1) {
            throw new BookLookupException("Invalid items list for ISBN " + isbn);
        }
        final Book book = results.get(0).getBook();
        return book;
    }

    private static GoogleBooksApi connect() {
        return Feign.builder()
            .decoder(new GsonDecoder())
            .logger(new Logger.ErrorLogger())
            .logLevel(Logger.Level.BASIC)
            .target(GoogleBooksApi.class, "https://www.googleapis.com");
    }
}

Entities that model the API response structure:
public class Results {
    int totalItems;
    List<Result> items;

    public int getTotalItems() {
        return totalItems;
    }

    public List<Result> getItems() {
        return items;
    }
}

public class Result {
    // the JSON field is named volumeInfo
    Book volumeInfo;

    public Book getBook() {
        return volumeInfo;
    }
}

public class Book {
    private String title;
    private List<String> authors;

    public String getTitle() {
        return title;
    }

    public List<String> getAuthors() {
        return authors;
    }
}

And last not least, test:
@RunWith(AndroidJUnit4.class)
public class BookLookupServiceAndroidTest {
    private BookLookupService bookLookupService = new BookLookupService();

    @Test
    public void whenMultipleLookupResultsThenReturnsFirst() throws Exception {
        assertThat(bookLookupService.fetchBookByISBN("9780321356680").getTitle(),
                   is(equalTo("Effective Java, 2nd Edition")));
    }
}

Note that you need to wrap the code in AsyncTask to make it asynchronous as network requests are not allowed on main thread.  The AsyncTask should update the UI in onPostExecute().
Here's an example:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final Button fetchBookButton = (Button) findViewById(R.id.FetchBookButton);
        fetchBookButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { new FetchBookTask().execute(getISBN()); }
        });
    }

    private String getISBN() {
        final EditText isbnField = (EditText) findViewById(R.id.BookIsbnField);
        return isbnField.getText().toString();
    }

    private void showMessage(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }

    class FetchBookTask extends AsyncTask<String, Void, Book> {

        @Override
        protected Book doInBackground(String... params) {
            final String isbn = params[0];
            try {
                return new BookLookupService().fetchBookByISBN(isbn);
            } catch (Exception e) {
                Log.e("fetchBookByISBN", e.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(Book book) {
            if (book != null) {
                showMessage("Got book: " + book.getTitle());
            } else {
                showMessage("Failed to fetch book");
            }
        }
    }
}

Using Google Books API in Android


Unix memory management

Question: When using top/free to see memory usage in Unix, there're 'used/free/shared/buffers/cached' categories. What do those exactly mean? I've tried to look for a wiki but didn't find detail information. Please advise, thanks.
Answer: Most of that information is in the man page for top.
Shared: The amount of shared memory used by a task.  It simply reflects memory that could be potentially shared with other processes.
Free: Actually unused memory.
Used: Allocated to processes.
Buffers: Memory used for various OS buffers. Such as OS file-structures.
Cache: Memory used for various OS caches, generally the block and file caches.

Unix memory management


Form API 'image_button' vs 'submit' breaks my AJAX form

Question: I have an AJAX form that works as expected with the following submit code:
<code>$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Go'),
);
</code>
I want to use an image for the button, but the type 'image_button' breaks the AJAX functionality (multiple repopulating select fields, won't appear, or update):
<code>$form['submit'] = array(
  '#type' => 'image_button',
  '#src' => '/themes/moon/images/go.gif',
  '#value' => t('Go'),
);
</code>
Oddly, the 'image_button' works fine when clicking it (form works as expected) it's just the AJAX updating of the form that stops working? Drupal Form API Reference
Comment: Is this a custom form and you bind the '#ajax' property to these submit elements yourself, or is it an existent form that you are trying to customize?
Comment: It's a custom form, but the submit element doesn't even have an #ajax property. Only the first & second select lists have an #ajax property. If anybody wants, I can post the whole form in the question.
Comment: Can you post the code relevant to this issue in the question, so we can understand the problem better.
Comment: Hi @ShabanaBlackborder, over a year later!? I'm not with that company anymore, but if I had to guess they're still working on that project (lol).
Comment: Hehhee, oops, sorry there.  Didn't even see the date!!!
Comment: No worries, I might have a little fault here because I vaguely remember finding a workaround (or fixing it) & I obviously didn't follow up here. So I owe an answer!
Comment: Actually reading it again, I kinda remember using some hacky CSS business to make it a image button; which in turn is probably why I didn't post the non-solution here.
Answer: You have to set an unique '#name' tag for EVERY button (submit, image_button, button) on the page. This worked for me.
Answer: Heads up that if you are using ctools modals, there is a bug with image buttons such that they aren't submitted when clicked (you can look at your POST details to check what values are submitted). I created a patch here that seems to fix it: https://www.drupal.org/node/1314894
Answer: Remove the <code>#value</code> from image button..
Comment: Welcome to Drupal Answers :) Answers here are expected to be of a higher quality than this. Please can you expand on what you mean, and perhaps explain _why_ you feel removing `#value` from the element array will fix the problem
Comment: With only 7 points @modhura doesn't seem to be DSE regular. Perhaps someone else could explain and get theirs accepted instead
Comment: This worked for me when I had 2 x image_buttons, one for 'Submit' and one for 'Preview'. Nothing else worked cross browser except for unsetting #value. I didn't look into why this happens :(


Keeping values selected after form submission with php

Question: I want to keep selected values after form submission, as suggested here by @ignacio-vazquez-abrams. I tried this:
<form action="" method="get">
    ...
    foreach ($file_array as $location)
        $options .= '<option name="' . $location . (($_GET['name'] == $location) ? 'selected="true"' : '') . '" value="' . $location . '">' . $location .'</option>';
    $select = '<select id="location" name="location">' . $options . '</select>';
    echo $select;
    ...
</form>

but I got a notice:

Notice: Undefined index: name in ...

UPDATE
Than I tried this (as was suggested in comments and I how is recommended here):
$options .= '<option name="' . $location . (!isset($_GET['selected']) ? 'selected="selected"' : '') . '" value="' . $location . '">' . $location .'</option>';

with no errors, but the expected result still has not been produced - selected values after form submission are not retained.
How to achieve this?
Comment: how does you form tag look like? `method="post"` or `method="get"`
Comment: `name=` should be `selected=`
Comment: Its throwing an error for `Undefined index: name` so check are you getting value within `$_GET` also `name` attribute is not for `option` but its for `select`
Comment: @swidmann I updated the question.
Comment: Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index)
Comment: @hasan-fathi I updated the question and I explained why it isn't a duplicate. Thanks for the link, it was helpful for me!
Answer: You are using a strict mode of PHP, therefore you need to check if the GET param is passed (by using isset()) before comparing its value to something.
<form action="" method="get">
    <select id="location" name="location">
        <?php foreach($file_locations as $location): ?>
        <option <?php echo ((isset($_GET['location']) && $_GET['location'] == $location) ? 'selected="selected"' : '') ?> value="<?php echo $location ?>"><?php echo $location ?></option>
        <?php endforeach; ?>
    </select>
</form>

Also you need to write selected="selected" or just selected instead of selected="true".
Answer: There's a whole lot missing to actually adding a right answer for this, but i'll try anyway.
PHP locations array:
$locations = array( 'Loc1', 'Loc2', 'Loc3' );

On the form:
<form action="" method="get">
    <select name="location">
        <?php
            foreach ( $locations as $location ) {
                echo '<option value="' . $location . '" ' . ( isset( $_GET['location'] ) && $_GET['location'] == $location ? 'selected="selected"' : '' ) . '>' . $location . '</option>';
            }
        ?>
    </select>
</form>

First of all there's no way of telling that your posted value is the value name. As i recall there's no name attribute for option, it has to be a select around it which holds the attribute name, and you are putting the selected="true" in the name attribute which you are not properly closing in the first place (and which is non existing).
Comment: Sorry! I updated the question with the missing data, but you guessed it anyway. In the future questions I will be more careful and I will include all necessary information. Now the code is working as was expected! Thank you very much?
Comment: another approach using `js` - https://stackoverflow.com/a/16458797/4050261


how to convert baseclass to subclass(subclass s = basceclass as subclass, but i dont' know this subclass type)

Question: For example:
<code>   class a { }
   class b : a { }
   class c : a { }
   ....

   List<a> a = new List<a>();
   a.Add(new b());
   c.Add(new c());
   ....
</code>
There are lots of subclass inherit a, but i don't know which one. how to convert one of the elements into subclasses, such as ( a[i] as subclass ) the subclass which I don't know but it inherits a ?
   I search in Google, many answers tell me to use reflection and Assembly.GetIntance, but  I think it create a new object, all the data owned by the subClass will be lost.
  Hope for help.
Comment: Smells like an [XY problem](https://en.wikipedia.org/wiki/XY_problem)... What is the greater goal you want to achieve? [Edit] the question and elaborate.
Comment: Welcome to Stack Overflow.
Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question.
Then [edit] your question to include the source code you have as a [mcve], which can be compiled and tested by others.
Comment: Do you want to use `a.OfType().ToList()`?
Answer: You can't convert to a type which you don't know (but it is not clear why you think you need to do that, hence @stickybit's comments about this being an XY problem). If you are trying to determine what type an object is so you can convert to it, then the is operator can be used to do that, or pattern matching can be used, although in many (most?) cases it is better from a design standpoint to add a virtual method to the superclass and override it in each subclass to do something different, so that you can retrieve an element from your List as an instance of the superclass and call the virtual method on it without needing to know which specific subclass the object actually is.
Comment: I want to load the subclass into the PropertyGrid, but I don't want to build too many subclass objects, so I want to get the subclass through the parent class and then transform it, and then load the subclass into the PropertyGrid


Density of stochastic process after time

Question: I'm playing around with a simulation of a particle that drifts around in space as time passes and looks like this
$$
x_{t+1} = x_{t} + \sqrt{dt}\cdot f(x_{t})\cdot Y + dt \cdot g(x_{t})
$$
Where the $dt$ is the time discretization of this process that we use for simulation processes and $f$ and $g$ are non-linear differentiable functions of $X$ and $Y\sim \mathcal{N}(0,1)$.  $X\in\mathbf{R}$.
I think I can write out the conditional density then as the following
$$
X_{t+1}\mid X_{t} \sim \mathcal{N}(X_{t} + dt\,g(X_{t}),dt\,\left(f(x)\right)^{2})
$$
My questions are as follows:

Can we think of this as a continuous time process if we take the limit $dt\to 0$?
Can we think of this as a brownian process?  I think the standard deviation being a function on the current position means we don't have stationary increments, so the answer (I think) is no
Is there a way to find a (nice?) closed form for the density $P(X_{t}\mid X_{0},t)$?
Answer: What you wrote there is the Euler-Maruyama discretization of the Ito SDE $dX_t=g(X_t) dt + f(X_t) dW_t$. It typically converges as $dt \to 0$. (Specifically, it is consistent but not necessarily stable, and a breakdown of stability can cause it to fail to converge). You can describe the time evolution of the density exactly using the forward Kolmogorov equation, also called the Fokker-Planck equation in the physics literature. This reads
$$\frac{\partial p}{\partial t} = -\frac{\partial}{\partial x}[g p] + \frac{1}{2} \frac{\partial^2}{\partial x^2}[f^2 p].$$
The update of the conditional density on a short time interval converges to what you said as the length of the interval goes to zero, but unless $f$ and $g$ are actually constants then this is not exact for finite $dt$.


What are common scale patterns for the cello?

Question: I am a guitar player of about 15 years and am very familiar with a variety of guitar scale patterns.  The major scale being generally played three notes on the first string, 3 on the 2nd and 2 on the 3rd.  Or 2 on the starting string and then 3 and 3.  This works very well with the tuning of the guitar on perfect fourths.
I recently purchased a cello which is tuned on 5ths, and I'm trying to learn the common major scale patterns on the cello.  The patterns for the guitar don't really work with the tuning of the 5ths.    Are the cello scales played across the neck like the guitar?  Or are the major scale patterns played on only 2 strings with 4 notes per string?  Or are they played only on 1 string up and down the neck?
Comment: Guitars are tuned (mostly) in fourths while, as you've already said, cellos are tuned in fifths. Since fourths and fifths are inversions of each other, you can literally invert the guitar patterns (ignoring the B and high E strings) and you'll find the patterns have the same shapes.
Comment: By the way, I'm not advocating that you jump in this way all on your own—competent instruction is always preferred—but it may help to orient yourself.
Answer: Are you planning on strumming your cello?   If not, i.e. you want to learn the bowed playing patterns,  I can assure you there are a number of patterns, depending on the actual progression of notes and the tone/timbre desired.
The simplest scales go:  open, 1,2or3,4, then open on the next string, etc.  Obviously once you get above certain pitches, you need to work up the string into what are referred to as "positions."  Again, the basic single-string pattern is 3 on the tonic, then 1-2,1-2,1-2-3 .
But there are multiple options even high up the fingerboard for playing across 2 or three strings to avoid shifting the left hand.
TL;DR:  you need to take a lot of lessons to learn how and when to choose a particular fingering pattern.
Answer: Indeed the standard positions do not really allow finger patterns for diatonic scales like you have on guitar, but require a position shift once every three or so notes, unless you use empty strings to fill some gaps. While this may seem, in a practical sense, a bit annoying, cellists tend to make a virtue of it by using the shifts as an expressive feature of their playing. Also, it certainly keeps you well-practiced for when you need to switch positions for other reasons!
But as a cello beginner, you'll have enough to worry about – even without position shifts. (I'd strongly recommend you take at least some proper lessons!) As far a scales are concerned, it's for the beginning best to stay in first position and make use of empty strings. The C-major scale works this way over the entire range, without any stretching needed.
<code>-------------------------0-1-2-
-----------------0-1-2-4-------
---------0-1-3-4---------------
-0-1-3-4-----------------------
</code>
(Those are finger numbers, not "frets"!)
G-major and D-major work of course exactly the same way, if you start on the third/second string instead of the low C.
I suppose you won't be very happy with this advice, but it's little use to try and immediately play in any key, if it distracts you from getting the basic technique right. For instance it's vital to get used to proper loose hands and arms, if you ever wish to be able to execute position shifts precise- and smoothly.
Once you're acquainted with the first position, the next thing to learn are occasional shifts to fourth position to extend the range. Then you can start with other positions, which then also opens up other keys.
At some point you may also learn the thumb positions: high up on the neck, you suddenly have enough fingers to play full scale patterns!
Comment: BTW, I too started cello late (at 16) and after years of (classical) guitar. One year I tried it autodidactically, but then fortunately though better of it and started taking proper cello lessons. Without these, I'd never have gotten very far on the instrument.
Comment: Well-- when you use thumb positions, you don't use your pinky, so either way you have four fingers available at any given time.
Comment: @CarlWitthoft: right (though I do occasionally use the pinky for trills in thumb position), but the difference is that, in thumb position, the fingers are assigned to diatonic scale degrees, e.g. f and f♯ are both played with 2 in 7th position, and the g is played with 3, so you don't _need_ 4 like you would in 1st position.


C# - Cycle through and get values of XML values with same name

Question: I am trying to take some values from an XML document that is laid out like so
<Work>
    <Name>Group Work</Name>
    <Data>
        <Day>
            <Attended>7</Attended>
            <StartTime>12:00</StartTime>
            <Date>01-01-2018</Date>
        </Day>
        <Day>
            <Attended>4</Attended>
            <StartTime>11:00</StartTime>
            <Date>02-01-2018</Date>
        </Day>
        <Day>
            <Attended>11</Attended>
            <StartTime>13:00</StartTime>
            <Date>03-01-2018</Date>
        </Day>
    </Data>
</Work>

I would like to take each individual day's out data individually.
i.e to take out the number of attendees per session and calculate an average while still displaying the attended number with its respective day.
So far I have managed to take out the first <Attended> value with the following code:
XmlNode attendedValue = xml.SelectSingleNode("/Work/Data/Day/Attended");

But I'm unsure as to how I go about cycling through each <Day> and taking its unique value. Is it possible to filter these by the date?
Comment: You might want to take a look at `Linq-to-XML` it's much nicer than the old DOM. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml
Comment: Took a look, I think you might be right on that one. Thank you for the helpful link.
Answer: Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, Dictionary<DateTime, int>> dict = doc.Descendants("Work")
                .GroupBy(x => (string)x.Element("Name"), y => y.Descendants("Day")
                    .GroupBy(a => ((DateTime)a.Element("Date")).Add((new TimeSpan(((DateTime)a.Element("StartTime")).Hour,((DateTime)a.Element("StartTime")).Minute,0))), b => (int)b.Element("Attended"))
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());

         }
    }

}


How to reset uploaded file list in Kendo Angular Upload component

Question: I have a kendo-upload component to upload just one file. After a files is uploaded I need to clear the list or uploaded files.

Initial state

After a file is selected

After a file was uploaded

I need the step 3. to looks like the step 1. = like if I would click on Clear button.
I tried to bind to (success) event and do:
a. this.pictureUpload.fileList.clear();
b. this.pictureUpload.fileList.remove(this.pictureFilePreview.uid);
But always get an exception from uploadService:

I did dig into uploadService source code and understand why I get an exception. I also looked into upload-component source code and tried to understand how to externally execute Clear button method, but did not find any easy way. I think I'm over-complicating this and there must be some easy solution I did not spot yet.
Answer: You can use Model binding to do that.
  import { FileInfo } from '@progress/kendo-angular-upload';

First capture the completed event in kendo-upload:
    [(ngModel)]="myFiles" (complete)="uploadCompleted()"

Add a member:
     myFiles: Array<FileInfo> = [];

And capture the event and reset the file list to be empty:
 public uploadCompleted(){
    this.myFiles = [];
 }

Comment: need to do without ngModal


Random subsetting a data frame from a larger dataframe

Question: n = 100 # (n=height * width)
height = 10
width = 10
column = [1,2,3,4,5,6,7,8,9,10]
indices = [1,2,3,4,5,6,7,8,9,10]

Rack2 = pd.DataFrame(np.random.choice(np.arange(n),size=(height, width), replace=False), index=list(indices), columns=list(column))
Rack = Rack2.sort_index(ascending=False)
a = np.repeat([True,False], Rack.size//2)
b = np.random.shuffle(a)
a = a.reshape(Rack.shape)

SI = Rack.mask(a)
RI = Rack.where(a)

StorageSet = SI.stack()
ss=dfStorage.index

RetrievalSet = RI.stack()
tt=D3.index

In the python code above, there is a 10x10 Rack. Half of the rack (50 items) consists of storage items and the other half consists of retrieval items.
I want to do it not half of the rack size but if I have a 10x10 rack for example 30 of that data frame are storage items. 30 of the remaining 70 items are the retrieval items. How can I do this?
Comment: `a = np.hstack([np.repeat(True, 30), np.repeat(False, 70)])`?
Comment: This works but number of the storage and retrieval items must be equal. But in this solution number of storage items is 30 and number of retrieval items is 70
Comment: a = np.hstack([np.repeat(True, 30), np.repeat(False, 30)]) is the wanted solution. Is it possible?
Comment: Ok, I get it now. Misread the last part of the question.
Comment: Then, for this example 40 many values of the dataframe are not used. Thanks in advance
Comment: I think you changed a couple of the variable names at the end of your code. `StorageSet` vs `dfStorage` and `RetrievalSet` vs `D3`.
Comment: Yes that's true.
Answer: You could do this with a couple revisions to the code. First change the initialization of a:
samp_size = 30
a = np.hstack([np.repeat(0, samp_size), np.repeat(1, samp_size), np.repeat(np.nan, n - (2 * samp_size)])

Then you can get SI and RI as:
SI = Rack.where(a==0)
RI = Rack.where(a==1)

The rest of your code should work the same.


Is it possible to get jedi autocomplete for a C++ library binded to python?

Question: I am using vim with jedi-vim to edit some python code. However, some libraries we use are C++ shared libraries for which we generated python bindings using pybindgen. When using jedi-vim, I do not get signature for any of the classes and methods, just a listing of them.
For example, in this library, https://github.com/jorisv/SpaceVecAlg if I install the library and import it:
import spacevecalg as sva

Then, sva. will correctly show all first-order functions and classes. However, if I select the first one, sva.ABInertia( jedi will not suggest me any of the class constructors.
I suppose I have to somehow export the class definitions to a kind of python documentation, and I figured I could use the doxygen annotations for that, but I have no idea how to feed that extra documentation to jedi (or any other completion engine, such as the one built in IPython).
Thanks a lot !
Answer: You cannot feed extra documentation to Jedi. However, you can set the __doc__ attribute in a way that Jedi understands it. If you define call signatures the same way as the standard library, I guess it should work.
As a side note, I have to mention that in Python 3.4+ there's an even better way of defining the docstrings. IMHO it's the proper way to define it. I'm not sure how exactly to do it (but there are ways to use it):
>>> inspect.signature(exit)
<inspect.Signature object at 0x7f2b5a05aa58>
>>> str(inspect.signature(exit))
'(code=None)'

Jedi doesn't understand it yet, but it definitely will in the future.
Comment: Does (or will) Jedi understand `__annotations__`?
Comment: According to http://legacy.python.org/dev/peps/pep-0362/ you can set `__signature__` to one of those `Signature` objects.
Comment: Jedi doesn't understand `__annotations__`, but it could in the future, if there's a need.
Comment: Hello, thank you for your answer ! I simply modified the way pybindgen handles the "no docstring provided" case to auto-generate one with `"function_name("+",".join(parameters)+")"` and it works :)


Detect if a device (printer, scanner, mouse, etc...) isn't working

Question: If a printer has a problem, Windows's Device manager shows a special icon next to the printer in question.
I'm using Delphi XE2 and I'd like to know how to programmatically detect such info for Windows XP or later, ie.
function DetectDriversProblems() : TStringList;
begin
    // Scan Computer or query Windows to know if a driver has issues and
    // return list of faulty hardware (if any)
end;

Answer: you can use the Win32_PnPEntity WMI class and ConfigManagerErrorCode property.
{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;

  Procedure ListDevicesConfigError;
    const
      wbemFlagForwardOnly = $00000020;
    var
      FSWbemLocator : OLEVariant;
      FWMIService   : OLEVariant;
      FWbemObjectSet: OLEVariant;
      FWbemObject   : OLEVariant;
      oEnum         : IEnumvariant;
      iValue        : LongWord;
    begin;
      FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
      FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\cimv2', '', '');
      FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM  Win32_PnPEntity WHERE ConfigManagerErrorCode <> 0','WQL',wbemFlagForwardOnly);
      oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
      while oEnum.Next(1, FWbemObject, iValue) = 0 do
      begin
        Writeln(Format('Class GUID %s',[String(FWbemObject.ClassGUID)]));
        Writeln(Format('Description %s',[String(FWbemObject.Description)]));
        Writeln(Format('Device ID %s',[String(FWbemObject.DeviceID)]));
        Writeln(Format('Manufacturer %s',[String(FWbemObject.Manufacturer)]));
        Writeln(Format('Name %s',[String(FWbemObject.Name)]));
        Writeln(Format('PNP Device ID %s',[String(FWbemObject.PNPDeviceID)]));
        Writeln('');
        FWbemObject:=Unassigned;
      end;
    end;

begin
 try
    CoInitialize(nil);
    try
      ListDevicesConfigError;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.


When to use MessageDigest.reset()

Question: I've blindly followed OWASP's recommendation on hash generation in java (see here), and I'm not sure I've done it correctly. Specifically, I'm unsure about the purpose and effect of MessageDigest.reset(), and therefore when and how to use it.

I'm "loading" my salt and payload by update()ing the digest several times with different values that altogether need to be signed. Should I reset() the digest beforehand? Or afterwards?
Why is the digest being reset() within the loop (see the example)?

Here's my code:
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt);
md.update(payload1);  // part 1 of payload
md.update(payload2);  // part 2 of payload
md.update(serialNumber);  // part 3 of payload
md.reset();
byte[] sig = md.digest();
for (int i=0; i<1000; i++) {
  md.reset();
  sig = md.digest(sig);
}

What I'm observing is that the signature remains the same even when serialNumber is changing. If I leave out the 'reset()' calls, the sig does change...
Comment: possible duplicate of [Do I need to call MessageDigest.reset() before using it?](http://stackoverflow.com/questions/7546549/do-i-need-to-call-messagedigest-reset-before-using-it)
Answer: You only need to call reset if you have already used that instance of MessageDigest. reset is being called here to clear all previous settings.
MessageDigest.getInstance is a factory method rather than a singleton so has significant overhead attached.
From MessageDigest.getInstance:

A new MessageDigest object encapsulating the MessageDigestSpi implementation from the first Provider that supports the specified algorithm is returned.

So better to re-use and avoid the overhead of calling MessageDigest.getInstance again.
Comment: I would go with reset & re-use :)
Comment: So the OWASP example and my code are wrong, yes? If I always get a new instance, I don't need `reset` at all?
Comment: @Hank - You aren't always getting a new instance as `.getInstance` is outside of the loop. Using `.reset` is fine here.
Comment: Thanks, your responses and a dose of thinking-about-them(tm) has completely answered my question!
Answer: The code looks off to me... maybe I'm mis-reading here, but the docs say digest() implicitly resets the instance. Thus, you'd call reset() if you had 1) previously called update() and 2) needed to re-use the instance, but didn't need the results from the update() calls.
In your case, I also think you need to leave out the first call to reset(). Otherwise, you are throwing away any benefit from the salt and payloads. The call to reset() inside the loop is unnecessary, but shouldn't change the results of the calculation.
Hope that helps.
Comment: Totally agree, the original code *was* off wrt first `reset()` call. Thanks for the pointer regarding implicit reset!

When to use MessageDigest.reset()


TS 2008 Per User CAL Report

Question: I am having an issue with a Win7 machine rdping into a windows server 2008 std TS server.
I get the following error in the event log when I try logging in.

Event ID 1004 The terminal server
  cannot issue a client license.  It was
  unable to issue the license due to a
  changed (mismatched) client license,
  insufficient memory, or an internal
  error. Further details for this
  problem may have been reported at the
  client's computer.

I found a Microsoft KB on it. I checked all the recommendations and it seems the only thing that could be an issue is if the self signed cert is corrupt. Is there a way to check that? Right now this isthe only computer that is having issues connecting.
I did run a license report on the server and I found it showing 17 used licenses. Which 4 are Domain Administrator accounts. Judging by the report showing those accounts, I'm assuming those 4 accounts get counted against your total license useage on a per user bases? If I need to upgrade the number of licenses per user licenses, I will need to include the number based on administrator accounts that login? Or am I looking at this correctly?
Comment: I am in the process of setting up our 2008 Remote Desktop Services Servers, formally Terminal Server Services. One thing I did see on our licensing is that we may have some new CALs coming in for the 2008 implementation vs our previous 2003. Are you using your TS CALs vs your RDS CALs? Are they interchangeable or are they different?
Answer: Looking back at this, there was a lot going on with the server. I was looking at the licensing thinking that could have been causing it, but the GPO printer deployment was causing the winlogon process to hang, after about 5 minutes of sitting there, the user would close out of the RDP, try to reconnect and have the issue reported.

TS 2008 Per User CAL Report


How can I make rails route helpers always use to_param to generate the path, even when I just pass in an ActiveRecord ID?

Question: So, I'm implementing a pretty/SEO-friendly URL scheme for my rails app.  I have a model called Artist, and I would like the Rails artist_path helper to always generate the friendly version of the path.
In my routes.rb file, I have the following line:
  get 'artists/:id(/:slug)', :to => 'artists#show', :as => 'artist'

If the slug is left out, or is incorrect (it's calculated by the artist name), the controller 301 redirects to the correct URL.  However, for SEO reasons, I want to ensure that all links internal to my site have the correct URL to start with.
The Artist model has the two following (very simple) functions to allow this to work:
  def slug
    name.parameterize
  end

  def to_param
    "#{id}/#{slug}"
  end

If I call artist_path with an artist object, this works as intended:
> app.artist_path(Artist.find 1234)
=> "/artists/1234/artist-name"

However, when I use call it with just the ID, it does not seem to use to_param at all:
> app.artist_path(id: 1234)
=> "/artists/1234"

tl;dr: How can I force Rails to always instantiate the object and call to_param on it when artist_path is called, even when only the ID is specified?
Comment: I just found this [gist](https://gist.github.com/1209733), which acknowledges this behavior for route helpers, but only says (paraphrasing) "just don't call the helper only with the id".  Is this the solution?  I'd hope not, because I don't want the developer [to have to know of any limitation specific to this model](http://en.wikipedia.org/wiki/Principle_of_least_astonishment).
Answer: As far as I'm aware, the reason why what you're asking won't work is because when you pass in values to the built-in/automatic URL helpers (like an ID, per your example), those values just get used to "fill in the blanks" in the route URL.
If you pass an array, the values from the array will get used in order until the URL is filled in.  If you pass a hash, those properties will get replaced into the URL.  An object, like your model, will use it's to_param method to fill in the values... etc.
I understand your concern regarding "having knowledge of the limitations of that model," however, this behavior is standard in Rails and I don't believe it would really throw anyone.  When you pass in an ID, as you do in your example, you're not telling the URL helper to "lookup a record via the model using this ID," you're simply telling it to "replace ':id' in the URL string with the ID you're providing."  I'm fairly certain the built-in URL helpers wouldn't even know how to lookup the record - what model to use, etc. - other than maybe inferring from the route/controller name.
My best suggestion is to always use the instantiated model/record.  If you were hoping the URL Helper would look that up for you, then there's no extra overhead as far as querying the database goes.  If there's some additional reason you want to avoid instantiating the record yourself, I'd be glad to hear it and possibly provide other suggestions.


How to make li tababble and readable by screenreader?

Question: I have the following list and I want each list item to be readable by screenreader.
However, the list and listitems themselves are not tababble.
Adding tabindex="0" is not really option because voiceover announces the listitem as a group and being interactive, when it is isn't.
Any idea?

        {date}
        {value}

Comment: The 2nd answer on the following link may help: https://stackoverflow.com/questions/54141817/use-aria-label-on-a-span
Answer: first of all, ask yourself why you want the lis to be tabbable (i.e., focusable by keyboard).
If the contents inside these lis must be clickable (i.e., really interactive), then mark it as such (as links, for instance). If not (i.e., the contents is, well, just text), then just don't make it focusable, you'll confuse your users. Please comment on my answer and/or update the question, probably I'll be more thorough then.


Swing Timer Not Working (Java)

Question: For some reason even though I am using the exact code example from oracle's website for the Swing Timer it is not waiting for 1 second. It just skips to the JOptionPane that says "Your score was etc etc".
Here is my source code for a school project. Why is this not working and not waiting for 1 second before running the rest of the code?
//Check to see if user has enetered anything
if(!answered)
{
    int delay = 1000; //milliseconds
    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //...Perform a task...
        }
    };
    new Timer(delay, taskPerformer).start();
    afk = true;
    incorrect += 1;
    answered = true; //This breakes it out of the loop
}

Comment: Again, it seems that you have an invalid assumption here. You seem to be thinking that by starting a Timer, all code calls after the Timer will be delayed until the Timer finishes, and that simply is not true. The Timer instead will only call the code within its ActionListener repeatedly (if desired) and after a certain delay.
Comment: You've posted a lot of code, much of it unrelated to your problem, which simply is that the timer is not working. I urge you to trim down your code to the smallest compilable and runnable program that demonstrates your problem, an [mcve](http://sscce.org). This will help *you* in that isolating the problem often helps you to see it and solve it, and it helps *us* in that if you don't fix it with this exercise, we will have code that is much easier to understand test and correct.
Comment: Your code after your timer call is not and should not be delayed. What is delayed is only that which is in the Timer's ActionListener.
Comment: Ok I did but you still did not clarify at all why my code is not working.
Comment: You did nothing of the sort -- please re-read the comment as you should only post compilable and runnable code -- a small self-contained program that demonstrates your problem and nothing else.
Comment: Also on a side note, look into use of a CardLayout to help you swap JPanels which is usually much simpler and cleaner than adding and removing components. Also I thought I saw a `null` layout snuck in there somewhere -- avoid use of these if humanly possible since they lead to the production of inflexible ugly GUI's that are wickedly difficult to update or enhance.
Answer: A timer is used to run a callback after a specific amount of time. If you simply want to delay, you can either move the code to be run after the delay into the taskPerformer action listener.
Thread.sleep(1000) is not ideal here, because it will cause the UI to completely freeze as you will make the UI thread sleep.

Swing Timer Not Working (Java)


Tenho um site multi-línguas, em questão de SEO qual o melhor: Usar Subdomínios ou Diretórios?

Question: Estou criando um site com vários idiomas (Português, Espanhol, Inglês).
Na questão do SEO qual é a maneira mais correta de se usar?
Subdomínios ( pt.meusite.com ) ou Diretórios ( meusite.com/pt ) ?
Visto que aos olhos do Google usar um subdomínio, seria como se fosse um novo site, um site separado sem nenhuma ligação ao site principal.
Penso que utilizar um diretório seja a melhor solução, até mesmo pelo PageRank. Mas tenho receio de pensar que estou fazendo bem e estou fazendo muito mal.
Vi em um artigo que só é recomendado usar subdomínios em sites de muito conteúdo, e que retratam diferentes conteúdos, como é o caso do Stack Exchange, UOL, G1, Terra, Estadão, IG, R7, etc.
Meu site vai tratar do mesmo conteúdo, só o que irá mudar são os idiomas, e algumas coisas, pois irei vender alguns produtos por países (Brasil, México, Portugal e Espanha), então precisa mudar os preços, moedas, informações, etc...
Um exemplo no UOL:
Para notícias somente de Economia: http://economia.uol.com.br
para somente Carros: http://carros.uol.com.br
Comment: Sim @BrunoAugusto você quer comparar uma rede com dezenas de sites diferentes, com conteúdos diferentes e com milhões de acessos, com apenas um site com cópias em outras línguas? Acho que você não me entendeu.
Comment: Não vou excluir a minha opinião. Metodologia é um conceito e conceitos devem ser aplicados antes mesmo de considerar o grau de popularidade de um site ou quantos outros sites o programador/empresa tem.
Comment: Veja os sites da Stack Exchange que é uma rede enorme. Você vê stackoverflow.com/pt ou pt.stackoverflow.com? Eis a sua resposta :)
Comment: @Kyllopardiun Tomei a liberdade de alterar um pouco seu último comentário e incluir um link.
Comment: *Taum tá*... *Cês* querem me deixar doido :p
Comment: Esta pergunta parece ser descontextualizada porque é sobre SEO. Ver [votação relevante no meta](http://meta.pt.stackoverflow.com/a/1460).
Comment: @bfavaretto ok, acho interessante ter esse link e havia esquecido de por o mesmo nesse comentário.
Answer: Veja o exemplo do Twitter e do Facebook, eles não mudam o subdominio.
Não importa o idioma que o usuário escolha, acho que não deve ser passado como parâmetro na URL. Ao meu ver, o idioma é uma opção assim como outra qualquer, onde o usuário escolhe o idioma que será exibido... (PT, EN, ES...).
Alguns sites de noticia usam o idioma na URL, mas não como referência para tradução da linguagem, mas sim como conteúdo regional para exibir o conteúdo de acordo com a região.
A menos que seu site tenha o conteúdo diferenciado como no exemplo acima, eu não recomendo o idioma na URL.

Imagine que você tenha o idioma na URL:
pt.example.com | en.example.com

Posteriormente, por algum motivo, você decide remover o idioma da URL... Terá que mudar os links, a chance de links quebrados são maiores, tanto externos, quanto internos... Além de correr o risco de considerar duplicidade de link, e isso sim pode e vai diminuir seu PAGERANK.
Os crawlers não identificam o idioma na URL.
Seu site pode ter a URL pt.example.com ou portugues.example.com, o que identifica o idioma é a lingua em que está escrito, e a TAG-LANG.

Quando um usuário acessa seu site, você identifica a região pelo IP e/ou combinando a opção do idioma do navegador e o sistema vai carregar o pacote de tradução automaticamente.
A definição monetária segue outra regra, se o usuário esta acessando em PT-BR, você mostra o valor em real, ou na moeda que ele escolher caso você permita a conversão... Mas essa explicação vai além da URL com parâmetro.
Eu recomendo uma URL limpa, sem parâmetros, pois é de fácil manutenção, com regras simples e sem risco de duplicidade de URLs pelos crawlers.
Comment: Até agora não entendi sua resposta, você quis dizer que nenhuma das soluções que mencionei prestam?
Comment: Agora eu entendi o que você que dizer, você me entendeu errado! Eu não me referi o SEO ao nome `pt.meudominio.com` ou `meudominio.com/pt`. Me referi somente pelo fato do PageRank e pelo fato de ser considerado um site sem ligação ao principal `meudominio.com`
Comment: Se vai traduzir URL então tudo bem. `pt.example.com/pagina-a | en.example.com/page-a` essas duas NÃO são consideradas iguais desde que traduzidas. Se os dois exemplos citados fossem escritos em um só idioma, seria link duplicado.
Comment: @Alexandre Lopes, é um assunto bem amplo e interessante que rende muitas linhas, o problema é que estão considerando fora de contexto... vou tentar responder alguma coisa la
Comment: Não disse que não prestam, apenas mostrei casos distintos em que o uso de idioma se faz necessário apenas para diferenciar o conteúdo exibido e não o pacote de tradução
Comment: Mas é porque em alguns casos precisa-se diferenciar o conteúdo. Imagine que no site BR você compra um produto em Reais, já no US você compra em dólares, etc... E que você tenha um Host e venda no BR domínios nacionais, e no MX domínios nacionais também.
Comment: Afinal, você recomenda que eu use subdomínio ou diretório? Sua resposta tá meio confusa.
Comment: Eu não disse que os `crawlers` identificam o idioma pela `URL` isso é lógico. Do mesmo jeito que eu citei `pt.meusite.com` e `meusite.com/pt`, eu poderia ter citado `blog.meusite.com` e `meusite.com/blog`
Comment: Minha resposta foi clara - recomendo uma URL sem parâmetros... Você disse "site multi-línguas" e foi com essa informação que respondi. Os exemplos que você citou(carro, economia) são **palavras** e são MUITO diferentes da abreviação de idioma(PT, EN...), palavras tem peso, por isso disse que crawler não se importa com o idioma na URL - isso não interfere em nada...
Comment: Então não tem problema usar a abreviação do idioma na URL?
Comment: Nem problema nem benefícios... Até onde sei, PAGERANK é individual, o dominio principal não alavanca o subdominio nem vice-versa. O problema maior do que um PAGEHANK baixo, é ser excluído por links duplicados.
Comment: Mas que tipo de links duplicados? Não entendi. Meu site vai ser totalmente traduzido, até mesmo as URLs.
Comment: Muito bom Papa! Você é o cara! Dá uma olhada aqui: http://pt.stackoverflow.com/questions/28602/dúvidas-sobre-seo
Answer: Se usar com subdomínio sabe que será tratado pelo google como um outro site que terá sua relevância destacada do domínio principal e terá que trabalhar cada idioma em termos de SEO como se fosse outro site.
Já se utilizar o idioma em diretórios estará garantido o page rank e relevância do domínio para todos os idiomas.


I have changed Visual Studio's "go to definition" shortcut, but it doesn't work

Question: I used Ctags before in Linux. Its shortcuts for 'go to definition' and 'go back' are 'Ctrl+]' and 'Ctrl+t'.
Now I try to bind these shortcuts to Visual Studio, whose default keys are 'F12' and 'Ctrl+-' separately.
I changed 'go back' with 'Ctrl+t' successfully. But 'go to definition' can't be changed with 'Ctrl+]'. I add new key-binding to it and remove previous key-binding. The right-click menu shows the new key-binding but it doesn't work.
Is there something wrong with my steps?
I am using Visual Studio 2017 Community version. My os is Windows 10 professional edition.
Answer: There may be other commands also using that keybinding, in a more specific context.  For example, on my machine, Ctrl+] is bound to the Edit.GotoBrace command in the Text Editor.  If your keybinding is in a less-specific context (like Global), then the Text Editor command would take precedent when the editor is active.
Comment: Thank you very very much. I have removed Edit.GotoBrace with 'Ctrl+]' and it worked! Thank you again!


Set of subsets of bounded $\Omega$ with pairwise symmetric difference bounded from below

Question: Let $\Omega \in \mathbb{R} ^d$ be bounded and consider the Borel $\sigma$-algebra $\mathcal{B}(\Omega)$.
Given $\epsilon >0$, does there exist a subset $\mathcal{A} \subset \mathcal{B}(\Omega)$ with infinitely many elements such that $|A \triangle B| \geq \epsilon$ for all $A\neq B\in \mathcal{A}$?
My intuition tells me that this should not be true, since every two sets in $\mathcal{A}$ "differ" by at least the volume $\epsilon$, but $\Omega$ is bounded.
However, I do not have any idea how to proof this.
Answer: Tried to prove your claim, as it appeals to intuition. After correcting the proof, it appeared that $\epsilon$ can be at most $|\Omega|/4$, so I tried constructing such sets by taking subintervals of $(0,1)$ of length $2^{-k}$.

Here is an construction for $\Omega=(0,1)$ and $\epsilon=1/4$:
Define
$$
A_1 = (0,1),
$$
$$
A_2 = (0,1/2),
$$
$$
A_3 = (0,1/4) \cup (1/2,3/4),
$$
$$
A_4 = (0,1/8) \cup (1/4,3/8)\cup (1/2,5/8)\cup (3/4,1/8), \dots
$$

I believe $\epsilon = |\Omega|/4$ is the best $\epsilon$ possible.
Take such a collection $\mathcal A$ containing at least $k$ sets $A_1 \dots A_k$.
Suppose $x\in \Omega$ is an element of $A_1 \dots A_j$ but not of $A_{j+1} \dots A_k$. Then $x$ belongs to $j \cdot (k-j)$ symmetric differences.
This product is maximal for $j \approx k/2$, so $k^2/4$ is an upper bound.
This implies
$$
\sum_{i,j=1}^{k} |A_i \Delta A_j|
= \int_\Omega\sum_{i,j=1}^{k} \chi_{A_i \Delta A_j}dx
\le \frac{k^2}4 |\Omega|.
$$
Due to the lower bound of the symmetric differences, we have
$$
\sum_{i,j=1}^{k} |A_i \Delta A_j| \ge (k^2 - k) \epsilon,
$$
so that
$$
\frac{k^2}4 |\Omega| \ge (k^2 - k) \epsilon.
$$
If $\mathcal A$ is infinite, then dividing the inequality by $k$ and letting $k\to \infty$ proves $\epsilon \le |\Omega|/4$.
Comment: This is great, thank you. The example for $\Omega = (0,1)$ even works with $\epsilon = 1/2$.
Comment: ? No, $\epsilon$ can at most be $1/4$, that is the second part of the answer.


Change of variables in double integrals intuitively

Question: So I have been trying to understand the intuitive proof of change of variables in double integrals.
Equations $$ x=x(u, v) \ \mathrm{and} \ y=y(u,v) $$
define a mapping from uv-Cartesian plane to points in xy-plane. The mapping is one-to-one.

The differential area element $$ dA = dx dy$$ is bounded in xy-plane by $$ u, \ u+du,\ v, \ \mathrm{and} \  v+dv.$$
Now the question is, what is dA in uv-plane?
In most intuitive proofs it is said that since du and dv are small and the area element is bounded by smooth curves, the area element is approximately a parallelogram and therefore its are is $$ dA = \left|\vec{AC} \times \vec{AB} \right|=\dots= \left|\frac{\partial(x, y)}{\partial(u, v)} \right| du dv,$$
where
$$ \vec{AB}=\frac{\partial x}{\partial u}du\hat{i}+\frac{\partial y}{\partial u}du\hat{j} \ \mathrm{and} \ \vec{AC}=\frac{\partial x}{\partial v}dv\hat{i}+\frac{\partial y}{\partial v}dv\hat{j}.$$
But if we approximate the area element as a parallelogram, shouldn't it be $$ \left \Vert  \vec{AB} \right \Vert = du \ \mathrm{and} \ \left \Vert  \vec{AC} \right \Vert = dv$$
and therefore we would have a different result for dA?
Edit: So my question really is, are $$ du=\left \Vert \frac{\partial x}{\partial u}du\hat{i}+\frac{\partial y}{\partial u}du\hat{j} \right \Vert  \ \mathrm{and} \ dv=\left \Vert \frac{\partial x}{\partial v}dv\hat{i}+\frac{\partial y}{\partial v}dv\hat{j} \right \Vert ?$$
Answer: How so? The reason we use the cross product is because the area element spanned by two vectors is given by the cross product of the two. If you do the way you are doing, then you need to take one side as base and find the 'height' of the parellogram, which will end up in the same formula. Here is a more explicit calculation of the proof you mentioned, consider a coordinate system $(x,y)$ and another old coordinate system $(u,v)$ , let's say we have a map from $(u,v)$ system to $(x,y)$ system then we can write:
$$ dx= < \frac{\partial x}{\partial u} du ,   \frac{\partial x}{\partial v} dv>$$
The idea here is the amount of increase in $u$ direction as we increase little bit in x in original system, is just slope of $x$ with $u$ times $u$ and similarly for in v direction
$$ dy = < \frac{\partial y}{\partial u} du , \frac{\partial y}{\partial v} dv>$$
So, it's like we have an area spanned by $dx$ and $dy$ in our original system, then the expression  equivalent area produced in the other system can be found by cross product the two vectors, that is:
$$ |dA| = dx \times dy = < \frac{\partial x}{\partial u} du ,   \frac{\partial x}{\partial v} dv> \times < \frac{\partial y}{\partial u} du , \frac{\partial y}{\partial v} dv>$$
Comment: No no , in the post I've written (x,y) as a function of the coordniates (u,v) and I have found the length dx and dy vectors caused by moving a little bit in the u,v coordinates.
Comment: thank you! I tried to calculate dA both ways but ended up with different results. I added a new question to the post. So is du the length of vector  ? I guess that would solve my problem.
Comment: I could also have done du = < du/dx * dx, du/dy * dy>  and that works because jacobian for forward and backward transform arei nverses of each other


How to implement typesafe enum pattern in entity framework core rc2

Question: How can I implement the typesafe enum pattern in entity framework core rc2?
public class TestStatus
{
    [Column("Id")]
    public int Id { get; private set; }

    [Column("Description")]
    public string Description { get; private set; }

    [Column("LongDescription")]
    public string LongDescription { get; private set; }

    private TestStatus(int id
        , string description
        , string longDescription)
    {
        Id = id;
        Description = description;
        LongDescription = longDescription;
    }

    public TestStatus() { }

    public static readonly TestStatus Active = new TestStatus(1, "Active", "Active Long Description");
    public static readonly TestStatus Pending = new TestStatus(2, "Pending", "Pending Long Description");
    public static readonly TestStatus Cancelled = new TestStatus(3, "Cancelled", "Cancelled Long Description");
}

The id generation strategy is set in OnModelCreating:
builder.Entity<TestStatus>()
    .Property(s => s.Id)
    .ValueGeneratedNever();

This is a simplified example, but the real code was working in rc1.  When upgrading to rc2, I had to add the Column attributes so that the properties would be mapped (I assume this is because of the private setter).  When attempting to assign the typesafe enum value:
var i = new TestItem
{
    Name = "Test Item 2",
    Status = TestStatus.Active
};
_context.Items.Add(i);
_context.SaveChanges();

I get one of the following errors depending on the use case:
InvalidOperationException: The instance of entity type 'TestStatus' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate  unique key values.
Or
SqlException: Violation of PRIMARY KEY constraint 'PK_Statuses'. Cannot insert duplicate key in object 'dbo.Statuses'. The duplicate key value is (1). The statement has been terminated.
I understand the error.  EF thinks that I am trying to create a new instance with the same Id.  How can I tell EF that these instances should be considered the same?  I can workaround this by moving away from the typesafe enum pattern.  I would just like to make it work with the pattern if possible.  It was working in rc1.
Comment: Why do the `TestStatus` objects all have the same `Id`?
Comment: @noox That was a typo.  I have edited the question to fix it.  Thanks!
Answer: Since you are using the Type-Safe Pattern there is no need to persist the whole object. Simply  store the id and create a wrapper like so:
    [Required]
    protected string ObjectTypeValue { get; set; }

    [NotMapped]
    public ObjectType Type
    {
        get { return ObjectType.Parse(ObjectTypeValue); }
        set { ObjectTypeValue = value.Print(); }
    }

For some reasons I use a string as an Id, but you can use any type you like.
Comment: It took me a minute or two to wrap my head around the answer @sam was proposing. For anyone that might be struggling with this, what he's saying is to create a property on the type that uses the Type-Safe Enum that only stores the value (or id or whatever you called it). That makes EF happy since all it has to do is store a simple type. Next, simply create a "wrapper" that exposes the Type-Safe Enum as an object by calling some kind of `.Parse` method on your enum. Ta-da!


Impossível encontrar componente Primefaces

Question: Estou com o seguinte problema:
Quero criar uma tela de login e senha. Estou utilizando o primefaces para pegar os componentes, porém não estou conseguindo fazer com que apareça o campo para preencher com a senha.
Analisando com minha visão leiga, parece que ele não reconhece a tag do primefaces
Link do componente no primefaces: https://www.primefaces.org/showcase/ui/input/password.xhtml
index.xhtml:

<?xml version='1.0' encoding='ISO-8859-1' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
 <title>Pagina Incial da Biblioteca</title>

</h:head>
<h:body>

<h:form>

    <h:panelGrid columns="2" id="matchGrid" cellpadding="5">

        <h:outputLabel for="pwd1" value="Senha: " />

    </h:panelGrid>

</h:form>

</h:body>

PasswordView:
import javax.faces.bean.ManagedBean;

@ManagedBean
public class PasswordView {

    private String password1;
    private String password2;
    private String password3;
    private String password4;
    private String password5;

    public String getPassword1() {
        return password1;
    }

    public void setPassword1(String password1) {
        this.password1 = password1;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }

    public String getPassword3() {
        return password3;
    }

    public void setPassword3(String password3) {
        this.password3 = password3;
    }

    public String getPassword4() {
        return password4;
    }

    public void setPassword4(String password4) {
        this.password4 = password4;
    }

    public String getPassword5() {
        return password5;
    }

    public void setPassword5(String password5) {
        this.password5 = password5;
    }
}

Erro apresentado:

mar 20, 2019 8:58:35 AM com.sun.faces.renderkit.html_basic.HtmlBasicRenderer getForComponent
  ADVERTÊNCIA: Não foi possível encontrar o componente com a ID pwd1 na exibição.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>2BIIM_Aula9_JSF</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
</web-app>
Comment: Poderia por gentileza incluir todo o código da sua `index.xhtml`?
Comment: Atualizei, agora com o index.xhtml completo
Comment: Você pode também postar o print da tela que não está abrindo?
Comment: Atualizado, no link do primefaces mostra como deveria ficar.

Link: https://www.primefaces.org/showcase/ui/input/password.xhtml
Comment: você configurou seu `web.xml` mapeando a servlet do JSF? Algo como `javax.faces.webapp.FacesServlet`? Caso você não tenha mapeado a extensão `.xhtml` para passar pelo servlet a página não será renderizada de acordo. Por gentileza poste seu `web.xml`
Comment: Atualizado, na imagem 1 e 2 do web.xml existe o javax.faces.webapp.FacesServlet, porém não tenho total certeza de que está correto.
Answer: Atualmente o mapeamento do servlet está apenas para urls /faces/*
Adicione o seguinte mapeamento ao web.xml:
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

Isso irá fazer as páginas xhtml serem processadas pelo servlet do JSF.

UPDATE: Existe mais um detalhe importante em sua implementação, sua versão do PrimeFaces (3.5) não suporta o JSF 2.2.
Para utilizar JSF 2.2, você deve atualizar o PrimeFaces para no mínimo a versão 4.0
Outra opção seria utilizar a versão 2.1 do JSF.
Mais informações podem ser encontradas nesta thread do StackOverflow em inglês
Comment: Ainda está dando o mesmo erro: ADVERTÊNCIA: Não foi possível encontrar o componente com a ID pwd1 na exibição.
-
-
-
Coloquei o nova mapeamento logo abaixo do /faces/*
Comment: @LucasTrigoSchott complementei a resposta com mais um detalhe
Comment: Cara, atualizei o primefaces para ultima versão, no caso 7.0 e ainda apresenta o erro de impossível encontrar componente
Comment: Deve ser algum erro de configuração do projeto em sí, vou tirar um tempo e subir um projeto de modelo funcionando para você no meu Github, te aviso aqui quando subir lá
Comment: Ok, muito obrigado. Pesquisei outras maneiras de fazer fazer também e estou aqui tentando ;)
Answer: Encontrei o erro, era na configuração do Deployment eu não havia colocado o primefaces lá.


Drupal Commerce: Add content nodes to checkout steps

Question: We have a number of checkout steps that have some content in them that can only be edited via templates which is not ideal for clients.
Is it possible to create content nodes in the CMS that can then be used on the checkout?
Answer: It is! With the module commerce_extra_panes you can add nodes (content) to the checkout.
Comment: Cheers Lenni, that does the trick.


SQL Replace multiple different characters in string

Question: I need to replace multiple characters in a string. The result can't contain any '&' or any commas.
I currently have:
REPLACE(T2.[ShipToCode],'&','and')

Which converts & to and, but how do you put multiple values in one line?
Answer: You just need to daisy-chain them:
REPLACE(REPLACE(T2.[ShipToCode], '&', 'and'), ',', '')

Answer: One comment mentions "dozens of replace calls"... if removing dozens of single characters, you could also use Translate and a single Replace.
REPLACE(TRANSLATE(T2.[ShipToCode], '[];'',$@', '#######'), '#', '')

Comment: However, TRANSLATE is only available from SQL Server 2017 onwards.
Comment: Why not TRANSLATE into blanks directly ?
Comment: @Ludovic because SQL spits this error if you try "The second and third arguments of the TRANSLATE built-in function must contain an equal number of characters."
Comment: Is there a performance gain/loss depending how many times you use replace on a single line, or a single replace and translate?
Answer: We used a function to do something similar that looped through the string, though this was mostly to remove characters that were not in the "@ValidCharacters" string. That was useful for removing anything that we didn't want - usually non-alphanumeric characters, though I think we also had space, quote, single quote and a handful of others in that string.  It was really used to remove the non-printing characters that tended to sneak in at times so may not be perfect for your case, but may give you some ideas.
CREATE FUNCTION [dbo].[ufn_RemoveInvalidCharacters]
 (@str VARCHAR(8000), @ValidCharacters VARCHAR(8000))
RETURNS VARCHAR(8000)
BEGIN
  WHILE PATINDEX('%[^' + @ValidCharacters + ']%',@str) > 0
   SET @str=REPLACE(@str, SUBSTRING(@str ,PATINDEX('%[^' + @ValidCharacters +
']%',@str), 1) ,'')
  RETURN @str
END

Comment: Preferring this solution since it doesn't daisy-chain dozens of `REPLACE` calls
Answer: If you need fine control, it helps to indent-format the REPLACE() nesting for readability.
SELECT Title,
REPLACE(
    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(RTRIM(Title),
                            ' & ',''),
                        '++', ''),
                    '/', '-'),
                '(',''),
            ')',''),
        '.',''),
    ',',''),
' ', '-')
AS Title_SEO
FROM TitleTable

Answer: If you use SQL Server 2017 or 2019 you can use the TRANSLATE function.
TRANSLATE(ShipToCode, '|+,-', '____')

In this example the pipe, plus, comma, and minus are all replaced by an underscore.
You can change every character with its own one.
So in the next example the plus and minus are replaced by a hash.
TRANSLATE(ShipToCode, '|+,-', '_#_#')

Just make sure the number of characters is the same in both groups.
Answer: Hope this might helps to anyone
If you want to replace multiple words or characters from a string with a blank string (i.e. wanted to remove characters), use regexp_replace() instead of multiple replace() clauses.
SELECT REGEXP_REPLACE("Hello world!123SQL$@#$", "[^\w+ ]", "")

The above query will return Hello world123SQL
The same process will be applied if you want to remove multiple words from the string.
If you want to remove Hello and World from the string Hello World SQL, then you can use this query.
SELECT REGEXP_REPLACE("Hello World SQL", "(Hello|World)", "")

This will return  SQL
With this process, the query will not look redundant and you didn't have to take care of multiple replace() clauses.
Conclusion
If you wanted to replace the words with blank string, go with REGEXP_REPLACE().
If you want to replace the words with other words, for example replacing & with and then use replace(). If there are multiple words to be replaced, use multiple nested replace().
Comment: Looks like this function is only available for Oracle, and not SQL Server
Comment: This function is available in Google BigQuery and PostgreSQL
Answer: In SQL server to avoid daisy-chain them, you can try this:
SELECT REPLACE(TRANSLATE('?File /03-0>6-99 *Test/*.pdf', '<>:"/\|*?', REPLICATE('~',9)),'~','');

Answer: For SqlServer 2014 and older, you can write the equivalent of the TRANSLATE function like this :
CREATE OR ALTER FUNCTION dbo.TranslateBefore2016(@chaine NVARCHAR(MAX), @chars NVARCHAR(MAX), @translations @NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @tmp NVARCHAR(MAX) = @chaine

    declare @i as integer = 1
    WHILE @i <= len(@accents)
    BEGIN
        SET @TMP = REPLACE(@TMP COLLATE Latin1_General_CS_AS, substring(@chars , @i, 1) COLLATE Latin1_General_CS_AS, substring(@translations , @i, 1))

        SET @i = @i + 1
    END

    RETURN @TMP
END

Example of usage to remove accents :
select dbo.TranslateBefore2016('ABCDE éeeà', N'ÁÀÂÄÃÅÉÈÊËÍÌÎÏÓÒÔÖÕÚÙÛÜÇáàâäãåéèêëíìîïóòôöõúùûüç', N'AAAAAAEEEEIIIIOOOOOUUUUCaaaaaaeeeeiiiiooooouuuuc')

Please note :

The usage of the case sensitive collations
This function will probably need a test to check that @chars and @translations have


Is $\iint\limits_{D}\frac{1}{(x^{2}+y^{2})^{5}+5}dx\,dy$ convergent in $D=[0,+\infty)\times[0,+\infty)$

Question: Can you tell me whether my approach is correct.
We first switch to polar coordinates and we get the following integral:
$\int\limits_{0}^{\frac{\pi}{2}}\int\limits_{0}^{\infty}\frac{r}{r^{10}+5}d\phi dr=\int\limits _{0}^{\frac{\pi}{2}}d\phi\int\limits _{0}^{\infty}\frac{r}{r^{10}+5}dr=\frac{\pi}{2}\int\limits _{0}^{\infty}\frac{r}{r^{10}+5}dr$
From now on we solve it as it were an improper integral of single variable. We know that $\int\limits _{1}^{+\infty}\frac{1}{r^{\alpha}}$ is convergent $\iff\alpha\ge2$.
We use the following criteria. Let $F(x)\ge 0,\,G(x)\ge 0$ be such that $\lim\limits_{x\to\infty}\frac{F(x)}{G(x)}=\lambda,\lambda\in\mathbb{{R}}\cup\{+\infty\}$. If $\lambda$ is real and if $\int\limits_{a}^{+\infty}G(x)dx$ is convergent $\implies \int\limits _{a}^{+\infty}F(x)dx$ is also convergent.
We take $G(r)=\frac{1}{r^{9}}$ and compute $\lim\limits_{r\to\infty}\frac{F(r)}{G(r)}=\frac{r^{10}}{r^{10}+5}=1$, hence the integral is convergent.
Comment: Seems reasonable to me
Comment: Your condition $\alpha \ge 2$ should be $\alpha > 1$.
Comment: Another possibility is just to substitute $u = r^2$, which gives $\frac{1}{2(u^5+5)} \leq \frac{1}{u^5}$
Answer: It's simpler to say that $0 < \frac{r}{r^{10}+5} < \frac1{r^9}$ in $[1,\infty)$, and $\int\limits_1^{\infty}\frac1{r^9}dr$ converges, so $\int\limits_1^{\infty}\frac{r}{r^{10}+5}dr$ converges.
(Also, $0 \le \frac{r}{r^{10}+5} < \frac15$ in $[0,1]$, so $\int\limits_0^1\frac{r}{r^{10}+5}dr$ converges.)


For which $u$ does the derivative $f'(u,0)$ of $f(x,y)=xy/(x^2+y^2)$ exist?

Question: Let $f: \mathbb{R}^2\to \mathbb{R}$ be defined by setting
$$f(x,y)=\begin{cases}\frac{xy}{x^2+y^2}&(x,y)\neq (0,0)\\0 & (x,y)=(0,0)\end{cases}$$
(a) For which vectors $u\ne 0$ does $f'(0; u)$ exist? Evaluate it when it
exists.
(b) Do $D_1f$ and $D_2f$ exist at $0$?
(c) Is $f$ differentiable at $0$?
(d) Is $f$ continuous at $0$?
I have thought a lot about this problem: for (a), let $u\neq 0$ and $u=(h,k)$ then $\lim_{t\to 0}\frac{f(o+tu)-f(0)}{t}=\lim_{t\to 0}\frac{f(0+t(h,k))-f(0)}{t}=\lim_{t\to 0}\frac{hk}{t(h^2+k^2)}$ and so this limit exists if $h=0$ or $k=0$.
Comment: I have taken the liberty to "compact" your title.
Comment: By considering $u=(h,h)$ and $u=(h,0)$, you'll be able to give a negative answer to (d), so as (c).
Comment: Both f(u, 0) and f(0, y) are identically 0.  The derivatives at (0, 0) are 0,
Comment: Why don't you use $(\partial f/\partial x, \partial f/\partial y)$ instead of $f'(u,v)$ ?
Comment: @JeanMarie Is my reasoning right to answer (a)?
Comment: @JeanMarie I am studying from the book "Analysis on Manifold" by Munkres and he uses the notation that I use, I do not know other notations because I am just beginning to study vector analysis.
Comment: @user247327 I could say that since the directional derivative of $f$ in $0$ with respect to $u=(1,1)$ does not exist then the function is not differentiable in $0$?
Answer: b) Let $h= \in \Bbb{R}$ then $f(h,0)=f(0,h)=0$ so from this you can deduce that the partial derivatives at $(0,0)$ are zero.
d) Take the paths $(t,t)$ as $t \to 0$ and $(t,0)$ as $t \to 0$ and from these paths you will find different limits when approaching $(0,0)$, so you functions is not continuous at $(0,0)$ thus not differentiable at $(0,0)$
$\text{EDIT}$
Paths are curves, where in this case they pass through the point $(0,0)$.
If a limit exists then it is unique,thus uniqueness is a necessary condition for the existence of a limit at a given point.
If the limit of a function at a point $(x_0,y_0)$ exists then it will have the same value $l$ for every path we choose to approach the point $(x_0,y_0)$
So in this case the curves $g(t)=(t,t) \to (0,0)$ as $t \to 0$ and $h(t)=(t,0) \to (0,0)$ as $t \to 0$.
You can see this as approaching the origin from $\text{x-axis}$ namely where $y=0$ and $x$ varies,or approaching the origin from the diagonal,namely the line $y=x$
But these two approaches give two different results for the value of  $l$ thus the limit does not exist.
Comment: @Nash i edited...if you want more help let me know.
Comment: Please be more clear with your response. Explain everything please.
Comment: When you refer to paths this is understood as vectors directors?


To what extent has functional analysis been used in understanding neural networks?

Question: Has the family of models encapsulated by neural networks been studied from a functional analysis perspective? Are there any general theorems, results, etc. about neural networks from this perspective?
Comment: https://en.wikipedia.org/wiki/Universal_approximation_theorem
Comment: http://neuralnetworksanddeeplearning.com/chap4.html
Answer: Probably the core appeal of neural networks is the so-called "universal approximation theorem". Loosely stated, it's possible to use a neural network to approximate a continuous function on a compact subset of $\mathbb{R}^n$ using only a single hidden layer and finitely many neurons.
The continuous and compact portions of that statement are the immediately obvious caveats. Other caveats include those related to actually training the neural network: it may not be easy to train achieve a specific precision because training neural networks is hard.
More information can be found in Chapter 4 of Neural Networks and Deep Learning by Michael Nielsen. Wikipedia has a formal statement of the theorem.


How to delimit in a selective fashion in SQL

Question: I am trying to import something into SQL. The error is that the last field, SUB, in this case is too large and would be truncated. It makes sense that it would do so. The sample data below will bear this out. The CODDESC (code description) field has to have commas. The source file is a csv (comma delimited) file. When I import it into SQL, it understandably puts everything from the first comma in CODDESC into SUB. It has 14K rows and so manually editing it in Notepad ++ is impractical. As is importing into Excel.
<code> state     code    period    codty     coddesc        sub
   32      12345     20        1     clerk,cashier     1
   32      13456     20        1     cleaner,janitor   1
</code>
I looked at others such as
Import CSV file into SQL Server
However, it is not clear how I would insert this FIELDTERMINATOR || into the text file/sql table. Is there a way to delimit in such a way to where you only do based on the first 5 commas. Fixed width does not work because the codedesc field is between 8 and 45 characters long.
Answer: Not really an answer but I was able to accomplish the task using find and replace in notepad ++ and then performing some manual edits so that I could import it into Excel.


Como representar uma matriz em Prolog?

Question: Estou fazendo um trabalho em Prolog que consiste basicamente em um problema de busca, há um cenário em um ambiente bidimensional e deve-se traçar o caminho que um personagem deve seguir para chegar ao outro. Há alguns obstáculos e regras mas minha dúvida inicialmente é sobre como representar esse ambiente:
Ambiente 5 x 10 quadrados
 | A | B | C | D | E | F | G | H | I | J |
 |---|---|---|---|---|---|---|---|---|---|
1|   |   |   |   |   |   |   |   |   |   |
2|   |   |   |   |   |   |   |   |   |   |
3|   |   |   |   |   |   |   |   |   |   |
4|   |   |   |   |   |   |   |   |   |   |
5|   |   |   |   |   |   |   |   |   |   |

Comment: Por favor, poste um trecho do código que você já tem para termos uma ideia melhor do problema, sugiro que leia esse artigo da ajuda do site: [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Answer: A forma mais comum de se representar matrizes em linguagens de programação que não possuem um tipo nativo para tal é através de uma lista de listas:
ambiente([[_,_,_,_,_,_,_,_,_,_], [_,_,_,_,_,_,_,_,_,_], ... [_,_,_,_,_,_,_,_,_,_]]).

No entanto, outras representações são possíveis. Uma lista em Prolog é sempre uma lista encadeada, de modo que para acessar o elemento (m,n) você precisaria percorrer os primeiros m elementos para achar a lista certa, e então os n elementos dessa lista, para achar a posição que quer:
posicao(0,N,[Cabeca|_],E) :-
    posicao_lista(N,Cabeca,E).
posicao(M,N,[_|Cauda],E) :-
    M1 is M - 1,
    posicao(M1,N,Cauda,E).

posicao_lista(0,[X|_],X).
posicao_lista(N,[_|R],X) :-
    N1 is N - 1,
    posicao_lista(N1,R,X).

Em alguns casos isso pode ser suficiente, mas em outros você pode preferir uma representação alternativa, com acesso mais rápido (porém com modificação mais difícil). Se seu ambiente é imutável, uma alternativa seria listar explicitamente o que tem em cada célula, através de uma série de fatos isolados. Por exemplo:
celula(0,0,x).
celula(0,1,y).
celula(0,2,z).
...
celula(0,9,w).
celula(1,0,a).
celula(1,1,b).
...
celula(4,9,o).

Outras representações intermediárias também são possíveis, tipo:
linha(0, a, b, c, d, e, f, g, h, i, j). /* Substitua a,b,etc pelo valor da célula */
linha(1, a, b, c, d, e, f, g, h, i, j).
...

No fim das contas não há um padrão, você escolhe a representação que for mais fácil e mais lógico pra você trabalhar, conforme o problema que está tentando resolver.

Como representar uma matriz em Prolog?


getting warning messages while sending push notification to multiple iphone device

Question: While i am sending  push notifications to multiple iphone devices using php webservices i am getting warning messages like :
Warning: stream_socket_client() [function.stream-socket-client]: SSL: crypto enabling timeout in /home/sample_app/pushnotification.php on line 66

Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in /home/sample_app/pushnotification.php on line 66

Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.push.apple.com:2195 (Unknown error) in /home/sample_app/pushnotification.php on line 66

Warning: fclose() expects parameter 1 to be resource, boolean given in /home/sample_app/pushnotification.php on line 79

This is my code :
$message='testing';
$q1="select devicetoken from tbl_devicetokens";
$re1 = mysql_query($q1);
while($row1=mysql_fetch_row($re1))
{
    pushMessage($row1[0],$message,'myapp');
}

function pushMessage($deviceToken,$message,$app) {
    echo "Sending iPhone Push Notifications to " . $deviceToken . "

";
    echo "Your Message: " . $message . "

";
    $time = time();
    $apnsHost = 'gateway.push.apple.com';
    $apnsPort = 2195;
    $apnsCert = 'apns-myapp.pem';
    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
    $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
    if($apns) {
            $payload = array();
            $payload['aps'] = array('alert' => $message, 'badge' => 0, 'sound' => 'default');
            $payload = json_encode($payload);
            $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
            fwrite($apns, $apnsMessage);
    } else {
            echo "Connection Failed - iPhone Push Notifications Server";
            echo $errorString."
";
            echo $error."
";
    }
    //socket_close($apns);
    fclose($apns);
}

So, can any one tell me how to solve this problem
Comment: http://stackoverflow.com/questions/14078182/openssl-file-get-contents-failed-to-enable-crypto
Comment: Please post your code.
Comment: See this http://stackoverflow.com/questions/15196145/apn-php-code-giving-warning-stream-socket-client-function-stream-socket-clie
Comment: this is not your full code. Paste your full code.
Answer: might seem like a dumb answer, but have you tried your firewall / iptables? Those errors without further information look like connection issues to me. First thing you need to resolve is the timeout problem.
Answer: Does this still happen when you push a single notification to a single device?
If it does:

Are you sure that you have the correct path to the certs?
Make sure that the cert file name does not contain other than alphabetic characters.

If not:

Make sure that you are using the correct cert for the correct device environment (development, production)
If a device is jailbroken it will not receive push notifications.
Comment: Yes,Warning messages are getting while i am sending push notifications to single device , even after giving correct path to the certs and not allowing alphabetic characters in the cert file name