qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
4,111,454 | I need to do a check on a page to check if certain images have loaded ie. not returned 404. If they arent available I want to replace the image with a default images.
I am aware I can assign an onerror handler to the images.
Firstly I need to use a selector to find all the images that have a source which contains the following image name -> /folder/Product\_1234\_P.jpg OR /folder/Product\_9876\_Q.gif
Any ideas how I can create a high performance selector that I can use to find such images so that I can check if the images loaded, if not replace the image name with: Product\_Default\_P.jpg or Product\_Default\_Q.gif
Any help or advice would be great. | 2010/11/06 | [
"https://Stackoverflow.com/questions/4111454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373674/"
] | You can use the image's [error handler](http://api.jquery.com/error/) and the [attribute contains selector](http://api.jquery.com/attribute-contains-selector/) like so:
```
$("img[src*=Product]").error(function() {
$(this).attr('src', 'notfound.jpeg');
});
``` | ```
$('img[src*="substring"]')
```
It's an attribute selector. Check it out <http://api.jquery.com/attribute-contains-selector/> |
50,550 | The [2020 Military Strength Rankings](https://www.globalfirepower.com/countries-listing.asp) list Russia's military as #2 in strength:
1. United States
2. Russia
3. China
However, [their defense budget rankings](https://www.globalfirepower.com/defense-spending-budget.asp) show that Russia's only #8 in spending:
1. United States (~750 billion USD)
2. China (~237 billion USD)
[... Saudi Arabia, India, United Kingdom, Germany, Japan ...]
8. Russia (~48 billion USD)
How is Russia able to maintain such a powerful military despite relatively low defence spending compared to other similarly ranked countries? | 2020/02/29 | [
"https://politics.stackexchange.com/questions/50550",
"https://politics.stackexchange.com",
"https://politics.stackexchange.com/users/28994/"
] | I have no experience in the Russian or US military, but my impression is that Russian weapons manufacturers face much greater pressures to charge lower prices.
US weapons manufactures consider the Pentagon a bottomless pit of money and face no pressure to reduce prices. 200 TOW missiles? Let's add a 3 extra zeros to the bill. Raytheon can charge whatever because there is no "mark to market" for a TOW.
The GDP of the Russian Federation is 1/3 the size of California alone. Russian generals count every penny spent on defense. On a weapons per weapons basis, Russia has much more parity than $ per $. Roughly speaking, 1 Kalibr = 1 Tomahawk. But, just because the US Navy is charged 4 times more for 1 Tomahawk than the Russian Navy is for 1 Kalibr does not make the US Navy 4 times stronger.
China has the weakest military. None of their weapons or soldiers have been proven in real combat. Mike Tyson famously said: "Everyone has a plan, until they get punched in the face." Soldiers have told me, no matter how much training you might do, nothing can prepare one for live incoming and facing death... US and Russia have proven their current weapons and soldiers in real battles (in the Middle East).
The future of India's national defense will be revealing. Will Modi switch from "as good" Russian weapons that cost ~1/10 in total ownership to that of US weapons... Unlike the Pentagon, Modi will have to monitor his defense budget. And, he might be using defense contractors that have never had concerns about controlling prices. So, let's see what Modi does. | The USA has military posts all over the world, at huge expense.
Russia has almost none in comparison.
Russia has been able to spend money on technology and internal infrastructure and therefore has a world-class military at a fraction of the cost. |
1,004,899 | I have a weird problem when using JQuery call in my ASP.NET MVC project. I found that the Ajax call gives 404 ( resource not found error). But when I use the usual URL GET call, I can successfully call the server without any problem. Any idea why this is so?
This my ASP.NET MVC code
```
public class ViewRecordController: Controller
{
public JSONResult GetSoftwareChoice(string username)
{
return Json(username);
}
}
```
This is my JQuery code:
```
$(function() {
$("#username").click(function() {
$.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
function(data) {
alert(data);
});
});
});
```
The above JQuery gives me a 404 error. Apparently the `ViewRecord/GetSoftwareChoice` is not found on server, as far as the AJAX call is concerned.
But if I type this in my web browser:
```
http://myapp/ViewRecord/GetSoftwareChoice?username=123
```
then there is no problem.
This is very weird, indeed.
Just in case if you are interested, this is my route:
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
```
Edit: I step into my code, and found that the URL call is `ViewRecord/GetSoftwareChoice?username=123`.
Related question: [Select Element inside Form not working in JQuery](https://stackoverflow.com/questions/1000246/select-element-inside-form-not-working-in-jquery) | 2009/06/17 | [
"https://Stackoverflow.com/questions/1004899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | ```
$(function() {
$("#username").click(function() {
$.getJSON('<%= Url.Action("GetSoftwareChoice", "ViewRecord")%>',{username: '123'}, function(data) {
alert(data);
});
});
});
``` | Old function :
```
function Chart() {
var url = "../Home/Pie/";
$.ajax({
url: url,
data: {},
cache: false,
type: "POST",
success: function (data) {
var chartData = data;
createChart(chartData);
$(document).bind("kendo:skinChange", createChart);
},
error: function (xhr, status, error) {
$('#alertdialog').html(status);
$('#alertdialog').dialog('open');
return false;
}
});
}
```
**Answers :**
**var url = "Home/Pie/**";
Removed ../ from url |
112,246 | I have a non-daemon server app that my Windows 2003 server needs to run all the time. The problem is, every time the server restarts, be it electricity or windows update, someone needs to press `Ctrl`+`Alt`+`Del` and enter username/password. Then the program starts, as it's in Startup. How do I make Windows 2003 to automatically log in to `Administrator` (or spawn a terminal services session) every time the system boots?
I know it's against the nature of servers and all. But this is the only thing the server does. | 2010/02/12 | [
"https://serverfault.com/questions/112246",
"https://serverfault.com",
"https://serverfault.com/users/3007/"
] | 1. Run `gpedit.msc`
Under `Local Computer Policy > Computer Configuration > Administrative Templates > System`, set "Display Shutdown Event Tracker" to "Not configured".

2. Run `control userpasswords2`
3. Uncheck "User must enter user name and password to use this computer."

4. Enter your password into the dialog that pops up.

5. Also, via `Desktop > right-click > [Display] Properties > Screen Saver (tab) > Power... (button) > Advanced (tab)`, uncheck "Prompt for password when computer resumes from standby":
 | 1. Run `control userpasswords2`
2. Uncheck checkbox "User must enter user name and password to use this computer."
3. Run `gpedit.msc`
Computer Configuration > Administrative Templates > System > Display Shutdown Event Tracker > Settings, and select radio button: "Disabled" (or "Not configured"). |
111,760 | How can I explain the relationship of building A to building B where building A is, e.g., on the NW corner of an intersection, and building B is on the SE corner?
Which of the following (if any) is the clearest? If none, is there a clearer way?
>
> The building A would be diagonally opposite the building B.
>
>
> The building A would be opposite the building B, with 45 degrees to the right.
>
>
> The building A would be kitty-corner to the building B.
>
>
> | 2013/04/19 | [
"https://english.stackexchange.com/questions/111760",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/42787/"
] | I assume you are asking about a situation like this:

It is technically and mathematically correct to say that they are on **opposite corners**. However, this can indeed be misconstrued, as you've noted. I do not believe that there are any terms in common usage that would be guaranteed to be clear to any given audience. | For me, I would say **opposing corners** on xyz street. |
66,527,812 | I have data like the example below. For each participant, if a particular string (`"trial_end"`) is present in the `my_strings` column I would like to remove all the rows after its appearance.
```
library(dplyr)
library(stringr)
library(tibble)
df1 <- tibble::tribble(
~participant_id, ~timestamp, ~my_strings,
1L, 1L, "other_string",
1L, 2L, "other_string",
1L, 3L, "trial_end",
1L, 4L, "other_string",
2L, 1L, "other_string",
2L, 2L, "other_string",
2L, 3L, "other_string",
2L, 4L, "other_string",
3L, 1L, "other_string",
3L, 2L, "trial_end",
3L, 3L, "other_string",
3L, 4L, "other_string"
)
```
My first attempt was to use `str_detect` to look for the presence of the string, `which` to provide the row number, then use `filter` to keep only that row and all those before it:
```
df2 <- df1 %>%
group_by(participant_id) %>%
filter(row_number() < (which(str_detect(my_strings, "trial_end"))) + 1)
```
This seems to throw an error when the string is not detected (e.g. participant 2 in the example here).
My next attempt was to add a conditional `if_else`, trying to effectively say 'IF the target string is detected THEN remove all the rows after for that participant, ELSE if the string is not detected, do nothing'.
```
df3 <- df1 %>%
group_by(participant_id) %>%
if_else(str_detect(my_strings, "trial_end"),
filter(row_number() < (which(str_detect(my_strings, "trial_end"))) + 1),
filter(timestamp < max(timestamp)))
```
This also returned an error:
*Error: `condition` must be a logical vector, not a `grouped_df/tbl_df/tbl/data.frame` object.*
My final attempt tried to make use of another answer already here, by placing the conditional if else inside `filter`, but this too produced an error.
```
df4 <- df1 %>%
group_by(participant_id) %>%
filter(if(str_detect(my_strings, "trial_end") < (which(str_detect(my_strings, "trial_end")) + 1))
else < n())
```
Can anyone point out the best approach for this problem? Is `filter` the wrong way to go about it?
Many thanks.
For clarity, the desired outcome would look like this:
```
desired_output <- tibble::tribble(
~participant_id, ~timestamp, ~my_strings,
1L, 1L, "other_string",
1L, 2L, "other_string",
1L, 3L, "trial_end",
2L, 1L, "other_string",
2L, 2L, "other_string",
2L, 3L, "other_string",
2L, 4L, "other_string",
3L, 1L, "other_string",
3L, 2L, "trial_end"
)
``` | 2021/03/08 | [
"https://Stackoverflow.com/questions/66527812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5115721/"
] | One option could be:
```
df1 %>%
group_by(participant_id) %>%
slice(if(all(my_strings != "trial_end")) 1:n() else 1:which(my_strings == "trial_end"))
participant_id timestamp my_strings
<int> <int> <chr>
1 1 1 other_string
2 1 2 other_string
3 1 3 trial_end
4 2 1 other_string
5 2 2 other_string
6 2 3 other_string
7 2 4 other_string
8 3 1 other_string
9 3 2 trial_end
``` | You could count the cumulative sum of matches up to the prior row and filter to only include rows up to the first match per participant:
```
df1 %>%
group_by(participant_id) %>%
filter(lag(cumsum(my_strings == "trial_end"), default = 0) < 1) %>%
ungroup()
# A tibble: 9 x 3
participant_id timestamp my_strings
<int> <int> <chr>
1 1 1 other_string
2 1 2 other_string
3 1 3 trial_end
4 2 1 other_string
5 2 2 other_string
6 2 3 other_string
7 2 4 other_string
8 3 1 other_string
9 3 2 trial_end
``` |
18,731,288 | I am trying to write a directive to deal with changing an icon class for table headers. What I would like is (what I believe anyway) the standard way of dealing with sorting by table headers. The directive would add a link element and upon a user's click sort by desc and change the icon to desc, upon click again sort by asc and once again the the icon. Here is what I have so far, but I am now at a loss for how to deal with the icon class as well as resetting other elements on the same table but outside of the directive's scope. Any help would be great!
```
angular.directive("tableHeaders", function() {
return {
restrict: 'E',
scope: {},
template:'<i class="glyphicon glyphicon-filter"></i>',
link: function(scope, element, attrs) {
attrs.class = 'glyphicon glyphicon-sort-by-alphabet-alt';
}
}
});
```
Here is what I have for the html side:
```
<th>First Name<a ng-click="newOrderBy('_firstName')"><table-headers></table-headers></a></th>
<th>Last Name<a ng-click="newOrderBy('_lastName')"><table-headers></table-headers></a></th>
<tr ng-repeat="item in items | orderBy:orderBy:reverse>
<td>{{item._firstName}}</td>
<td>{{item._lastName}}</td>
</tr>
```
The order by is currently handled in the controller:
```
$scope.newOrderBy = function(order) {
$scope.orderBy = order;
$scope.reverse = !$scope.reverse;
};
``` | 2013/09/11 | [
"https://Stackoverflow.com/questions/18731288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/953088/"
] | What you need to do is for each element using your directive providing both an order and the current order (the one from your controller).
BTW I think your directive will be a better match as an attribute and not a tag. You can check the following code :
```
angular.module('myApp', []).directive("sort", function() {
return {
restrict: 'A',
transclude: true,
template :
'<a ng-click="onClick()">'+
'<span ng-transclude></span>'+
'<i class="glyphicon" ng-class="{\'glyphicon-sort-by-alphabet\' : order === by && !reverse, \'glyphicon-sort-by-alphabet-alt\' : order===by && reverse}"></i>'+
'</a>',
scope: {
order: '=',
by: '=',
reverse : '='
},
link: function(scope, element, attrs) {
scope.onClick = function () {
if( scope.order === scope.by ) {
scope.reverse = !scope.reverse
} else {
scope.by = scope.order ;
scope.reverse = false;
}
}
}
}
});
```
And the plunker that goes with it : <http://plnkr.co/edit/P4cAm2AUGG36nejSjOpY?p=preview>
The directive is used as such :
```
<thead>
<tr>
<th sort by="order" reverse="reverse" order="'name'">Name</th>
<th>Phone</th>
<th sort by="order" reverse="reverse" order="'age'">Age</th>
</tr>
</thead>
``` | Unless you are intent on writing your own directive, you might consider looking at what is available.
[ngmodules.org](http://ngmodules.org) shows some directives that are already set up for table headers.
Here are a couple options with some sample code to give you a feel for both. They both look to be developed and very customizable.
[ngTable](http://bazalt-cms.com/ng-table/example/3)
---------------------------------------------------

```
angular.module('main', ['ngTable'])
.controller('DemoCtrl', function($scope, $filter, ngTableParams) {
var data = [{name: "Moroni", age: 50}, ... ]
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: data.length, // length of data
getData: function($defer, params) {
// use build-in angular filter
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) :
data;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
});
```
[UI Grid](http://ui-grid.info/)
-------------------------------

```
angular.module('app', ['ngAnimate', 'ui.grid'])
.controller('MainCtrl', function ($scope) {
$scope.gridOptions1 = {
enableSorting: true,
columnDefs: [
{ field: 'name' },
{ field: 'gender' },
{ field: 'company', enableSorting: false }
],
onRegisterApi: function (gridApi) {
$scope.grid1Api = gridApi;
}
};
});
``` |
4,255,154 | Is there some kind of `split()` function in XPath?
Say I have this XML:
```
<root>
<path>C:\folder\filename</path>
</root>
```
And I want to retrieve `filename`, how can I do this? I know I can get the node value like this:
```
//path/text()
```
How can I get only the filename? (I know there is a `concat()` function, so maybe there is a `split()` function?) | 2010/11/23 | [
"https://Stackoverflow.com/questions/4255154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/431879/"
] | If you have an xpath-2.0 capable API, you can solve this in two ways:
**replace technique**
Try using:
```
fn:replace(string,pattern,replace)
```
e.g.
```
fn:replace(//path/text(),".*/","")
```
**tokenize technique**
You may get some mileage from tokenize:
```
fn:tokenize(string,pattern)
```
e.g. (thanks to Martin)
```
tokenize(/root/path, '\\')[last()]
```
[w3schools xml processing "xsl functions" documentation](https://www.w3schools.com/xml/xsl_functions.asp#string) | **While I would use**:
```
tokenize(/*/*, '\\')[last()]
```
**there are also numerous other ways to obtain the desired string**:
```
codepoints-to-string
(reverse
(string-to-codepoints
(substring-before
(codepoints-to-string
(reverse
(string-to-codepoints(/*/*)
)
),
'\'
)
)
)
)
```
**Or**:
```
substring(/*/*,
index-of(string-to-codepoints(/*/*),
string-to-codepoints('\')
)
[last()]
+ 1
)
``` |
19,280,416 | My xml and xslt file looks like follow. problem is when i apply my transformation file only 2nd one happens 1st one skips. How could i run both on first run. Please help Thanks.
```
//BEFORE TRANSFORMATION
<A>
<B>
<Name>ThisOne</Name>
<Target>abc</Target>
</B>
</A>
```
My XSLT FIle
```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="xml" indent="yes"/>
<!--Transformation 1 to replace Target Text-->
<xsl:template match="A/B/Target/text()">
<xsl:text>xyz</xsl:text>
</xsl:template>
<!--Transformation 2 to Add a new node after Target-->
<xsl:template match="A/B/Target">
<xsl:copy-of select="."/>
<JOJO></JOJO>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
```
What i would like to see after transformation is following
```
<A>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target>
<JOJO/>
</B>
</A>
``` | 2013/10/09 | [
"https://Stackoverflow.com/questions/19280416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585883/"
] | There are two types of variable in C#. The first is called a "Value" type. When you assign it a value, the value is copied to that location, so when you write
```
int b = a;
```
You are *copying* the value of a to b.
However, there is also a "Reference" type. This only copies over a *reference* to the variable - in other words, it gets a sort of handle to the variable, so that when changes are made to that variable, they get reflected in both places.
Value types include `struct`s and all primitives - ints, doubles, chars, etc. *except* strings. Reference types are everything else.
Some commenters have already provided good links, so I won't add any here. | In C# Arrays are Reference Types. See [this](http://msdn.microsoft.com/en-us/library/4d43ts61%28v=vs.90%29.aspx)
Though I assumed this would end up being a duplicate question, I do apologize for not expounding further on the link.
In C# you have Value Types and Reference Types. All Arrays (even if they are arrays of Value types) are Reference Types.
A Value Type behaves as in your first example and the memory necessary to store its value is allocated on the Stack which lives and dies with the scope of the containing object.
A Reference type stores only a pointer to a location on the Heap where memory is allocated and it lives until the Garbage Collector determines nothing is using it anymore and it can be cleaned up. So if you assign a reference type to another reference type, they are the same object with different names.
This is of course horribly oversimplified, but you can get more information at the link in my answer or in any of the wonderful SO Questions addressing this same topic. |
4,501,883 | Can anyone explain me this code split("[ ]+", $s);
thanks
```
$s = "Split this sentence by spaces";
$words = split("[ ]+", $s);
print_r($words);
Output:
Array
(
[0] => Split
[1] => this
[2] => sentence
[3] => by
[4] => spaces
)
``` | 2010/12/21 | [
"https://Stackoverflow.com/questions/4501883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The first argument to [split](http://www.php.net/split) is a regex pattern, which in this instance is effectively saying "match the space character as many times as possible".
**N.B.: split is deprecated as of PHP 5.3, so I wouldn't recommend using this.**
You could achieve precisely the same effect via:
```
$words = explode(" ", $s);
```
See the [explode manual page](http://www.php.net/explode) for more info. | ```
"[ ]+"
```
Is a regex expression. It will split the string according to spaces. |
10,638,951 | So I have this huge tree that is basically a big switch/case with string keys and different function calls on one common object depending on the key and one piece of metadata.
Every entry basically looks like this
```
} else if ( strcmp(key, "key_string") == 0) {
((class_name*)object)->do_something();
} else if ( ...
```
where `do_something` can have different invocations, so I can't just use function pointers. Also, some keys require object to be cast to a subclass.
Now, if I were to code this in a higher level language, I would use a dictionary of lambdas to simplify this.
It occurred to me that I could use macros to simplify this to something like
```
case_call("key_string", class_name, do_something());
case_call( /* ... */ )
```
where `case_call` would be a macro that would expand this code to the first code snippet.
However, I am very much on the fence whether that would be considered good style. I mean, it would reduce typing work and improve the DRYness of the code, but then it really seems to abuse the macro system somewhat.
Would you go down that road, or rather type out the whole thing? And what would be your reasoning for doing so?
**Edit**
Some clarification:
This code is used as a glue layer between a simplified scripting API which accesses several different aspects of a C++ API as simple key-value properties. The properties are implemented in different ways in C++ though: Some have getter/setter methods, some are set in a special struct. Scripting actions reference C++ objects casted to a common base class. However, some actions are only available on certain subclasses and have to be cast down.
Further down the road, I may change the actual C++ API, but for the moment, it has to be regarded as unchangeable. Also, this has to work on an embedded compiler, so boost or C++11 are (sadly) not available. | 2012/05/17 | [
"https://Stackoverflow.com/questions/10638951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1034/"
] | Looks like you are missing some semi-colons after your strings as well.
```
if($form_id == "offense") {
$query="INSERT INTO ff_offense (ID, PLAYER, POSITION, TEAM, PASS_YDS, RUSH_YDS, REC_YDS, RECEPTIONS, TD)
VALUES ('NULL','$_POST[PLAYER]','$_POST[POSITION]','$_POST[TEAM]','$_POST[PASS_YDS]','$_POST[RUSH_YDS]','$_POST[REC_YDS]','$_POST[RECEPTIONS]','$_POST[TD]')";
} elseif($form_id=="kicker") {
$query="INSERT INTO ff_kicker {K_ID, K_PLAYER, K_TEAM, K_EXTRA_PTS, K_FG)
VALUES ('NULL','$_POST[K_PLAYER]','$_POST[K_TEAM]','$_POST[K_EXTRA_PTS]','$_POST[K_FG]')";
} elseif($form_id=="defense") {
$query= "INSERT INTO ff_defense {D_ID, D_TEAM, D_SACKS, D_INT, D_TD}
VALUES ('NULL','$_POST[D_TEAM]','$_POST[D_SACKS]','$_POST[D_INT]','$_POST[D_TD]')";
}
``` | These other answers are right, but there's a missing semicolon at the end of this declaration also, which is what's causing the syntax error:
```
if($form_id ="offense") { $query="INSERT INTO ff_offense (ID, PLAYER, POSITION, TEAM, PASS_YDS, RUSH_YDS, REC_YDS, RECEPTIONS, TD)
VALUES ('NULL','$_POST[PLAYER]','$_POST[POSITION]','$_POST[TEAM]','$_POST[PASS_YDS]','$_POST[RUSH_YDS]','$_POST[REC_YDS]','$_POST[RECEPTIONS]','$_POST[TD]')"; }
```
edit: To be clear, all of the declarations are missing a semicolon, not just the one. |
35,491,089 | I can't seem to get the date-picker working. I'm not sure what im doing wrong. Im pretty sure Im passing the right name but Im not sure if I have it all setup right?
HTML:
```
{% extends "base.html" %}
{% load bootstrap3 %}
{% load static %}{% load staticfiles i18n %}
{% block title %}Jobs{% endblock %}
{% block head %}
<link rel="stylesheet" href="{% static "datepicker/css/datepicker.css" %}"/>
<script src="{% static "datepicker/js/bootstrap-datepicker.js" %}"></script>
<script>
$(document).ready(function() {
$('#job_pickup_date, #filter_pickup_date, #filter_dropoff_date').datepicker({
'format': 'yyyy-mm-dd'
});
});
</script>
{% endblock %}
{% block content %}
<div class="modal fade" id="modal_new">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">New Job</h4>
</div>
<div class="modal-body">
<form method="post" action="">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
{% bootstrap_field form_job.pickup_date class="datepicker" %}
{% bootstrap_field form_job.pickup_city %}
{% bootstrap_field form_job.pickup_state %}
```
Base HTML:
```
{% bootstrap_css %}
{% bootstrap_javascript %}
<link rel="stylesheet" href="{% static "css/app.css" %}"/>
<script src="{% static "js/app.js" %}"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
{% block css %}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css">
<!-- Your stuff: Third-party css libraries go here -->
{% bootstrap_css %}
<link href="http://v4-alpha.if %.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="{% static 'css/narrow-jumbotron.css' %}" rel="stylesheet">
<!-- This file store project specific CSS -->
<link href="{% static 'css/app.css' %}" rel="stylesheet">
{% endblock %}
{% block angular %}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
{% endblock %}
```
And bottom of base.html:
```
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
{% block javascript %}
<!-- Latest JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
<!-- Your stuff: Third-party javascript libraries go here -->
<script src="{% static 'js/app.js' %}"></script>
<script src="http://twitter.github.com/bootstrap/assets/js/bootstrap.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- place project specific Javascript in this file -->
<script src="{% static 'js/project.js' %}"></script>
{% endblock javascript %}
{% block sripts %}{% endblock %}
</body>
</html>
``` | 2016/02/18 | [
"https://Stackoverflow.com/questions/35491089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699345/"
] | Here is [my solution](http://ideone.com/eWqWeP):
```
$re = "/{{(?<inner>.*?)}}|(?<outer>[^{}]*(?:{(?!{)[^{}]*|}(?!})[^{}]*)*)/";
$str = "{{Friday}}today{{Sunday}}";
preg_match_all($re, $str, $matches);
print_r(array_filter($matches["outer"]));
print_r(array_filter($matches["inner"]));
```
**Why does it look so complex?**
The regex contains 2 alternatives, one is for capturing all substrings inside `{{` and `}}` into Group "inner", and the Group "outer" captures all substrings other than those inside `{{` and `}}`. Let me explain these patterns:
*Part 1*:
`{{(?<inner>.*?)}}`
This finds and consumes `{{` substring, followed with zero or more characters other than a newline (use an `/s` dotall modifier at the end of the regex to also match newlines), zero or more occurrences (use `.+?` to match one or more), as few as possible (meaning we stop at the first `}}`). Then, `}}` are matched.
*Part 2*:
`(?<outer>[^{}]*(?:{(?!{)[^{}]*|}(?!})[^{}]*)*)`
This subpattern is equal to `(?<outer>(?:(?!{{(?!{)|}}(?!})).)*)`, but is an unrolled version of this [tempered greedy token](http://www.rexegg.com/regex-quantifiers.html#tempered_greed) (and is thus more efficient than a tempered greedy token with 2 alternatives). It just matches non-braces `[^{}]*` (zero or more) followed with zero or more sequences (=optionally matches) of a `{` not followed with another `{` or `}` not followed with another `}` and then zero or more non-braces.
The [`array_filter`](http://php.net/manual/en/function.array-filter.php) removes empty elements from the resulting arrays.
And here is a **[regex demo](https://regex101.com/r/oD9bT6/1)** | I have managed it. The problem of empty strings still remains. The single braces do not make a problem.
```
(?<={{)(?P<THINGS>((?<!}}).)+)(?=}})|((?<=}})(?P<AREA>((?<!{{).)+)(?={{))|(?P<AREA2>^((?<!{{).)+)(?={{)|(?<=}})(?P<AREA3>((.)+$))
```
[Debuggex Demo](https://www.debuggex.com/r/vzlA_hbB1LdQbD1y)
The result array:
```
array (
0 =>
array (
0 => 'Fo{rest',
1 => 'Go{l}d',
2 => 'Beach',
3 => 'Monay',
4 => 'Grass',
5 => 'Diamond',
6 => 'S{ea',
),
'THINGS' =>
array (
0 => '',
1 => 'Go{l}d',
2 => '',
3 => 'Monay',
4 => '',
5 => 'Diamond',
6 => '',
),
1 =>
array (
0 => '',
1 => 'Go{l}d',
2 => '',
3 => 'Monay',
4 => '',
5 => 'Diamond',
6 => '',
),
2 =>
array (
0 => '',
1 => 'd',
2 => '',
3 => 'y',
4 => '',
5 => 'd',
6 => '',
),
3 =>
array (
0 => '',
1 => '',
2 => 'Beach',
3 => '',
4 => 'Grass',
5 => '',
6 => '',
),
'AREA' =>
array (
0 => '',
1 => '',
2 => 'Beach',
3 => '',
4 => 'Grass',
5 => '',
6 => '',
),
4 =>
array (
0 => '',
1 => '',
2 => 'Beach',
3 => '',
4 => 'Grass',
5 => '',
6 => '',
),
5 =>
array (
0 => '',
1 => '',
2 => 'h',
3 => '',
4 => 's',
5 => '',
6 => '',
),
'AREA2' =>
array (
0 => 'Fo{rest',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => '',
),
6 =>
array (
0 => 'Fo{rest',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => '',
),
7 =>
array (
0 => 't',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => '',
),
'AREA3' =>
array (
0 => '',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => 'S{ea',
),
8 =>
array (
0 => '',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => 'S{ea',
),
9 =>
array (
0 => '',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => 'S{ea',
),
10 =>
array (
0 => '',
1 => '',
2 => '',
3 => '',
4 => '',
5 => '',
6 => 'a',
),
)
```
The php code:
```
$returnValue = preg_match_all('/(?<={{)(?P<THINGS>((?<!}}).)+)(?=}})|((?<=}})(?P<AREA>((?<!{{).)+)(?={{))|(?P<AREA2>^((?<!{{).)+)(?={{)|(?<=}})(?P<AREA3>((.)+$))/', 'Fo{rest{{Go{l}d}}Beach{{Monay}}Grass{{Diamond}}S{ea', $matches);
``` |
7,570,813 | Can anybody help me with this?
I am taking a table in Excel and exporting it as a web page. I noticed that the webpage rendered things differently -- such as spacing (it's putting in LOTS of white space where there should be none). Also, it's displaying columns that were hidden in my excel file.
Can anybody let me know how to export this so that the space rendering is not so different?
Also, does anybody know how to export this in a way where I can keep some Excel functions (i.e. sort, filtering, etc.)? | 2011/09/27 | [
"https://Stackoverflow.com/questions/7570813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102398/"
] | Finally it turns out that mustache doesn't handle array of objects sent to the template, so i had to wrap it with other object like this
```
render: function() {
var item_wrapper = {
items : this.collection
}
$(this.el).html(Mustache.to_html(JST.item_template(),item_wrapper ));
}
```
and in template just looped the items array to render the html
```
{{#items}}
<li>
<div>
<div style="float: left; width: 70px">
<a href="#">
<img class="thumbnail" src="http://placehold.it/60x60" alt="">
</a>
</div>
<div style="float: right; width: 292px">
<h4> {{name}} <span class="price">Rs {{price}}</span></h4>
</div>
</div>
</li>
{{/items}}
```
Hope it helps to someone. | Mustache can handle arrays using `{{#.}}{{.}}{{/.}}` |
48,425,043 | I'm trying to migrate a SF 3.3 app to SF 4 with its new directory structure and everything.
I'm struggling on this exception:
>
> The "simplethings\_entityaudit.reader" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.
>
>
>
(This service comes from an external bundle located in /vendor).
Nevertheless, when I `bin/console debug:container simplethings_entityaudit.reader` you'll see the service exists and is public:
```
Information for Service "simplethings_entityaudit.reader"
=========================================================
----------------- --------------------------------------
Option Value
----------------- --------------------------------------
Service ID simplethings_entityaudit.reader
Class SimpleThings\EntityAudit\AuditReader
Tags -
Public yes
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired no
Autoconfigured no
Factory Service simplethings_entityaudit.manager
Factory Method createAuditReader
----------------- --------------------------------------
```
This service is currently called in one of my own with `$this->container->get('simplethings_entityaudit.reader')`.
I also tried to inject `SimpleThings\EntityAudit\AuditReader` into my service constructor, but here's what I get:
>
> Argument "$auditReader" of method "\_\_construct()" references class "SimpleThings\EntityAudit\AuditReader" but no such service exists. It cannot be auto-registered because it is from a different root namespace.
>
>
>
When I add this into my `services.yaml` it works, but I shouldn't need to do this:
```
SimpleThings\EntityAudit\AuditReader:
alias: simplethings_entityaudit.reader
```
Any ideas? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48425043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4994579/"
] | In my case, the error appears in a unit test.
I had a single service, which could not be loaded in tests (Symfony 4.2) while all other services in my project worked well.
I've cleared the cache, but it didn't help. Then I created a simple controller with a route and injected the service as method parameter. Afterwards the service worked in my test as well.
Conclusion: If you have a unit test and want to test your service, you must also provide a controller where the service is injected, otherwise it is not available in the test service container. An explicit service configuration might also help. | In Symfony 4.0, any service that does not specify its visibility is private, <https://github.com/symfony/symfony/pull/24238>.
As far as I can see, the service you mention does not specify the visibility: <https://github.com/simplethings/EntityAuditBundle/blob/1.0/src/SimpleThings/EntityAudit/Resources/config/auditable.xml#L23-L26>, so this is probably the reason for your exception.
If `simplethings_entityaudit.reader` service cannot be autowired (and this is probably because it uses a factory service), you can inject it into your own service by referencing it with `@simplethings_entityaudit.reader` notation as per this: <https://symfony.com/doc/current/service_container.html#services-manually-wire-args>, something like this:
```yaml
services:
My\Service:
arguments:
$auditReader: @simplethings_entityaudit.reader
``` |
11,747 | Are micrometeorites just dust grains at high relative speed, or is there some difference between them and cosmic or interstellar or solar nebula dust? Dust as in the clouds which obscure parts of the Milky Way in our night sky. | 2015/09/06 | [
"https://astronomy.stackexchange.com/questions/11747",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/1030/"
] | I'd like to add more inputs on the physics behind telescope resolution. The telescope resolution is given by its primary mirror size which produces a "quasi" punctual image for each light source it sees, that is called a airy disk. The airy disk size is inversely proportional to the telescope primary mirror diameter and like pixels on a LCD screen the lower the pixel size the better the resolution. However, the limiting factor on the ground is the atmospheric turbulence, this is why huge telescope of few meters wide cannot see better than a 500mm amateur telescope resolution wise (see Fried parameter). So in order to reach the telescope full resolution potential we need to build adaptive optics or better we could send the telescope to space. | Just a small supplementary -- there is no point in building a larger telescope unless you can manufacture a mirror that big without any kind of flaw or deformation and then mount it so that it doesn't change shape as you point it in different directions. This is a whole pile of really hard engineering problems which have also limited the size of telescopes that could be built at various times, or at the very least shifted the price-performance tradeoff. |
3,160 | I'm starting to learn how to shoot. Up until now I've only used point-and-shoot cameras mostly on automatic settings. My view is there are basically three classes of cameras sold by the major manufacturers:
1. **Point-and-shoot:** for those who want nothing to do with photography
2. **Advanced:** (Canon's *G* series, or Panasonic's *LX*) - some settings, but not complete flexibility
3. **SLR**: The "real deal"
My question is, if I want to learn how to shoot good photographs, can I start with a camera from the 2nd category, instead of an SLR? There are still options for manually setting the ISO, aperture and shutter speed on those models, I just don't understand how lacking they are and if they would hinder my learning. | 2010/09/08 | [
"https://photo.stackexchange.com/questions/3160",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1208/"
] | No. An SLR is not a must when learning photography.
In fact, I'd even say that an SLR can be a real hindrance. There are so many controls and functions that it can be overwhelming, and it's pretty discouraging to spend $500+ on a camera kit, and turn bad photos. So much that it might make you want to switch back to full auto-mode.
A camera is a tool. Nothing more. The advantages of having full-manual have been explained in other answers, but knowing the technical details of iso/aperature/shutter are tangential to what you want to learn: How to shoot good photographs.
The fundamentals of good photography are composition, subject, and lighting. All of which you can learn without having a camera with manual controls. While I hardly consider myself a good photographer, I often have people ask how I am able to take nice pictures with my iphone.
I also wouldn't dare say a point-and-shoot isn't for people who don't want anything to do with photography. I know several photographers (including myself) who use point-and-shoot cameras in places where an SLR does not make sense.
My advice for anyone who has questions regarding the relationship between cameras and good photography is to check out flickr's camera finder.
<http://www.flickr.com/cameras/apple/iphone_3gs/> | I started with an advanced P&S, and moved on to an SLR a few years ago when the P&S died. Two aspects where I saw a huge improvement with the SLR:
* Low light photography. The flash, even the built-in one, works much better. And even without a flash, I can get a much larger aperture with a low-light lens, something that my previous camera did not allow.
* Depth-of-field. Even with the largest aperture on my P&S, I couldn't get nice blurry backgrounds, even when following all the rules. Others can explain it better, but it has to do with the sensor size.
That said, the P&S allowed me to learn about all the fundamentals of photography, and I got many excellent shots out of it. |
43,181,228 | I'm using jackson lib to add json object into jsonarray then Stringify my jsonarray to save it into my a table as string
```
JsonObject obj = new JsonObject();
obj.put("id",1).put("data","test");
JsonArray arr = new JsonArray();
arr.add(obj);
arr.toString();
//out : [{"map":{"id":1,"data":"test"},"empty":false}]
//result wanted : [{"id":1,"data":"test"}]
```
So how can I get the last result without map and empty keys, and why it adds those keys in the first place ? | 2017/04/03 | [
"https://Stackoverflow.com/questions/43181228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4824279/"
] | In your laravel folder open app/Exceptions/Handler.php paste the following code. That will return custom error page for 403 and 500 error.
```
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom_all', [], 500);
}
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->view('errors.custom', [], 403);
}
return parent::render($request, $exception);
}
``` | ```
public function authorize()
{
$job_posting_id = $this->route('id');
$job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();
if($job_posting){
return true;
}
return redirect('/error');
}
public function failedAuthorization()
{
return view('errors.dashboard.parent.403');
}
```
In your route
```
Route::get('error', 'YourController@failedAuthorization');
``` |
1,972,625 | I am trying to fill a uitableview with multiple sections.
This is my code:
```
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
case 1:
[[cell textLabel] setText:[usersTeachers objectAtIndex:(indexPath.row+1)]];
return cell;
break;
```
I get this error when I try to load the view:
```
2009-12-28 21:09:48.380 FSS[2046:207] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit/UIKit-984.38/UITableView.m:4709
2009-12-28 21:09:48.381 FSS[2046:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
```
The array at that index logs as a legitimate string but it does not return the cell properly. Thus it doesnt load past this point. Please help. | 2009/12/29 | [
"https://Stackoverflow.com/questions/1972625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229067/"
] | Check you got
```
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
```
in
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
``` | In my case i was having the same error because i was missing the alloc/init:
```
if (cell == nil) {
cell = [[UITableViewCell alloc] init];
}
``` |
50,620,511 | How to pass parameters with `Volley` GET method?.
```
private void getData(int ClassIDs){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "";
StringRequest request = new StringRequest(com.android.volley.Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(ActivityStarsEntryTestPrep.this, "Success", Toast.LENGTH_SHORT).show();
}
``` | 2018/05/31 | [
"https://Stackoverflow.com/questions/50620511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7243174/"
] | You can set GET volley request like this
```
StringRequest commonRequest = new StringRequest(Request.Method.GET, url/* URL OF WEBSERVICE*/, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//HANDLE RESPONSE
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No
// connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user
// credentials.
// For ClientError, 400 & 401, Errors happening on
// client side when sending api request.
// In this case you can check how client is forming the
// api and debug accordingly.
// For ServerError 5xx, you can do retry or handle
// accordingly.
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("KEY","VALUE");
return hashMap;
}
};
commonRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 2));
INSTANCE OF VOLLEY.addToRequestQueue(commonRequest);
```
This portion of code is useful for you
```
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("KEY","VALUE");
return hashMap;
}
``` | Here is the full method I use to get string response using `Volley`. Use POST method if you pass parameters. Define your value and post URL. Get response using `onResponse` method.
```
public void getPostData() {
String value = "value";
String s; //to get response
final String URL = "Your php URL paste here";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
s = response;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityName.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("value", value.toString);
return hashMap;
}
};
final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
@Override
public void onRequestFinished(Request<Object> request) {
requestQueue.getCache().clear();
}
});
}
``` |
54,683,189 | This is `scripts` section of my `package.json`:
```
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"compile-prebuild": "tsc -p prebuild-tsconfig.json --pretty",
"prebuild": "ts-node --project PreBuild/tsconfig.json PreBuild/prebuild.ts",
"testJs": "node test.js",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"extract-i18n": "ng xi18n Paradise --i18n-format=xlf2 --output-path=i18n --i18n-locale=en && ng run Paradise:xliffmerge"
},
```
The wonderful thing is **when I try `npm run build` or `npm run build -- --prod` another script (`prebuild`) is executed**:
```
> npm run build -- --prod
> project@0.1.1 prebuild ...
> ts-node --project PreBuild/tsconfig.json PreBuild/prebuild.ts
```
Now, if I rename `prebuild` script to `pre-build` (in `package.json`), everything is going to be alright:
```
> npm run build -- --prod
> project@0.1.1 build ...
> ng build "--prod"
...
```
Now, if I reverted to back, the problem appears again!
---
```
> npm -v
6.7.0
``` | 2019/02/14 | [
"https://Stackoverflow.com/questions/54683189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5318303/"
] | The variable `length` is used to limit iterations of both your loops but is never assigned a value. This is undefined behaviour and a bus error is definitely a possible outcome of it.
Did you intend to use `len` for this purpose?
EDIT: `strlen` already does not include the null terminator in its return value. `strlen(buf) - 1` is probably not what you want. | The scope of len should be through 'main()'.
So, remove declaration of length and instead declare len there.
Here is the corrected code.
```
#include <stdio.h>
#include <string.h>
#define MAX_BUF 1024
int main ()
{
char buf[MAX_BUF];
int len;
do {
fgets(buf, MAX_BUF, stdin);
len = strlen(buf) - 1;
printf("%d",len);
char buf2[MAX_BUF];
strcpy(buf2, buf);
int i;
for(i = 0; i < len; i++){
if (buf2[i] == 'E' || buf2[i] == 'e'){
buf2[i] = '3';
}
if (buf2[i] == 'I' || buf2[i] == 'i'){
buf2[i] = '1';
}
if (buf2[i] == 'O' || buf2[i] == 'o'){
buf2[i] = '0';
}
if (buf2[i] == 'S' || buf2[i] == 's'){
buf2[i] = '5';
}
}
printf("%s", buf2);
} while (len > 1);
}
``` |
17,567 | My kitchen counter top has a small patch that is losing color. The patch is the main area of the countertop where my wife cuts veggies/processes food/other stuff.
I am looking for some fix to get it back in its original color since we live in a rented house, and this thing is not covered in the standard maintenance provided to us. | 2017/10/10 | [
"https://lifehacks.stackexchange.com/questions/17567",
"https://lifehacks.stackexchange.com",
"https://lifehacks.stackexchange.com/users/21948/"
] | First of all: 400 thread cottons that are "scratchy" should be returned.
Second: [Maneesh's answer](https://lifehacks.stackexchange.com/a/17547/21979) is way better than the current votes reflect. Vinegar is the most effective and safe for most cotton fabrics, most colours, the washing machine and the environment. (It also helps to protect the washer from built-up residue.)
---
That said, this is mainly to be read as a small addition to Maneesh's answer about chemicals.
Cotton, especially heavy cotton in canvas style (plain weave) or jeans (twill) or similar styles *are* quite stiff when brand new. That is a feature.
To break the stiffness you need to break some fibres and loosen the weave. Chemical fabric softeners are one way.
Washing them intensely (long cycle *and* high heat) is the method the industry uses. To amplify the effect add some tumble [dryer balls](https://en.wikipedia.org/wiki/Dryer_ball) (those plastic things looking like chestnuts on LSD) or [just something like tennis balls](https://www.mumsnet.com/Talk/housekeeping/279439-tumble-dryer-balls-do-they-work) into the washing machine *and* the dryer. Quality cotton can withstand cooking temperatures. Some colours on that fabric might not. White sheets can go all the way.
Ageing the fabric softens it. Quality fabric will last long after this breaking in with physical or chemical stresses. That means of course to not do this every time you wash, just in the beginning. | I suggest you the following methods:
Wash with Baking Soda and Vinegar in a washing machine(as you have not specified about vinegar, I feel you should try this combination: washing soda and vinegar). More methods are as follows:
* Add a cup of **vinegar** during the rinse cycle of washing machine.
* **Use turpentine**: Add half a cup of turpentine to the washing water with the sheets and wash on a regular cycle using warm water.Rinse thoroughly to remove most of the turpentine. Hang the sheets outside or on a clothes horse to dry.It is very important that you do not put the sheets in the dryer after washing with turpentine as turpentine is combustible and could cause a fire.
* **Use Epsom salts**: Fill a laundry tub with cold water and add 50g of Epsom salts. Stir the sheets around in the tub for two minutes (use a wooden spoon if you don't want your hands to get cold!)Leave the sheets to soak overnight in the Epsom salts mixture. The following morning, rinse the sheets out thoroughly, then hang them outside to dry.
* **Use borax**: Fill a laundry tub with cold water and add 6 tablespoons of borax to the tub.Add the sheets to the water, stir them around and leave them to soak overnight.Rinse thoroughly the next morning and hang outside to dry.
* **Use salt**: Fill a laundry tub with cold water and throw in 2 handfuls of salt. Add the sheets and leave them to soak overnight. Wash, rinse, and dry as usual. |
21,639,396 | I have a *windows* machine setup with a something like this:
```
N:\path\to\dir\project1.git
N:\path\to\dir\running_dir
```
where `N:` is a **mapped network drive**.
I'm trying to automatically checkout `project1.git` in my `running_dir` upon pushing to `project1.git`. I have followed [this post on exporting GIT\_WORK\_TREE](https://stackoverflow.com/questions/9132144/how-can-i-automatically-deploy-my-app-after-a-git-push-github-and-node-js); however, I am confused on what path to use in my `post-receive` hook:
```
#!/bin/sh
GIT_WORK_TREE= ????????
export GIT_WORK_TREE
git checkout -f
```
Suppose that `N:` maps to `C:\a\b` on the remote windows machine.
Currently trying: `/c/a/b/path/to/dir/running_dir`
**edit**: Also trying:
```
git --work-tree=/c/a/b/path/to/dir/running_dir checkout -f
```
and getting: `fatal: this operation must be run in a work tree` | 2014/02/07 | [
"https://Stackoverflow.com/questions/21639396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3192193/"
] | Adding absolute paths weren't working - regardless what I tried. Easily fixed by supplying a relative path to `--work-tree` though | Run bash-shell in `N:\path\to\dir\running_dir`, in which perform `pwd`.
Output of this command will be path, translated for bash |
56,044,394 | I'm trying to test a program using Python's `pathlib` module. With the `os` module, you used to be able to access networked drives by just following the same url-like form. But for some reason, you can't do this with `pathlib`. Or at least I can't figure out how to do it.
With the `os` module, all one would have to do is:
```
path = os.path.join(r'//server-01', 'directory', 'filename.txt')
```
But if you try to do this with the `pathlib` module, one could try something like:
```
path = Path('//server-01', 'directory', 'filename.txt')
```
If I'm on a Windows machine, path will resolve to:
```
>> WindowsPath('/server-01/directory/filename.txt)
```
And if I were to say `path.exists()` I will of course get `False`. Because yes, `/server-01` does NOT exist, however `//server-01` **does** exist.
Ideally of course, the result I expect to get when I run `path.exists()` is `True` and if I were to display `path` it would look something like:
```
>> WindowsPath('//server-01/directory/filename.txt')
```
**Update**
It's kind of hacky, but it works I guess, regardless I'd like to know the right way to do it.
In order to get to the network location you can:
```
os.chdir(join(r'//server-01', 'directory', 'filename.txt'))
path = Path()
path = path.resolve()
```
The result is something like:
```
>> WindowsPath('//server-01/directory/filename.txt')
path.exists()
>> True
```
If anyone knows the better way to do it, let me know. | 2019/05/08 | [
"https://Stackoverflow.com/questions/56044394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10542930/"
] | The server name by itself is not a valid component of a UNC path. You must also include a share. So `path = Path('//server-01/directory', 'file')` will work. It should `resolve` and return `True` when you run `path.exists()`.
Microsoft docs here: <https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dfsc/149a3039-98ce-491a-9268-2f5ddef08192> | Instantiating `path` as a `PureWindowsPath` should do the trick:
```
path = PureWindowsPath("//server-01", "directory", "file") # '\\\\server-01\\directory\\file'
``` |
9,178 | It's a homework assignment, we were asked to read, understand, and present to our colleagues a short paper/article (suggested 4-6 pages) for our Computability, Decidability or Complexity class.
The articles I was able to find in the past couple days using google scholar a way over what we were taught, plus, 50-100+ pages is way over the scope of my assignment. In class, we were provided with an introduction to the three topics, complexity classes, relations between them, and (mostly informal) proofs for the most representative problems from each class by modelling them using all kinds of Turing Machines.
Any possible solutions? It's the first time in my life I'm touching anything related to research, I can barely understand even the scope of most papers I find.. I guess any advice would be welcome. | 2013/01/26 | [
"https://cs.stackexchange.com/questions/9178",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/6572/"
] | "By definition" recent research papers usually contain non-trivial results and they often (always?) require a deep knowledge of the argument in order to be well understood, so if you pick a paper at random you'll probably find a bunch of obscure signs in your hands :-)
So my suggestion is to look at "old" research papers (but not *"too old"*):
1. pick a particular argument/theorem that you think you have understood informally (or an argument that intrigues you);
2. read more about it on a theory of computation book or on Internet (for example start from Wikipedia and look at the references at the bottom, or search it on Google adding the keywords "introduction" or "lecture notes");
3. finally search the paper in which that argument/theorem was originally published and read it;
For example one of the fundamental basic results in computational complexity is the (deterministic) [Time Hierarchy theorem](http://en.wikipedia.org/wiki/Time_hierarchy_theorem). *Very informally* the theorem says that given more time, a Turing machine can solve more problems. You can start reading the Wikipedia article, then pick a lecture note with a more formal proof Googling around (for example [pick this one by Arora](http://www.cs.duke.edu/~reif/courses/complectures/Arora/lec3.pdf)). Finally when you think that you've understood the proof well download and read the original paper [R. Stearns and J. "Hartmanis paper On the computational complexity of algorithms", 1965](http://www.ams.org/journals/tran/1965-117-00/S0002-9947-1965-0170805-7/S0002-9947-1965-0170805-7.pdf). You'll find that it contains even more details and is more formal. | I'd look at the "further reading" suggestions in your textbook. If the author made some effort here, the papers listed should be on-topic, important, and probably accessible. |
1,860,216 | I have an update statement that updates fields x, y and z where id = xx.
In the table I have a few different x\_created\_datetime fields (for different portions of the record that are maintained/entered by different folks). I'd like to write a single query that will update this field if is null, but leave it alone if is not null.
So what I have is:
```
UPDATE newspapers
SET scan_notes = "data",
scan_entered_by = "some_name",
scan_modified_date = "current_unix_timestamp"
WHERE id = X
```
What I need is a way to add in the following, but still always update the above:
```
scan_created_date = "current_unix_timestamp"
where scan_created_date is null
```
I'm hoping I can do this without a second transaction to the DB. Any ideas on how to accomplish this? | 2009/12/07 | [
"https://Stackoverflow.com/questions/1860216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22216/"
] | You could use COALESCE() wich returns the first NON-NULL value):
```
scan_created_date = COALESCE(scan_created_date, "current_unix_timestamp")
``` | Its like equivalent to Oracle's NVL.
You can use it like below in a prepared statement using parameters
```
UPDATE
tbl_cccustomerinfo
SET
customerAddress = COALESCE(?,customerAddress),
customerName = COALESCE(?,customerName),
description = COALESCE(?,description)
WHERE
contactNumber=?
``` |
14,433,646 | I realized that `iOS` is not working on a form that you can close the application.
I work with `PhoneGap` version 2.2.0 and I do like to have my application exit button,
I thought about the possibility to **move the app to the background and back to the iPhone home page** when you click on the button to exit.
I did not find how to do it through `PhoneGap`
is there a way? | 2013/01/21 | [
"https://Stackoverflow.com/questions/14433646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856206/"
] | In the pattern/action language of AWK, there is an implicit action of printing of $0 when the pattern evaluates to true, but there is no explicit action described. Regarding your challenge, see this example (13 characters):
```
{$0+=$0%2+1}1
```
Hat tip to 'some guy', who was quicker on the draw to post the code than me. | Shorter by two characters:
`'{$0%2?$0+=2:$0+=1}1'`
`1` here instead of `{print $0}`. `1` is pattern, that matches any record. `{print $0}` is default action.
**Edited.** Even better ( -6 characters ):
`{$0+=$0%2?2:1}1` |
12,268 | Does the rule "Don't use the same name/word to refer to two different things" have a name, and, if so, what is that name? | 2011/10/03 | [
"https://ux.stackexchange.com/questions/12268",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/8779/"
] | Maybe **Terminology standardisation**?
In the book [Language, culture and communication in contemporary Europe](http://books.google.co.uk/books?id=whacJr2_JVcC&pg=PA21&lpg=PA21&dq=%22terminology%20standardisation%22&source=bl&ots=EOor-T-Z_W&sig=2VKmDN_X6dk4FkpU29LjUm01Tvk&hl=en&ei=q-OJTqmSKYGY1AW2xOgB&sa=X&oi=book_result&ct=result&resnum=8&ved=0CEQQ6AEwBw#v=onepage&q=%22terminology%20standardisation%22&f=false), by Charlotte Hoffmann, she writes:
 | One form of this two-meanings-for-same-term is known as a [synecdoche](http://en.wikipedia.org/wiki/Synecdoche), and is particularly confusing.
* Part of something is used to refer to the whole thing (*pars pro toto*), or
* A thing (a "whole") is used to refer to part of it (*totum pro parte*), or
* A specific class of thing is used to refer to a larger, more general class, or
* A general class of thing is used to refer to a smaller, more specific class, or
* A material is used to refer to an object composed of that material, or
* A container is used to refer to its contents.
I was once in a meeting with 6 others discussing a website for a radio station, and only after an hour of confused back and forth did someone stop to ask "when you say 'programme', do you mean the instance of broadcast, or the conceptual ongoing series of broadcasts under that name?". |
10,683,844 | I have used border-radius in my form field. It works fine. But the chrome it appears some line around the filed. Please refer the fiddle.
<http://jsfiddle.net/JKdzc/>
Please help me. | 2012/05/21 | [
"https://Stackoverflow.com/questions/10683844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1101236/"
] | Are you referring to the orange highlight? If so, add this style:
```
outline:none;
``` | Chrome adds a yellow/orange **outline** when users focus on an input. Remove it like this:
```
input:focus
{
outline: none;
}
``` |
43,159,565 | I've been using the script below to download technical videos for later analysis. The script has worked well for me and retrieves the highest resolution version available for the videos that I have needed.
Now I've come across a [4K YouTube video](https://youtu.be/vzS1Vkpsi5k), and my script only saves an mp4 with 1280x720.
I'd like to know if there is a way to adjust my current script to download higher resolution versions of this video. I understand there are python packages that might address this, but right now I would like stick to this step-by-step method if possible.
[](https://i.stack.imgur.com/0XvsY.png) [](https://i.stack.imgur.com/Ihmly.png)
**above:** info from Quicktime and OSX
```
"""
length: 175 seconds
quality: hd720
type: video/mp4; codecs="avc1.64001F, mp4a.40.2"
Last-Modified: Sun, 21 Aug 2016 10:41:48 GMT
Content-Type: video/mp4
Date: Sat, 01 Apr 2017 16:50:16 GMT
Expires: Sat, 01 Apr 2017 16:50:16 GMT
Cache-Control: private, max-age=21294
Accept-Ranges: bytes
Content-Length: 35933033
Connection: close
Alt-Svc: quic=":443"; ma=2592000
X-Content-Type-Options: nosniff
Server: gvs 1.
"""
import urlparse, urllib2
vid = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init = "https://www.youtube.com/get_video_info?video_id=" + vid
resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info = urlparse.parse_qs(data)
title = info['title']
print "length: ", info['length_seconds'][0] + " seconds"
stream_map = info['url_encoded_fmt_stream_map'][0]
vid_info = stream_map.split(",")
mp4_filename = save_title + ".mp4"
for video in vid_info:
item = urlparse.parse_qs(video)
print 'quality: ', item['quality'][0]
print 'type: ', item['type'][0]
url_download = item['url'][0]
resp = urllib2.urlopen(url_download)
print resp.headers
length = int(resp.headers['Content-Length'])
my_file = open(mp4_filename, "w+")
done, i = 0, 0
buff = resp.read(1024)
while buff:
my_file.write(buff)
done += 1024
percent = done * 100.0 / length
buff = resp.read(1024)
if not i%1000:
percent = done * 100.0 / length
print str(percent) + "%"
i += 1
break
``` | 2017/04/01 | [
"https://Stackoverflow.com/questions/43159565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904031/"
] | In Windows you will need to right click a .py, and press Edit to edit the file using IDLE. Since the default action of double clicking a .py is executing the file with python on a shell prompt.
To open just IDLE:
Click on that. `C:\Python36\Lib\idlelib\idle.bat` | My solution to setting options and then invoking Idle on a python script is:
```
Set optn=blah
...
Set optn=blah
start pythonw C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Lib\idlelib\idle.py STFxlate.py
```
This allows you to setup the environment prior to invoking idle.
This assumes that pythonw is in the current path |
28,327,081 | I am trying to create this interface :

And here is my actual result :

* The status bar is well transparent and we see my image as background : OK
* The action bar is not transparent : NOK
Here is the code of my theme that I use for this activity :
```
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- inherit from the material theme -->
<style name="MaterialAppDetailTheme" parent="android:Theme.Material.Light">
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowActionBarOverlay">true</item>
<!-- enable window content transitions -->
<item name="android:windowContentTransitions">true</item>
<!-- specify shared element transitions -->
<item name="android:windowSharedElementEnterTransition">
@transition/change_image_transform</item>
<item name="android:windowSharedElementExitTransition">
@transition/change_image_transform</item>
<item name="android:windowTranslucentNavigation">true</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
``` | 2015/02/04 | [
"https://Stackoverflow.com/questions/28327081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076026/"
] | You can change your toolbar color to transparent like this:
```
mToolbar.setBackgroundColor(getResources().getColor(android.R.color.transparent));
```
You can change it's background on the XML too:
```
android:background="@android:color/transparent"
```
Or if you're using ActionBar:
```
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
```
Use `getActionBar()` if you're not using `ActionBarActivity`
Result:
 | For API that >= 21, add to theme these lines of code
`<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>`
Don't forget to add
`android:fitsSystemWindows="true"` |
11,825,718 | Could anyone please provide me with a regular expression to allow only digits (0-9) excluding even '.' (decimal point) in a textbox in JSP using javascript. I would be using it to replace the resricted characters with '' (empty string).
I tried few but they are not restricitng the DOT.
Thanks in advance | 2012/08/06 | [
"https://Stackoverflow.com/questions/11825718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461967/"
] | You need to [anchor](http://www.regular-expressions.info/anchors.html) the regex:
```
/^\d*$/
```
to make sure that the *entire string* consists of digits.
Without `^` and `$`, the regex would match `1` (and `234`) in `1.234`. | I would use the class `\d`, it includes only digits. If you want to replace all non-digits you would need to replace `\D+` with `""`. |
4,578,544 | So here is the problem. There is a HTML/JS code, but I can't read v3 variable. In short anything after `DDDD(D,{"COM":"lng","leaf":145,"AXIS":true});` (which is some kind of predefined random array) is unreadable(or ignored as JS code). Why? And how can i get contents of v3? Is this a javascript parse bug?
```
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<script type="text/javascript">
<!--
var v1 = 12345;
var v2 = "Hello world";
DDDD(D,{"COM":"lng","leaf":145,"AXIS":true});
var v3 = "World Hello!!!";
//-->
</script>
</head>
<!-- some html code -->
<script>
alert("This is "+v3);
</script>
<!-- some html code -->
</html>
``` | 2011/01/02 | [
"https://Stackoverflow.com/questions/4578544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560333/"
] | I assume that `D` and `DDDD` are defined somewhere? Your code excerpt doesn't define them. If they're defined, I'm not seeing the error; if they aren't, well, that's your problem. | When javascript gets an error in a line (depends the egine) it either breaks or fails to load entirely. And like most people already said before me, the DDDD() has to exist somewhere else is undefined. |
57,247 | Freelance based question.....
**Scenario:** A piece was designed two years ago. In the piece there are several client-supplied photographs. When the original piece was designed, the only image alterations which were made to these client-supplied photos was to extract them and remove the background. This was all built into the original design fee for the piece.
Today, the client requests just the photos.
1. They are client supplied images so I *automatically* do **not**
associate any fee with sending the images back. Client is merely lucky if I still have them years later.
2. Work *was* done to facilitate the photos in the original piece.
Returning the edited photos *would* constitute additional use of the
work *beyond* the original scope.
3. There's no real way to know what the *original* amount of time
the extractions took. It's been years, skills have improved and if time were to be calculated today it may be inaccurate and rates may be
different.
4. If these were designer-supplied photos, original artwork, or even original constructon images based upon client supplied photos I *would* automatically associate
additional usage fees with this request
Original construction: i.e. a client sends 5 separate photos and all must be extracted then combined to create a "global product shot" and client is requesting this global shot.
**Is it appropriate to charge the client anything for return of these edited client-supplied photos?**
I *do* realize this is somewhat subjective and opinion-based. I am merely seeking "best practices" or "common procedures" used by professionals in the field.
I'm leaning towards "no" based upon the quantity of photos in *this* instance (only 2). However, if there were a great many photos I'd be far more uncertain as to whether or not I should charge. | 2015/07/29 | [
"https://graphicdesign.stackexchange.com/questions/57247",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/3270/"
] | I think it's more than fair to at least charge a 'archive retrieval' fee. It takes time to locate old work and prep it for delivery. That should be time you bill for. | if all you're doing is emailing them photos.... PLEASE don't be that petty to charge them. sure you could charge them, but little things like this is why our industry suffers the way it does with people coming through the door with a million tricks up their sleeve to screw us around somehow.
If this client RESPECTS you and APPRECIATES you, I would suggest not only emailing them the pictures... but if there happens to be a little touching up that could be done, I'd do it and send it back letting them know I polished it up for them. In the end stuff like this lets them know you appreciate the relationship you have AND you actually care about them and their success. When a client knows hands down that you actually truly care about them and what they're doing it instills a stronger sense of loyalty to you that's more valuable than money. I recently had a client ask me if I could vectorize their logo because the Artist they had design it charges $35 for a .png, jpeg or gif, $55 for a TRANSPARENT .png, then $85 for a vector .pdf or .eps..... WHEN THEY DESIGNED IT IN ILLUSTRATOR TO BEGIN WITH!!!!.
All that extra hassle just to click "save as" and choose a format, but told her he has to do more work to it and let it render and a bunch of other mumbo jumbo. If our clients can't even effectively use what they get from us then how valuable are we? If she wanted to get that design silk screened she'd have to pay a good $120 for a setup fee... which would be VECTORIZING IT... when he could've just given her a vector format from the beginning.
Don't be one of those guys, all it does is keep you trapped in a position where you have to be that petty over every little thing that comes through the door to milk as much as possible out of it because NOBODY WANTS TO DO BUSINESS WITH YOU!!!. if it's small and simple, just do it, why go through all of that? |
33,622,445 | I'm setting up SQL access in a newly created OpenEdge 11.5 database.
In checking the contents of the sysdbauth table using "select \* from sysprogress.sysdbauth", I see that there are two users setup by default: sysprogress and a user with the name of the Linux user account that was used to create the database.
I'm looking for recommendations as to how to handle these two accounts. Obviously I want to have an account to use for DBA tasks. Should I use one of these accounts for the purpose? If so, what should I do with the other account?
Is it possible (and safe) to be deleting either of these predefined accounts? | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5544954/"
] | On page 175 of the [Database Administration guide](http://documentation.progress.com/output/OpenEdge115/pdfs/dmadm/dmadm.pdf) you can read about default users and why they are created:
>
> **Tables used from SQL only**
>
>
> An SQL database administrator (DBA) is a person assigned a sysdbauth record in the database.
> SQL DBAs have access to all meta data and data in the database. To support internal schema
> caching, every OpenEdge database begins with a DBA defined as "sysprogress." However,
> OpenEdge restricts the use of "sysprogress."
> When you create an OpenEdge database using the PROCOPY or PRODB commands, and the
> database does not have any \_User records defined (from the source database, for example), then
> a DBA is automatically designated with the login ID of the person who creates the database. This
> person can log into the database and use the GRANT statement to designate additional SQL DBAs,
> and use the CREATE USER and DROP USER statements to add and delete user IDs.When creating
> users, this DBA can also specify users as SQL-only users, who can only access the database
> through SQL.
>
>
>
There are several knowledge base entries around the task of deleting or disabling the default users.
<http://knowledgebase.progress.com/articles/Article/P5094>
<http://knowledgebase.progress.com/articles/Article/P161411>
This suggests that it's really safe to delete or disable these accounts but you should:
1) Create replacing accounts first.
2) As always: test in a separate environment first and not in production! | Yes, in fact Progress kind of expects you to do so. Create a root account and get rid of both. It's fine. |
37,958 | I understand ([ref](https://photo.stackexchange.com/questions/3435/can-i-simulate-active-d-lighting-on-post-processing)) that I can do my own post processing to get the same effect that Active D-Lighting gives.
But does the in-camera ADL get applied to the raw image data or is it only done to the accompanying jpeg (when shooting RAW+JPEG) It might be nice to see the preview image with that effect, knowing that the Raw image is still unmodifed.
If it only affects the jpeg, what does ADL do when shooting RAW only? | 2013/04/12 | [
"https://photo.stackexchange.com/questions/37958",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/8573/"
] | ADL doesn't cause any processing to happen to your RAW, but it does affect metering. If you want to replicate the effect then you can set the EC to underexpose.
But rather than just relying on metering and having the camera intentionally underexposure to prevent accidental clipping of highlights, a better approach is to use the histogram to judge the exposure and make adjustments as necessary. Or better still (since there is still no manufacturer that offers RAW histograms) bracket your shots. | If you are taking both jpeg and RAW, ADL will certainly give you better jpegs if you have set the ADL correctly. The RAW files are are usually unaffected, but that depends on the camera. |
116,104 | First of all, I am very new to wordpress and know almost nothing about it.
When I create the page foo using in wp-admin, I get the message that the page is created. When I click on `view page`, it 404s. I've followed the steps on <http://codex.wordpress.org/Pages#Creating_Pages>, but apparently I'm missing something.
I let Wordpress rebuild my `.htaccess`, but still no luck.
**System specifications:**
* Ubuntu 13.04
* Apache2
* PHP 5.4.9
* MySQL 14.14 Distrib 5.5.32
**Installed Wordpress Plugins:**
* Debug This
* My own (empty) plugin
**.htaccess**
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
**"Debug This" output for query -> rewrite**
```
Current Rewrite
Matched Rule:
Matched Query:
Query String: debug-this=rewrites
Rewrite Rules
Rule Rewrite
dating_user/?$ index.php?post_type=dating_user
dating_user/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?post_type=dating_user&feed=$matches[1]
dating_user/(feed|rdf|rss|rss2|atom)/?$ index.php?post_type=dating_user&feed=$matches[1]
dating_user/page/([0-9]{1,})/?$ index.php?post_type=dating_user&paged=$matches[1]
category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?category_name=$matches[1]&feed=$matches[2]
category/(.+?)/(feed|rdf|rss|rss2|atom)/?$ index.php?category_name=$matches[1]&feed=$matches[2]
category/(.+?)/page/?([0-9]{1,})/?$ index.php?category_name=$matches[1]&paged=$matches[2]
category/(.+?)/?$ index.php?category_name=$matches[1]
tag/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?tag=$matches[1]&feed=$matches[2]
tag/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?tag=$matches[1]&feed=$matches[2]
tag/([^/]+)/page/?([0-9]{1,})/?$ index.php?tag=$matches[1]&paged=$matches[2]
tag/([^/]+)/?$ index.php?tag=$matches[1]
type/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?post_format=$matches[1]&feed=$matches[2]
type/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?post_format=$matches[1]&feed=$matches[2]
type/([^/]+)/page/?([0-9]{1,})/?$ index.php?post_format=$matches[1]&paged=$matches[2]
type/([^/]+)/?$ index.php?post_format=$matches[1]
dating_user/[^/]+/attachment/([^/]+)/?$ index.php?attachment=$matches[1]
dating_user/[^/]+/attachment/([^/]+)/trackback/?$ index.php?attachment=$matches[1]&tb=1
dating_user/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
dating_user/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
dating_user/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?attachment=$matches[1]&cpage=$matches[2]
dating_user/([^/]+)/trackback/?$ index.php?dating_user=$matches[1]&tb=1
dating_user/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?dating_user=$matches[1]&feed=$matches[2]
dating_user/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?dating_user=$matches[1]&feed=$matches[2]
dating_user/([^/]+)/page/?([0-9]{1,})/?$ index.php?dating_user=$matches[1]&paged=$matches[2]
dating_user/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?dating_user=$matches[1]&cpage=$matches[2]
dating_user/([^/]+)(/[0-9]+)?/?$ index.php?dating_user=$matches[1]&page=$matches[2]
dating_user/[^/]+/([^/]+)/?$ index.php?attachment=$matches[1]
dating_user/[^/]+/([^/]+)/trackback/?$ index.php?attachment=$matches[1]&tb=1
dating_user/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
dating_user/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
dating_user/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?attachment=$matches[1]&cpage=$matches[2]
gn-genre/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-genre&term=$matches[1]&feed=$matches[2]
gn-genre/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-genre&term=$matches[1]&feed=$matches[2]
gn-genre/([^/]+)/page/?([0-9]{1,})/?$ index.php?taxonomy=gn-genre&term=$matches[1]&paged=$matches[2]
gn-genre/([^/]+)/?$ index.php?taxonomy=gn-genre&term=$matches[1]
gn-location-3/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-location-3&term=$matches[1]&feed=$matches[2]
gn-location-3/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-location-3&term=$matches[1]&feed=$matches[2]
gn-location-3/([^/]+)/page/?([0-9]{1,})/?$ index.php?taxonomy=gn-location-3&term=$matches[1]&paged=$matches[2]
gn-location-3/([^/]+)/?$ index.php?taxonomy=gn-location-3&term=$matches[1]
gn-location-2/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-location-2&term=$matches[1]&feed=$matches[2]
gn-location-2/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-location-2&term=$matches[1]&feed=$matches[2]
gn-location-2/([^/]+)/page/?([0-9]{1,})/?$ index.php?taxonomy=gn-location-2&term=$matches[1]&paged=$matches[2]
gn-location-2/([^/]+)/?$ index.php?taxonomy=gn-location-2&term=$matches[1]
gn-location-1/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-location-1&term=$matches[1]&feed=$matches[2]
gn-location-1/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?taxonomy=gn-location-1&term=$matches[1]&feed=$matches[2]
gn-location-1/([^/]+)/page/?([0-9]{1,})/?$ index.php?taxonomy=gn-location-1&term=$matches[1]&paged=$matches[2]
gn-location-1/([^/]+)/?$ index.php?taxonomy=gn-location-1&term=$matches[1]
robots\.txt$ index.php?robots=1
.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$ index.php?feed=old
.*wp-app\.php(/.*)?$ index.php?error=403
.*wp-register.php$ index.php?register=true
feed/(feed|rdf|rss|rss2|atom)/?$ index.php?&feed=$matches[1]
(feed|rdf|rss|rss2|atom)/?$ index.php?&feed=$matches[1]
page/?([0-9]{1,})/?$ index.php?&paged=$matches[1]
comments/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?&feed=$matches[1]&withcomments=1
comments/(feed|rdf|rss|rss2|atom)/?$ index.php?&feed=$matches[1]&withcomments=1
search/(.+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?s=$matches[1]&feed=$matches[2]
search/(.+)/(feed|rdf|rss|rss2|atom)/?$ index.php?s=$matches[1]&feed=$matches[2]
search/(.+)/page/?([0-9]{1,})/?$ index.php?s=$matches[1]&paged=$matches[2]
search/(.+)/?$ index.php?s=$matches[1]
author/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?author_name=$matches[1]&feed=$matches[2]
author/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?author_name=$matches[1]&feed=$matches[2]
author/([^/]+)/page/?([0-9]{1,})/?$ index.php?author_name=$matches[1]&paged=$matches[2]
author/([^/]+)/?$ index.php?author_name=$matches[1]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&feed=$matches[4]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&feed=$matches[4]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/page/?([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&paged=$matches[4]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]
([0-9]{4})/([0-9]{1,2})/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&monthnum=$matches[2]&feed=$matches[3]
([0-9]{4})/([0-9]{1,2})/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&monthnum=$matches[2]&feed=$matches[3]
([0-9]{4})/([0-9]{1,2})/page/?([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&paged=$matches[3]
([0-9]{4})/([0-9]{1,2})/?$ index.php?year=$matches[1]&monthnum=$matches[2]
([0-9]{4})/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&feed=$matches[2]
([0-9]{4})/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&feed=$matches[2]
([0-9]{4})/page/?([0-9]{1,})/?$ index.php?year=$matches[1]&paged=$matches[2]
([0-9]{4})/?$ index.php?year=$matches[1]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/attachment/([^/]+)/?$ index.php?attachment=$matches[1]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/attachment/([^/]+)/trackback/?$ index.php?attachment=$matches[1]&tb=1
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?attachment=$matches[1]&cpage=$matches[2]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/trackback/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&tb=1
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&feed=$matches[5]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&feed=$matches[5]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/page/?([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&paged=$matches[5]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&cpage=$matches[5]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)(/[0-9]+)?/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&page=$matches[5]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/([^/]+)/?$ index.php?attachment=$matches[1]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/([^/]+)/trackback/?$ index.php?attachment=$matches[1]&tb=1
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?attachment=$matches[1]&cpage=$matches[2]
([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/comment-page-([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&cpage=$matches[4]
([0-9]{4})/([0-9]{1,2})/comment-page-([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&cpage=$matches[3]
([0-9]{4})/comment-page-([0-9]{1,})/?$ index.php?year=$matches[1]&cpage=$matches[2]
.?.+?/attachment/([^/]+)/?$ index.php?attachment=$matches[1]
.?.+?/attachment/([^/]+)/trackback/?$ index.php?attachment=$matches[1]&tb=1
.?.+?/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
.?.+?/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ index.php?attachment=$matches[1]&feed=$matches[2]
.?.+?/attachment/([^/]+)/comment-page-([0-9]{1,})/?$ index.php?attachment=$matches[1]&cpage=$matches[2]
(.?.+?)/trackback/?$ index.php?pagename=$matches[1]&tb=1
(.?.+?)/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?pagename=$matches[1]&feed=$matches[2]
(.?.+?)/(feed|rdf|rss|rss2|atom)/?$ index.php?pagename=$matches[1]&feed=$matches[2]
(.?.+?)/page/?([0-9]{1,})/?$ index.php?pagename=$matches[1]&paged=$matches[2]
(.?.+?)/comment-page-([0-9]{1,})/?$ index.php?pagename=$matches[1]&cpage=$matches[2]
(.?.+?)(/[0-9]+)?/?$ index.php?pagename=$matches[1]&page=$matches[2]
```
I also verified that Apache's `mod_rewrite` module is installed and enabled.
**apache2.conf (comments removed):**
```
LockFile ${APACHE_LOCK_DIR}/accept.lock
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
AccessFileName .htaccess
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
DefaultType None
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
Include mods-enabled/*.load
Include mods-enabled/*.conf
Include ports.conf
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
Include conf.d/
Include sites-enabled/
Include /etc/phpmyadmin/apache.conf
``` | 2013/09/19 | [
"https://wordpress.stackexchange.com/questions/116104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38405/"
] | Like Manish, I think the issue is with `AllowOverride`.
The following is based on a Debian server. Ubuntu, if you are not aware, is based on Debian.
In your `apache2/` directory, you should have a `sites-available/` and a `sites-enabled/` directory.
1. Disable your site with `a2dissite`
2. Edit the appropriate file in `sites-available/` to include the
`AllowOverride` directive.
3. Enable the site with `a2ensite`.
The following is based on y entry for my sandbox install of the current WordPress on my dev server:
```
# Apache configuration
Alias /wp_release /path/to/site/files
<Directory /path/to/site/files>
AllowOverride FileInfo
DirectoryIndex index.php
Allow from All
<IfModule mod_php5.c>
AddType application/x-httpd-php .php
php_flag magic_quotes_gpc Off
php_flag track_vars On
php_flag register_globals Off
php_value include_path .
</IfModule>
</Directory>
```
That is from a dev site with no access to the public internet (and I may have twitched something as an experiment at some point along the way). You may not want exactly that on a production server but the key parts are these bits:
```
AllowOverride FileInfo
DirectoryIndex index.php
```
Reference: <http://httpd.apache.org/docs/current/mod/core.html#allowoverride> | 1. Delete .htaccess file
2. Go To Setting > Permalinks
3. Change your Permalinks type to anything else than current one
4. Save Changes
That will create new .htaccess, hopefully it will be formatted the way WordPress loves! |
44,838,477 | I have the following html element:
```
<a href onClick={() => fields.push()}>Add Email</a>
```
I need the href attribute so bootstrap styles the element with a link styling (color, cursor).
Problem is, if I click that now it causes the browser to redirect. How can I update the above to not redirect the browser onClick but still run `fields.push()`? | 2017/06/30 | [
"https://Stackoverflow.com/questions/44838477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149080/"
] | Add `e.preventDefault()` to onClick and add `href="#"` attribute
```
<a href="#" onClick={(e) => { e.preventDefault(); fields.push(); }}>Add Email</a>
``` | try this code;
```
<a href={undefined} onClick={() => {/*function code*/}}></a>
```
void(0) returns undefined. so you should write directly undefined on React because javascript:URL deprecated by React.
<https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-javascript-urls> |
71,414,598 | If the arguments to functions are passed by value in javascript how come the console.log() below seems to get its input by reference? Shouldn't each time it is invoked inside setTimeout just the value of i be passed and not its reference?
```js
let i;
for (i = 1; i <= 5; i++) {
setTimeout(function timer() {
console.log(i);
}, i * 1000);
}
``` | 2022/03/09 | [
"https://Stackoverflow.com/questions/71414598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> Shouldn't each time it is invoked inside setTimeout just the value of i be passed and not its reference?
>
>
>
Yes, and this is exactly what is happening. It is passing the value of `i` by value to `console.log(i)`. But, you're passing that value AFTER the entire `for` loop has completed when `i` has its terminal value because this is the order that things run:
1. You declare `let i`.
2. You start your `for` loop.
3. The `for` loop runs to completion, each iteration starting an additional timer. The timer is non-blocking and asynchronous so it just starts the timer and execution of the loop continues.
4. Then, sometime later (after the `for` loop is completely done) with the value of `i` sitting on its terminal value, then the timers start firing which causes them to call their callback and then output `console.log(i)`.
---
Note, that if you made the `let i` be part of the `for` loop declaration, you would get completely different results:
```js
for (let i = 1; i <= 5; i++) {
// Because let i was inside the for loop declaration,
// there is a separate copy of i for each iteration of the for loop here
setTimeout(function timer() {
console.log(i);
}, i * 1000);
}
```
Because here there is special treatment for the `let i` in the `for` loop. Each iteration of the loop gets it own separate copy of `i` and thus it still has the value it had when the loop iteration was run at the later time when the timer fires.
This is completely different than your original version where there is only one `i` for the entire loop and its value is incremented on each iteration and thus the value `i` had when each iteration of the loop ran is no longer available when the timer fires. | setTimeOut is an asynchronous function. It means it won't stop execution of other synchronous code. Each Console Log will wait 1 second to execute. But as the value of i has become 6 it will print that 5 times. |
33,397,113 | I'm new to docker. I tried executing the following docker command to created a container,
```
docker run -d -p 9999:80 httpd
```
After this, when i visited the URL <http://127.0.0.1:9999/>, It loads with "It works!" message. So, to change the message, I went inside the httpd container and changed the value of /usr/local/apache2/htdocs/index.html (Hope, that is the correct location) to `<html><body><h1>It works at port 9999!</h1></body></html>`.
But still it is showing the same old message and the weird part is it is still showing up after removing the container. Am i doing anything wrong or is this coming from any cache or something?
Please help.
**Edit**: I found it is due to browser cache and nothing else. | 2015/10/28 | [
"https://Stackoverflow.com/questions/33397113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698072/"
] | Here is the extension I created, first it finds sunday and then it adds one day
```
extension Date {
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
}
``` | **Swift 4 Solution**
I have figured out according to my requirement, where I have find out dates for following.
```
1. Today
2. Tomorrow
3. This Week
4. This Weekend
5. Next Week
6. Next Weekend
```
So, I have created `Date Extension` to get Dates of *Current Week* and *Next Week*.
**CODE**
```
extension Date {
func getWeekDates() -> (thisWeek:[Date],nextWeek:[Date]) {
var tuple: (thisWeek:[Date],nextWeek:[Date])
var arrThisWeek: [Date] = []
for i in 0..<7 {
arrThisWeek.append(Calendar.current.date(byAdding: .day, value: i, to: startOfWeek)!)
}
var arrNextWeek: [Date] = []
for i in 1...7 {
arrNextWeek.append(Calendar.current.date(byAdding: .day, value: i, to: arrThisWeek.last!)!)
}
tuple = (thisWeek: arrThisWeek,nextWeek: arrNextWeek)
return tuple
}
var tomorrow: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
}
var noon: Date {
return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
var startOfWeek: Date {
let gregorian = Calendar(identifier: .gregorian)
let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
return gregorian.date(byAdding: .day, value: 1, to: sunday!)!
}
func toDate(format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: self)
}
}
```
**USAGE:**
```
let arrWeekDates = Date().getWeekDates() // Get dates of Current and Next week.
let dateFormat = "MMM dd" // Date format
let thisMon = arrWeekDates.thisWeek.first!.toDate(format: dateFormat)
let thisSat = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 2].toDate(format: dateFormat)
let thisSun = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 1].toDate(format: dateFormat)
let nextMon = arrWeekDates.nextWeek.first!.toDate(format: dateFormat)
let nextSat = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 2].toDate(format: dateFormat)
let nextSun = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 1].toDate(format: dateFormat)
print("Today: \(Date().toDate(format: dateFormat))") // Sep 26
print("Tomorrow: \(Date().tomorrow.toDate(format: dateFormat))") // Sep 27
print("This Week: \(thisMon) - \(thisSun)") // Sep 24 - Sep 30
print("This Weekend: \(thisSat) - \(thisSun)") // Sep 29 - Sep 30
print("Next Week: \(nextMon) - \(nextSun)") // Oct 01 - Oct 07
print("Next Weekend: \(nextSat) - \(nextSun)") // Oct 06 - Oct 07
```
You can modify `Extension` according to your need.
**Thanks!** |
355,670 | Myself and a colleague have a dispute about which of the following is more elegant. I won't say who's who, so it is impartial. Which is more elegant?
```
public function set hitZone(target:DisplayObject):void
{
if(_hitZone != target)
{
_hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
_hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
_hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);
_hitZone = target;
_hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
_hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
_hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
}
}
```
...or...
```
public function set hitZone(target:DisplayObject):void
{
if(_hitZone == target)return;
_hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
_hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
_hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);
_hitZone = target;
_hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
_hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
_hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
}
``` | 2008/12/10 | [
"https://Stackoverflow.com/questions/355670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] | In most cases, returning early reduces the complexity and makes the code more readable.
It's also one of the techniques applied in [Spartan programming](http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming):
>
> **Minimal use of Control**
>
>
> 1. Minimizing the use of conditionals by using specialized
> constructs such ternarization,
> inheritance, and classes such as Class
> Defaults, Class Once and Class
> Separator
> 2. Simplifying conditionals with early `return`.
> 3. Minimizing the use of looping constructs, by using action applicator
> classes such as Class Separate and
> Class FileSystemVisitor.
> 4. Simplifying logic of iteration with early exits (via `return`,
> `continue` and `break` statements).
>
>
>
In your example, I would choose option 2, as it makes the code more readable. I use the same technique when checking function parameters. | I've had this debate with my own code over the years. I started life favoring one return and slowly have lapsed.
In this case, I prefer option 2 (one return) simply because we're only talking about 7 lines of code wrapped by an if() with no other complexity. It's far more readable and function-like. It flows top to bottom. You know you start at the top and end at the bottom.
That being said, as others have said, if there were more guards at the beginning or more complexity or if the function grows, then I would prefer option 1: return immediately at the beginning for a simple validation. |
54,839,699 | I have two Cloudformation stacks. One of them defines the Dynamodb.
I want the second stack to use the Dynamodb referenced in the first stack. The second stack has a Lambda function which will receive dynamodb stream from stack 1.
How should I export and import dynamodb from one stack to another for Lambda stream consumption? | 2019/02/23 | [
"https://Stackoverflow.com/questions/54839699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2297972/"
] | In the DynamoDB table stack, export the [`StreamArn`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping.html) attribute of the table. Use that as the value of the `EventSourceArn` to define an [EventSourceMapping](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping.html) resource in your Lambda stack.
```
# DynamoDB stack
Resources:
Table:
Type: AWS::DynamoDB::Table
Properties:
StreamSpecification: NEW_AND_OLD_IMAGES
# etc.
Outputs:
TableStreamArn:
Value: !GetAtt Table.StreamArn
Export:
Name: StreamArn
# Lambda stack
Resources:
Function:
Type: AWS::Lambda::Function
# etc.
EventMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
EventSourceArn: !ImportValue StreamArn
FunctionName: !GetAtt Function.Arn
# etc.
```
You could also do it the other way around - import the Lambda function ARN to the DynamoDB stack and define the event mapping there, but that feels less logical to me. | If your lambda stack looks like this
```
functions:
hello:
handler: handler.hello
events:
- stream:
type: dynamodb
arn: dynamoStreamArn
```
and you want to consume the dynamoDB stream arn from the stack where dynamoDB is defined, you can use several different options.
**1. Import/Export**
Exporting the dynamo stream arn from the first stack as mentioned in answers before, but import it in lambda stack using [ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) function
```
events:
- stream:
type: dynamodb
arn: Fn::ImportValue: NameWhichYouExported
```
**2. Serverless plugins**
Searching for the solution for this problem, found two plugins on NPM that import the stream arn by table name.
[Plugin 1](https://www.npmjs.com/package/serverless-dynamo-stream-plugin)
[Plugin 2](https://www.npmjs.com/package/serverless-dynamodb-stream-arn-plugin)
Example from one of the plugins:
```
events:
- stream:
arn: ${fetchStreamARN(<tableName>)} // This is all the change you need to do
startingPosition: LATEST
enabled: true // Any other parameters can be added as provided by serverless
``` |
136,466 | $T(n) = T(n/3) + T(2n/3) + n$
How can I solve this recurrence formula? | 2021/03/11 | [
"https://cs.stackexchange.com/questions/136466",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/132945/"
] | Look at the recursion from QuickSort for the average case:
$T(n) = T(n/2) + T(n/2) + n$
which ends up in $O (n \log n)$.
Note that $n/2 + n/2$ sums up exactly to $n$. Just like $n/3 + 2n/3$ sums up exactly to $n$. Substitute the formula for $T(n)$ in $T(n/3)$ and $T(2n/3)$ and you'll see it's the sum of $T(x)$ for four values $x$ which add up to $n$, plus $2n$. Substitute again, and you see it's the sum of $T(x)$ for eight smaller values $x$ which add up to $n$, plus $3n$. And so on. Since the $x$ shrink by at least a factor $2/3$, the number of rounds until you end up at $T(1)$ is $O(\log n)$.
So that's what you guess, and once you guessed it you can prove it: $T(n) = O (n\log n)$. | You can solve recurrences of this form using the [Akra–Bazzi method](https://en.wikipedia.org/wiki/Akra%E2%80%93Bazzi_method). The answer is $O(n\log n)$. |
73,735,688 | Sample output:
Rise\_ID FROM\_LOCATION TO\_LOCATION SEATS\_LEFT
SEATS\_TOTAL RIDE\_PROVIDER START\_ON ENDS \_ON IS\_STARTED IS\_FINISHED 12014 Nandi hills banglore 0 3 11002 13-Nov-20
04.00.13.36 PM. 13-Dec-20 08.02.13.36PM yes yes | 2022/09/15 | [
"https://Stackoverflow.com/questions/73735688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20006282/"
] | Using **in** (as others have suggested) is incorrect. Because you want to check it as a prefix not merely whether it is contained.
What you want to do is use startswith() for example this:
```
list1 = []
for name in all_quads_names:
if name.startswith('qc1r'):
list1.append(name)
```
The full solution would be something like:
```
prefixes = ['qfg', 'qc1r']
lists = []
for pref in prefixes:
list = []
for name in all_quads_names:
if name.startswith(pref):
list.append(name)
lists.append(list)
```
Now lists will contain all the lists you want. | Try something like this:
```py
prefixes = ['qfg1', … ]
top = [ […], […], … ]
extracted = []
for sublist in top:
if sublist and any(prefix in sublist[0] for prefix in prefixes):
extracted.append(sublist)
``` |
43,230,303 | I have a canvas function which draws a square if I click on the canvas field and move the mouse, that works so far.
My Problem is that if I release the mouse and click at the canvas again the old drawn rectangle vanishes.
How do I make it possible that the old drawn does not get vanished.
My function:
```
function foo() {
var tool = this;
this.started = false;
var canvasx = canvas.offsetLeft;
var canvasy = canvas.offsetTop;
var last_mousex = 0;
var last_mousey = 0;
var mousex = 0;
var mousey = 0;
this.mousedown = function (ev) {
if(checkboxSquare.checked) {
last_mousex = parseInt(ev.clientX-canvasx);
last_mousey = parseInt(ev.clientY-canvasy);
context.strokeStyle = $('#selectColor').val();
context.lineWidth = $('#selectWidth').val();
tool.started = true;
}
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
mousex = parseInt(ev.clientX-canvasx);
mousey = parseInt(ev.clientY-canvasy);
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
context.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
context.rect(last_mousex,last_mousey,width,height);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
tool.started = false;
}
};
}
```
It Looks something like this: <http://jsfiddle.net/AbdiasSoftware/kqW4X/> | 2017/04/05 | [
"https://Stackoverflow.com/questions/43230303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7750768/"
] | The old drawn rectangle vanishes on click because, you are clearing the entire canvas each time before drawing a rectangle.
The *easiest* workaround would be to save the entire canvas as an image on mouseup and draw that image before drawing each rectangle.
```js
var canvas;
var _foo = new foo();
canvas.onmousedown = _foo.mousedown;
canvas.onmousemove= _foo.mousemove;
canvas.onmouseup = _foo.mouseup;
function foo() {
canvas = $('#canvas')[0];
var context = canvas.getContext('2d');
var checkboxSquare = $('#checkboxSquare')[0];
var img = new Image();
var tool = this;
this.started = false;
var last_mousex = 0;
var last_mousey = 0;
var mousex = 0;
var mousey = 0;
this.mousedown = function (ev) {
if(checkboxSquare.checked) {
last_mousex = ev.offsetX;
last_mousey = ev.offsetY;
context.strokeStyle = $('#selectColor').val();
context.lineWidth = $('#selectWidth').val();
tool.started = true;
}
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
mousex = ev.offsetX;
mousey = ev.offsetY;
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
context.drawImage(img, 0, 0); // draw saved canvas (image)
context.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
context.rect(last_mousex,last_mousey,width,height);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
img.src = canvas.toDataURL(); // save canvas as image
tool.started = false;
}
};
}
```
```css
canvas {
border: 1px solid black;
cursor: default;
margin-top: 5px
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkboxSquare">Square | Color
<select id="selectColor">
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select> | Width
<select id="selectWidth">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<canvas id="canvas" width="400" height="400"></canvas>
``` | I'm assuming that the `foo()` function is being called for every frame, either through `setInterval` or `requestAnimationFrame`. If my assumption is right, the reason why your previously drawn square disappears is because you are only storing the x and y coordinates of one rectangle, and every time you click on the canvas again, it gets overwritten by the new values for the new rectangle.
To solve your problem, you should store the x and y coordinates as well as the dimensions of the square on mouseup. These coordinates can be stored in an array.
```
var squares = [];
this.mouseup = function (ev) {
// other code
var square = {
x: last_mousex,
y: last_mousey,
width: mousex - last_mousex,
height: mousey - last_mousey
};
squares.push(square);
};
```
Now every time you draw the square, draw the squares stored in the `squares` array first.
```
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
// other code
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
// draw each square in the squares array after clearning the canvas
squares.forEach(function(square) {
context.beginPath();
context.rect(square.x, square.y, square.width, square.height);
});
context.beginPath();
var width = mousex - last_mousex;
var height = mousey - last_mousey;
context.rect(last_mousex, last_mousey, width, height);
context.stroke();
}
};
```
You'll see some code repetitions in drawing the squares, it's a good opportunity to abstract it into a separate function. |
57,513,230 | My goal is to export an extended class called `Entrance` without using curly brackets (Let's say `subclass`).
The problem is I can't access to the `subclass` while I'm using `default` keyword on it and the browser gives me an error such as this:
>
> Uncaught SyntaxError: Duplicate export of 'default'
>
>
>
Code:
```
// terminal.js
export default class Terminal {
constructor(output) {
this.output = output;
console.log(`This is Terminal`);
}
}
export default class Entrance extends Terminal {
constructor(output) {
super(output);
}
ticket() {
console.log(`Ticket please`);
}
}
// human.js
import Entrance from './terminal.js';
class People {
constructor(name, input) {
this.name = name;
this.input = new Entrance(this);
this.input.ticket();
}
}
const guy = new People('james');
```
Is this type of structure doesn't allow originally? Or did I miss something in the code?
Thanks for listening. | 2019/08/15 | [
"https://Stackoverflow.com/questions/57513230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11414756/"
] | I adapted your project to Node.js because this is easier for testing. In the browser you can still use the .js extension but you need to reference the files as modules, not as scripts.
For Node.js use the extension .mjs for ECMAScript Modules ('import' and 'export' are a feature of ECMAScript modules).
You only need to export the identifiers you reference externally: (the 'Entrance' class).
Use 'node --experimental-modules ./human.mjs' to run it
```
// terminal.mjs: only 'Entrance' is exported
// no need to export 'Terminal' as long as it's name is not referenced outside
class Terminal {
constructor(output) {
this.output = output;
console.log(`This is Terminal`);
}
}
export default class Entrance extends Terminal {
constructor(output) {
super(output);
}
ticket() {
console.log(`Ticket please`);
}
}
// human.mjs
import Entrance from './terminal.mjs';
class People {
constructor(name, output) {
this.name = name;
this.input = new Entrance(this);
this.input.ticket();
}
}
const guy = new People('james');
```
If you want to reference also the Terminal class outside, dont use 'default' exports/imports (or create a top level object with Terminal and Entrance as members):
```
// terminal2.mjs
export class Terminal {
constructor(output) {
this.output = output;
console.log(`This is Terminal`);
}
}
export class Entrance extends Terminal {
constructor(output) {
super(output);
}
ticket() {
console.log(`Ticket please`);
}
}
// human2.mjs: import the whole module under the alias 'term'
import * as term from './terminal2.mjs';
class People {
constructor(name, output) {
this.name = name;
this.input = new term.Entrance(this);
this.input.ticket();
new term.Terminal(this);
}
}
// human3.mjs: using named imports which are directly usable
import { Terminal, Entrance} from './terminal2.mjs';
class People {
constructor(name, output) {
this.name = name;
this.input = new Entrance(this);
this.input.ticket();
new Terminal(this);
}
}
const guy = new People('james');
```
Now with default exports but encapsulated into a library object. This might be the standard way to do it, but only export the symbols you reference outside:
```
// terminal4.mjs: using a top level object and a default export
class Terminal {
constructor(output) {
this.output = output;
console.log(`This is Terminal`);
}
}
class Entrance extends Terminal {
constructor(output) {
super(output);
}
ticket() {
console.log(`Ticket please`);
}
}
const myLib = {Terminal, Entrance};
export default myLib;
// or just: export default {Terminal, Entrance};'
// human4.mjs
import term from './terminal4.mjs';
class People {
constructor(name, output) {
this.name = name;
this.input = new term.Entrance(this);
this.input.ticket();
new term.Terminal(this);
}
}
const guy = new People('james');
```
references:
* 'export': <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export>
* 'import': <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import>
* Node.js ECMAScript Modules: <https://nodejs.org/api/esm.html> | The error is shown because you are exporting both Terminal and Entrance classes as default.
if you need only Entrance class from terminal.js, remove `export default` from Terminal class. |
56,164,557 | I am trying to import data from elasticsearch to sql server database, I have done import of data from sqlserver to elastic search using logstash, I reversed input and output but its throwing the error as shown in second screen:
[](https://i.stack.imgur.com/KxkK8.png)
[](https://i.stack.imgur.com/4DZdg.png) | 2019/05/16 | [
"https://Stackoverflow.com/questions/56164557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306094/"
] | I've successfully finished it. You can see my blog or the config.
blog:
[Output to SQL database by Logstash](https://datamansamxiao.wordpress.com/2019/12/25/logstash-data-output-to-sql-database/)
OK. now we need to install the “logstash" output JDBC plug-in. It’s very important if you don’t have the plug-in. Ya! You DO NOT need a “input" plug-in because it’s default set. But you need the output JDBC plug-in. It’s really important.
```
> bin\logstash-plugin.bat install logstash-output-jdbc
```
config:
```
input
{
elasticsearch {
hosts => [“localhost:9200″]
index => “yourindex"
}
}
output {
jdbc{
driver_jar_path => “C:\MSSQLJDBC\sqljdbc_4.2\enu\jre8\sqljdbc42.jar"
connection_string => “jdbc:sqlserver://localhost:1433;databaseName=databasename;user=username;password=userpassword"
statement => [ “INSERT into DB.TMP.samsamt (w, test1, test2, kkk) VALUES(?,?,?,?)", “client_num", “consignee_name", “@timestamp","host" ]
}
}
```
Operation
```
> bin\logstash.bat -f config\elk.conf
```
And the statement will be the transform design part. You need to mapping the columns you want in statement.
```
(w, test1, test2, kkk)
```
is the part of structured table column.
```
“client_num", “consignee_name", “@timestamp","host"
```
is the mapping column in Elasticsearch. | The error is showing in the log
>
> Couldn't find any output plugin named 'jdbc'.
>
>
>
It is available as a community plugin, though not sure it works with Logstash 7 (yet):
<https://github.com/theangryangel/logstash-output-jdbc> |
23,414,150 | I want to verify broken links on a website and I am using this code:
```
public static int invalidLink;
String currentLink;
String temp;
public static void main(String[] args) throws IOException {
// Launch The Browser
WebDriver driver = new FirefoxDriver();
// Enter URL
driver.get("http://www.applicoinc.com");
// Get all the links URL
List<WebElement> ele = driver.findElements(By.tagName("a"));
System.out.println("size:" + ele.size());
boolean isValid = false;
for (int i = 0; i < ele.size(); i++) {
isValid = getResponseCode(ele.get(i).getAttribute("href"));
if (isValid) {
System.out.println("ValidLinks:" + ele.get(i).getAttribute("href"));
driver.get(ele.get(i).getAttribute("href"));
List<WebElement> ele1 = driver.findElements(By.tagName("a"));
System.out.println("InsideSize:" + ele1.size());
for (int j=0; j<ele1.size(); j++){
isValid = getResponseCode(ele.get(j).getAttribute("href"));
if (isValid) {
System.out.println("ValidLinks:" + ele.get(j).getAttribute("href"));
}
else{
System.out.println("InvalidLinks:"+ ele.get(j).getAttribute("href"));
}
}
} else {
System.out.println("InvalidLinks:"
+ ele.get(i).getAttribute("href"));
}
}
}
}
public static boolean getResponseCode(String urlString) {
boolean isValid = false;
try {
URL u = new URL(urlString);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
h.setRequestMethod("GET");
h.connect();
System.out.println(h.getResponseCode());
if (h.getResponseCode() != 404) {
isValid = true;
}
} catch (Exception e) {
}
return isValid;
}
}
``` | 2014/05/01 | [
"https://Stackoverflow.com/questions/23414150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3521843/"
] | I would keep it returning an int, and just have the MalformedURLException be a special case, returning -1.
```
public static int getResponseCode(String urlString) {
try {
URL u = new URL(urlString);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
h.setRequestMethod("GET");
h.connect();
return h.getResponseCode();
} catch (MalformedURLException e) {
return -1;
}
}
```
EDIT: It seems you're sticking with the boolean approach, as I said before this has it's limitations but should work ok for demonstartion purposes.
There is no reason to find all elements a second time taking the approach you have. Try this:
```
// Get all the links
List<WebElement> ele = driver.findElements(By.tagName("a"));
System.out.println("size:" + ele.size());
boolean isValid = false;
for (int i = 0; i < ele.size(); i++) {
string nextHref = ele.get(i).getAttribute("href");
isValid = getResponseCode(nextHref);
if (isValid) {
System.out.println("Valid Link:" + nextHref);
}
else {
System.out.println("INVALID Link:" + nextHref);
}
}
```
This is untested code, so if it does not work, please provide more detail than just saying 'it doesn't work', provide output & any stack traces/error messages if possible. Cheers | You can try below code.
```
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
List<String> brokenLinks = getBrokenURLs(driver, "http://mayurshah.in", 2, new ArrayList<String>());
for(String brokenLink : brokenLinks){
System.out.println(brokenLink);
}
}
public static List<String> getBrokenURLs(WebDriver driver, String appURL, int depth, List<String> links){
{
driver.navigate().to(appURL);
System.out.println("Depth is: " + depth);
while(depth > 0){
List<WebElement> linkElems = driver.findElements(By.tagName("a"));
for(WebElement linkElement : linkElems)
if(!links.contains(linkElement))
links.add(linkElement.getAttribute("href"));
for(String link : links)
getBrokenURLs(driver, link, --depth, links);
}
}
return getBrokenURLs(driver, links, new ArrayList<String>()) ;
}
public static List<String> getBrokenURLs(WebDriver driver, List<String> links, List<String> brokenLinks){
{
for(String link : brokenLinks){
driver.navigate().to(link);
if(driver.getTitle().contains("404 Page Not Found")){
brokenLinks.add(link);
}
}
}
return brokenLinks ;
}
```
In above code, I am first getting list of URLs from the first page. Now I am navigating to the first link of the IInd page and getting all URLs, this way I will keep on storing all URL by going to each page one by one, till depth is mentioned.
After collecting all URLs, I will verify validity of each URL one by one and return List of URLs with 404 page.
Hope that helps!
src:
<https://softwaretestingboard.com/qna/1380/how-to-find-broken-links-images-from-page-using-webdriver#axzz4wM3UEZtq> |
71,156,797 | *[This is the [Codesandbox](https://codesandbox.io/s/busy-sky-bkczeq?file=/src/Tabs.js) with all of the code that exemplifies the issue I'm having. Sorry, SO doesn't allow for proper React code with TSX, etc.]*
I have some tabs, naturally, whenever I click on each of them, my state changes (namely `selectedTab`) and the body that's being rendered. Each tab item has a body that goes with it, the first tab, in my case, has a component that, if you click, a count is increased. Well, whenever the tab changes, that count gets reset. In fact, it's a full-rerender all around.
The problem with doing a full re-render is that - not only is it inefficient, given how the user's gonna use it, but it also adds fuel to the fire: what if the user inputs something on a tab, then switches to another tab to do something else and then back to the original one? He's just lost what he typed in.
Naturally, this can be solved if we render all of the tabs' content upfront and we just play with `display: none`, and it'd be a good solution, but I'm also trying to learn.
I understand how React re-renders things and why this happens, but is there a way to fix it?
In my case, if you look at `useTabs`, the `content` variable simply looks at the corresponding tab's `component` key and takes outputs that. It's there that, I think, I need to memoize things. | 2022/02/17 | [
"https://Stackoverflow.com/questions/71156797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18232568/"
] | Well i dont know what the issue was but changing :
```
l = map(str, l)
```
to this:
```
l = list(map(str, l))
```
fixed the issue | In Python 3 [*map*](https://docs.python.org/3/library/functions.html#map) doesn't return a list. Instead, it returns an iterator object. [*pop*](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) is the method of the list object. There is no *pop* method of an iterator object, hence it's considered an attribute, which is missing. As a result, you're getting the error.
>
> 'map' object has no attribute 'pop'
>
>
>
When you convert the iterator object to a list then you can use the method *pop*. |
35,342,543 | I have a gridview that contains inventory data. I am trying to put together a search function that will create a SQL WHERE clause on the fly, based on the contents of each control in the gridview header.
Each column in the gridview is a template field, with the controls added in the Header Template.
This is my code. Whenever it runs, the control (in this case, chkCaseSearch) is null, and I get the "object reference not set to an instance of an object" error.
This is my C# code; it is located in a button click event (the button is also a control in the gridview header). Each control has an equivalent if statement, but I'm only showing one for the sake of brevity.
Thanks!
```
TextBox tbManufacturerSearch = gvFirearms.FindControl("txtManufacturerSearch") as TextBox;
TextBox tbModelSearch = gvFirearms.FindControl("txtModelSearch") as TextBox;
TextBox tbSerialSearch = gvFirearms.FindControl("txtSerialSearch") as TextBox;
TextBox tbCaliberSearch = gvFirearms.FindControl("txtCaliberSearch") as TextBox;
DropDownList ddlTypeSearch = gvFirearms.FindControl("ddlTypeSearch") as DropDownList;
DropDownList ddlFormSearch = gvFirearms.FindControl("ddlFormSearch") as DropDownList;
CheckBox chkCaseSearch = gvFirearms.FindControl("chkCaseSearch") as CheckBox;
TextBox tbMagazineSearch = gvFirearms.FindControl("txtMagazineSearch") as TextBox;
TextBox tbLocationSearch = gvFirearms.FindControl("txtLocationSearch") as TextBox;
TextBox tbCommentsSearch = gvFirearms.FindControl("txtCommentsSearch") as TextBox;
if (chkCaseSearch.Checked)
{
strWhereClause = "[Case] = 1";
}
else if (!chkCaseSearch.Checked)
{
strWhereClause = "[Case] = 0";
}
``` | 2016/02/11 | [
"https://Stackoverflow.com/questions/35342543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894918/"
] | Looks like you have to access it through the `HeaderRow` like so
```
CheckBox chkCaseSearch = gvFirearms.HeaderRow.FindControl("chkCaseSearch") as CheckBox;
``` | If you are in a web environment, did you specify the ID tag in your aspx page?
If you are in a Winform app, it will be sufficient the (for example) `this.txtMagazineSearch` invocation to access the control properties. |
1,075,997 | We have an old web app written in classic ASP. We don't have the resources to rewrite the app.
I know that asp and aspx pages can coexist in the same ASP.NET web app, but it appears as those you cannot share Application and probably Session variables across these two groups of page extension types.
I was hoping to do new development in ASP.NET and to in theory, convert the Classic ASP pages over as we go.
Is there a way to share IIS variables across these two types of web pages (aside from passing information using the query string and forms fields)? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1075997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109676/"
] | There is no straigthforwad solution for sharing session variables between classic ASP and ASP.NET. I would recommend you to persist sessions into a database, like it is described in this [Microsoft Article](http://msdn.microsoft.com/en-us/library/aa479313.aspx). This way both ASP and ASP.NET can access session variables. | You could create a simple table in your DB to store the "session" info in. Both the classic asp and the .net pages could read and write there. |
60,078,007 | I have the following query:
```
SELECT DISTINCT A + ' ' + B + ' ' + C AS 'ABC', D
FROM Table
ORDER BY A, B
```
This gives the following error message:
```
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
```
I tried changing the ORDER By to this:
```
ORDER BY A, B, C 'ABC', D
```
And pretty much every variation there is of those possible combinations but the error remains.
So how can i get the distinct ABC and D first sorted by the A value, and after that the B value? (The C and D may remain unsorted and don't have to be Distinct seeing the ABC combination is already enough to indicate a unique value)
EDIT:
Alternatively, is it possible to remove duplicates based on Columns A AND B without using DISTINCT? | 2020/02/05 | [
"https://Stackoverflow.com/questions/60078007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11834607/"
] | Thanks to Brock's example of using "row\_number() OVER" i thought of a way to do it myself using PARTISION BY.
```
WITH ordering AS
(
SELECT
A,
B,
C,
D,
row_number() OVER
(
PARTITION BY
A,
B,
C
ORDER BY
A,
B,
C
) AS order_num
FROM
Table
)
SELECT A + ' ' + B + ' ' + C AS 'ABC', D
FROM ordering
WHERE order_num = 1
ORDER BY A, B, C
```
This way, instead of using DISTINCT i use *"row\_number() OVER ( PARTITION BY"* to give all records a number, with the duplicates getting an increased number. This allows me to filter on the order\_num being 1 to remove all duplicates. This way i can simply order by the original 3 columns seeing Distinct is no longer a part of the query. | ```
SQL>create table t (id int, c1 varchar(3), c2 varchar(3));
SQL>insert into t values (1,'AX','B');
SQL>insert into t values (2,'AB','D');
SQL>insert into t values (3,'A','XB');
SQL>select concat(c1,c2) from t order by c1, c2;
======
AXB
ABD
AXB
3 rows found
```
You can see above that row 2 (`ABD`) is sorted after one `AXB` row, and before the other `AXB` row, as the `order by c1, c2` specifies.
When you do `SELECT DISTINCT`, these two `AXB` rows will become only one row - which represents two separate rows in the table, one which is sorted before the `ABD` row, and one after the `ABD` row.
You can't put the duplicate eliminated `AXB` both before and after `ABD`. That's why
>
> ORDER BY items must appear in the select list if SELECT DISTINCT is
> specified.
>
>
> |
47,049 | I read about 2 methods for initializing WordPress function outside of WordPress files so We can use these functions on any page or website outside the WordPress blog.
Which one of these 2 methods is the correct one? What are the use cases for each method if both are correct? What is the deference between using one method or the other?
**Method 1:**
```
<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>
```
**Method 2:**
```
<?php
define('WP_USE_THEMES', false);
require('./wp-load.php');
?>
``` | 2012/03/27 | [
"https://wordpress.stackexchange.com/questions/47049",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13285/"
] | wp-blog-header.php will attached a header status, it will return a http status code of 404
wp-load.php will not
Useful to note when using ajax as it checks the http status code | You don't have to call the entire theme to use functions, just use the location for wp-load.php in wordpress directory.
```
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/wordpress/wp-load.php');
?>
``` |
37,629,891 | Currently I have calls like this all over my three controllers:
```
$scope.getCurrentUser = function () {
$http.post("/Account/CurrentUser", {}, postOptions)
.then(function(data) {
var result = angular.fromJson(data.data);
if (result != null) {
$scope.currentUser = result.id;
}
},
function(data) {
alert("Browser failed to get current user.");
});
};
```
I see lots of advice to encapsulate the `$http` calls into an HttpService, or some such, but that it is much better practice to return the promise than return the data. Yet if I return the promise, all but one line in my controller `$http` call changes, and all the logic of dealing with the response remains in my controllers, e.g:
```
$scope.getCurrentUser = function() {
RestService.post("/Account/CurrentUser", {}, postOptions)
.then(function(data) {
var result = angular.fromJson(data.data);
if (result != null) {
$scope.currentUser = result.id;
}
},
function(data) {
alert("Browser failed to get current user.");
});
};
```
I could create a RestService for each server side controller, but that would only end up calling a core service and passing the URL anyway. | 2016/06/04 | [
"https://Stackoverflow.com/questions/37629891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | There are a few reasons why it is good practice in non-trivial applications.
Using a single generic service and passing in the url and parameters doesn't add so much value as you noticed. Instead you would have one method for each type of fetch that you need to do.
Some benefits of using services:
* **Re-usability**. In a simple app, there might be one data fetch for each controller. But that can soon change. For example, you might have a product list page with getProducts, and a detail page with getProductDetail. But then you want to add a sale page, a category page, or show related products on the detail page. These might all use the original getProducts (with appropriate parameters).
* **Testing**. You want to be able to test the controller, in isolation from an external data source. Baking the data fetch in to the controller doesn't make that easy. With a service, you just mock the service and you can test the controller with stable, known data.
* **Maintainability**. You may decide that with simple services, it's a similar amount of code to just put it all in the controller, even if you're reusing it. What happens if the back-end path changes? Now you need to update it everywhere it's used. What happens if some extra logic is needed to process the data, or you need to get some supplementary data with another call? With a service, you make the change in one place. With it baked in to controllers, you have more work to do.
* **Code clarity**. You want your methods to do clear, specific things. The controller is responsible for the logic around a specific part of the application. Adding in the mechanics of fetching data confuses that. With a simple example the only extra logic you need is to decode the json. That's not bad if your back-end returns exactly the data your controllers need in exactly the right format, but that may not be the case. By splitting the code out, each method can do one thing well. Let the service get data and pass it on to the controller in exactly the right format, then let the controller do it's thing. | It would make sense to have your service look like this:
```
app.factory('AccountService', function($http) {
return {
getCurrentUser: function(param1, param2) {
var postOptions = {}; // build the postOptions based on params here
return $http.post("/Account/CurrentUser", {}, postOptions)
.then(function(response) {
// do some common processing here
});
}
};
});
```
Then calling this method would look this way:
```
$scope.getCurrentUser = function() {
AccountService.getCurrentUser(param1, param2)
.then(function(currentUser){
// do your stuff here
});
};
```
Which looks much nicer and lets you avoid the repetition of the backend service url and `postOptions` variable construction in multiple controllers. |
142,355 | Online sources show two supposedly equivalent ways to write an R linear model formula with nested factors:
```
y ~ a/b # b is nested within a
y ~ b %in% a # b is nested within a
```
Yet when you run data through lm() with these two formulas, you get very different results, as if the default contrasts are different. Why? | 2015/03/18 | [
"https://stats.stackexchange.com/questions/142355",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/71202/"
] | I think there may be a problem in some of the documentation, or at least an opportunity to make things clearer.
In the document ["An Introduction to R"](http://cran.r-project.org/doc/manuals/R-intro.pdf), the first place that we see the `%in%` term for a formula it implies that your 2 formulas give an identical result: "the second two specify the same nested classification".
But if you scroll/search down further then it says that `M_1 / M_2` equates to `M_1 + M_2 %in% M_1` which differs by a main effect term, not having the main effect term would change the interpretation and even how contrasts are applied.
The second version is what I remember having learned about the `a/b` notation, but given the description where we first see these terms it is easy to see why you (and probably many others) would expect identical results. | Which sources? They are wrong. `a/b` is equivalent to `a + a:b` and `a + b %in% a`. |
4,500,232 | I understand why interpretation overhead is expensive, but why are JITted Python implementations (Psyco and PyPy) still so much slower than other JITted languages like C# and Java?
Edit: I also understand that everything is an object, dynamic typing is costly, etc. However, for functions where types can be inferred, I'm not sure why this matters. | 2010/12/21 | [
"https://Stackoverflow.com/questions/4500232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
] | Python is a [dynamic language](http://en.wikipedia.org/wiki/Dynamic_programming_language).
This means that much of the work that other static languages (like C# and Java) do at compile time, is done at runtime and this reduces performances.
**EDIT:**
Furthermore, JIT compiler for a dynamic language like python, can perform much less optimisations on the code because it can't do many assumptions due to the dynamicity of the code.
**e.g.**
Dynamic typing prevents assumptions about type of fields/variables/parameters... , thus any optimisation involving that is almost impossible.
**EDIT2:**
just a clarification:
when I say compile time, I mean also JIT compile time, because actually JIT is a compiler.
Applying this to my first sentence, yields that Python can perform much less work at JIT time than C# or Java... | >
> I understand why interpretation
> overhead is expensive...
>
>
>
Compare those Python implementations [to non-JIT **interpreted-mode Java**](http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=javaxint&lang2=pypy) and think about your question again. |
46,949,954 | As it is said in the title I could use some help regarding a problem I have with my App.
My App scans a Barcode and offers to safe this barcode in a table together with a second String that can be put in which describes the number of times you want to save this barcode.
The customInit of the cell displays this as the barcode on the left and a grey number on the right representing the count. All of this information is saved in an array of form list=["972537657, 12"; ...]
My last functionality I want to implement is to have a function check for a maybe already existing barcode in the table and if there is instead of inserting a new row with the same barcode and a different number I want my app to just add the number I put in , to the number of the already existing table element with this specific barcode.
**My problem:** The logic in this works fine ; if there is an already existing element execute this function if not just insert a new row with the input data.
But I Have no idea how to tell the app what to change and how I can access this element of the array.
Maybe someone has an idea (I can also add some of my code if someone would like to inspect my problem further) | 2017/10/26 | [
"https://Stackoverflow.com/questions/46949954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8719318/"
] | First, find the index of the string your looking for, then remove it and insert it at the index.
```
let arr:Array = ["a","b","c"]
let indexOfA = arr.index(of: "a")
arr.remove(at: indexOfA)
arr.insert("YourString", at: indexOfA)
``` | if you only care about the duplication, why don't use Set instead of Array.
```
var barcode:Set = ["972537657","972537651","972537653"]
let result = barcode.insert("972537651")
if result.inserted {
print("insert")
}else {
print("duplication")
}
``` |
64,103,277 | I have two arrays :
```
let channelList = [
{
"channelId": 1,
"channelName": "SMS"
},
{
"channelId": 2,
"channelName": "EMAIL"
},
{
"channelId": 3,
"channelName": "ANDROID"
},
{
"channelId": 4,
"channelName": "IOS"
}
]
```
and
```
let promoList = [
{
"id": 124,
"channelType": "SMS"
},
{
"id": 125,
"channelType": "ANDROID"
},
{
"id": 126,
"channelType": "IOS"
}
]
```
I want a new array `remainingChannels` which has
```
{
"channelId": 2,
"channelName": "EMAIL"
}
```
because it is not present in `promoList`, but it is there in `channelList`.
I am trying to get it using the filter operation like this:
```
for(let channel of this.promoDetailList) {
remainingChannels = this.channelList.filter(e => {
e.channelName == channel.channelType
});
}
```
How to do this? | 2020/09/28 | [
"https://Stackoverflow.com/questions/64103277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8643979/"
] | You can do it using `Array.filter`.
```js
let channelList = [
{
"channelId": 1,
"channelName": "SMS"
},
{
"channelId": 2,
"channelName": "EMAIL"
},
{
"channelId": 3,
"channelName": "ANDROID"
},
{
"channelId": 4,
"channelName": "IOS"
}
]
let promoList = [
{
"id": 124,
"channelType": "SMS"
},
{
"id": 125,
"channelType": "ANDROID"
},
{
"id": 126,
"channelType": "IOS"
}
]
const result = channelList.filter(({channelName}) => {
return promoList.filter(({ channelType }) => channelType === channelName).length == 0;
});
console.log(result);
``` | Extract the items of one of the arrays into a string array.
```js
let channelList = [
{
"channelId": 1,
"channelName": "SMS"
},
{
"channelId": 2,
"channelName": "EMAIL"
},
{
"channelId": 3,
"channelName": "ANDROID"
},
{
"channelId": 4,
"channelName": "IOS"
}
]
let promoList = [
{
"id": 124,
"channelType": "SMS"
},
{
"id": 125,
"channelType": "ANDROID"
},
{
"id": 126,
"channelType": "IOS"
}
]
function cross(a, b) {
const b_ = b.map(item => item.channelType)
const res = []
a.forEach(item => {if (!b_.includes(item.channelName)) res.push(item)})
console.log(res)
}
cross(channelList, promoList)
``` |
41,772 | Sometimes, some of the employees over perform while others perform very badly.
for those who work very hard, **thank you letters and raises** are motivations for them.
As CTO, I have a case that one of my senior staff members is not performing well. I have had a one-to-one meeting with him, I sent him encouraging emails, and finally tough emails telling him that he is under performing and should do better. He is not changing!
This is starting to affect the morale of the team he is in - the argument (from mainly for intermediate and junior level employees) being:
>
> How is he considered senior when we are performing better than him? It is not fair that he is paid more than us.
>
>
>
Now, honestly, I am thinking of terminating him, but I don't want to leave a chance for anybody to explain, justify or predict the reasons behind termination on his/her behalf.
Do you recommend publishing Appreciation Letters for those who perform well and warning letters for those who perform badly using email to all or by posting these letters on bulletin board? What is the best way to let everybody know that the company is appreciating the work of hard workers and punishing the negligent ones. | 2015/02/22 | [
"https://workplace.stackexchange.com/questions/41772",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/32272/"
] | Praise in public, punish in private, for anything short of an immediate-firing offense. | I am writing this on the assumption that you are the line manager. If you are not then the correct thing to do is feed back your concerns to them initially and if that doesn't elicit a satisfactory response, to their line manager.
>
> i tried to discuss it with him by one-to-one meeting, by encouragement email, and finally by tough email
>
>
>
Did you try to have a discussion one-to-one or did you actually have a discussion? Did you make your expectations clear? Did you both come out of it with more understanding of expectations and why they're not being met? What did you agree between the two of you? What did you not agree on?
Certainly document serious problems in writing, but writing a 'tough email' is not an assertive or effective way of improving the performance of someone working for you. You should arrange a meeting between yourself and the employee in which you can discuss the problem, ask why things weren't done how you'd expect, and work out a plan for how to support them to meet expectations (and, if necessary, for you and others to communicate their expectations)
Your company should have a policy for managing performance. Follow it. If it doesn't, ask HR to produce one. Local laws or union agreements may require you to follow certain minimum procedures so that people are protected from bullying and have the opportunity to engage with constructive feedback. In most cases performance management is done privately.
However, if people complain about someone's performance focus on the listening. You need only one of two answers:
* "Thanks for letting me know, I'll talk to X about it"
* "Thanks for letting me know, I've already spoken to X about it and we're working on improving that" (In this case it's a good idea to make sure X knows that you'll be saying that).
Don't go into details, don't complain about other things X has done, work on the assumption that X is able to improve and give them the support and direction they need. |
3,187 | I understand, and practice, [bear-safe rules](https://outdoors.stackexchange.com/questions/225/what-precautions-should-i-take-to-protect-myself-and-my-camp-from-bears) like [hanging (or canister-ing)](https://outdoors.stackexchange.com/questions/86/bear-bags-vs-bear-canisters-which-is-better) during summer months, but what about in the winter when bears are (theoretically) hibernating, and the shorter / colder days make every extra task 10 times more difficult?
Is there some room for leeway? | 2012/11/10 | [
"https://outdoors.stackexchange.com/questions/3187",
"https://outdoors.stackexchange.com",
"https://outdoors.stackexchange.com/users/86/"
] | Bear canister rules are often relaxed in the winter. However, this will depend on where you are camping. On the east coast, in the Adirondacks, the rule is:
>
> NYSDEC Regulation Requires The Use of Bear Resistant Canisters by
> Overnight Users in The Eastern High Peaks Wilderness Between April 1
> And November 30. NYSDEC encourages campers to use bear resistant
> canisters throughout the Adirondack and Catskill backcountry.
>
>
>
On the other hand, out west bear cans are often required year round.
Obviously, you'll want to check the rules for the specific park you are going to be in, but as a more general guideline, if the temperature is generally staying below freezing there shouldn't be much bear activity. Combined with the general bear population this will determine if bears are likely to be a problem.
Another thing to consider though, is that hanging your food protects it from more than just bears (eg mice). While the bears might not be a problem, mice don't hibernate. | I would suggest following the bear rules year round. In the Canadian Rockies, we still have areas closed due to bear activity in the middle of January. Plus ravens will make short work of anything left accessible, not to mention worrying about attracting cougars and wolves.
Here's a couple links outlining safety for camping in the backcountry, and in case you do see a bear.
[Be Bear Smart](http://www.albertaparks.ca/kananaskis-country/advisories-public-safety/wildlife/be-bear-smart.aspx)
[Backcountry Camping](http://www.albertaparks.ca/kananaskis-country/advisories-public-safety/backcountry-safety.aspx) |
20,251,162 | I have seen numerous posts on how to display progress bar while the data loads in the background. All suggestions requires we manually place a ProgressBar in the layout xml and then use an `AsyncTask` to show and hide the ProgressBar and the View in question.
However, I would like to make a generic class which creates the ProgressBar programmatically at runtime and place it exactly over the view in question and maybe also slightly shade or blur the view while the ProgressBar is displayed. Had this been a Swing application I would have painted my progress bar on the ["glass pane"](http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html) of the view after slightly shading it with gray. In that case since the progress bar is the child of the same pseudo parent hence I could easily position that as centred.
In Android UI toolkit I am not aware of any such "glass panes". How do I achieve this effect? | 2013/11/27 | [
"https://Stackoverflow.com/questions/20251162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137893/"
] | The PhotoImage method creates an image for the first TK () instance created.
Thus, it seems to have solved to inherit TK () instance by replacing TopLevel ().
This can be solved by specifying the master of the Tk () instance as the option of PhotoImage.
I think this should be changed.:
```
splsh_img = tkinter.PhotoImage(file=file,master=wlcm_scrn)
``` | Maybe not for this exact case, but for a similar one, I found that the customary
```
if __name__ == '__main__':
wlcm_scrn() #Call through procedure.
```
solves the problem as well.
This seems to kill the active window and to create a new one each time you re-call the same module. |
9,512,695 | In PHP
If you had an array of one million integers, how would you go to print each integer that contain the number seven(eg..7,17,67..) with out using a loop? | 2012/03/01 | [
"https://Stackoverflow.com/questions/9512695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/847085/"
] | Try with:
```
function sevens($var) {
return strpos($var, '7') !== false;
}
$input = array( /* one million integers */ );
$output = array_map($input, 'sevens');
``` | I think you can just do
```
WHERE intVal LIKE '%7%'
```
and the integer will automatically be cast to a string. It is worth a go, anyway. |
59,053,189 | When I label images or text for Machine Learning purposes, I often export the results in a `json` format. Then, I can open it in `vim` and simply pretty print using
```
:execute '%!python -m json.tool'
```
I often add `| w` which automatically writes changes to the file.
Is there a way to reverse this process? To compact the json, so there are no redundant characters?
### Example input:
```
{
"name": "John",
"email": "john@smith.co.uk"
}
```
### Desired output:
```
{"name":"John","email":"john@smith.co.uk"}
```
I would be fulfilled with Vimish, Pythonish and Bashish solution. | 2019/11/26 | [
"https://Stackoverflow.com/questions/59053189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4723795/"
] | There is no tool that takes a SAS program or step and compiles it into a separate .exe or .dll.
If you are working at a company that has a SAS Server installed you can published your code as a stored process, and other users can run the stored process through a browser when they are logged into the SAS Server.
You can create a .dll or (.exe) that protects the computation method and makes it available to non SAS environs. The .dll would require all the data for the computation be passed into it, or some data retrieval parameters if the .dll is supposed to retrieve the data itself (2 examples: (1) a data filename, or (2) an odbc connection string and query).
SAS has several interfacing methods and call routines that allow a SAS session to execute a method in a dynamic load library (.dll) or run an external program.
DLL:
* `module` call routine
* `modulen` function
* `modulec` function
EXE:
* `X` statement
* %SYSEXEC statement
If you are looking to make a whole bunch of data reporting features available to a wide audience of non-SAS users you will have to implement that functionality in a non-SAS system that is widely and freely distributable, some examples:
* separate exe you compile and distribute that users can run
+ might require other (non-SAS) 3rd party library licensing to get the output charts you want
* web server endpoint
+ output be generated by technology such as R, PHP, Perl, ASP, etc...
* program source code for different system (such a R)
+ Users would install R and run the source code themselves
The requirement to protect the health data means the most likely scenario is you MME computation is performed and delivered through some sort of web server. This also provides you the greatest control over 'versions' of the computation that users will be using. | You probably still want to use "a statistics-oriented language," and one possibility that occurs to me is the open-source language **"R."**
<https://en.wikipedia.org/wiki/R_(programming_language)>
Now, this is not a direct "answer" to your question but it might be a pointer in a viable direction. "R" is specifically oriented towards statistics work, and, unlike SAS (which consists of macro-calls except in the `DATA` steps), it is entirely a procedural programming language. Hope this helps ...
(Both SAS and SPSS today include interfaces to "R," because it is a powerful adjunct to both of these tools and somewhat "fills a hole" in their traditional approaches.)
Another open-source programming language that is often used in statistics work, in conjunction with "R," is **Python:**
<https://en.wikipedia.org/wiki/Python_(programming_language)>
It is particularly well-suited to working with lists, and I see these two products being successfully used together in projects where SAS or SPSS might otherwise be used. Both have a vibrant and active user community and are well-supported. |
1,063 | Which one is correct?
>
> A partir de ahora, voy a hablar en español.
>
>
>
or
>
> Desde ahora, voy a hablar en español.
>
>
>
In meaning I think both are close to "from." Are there any specific instances where one cannot replace the other. | 2011/12/21 | [
"https://spanish.stackexchange.com/questions/1063",
"https://spanish.stackexchange.com",
"https://spanish.stackexchange.com/users/359/"
] | **RAE**:
>
> **partir**:
>
>
> intr. Tomar un hecho, una fecha o cualquier otro antecedente como base para un razonamiento o cómputo.
>
>
> **desde**:
>
>
> prep. Denota el punto, en tiempo o lugar, de que procede, se origina o ha de empezar a contarse una cosa, un hecho o una distancia. Desde la Creación. Desde Madrid. Desde que nací. Desde mi casa. U. t. en locs. advs. Desde entonces. Desde ahora. Desde aquí. Desde allí.
>
>
>
*A partir de* is used when an action is going to take place starting from that point on. You can indicate the end by using *hasta*.
**Example**:
>
> **A partir** del lunes voy a hacer ejercicio.
>
>
> **A partir** de mañana voy a empezar a estudiar hasta que presente el examen.
>
>
>
*Desde* means the same thing as *a partir* but the difference is that desde is used for actions that have already taken place and are still valid in the present or a specified point in time (you use hasta to indicate the end).
>
> **Desde** el año 2004 en Europa se transmite televisión en alta definición. (and still being transmitted)
>
>
> Los niños comenzaron a jugar **desde** que la maestra salió del salón **hasta** que la directora llegó y los regañó.
>
>
>
So which one is correct? It's difficult because of the *ahora* but for me as a native speaker it sounds more natural "**Desde ahora**...". | Desde works nearly everywhere, but a partir de only really works with sustantives.
* Desde que te fuiste, nada es lo mismo, you can't really say "a partir de que te fuiste" (I think it's strictly correct, but it screeches), although you could say "A partir del día que te fuiste"
"A partir de" is used frequently for resolutions, either personal resolutions like your example or "lawful" stuff ("a partir del lunes, las horas extras estarán prohibidas" [from Monday on, working overtime will be illegal]). It's also more natural if the point of time is just now or in the future, desde seems more natural for the past (i.e. hablo español desde el mes pasado; hablaré español a partir del mes que viene). |
1,747,744 | We have a large MFC/C++ Visual Studio 2005 solution which currently consists of two projects:
* Code (around 1500 .h/.cpp files, linked dynamically to MFC)
* Resource DLL (we translate the resources using an external tool)
What options do we have (lib, dll, ...)?
Where do we start?
Is there a technical sample of this or a tutorial (I could not find anything)?
PS: We have no experience with creating dlls and/or libs with C++/Visual Studio yet, so any tips how to get started are appreciated. | 2009/11/17 | [
"https://Stackoverflow.com/questions/1747744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54159/"
] | This depends very much on the quality of you codebase. If you have nicely encapsulated classes/components that interact through well defined interfaces, it should not be to hard to seperate those into different projects.
Also, before you start, think about what you want to achieve. Are there reusable or platform dependent components in the system that you want to isolate? In my department, we have written a set of Visual C++ 2005 Wizards that make sure, that all newly created projects comply to a certain directory structure and organisation (e.g. we can automatically create unit test projects for our libraries). We also use them to make sure that reusable components can be included via SVN externals, which really saves a lot of work.
So, before you look any further, make sure you get you requirements right. | MFC this or not you have to start from extracting business logic from GUI handlers. Once you done this you can put them inside alib. |
5,041,498 | May you please help me on this: I developed a web application that has Checkboxes and i want to show some controls when the user tick the box and hide them when the user untick the box. I only managed to do the showing part when the user tick the box, now i'm failing to hide them when the user untick the box.
Here is the showing part of the my code:
```
protected void chkboxMentor_CheckedChanged(object sender, EventArgs e)
{
lblMentorName.Visible = true;
txtMentorName.Visible = true;
lblMentorStuff.Visible = true;
txtMentorStaffNo.Visible = true;
lblMentorDate.Visible = true;
btnShowCal.Visible = true;
}
```
Please help me with the hiding part.
Any help please!!! It will be highly appreciated | 2011/02/18 | [
"https://Stackoverflow.com/questions/5041498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/621381/"
] | You need to set the `Visible` property to the checkbox's `Checked` property. | ```
protected void chkboxMentor_CheckedChanged(object sender, EventArgs e)
{
if(chkboxMentor.Checked)
{
lblMentorName.Visible = true;
txtMentorName.Visible = true;
lblMentorStuff.Visible = true;
txtMentorStaffNo.Visible = true;
lblMentorDate.Visible = true;
btnShowCal.Visible = true;
}
else
{
lblMentorName.Visible = false;
txtMentorName.Visible = false;
lblMentorStuff.Visible = false;
txtMentorStaffNo.Visible = false;
lblMentorDate.Visible = false;
btnShowCal.Visible = false;
}
}
``` |
45,594,707 | I've recently seen the `--no-cache-dir` being used in a Docker file. I've never seen that flag before and the help is not explaining it:
```
--no-cache-dir Disable the cache.
```
1. Question: **What is cached?**
2. Question: **What is the cache used for?**
3. Question: **Why would I want to disable it?** | 2017/08/09 | [
"https://Stackoverflow.com/questions/45594707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/562769/"
] | 1. **Cached is**: store away in hiding or for future use
2. **Used for**
* store the installation files(`.whl`, etc) of the modules that you install through pip
* store the source files (`.tar.gz`, etc) to avoid re-download when not expired
3. **Possible Reason** you might want to disable cache:
* you don't have space on your hard drive
* previously run `pip install` with **unexpected** settings
+ eg:
- previously run `export PYCURL_SSL_LIBRARY=nss` and `pip install pycurl`
- want new run `export PYCURL_SSL_LIBRARY=openssl` and `pip install pycurl --compile --no-cache-dir`
* you want to keep a Docker image as small as possible
**Links to documentation**
<https://pip.pypa.io/en/stable/reference/pip_install/#caching> – @emredjan
<https://pip.pypa.io/en/stable/reference/pip_install/> - @mikea | Another reason to disable the pip cache - if you run pip as a user that does not yet exist, their home directory will be created, but owned by root.
This happens to us when building Amazon AMIs in a chroot - pip is being run as a user that exists on the builder machine, but not in the chroot jail where the AMI is being constructed. This is problematic as that specific user can now not ssh to what was just built as their .ssh directory is not readable by them.
I can't think of any other reason pip would be run as a user that doesn't exist though, so it's very much an edge case. |
31,945,632 | I have a problem I'm not quite sure how to approach. I have a template that will render a section of text that will itself contain a template tag to be dynamically updated.
```
<ul>
{% for section in sections %}
<li>{{ section.content | safe }}</li>
{% endfor %}
</ul>
```
will render:
```
{{ document.customer }} Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sit amet tortor eu velit accumsan ornare vel in purus.
{{ document.customer }} Aenean rhoncus elit tempus finibus fermentum. Nullam accumsan ullamcorper felis, eu vestibulum neque laoreet ac.
```
I then need to dynamically update the `{{ document.customer }}` tag within `section.content`. This same tag renders fine in the template, but not as part of the individual sections also being rendered. How would I go about rendering the template variable within the section within the template?
I've tried replacing the above with `{% include "display_lld_sections.html" with sections=sections document=document %}` but this doesn't make a difference, as I assume it's just moving the issue to a different template. And I can't see that writing a custom tag is going to help either as it's still going to only work on the sections rather then the content within the sections, am I right?
I have also tried using a `with` statement:
```
<ul>
{% for section in sections %}
{% with document=document %}
<li>{{ section.content | safe }}</li>
{% endwith %}
{% endfor %}
</ul>
```
I also started to rewrite my view:
```
rendered_sections = {}
for section in sections:
x = render(request, 'lld/lld_sections.html',{'document': document})
rendered_sections[section.name] = x
```
Though this is not, I suspect the way to approach this. Is this something that will need to being done using code in my view or model, rather than something that will be done in my template? | 2015/08/11 | [
"https://Stackoverflow.com/questions/31945632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3250984/"
] | The `Object3D` class has a property `userData` where you can *safely* add custom data.
Since the `Mesh` class is derived from `Object3D`, it has that property, too.
Use it like so:
```
mesh.userData.name = "TheName";
```
three.js r.71 | Its still JavaScript so you can add a custom object to the mesh:
```
var building = new THREE.Mesh( [...] );
building.info = { name: "myHouse", lat: 48.12, lng: 8.54, [...] };
console.log( building.info.name ); //myHouse
``` |
11,552,732 | I am trying to accomplish something like this:
I am creating a simple blog. I have set up categories for my blog.
I want that when my user goes to posts/index, he sees a list of all categories.
Example:
Text
Image
Upon clicking on a category, my user gets redirected to the posts/new page, where the category\_id field will by transmitted through a hidden\_field.
So my code right now is:
in posts/index
```
<% @categories.each do |c| %>
<%= link_to c.name, new_post_path(:category => c.id) %><br />
<% end %>
```
and in my posts/\_form i'm trying to do something like this
```
<%= f.hidden_field :category_id, :value => params[:category_id] %>
```
which is not working though, because the html output is
No value is being passed.
What is the correct way to proceed here?
Thx! | 2012/07/19 | [
"https://Stackoverflow.com/questions/11552732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731882/"
] | Among some professionals, the single common lookup table is a design error you should avoid. At the very least, it will slow down performance. The reason is that you will have to have a compound primary key for the common table, and lookups via a compound key will take longer than lookups via a simple key.
According to Anith Sen, this is the first of five design errors you should avoid. See this article: [Five Simple Design Errors](http://www.simple-talk.com/sql/database-administration/five-simple--database-design-errors-you-should-avoid/) | You can store them in a text search (ie nosql) database like [Lucene](http://lucene.apache.org). They are ridiculously fast.
I have implemented this to great effect. Note though that there is some initial setup to overcome, but not much. Lucene queries on ids are a snap to write. |
179,270 | I'm trying to set up an ssh tunnel layout where:
1. client A (not ssh-server enabled) initiates ssh connection to server S
2. socks server is opened on server S:yyyy that tunnels all data via client A
3. client B connects socks server on server S, and tcp data routes via client A to the Internet
A possible solution would be to add a proxy server on Client A (binded to localhost:xxxx), and then run on client A `ssh -R yyyy:localhost:xxxx Server`. That would achieve the goal. But that's not as clean as using just ssh.
Is it possible to achieve this with just the ssh client on A and ssh-server on S? it's like reverse-dynamic-port-forwarding on ssh - creating `ssh -D` from A to S, and then somehow setup on this tunnel a second tunnel of `ssh -D` from S to A. Somewhat confusing, and not sure if possible. | 2015/01/15 | [
"https://unix.stackexchange.com/questions/179270",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/99373/"
] | Don't know whether this helps anyone, here is a diagram for my setup that I managed to construct...
[](https://i.stack.imgur.com/PM6gQ.png)
You will see two processes on MACHINE\_B:
The SSH client connection to MACHINE\_A (olive):
```
ssh -R 127.0.0.1:22344:127.0.0.1:4444 -i privkey.sshkey -N user_a@machine_a
```
The SSH client working as SOCKS server on port 4444 (dark green):
```
ssh -D localhost:4444 -N user_c@localhost
```
And one processes on MACHINE\_A, the one playing server listening on port 22344 (olive).
The light green process on MACHINE\_B should appear when the light green process on MACHINE\_A asks for a connection... | This is quite straightforward.
On local side (Server S), start your openssh server server. This will start ssh server by default on port 22 - you could change this port in /etc/ssh/sshd\_config file, if necessary.
```
service ssh start
```
On remote side (Client A), start a socks proxy AND set a remote port on the local side to connect to the socks proxy.
```
ssh -N -D 127.0.0.1:8888 -p 22 <server-s>
ssh -N -R 2222:127.0.0.1:8888 -p 22 <server-s>
```
On local side (Server S), use socks proxy setup on port 2222 via e.g. to connect to Google.
```
curl --socks5 127.0.0.1:2222 https://www.google.com
``` |
4,635,579 | I want to include the latest news as part of my application, does anybody know any news APIs or sites where they say you can use their news for your app? | 2011/01/08 | [
"https://Stackoverflow.com/questions/4635579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561395/"
] | There is a plenty of RSS reader samples on the internet, for Mac OS X or iPhone. You can use custom XML parser or JSON. Check github for samples. | If you want stock news specifically I suggest IEX, Alphavantage or [stocknewsapi](https://www.stocknewsapi.com) I personally use stock news api as it is the most relevant and the images are great quality. Hope this helps! |
6,457,546 | How can i make my laptop to act as a multicast router.
I need to stream video content to other computers with in same network. How can i make my laptop to work as a multicast router. | 2011/06/23 | [
"https://Stackoverflow.com/questions/6457546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/773054/"
] | If your functions all share the `currentSocket` global variable (and if you can't change them), it is not possible to have multiple connections (as long as the functions are async). If you could change them it would be best just to pass the socket as first parameter to your functions. Another way is to move the definition of `currentSocket` and your functions inside of the `io.sockets connection` callback. In this case the `currentSocket` variable forms a closure and everything should work as expected:
```
io.sockets.on('connection', function (socket) {
var currentSocket = socket;
socket.on('msg', function (data) {
global[data.functionToInvoke];
});
//global function that I can't change or even analyze/read
//========================================================
function g1(){
//might use currentSocket
//might invoke async stuff like
fs.readfile(...cb)
}
function g2(){
//might use currentSocket
//might invoke async stuff like
redisClient.get(...cb)
}
});
``` | If you want to wrap an established method in JS the way to do it is by renaming & replacing.
e.g.
```
Array.prototype._toString = Array.prototype.toString;
Array.prototype.toString = function(){ return "wrapped["+this._toString()+"]"; };
console.log(["1","2","3"].toString());
```
I'd suggest applying that to your use case, in this case either the io.sockets object, or a deeper object, perhaps all the way down on the EventEmitter.emit() method. |
320,049 | I have a Lenovo X201s with i7 L620 @ Ghz and 4Gb Ram
Windows 7 Professional 64bit is installed on it and
all 4Gb is visible from task manager and all other system tools
Virtual memory is set manually for initial 4096Mb and max 8192Mb
There is 22Gb free space on the one and only local disk where its configured.
When memory usage according to task manager reaches about 3.18 Gb (83%)
the machine starts to swap heavily and becomes very unresponsive.
Resource monitor says:
HW reserverd 205Mb
In use 3262Mb
Modified 6Mb
Standby 606Mb
Free: 17Mb
Available 627Mb
Cached 623Mb
Total 3891Mb
Installed 4096Mb
After a clean boot I have 1.2Gb used memory according to Task Manager
and 1.7Gb used after all memory hogs like skype and desktop gadgets are
loaded.
I have checked through fully with nod32 virus scanner (nothing found),
made sure that all the latest Updates are installed, ran memtest86+ overnight
(no errors)
I know Im not really using the memory too sparingly, can get carried
away with the number of browser tabs open and usually I have openoffice
or some other application running as well with some other utilities,
like calculator, notepad, winamp. However I just feel this is not really
out of ordinary extreme usage and 4Gb seemingly insufficient to handle it
surprises me.
My questions are the following:
1. Does the above way of operation (starting to swap around 80% of usage)
seem correct, or is something wrong with my system? If something is wrong
how can I trace it down? What are the most common fixes for similar situations?
2. If the system operates fine. Is there a way to improve the situation
without changing my habits of using the machine (ie. avidly closing applications
and browser tabs before I open new ones) or buying more RAM?
I found <http://www.koshyjohn.com/software/memclean/>
to be useful. I tried to track down what windows service could I disable which
I do not need and consumes memory (I disabled quite a few already) | 2011/08/07 | [
"https://superuser.com/questions/320049",
"https://superuser.com",
"https://superuser.com/users/89772/"
] | 1. Yes this is normal.
2. If you really want to you can 'fix' this by disabling the page file. There are no good reasons to do that in your situation (and some would argue in any situation), so just leave it alone. | With certain kind of usage patterns it's very much possible to just run out of memory if you have only 4G. Lots of tabs open in browsers, office applications, Photoshop etc use quite a lot of memory these days. |
11,987,289 | When my app receives a notification it handles it like this opening a specific view:
```
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(@"Recieved Notification didFinishLaunchingWithOptions %@",localNotif);
[theLastPresentedViewController presentViewController:myVC animated:YES completion:nil];
}
```
Basically my question is how to get access to the last presented ViewController **theLastPresentedViewController** so I can present `myView` on top of it ?
While the app uses a tabBarViewController as the basis, I present other viewControllers on top of other views so there is no way to know which ViewController has beed presented as the last one.
Do I have to manually remember each ViewController I present, so when the app launches I can access the last one or is there a way to directly access the last visible viewController of the app ?
Since the user can just press the HOME Button and exit the app there is no way to know which view was shown at this moment. It would also be OK to dismiss all these views from the stack until the tabBarViewController is reached.
Many thanks! | 2012/08/16 | [
"https://Stackoverflow.com/questions/11987289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387184/"
] | I found this to access the top most window/view:
```
[[[UIApplication sharedApplication] keyWindow] addSubview:someView]
``` | ```
- (void)applicationDidEnterBackground:(UIApplication *)application{
saveIndex = self.tabBarController.selectedIndex //shows the current index of the viewController of the Array of the tabBarController
//add some stuff to save the integer}
```
You could save this integer when the User quits the App and after the app becomes active load the tabBarController with this element of the Array
To open the saved view write this in your AppDelegate:
```
- (void)applicationDidBecomeActive:(UIApplication *)application{
[self.tabBarController setSelectedIndex:savedIndex];}
```
This should do it |
2,111,610 | I just noticed that Intellij has a UML diagram drawer. I am attempting to use it to figure out what is going on in some code that is new to me.
Is there anyway to show the dependencies between all of the classes/interfaces on the screen? Is this a useful feature? It seems to be missing somethings but it might just be that I am not that familiar with UML.
Anyone have any observations?
---
Is there anyway to show has-a relationships? | 2010/01/21 | [
"https://Stackoverflow.com/questions/2111610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251589/"
] | Streams are generally quite safe. Under some circumstances, they can be slow and/or clumsy. Slow, mostly stems from the fact that they impose a few extra layers between your code and the OS, and under the wrong circumstance those layers can add overhead. The clumsiness is mostly in comparison to C's printf, not direct use of something like WriteFile (which doesn't directly support formatting at all). For example, however, consider:
```
printf("%2.2x", ch);`
```
to
```
std::cout << std::hex << std::setw(2) << std::setprecision(2) << std::setfill('0') << ch;
std::cout << setfill(' ');
```
Then consider the fact that if you care about i18n, `printf` is using a string that's easy to read in from an external source, where the C++ stream is embedding all the formatting into the structure of the code, so nearly any change in formatting requires rewriting the code, recompiling and relinking.
`CreateFile, ReadFile`, etc, also allow a number of things like memory mapped files and overlapped reading and writing that aren't supported by iostreams at all. If the situation lets you make good use of these, iostreams often won't be competitive. | There are three alternatives you've mentioned here:
1. C++ streams (ostream, istream, fstream)
2. C stdio (printf, sprintf fprintf)
3. Windows files (ReadFile, WriteFile)
Options 1 & 2 are platform independant. This means you can compile the code for mac, linux, or many other operating systems. Option 3 is Windows only. That means you cannot compile it for anything but Windows.
When deciding between options 1 & 2, it is up to how you want to use it. The C library is easier to use regarding languages. It's a nightmare trying to replace text with alternative languages in streams, however it's much easier to make streams thread-safe, translate more complicated classes to a printable format, and extend stream capabilities.
C++'s iostream versus C's stdio is a highly heated argument which is discussed in many other places in this forum such as
[C++ Streams vs. C-style IO?](https://stackoverflow.com/questions/5328873/c-streams-vs-c-style-io) and other places online. |
9,780,333 | I'm getting confused about the various options in the [twitter bootstrap grid](http://twitter.github.com/bootstrap/scaffolding.html%5C), and how they go together.
To begin with, you can have an ordinary fixed `container`, or a `container-fluid`.
Then either one can include either an ordinary `row`, or a fluid row, `row-fluid`. That is, you can have a fixed container with a fluid row, or a container-fluid... with a fixed row?
Then on top of that, you can include the 'responsive' media queries, or not.
I am getting confused as to how these things interact. But let's start with one obvious example.
On [the examples page](http://twitter.github.com/bootstrap/scaffolding.html) itself, there's what's presented as an example of both a [fixed grid](http://twitter.github.com/bootstrap/scaffolding.html#gridSystem) and a [fluid grid](http://twitter.github.com/bootstrap/scaffolding.html#fluidGridSystem)
However, in my browser, on that example page itself -- both grids behave identically. Perhaps because the example page uses the optional responsive media queries? In **both** grid examples, if I start gradually narrowing my browser window, the grid elements do *not* get gradually narrower -- once a certain (responsive) boundary width is reached, they snap to a smaller size, and again at further boundary widths. But both the ordinary 'fixed' example AND the 'fluid' example behave exactly the same here -- so what the heck is the difference? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9780333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/307106/"
] | Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.
The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.
Here is [a good article about fluid vs. flex](http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/). | you may use this - <https://github.com/chanakyachatterjee/JSLightGrid> ..JSLightGrid. have a look.. I found this one really very useful. Good performance, very light weight, all important browser friendly and fluid in itself, so you don't really need bootstrap for the grid. |
31,266,953 | I have included given code in my en-US.yml
```
en-US:
date:
formats:
default: "%m-%d-%Y"
long: "%B %d, %Y"
short: "%b %d"
```
and I want to show format short so for this I have given
```
@title= I18n.l (Time.now, format: :short)
```
its not working it gives me
>
> syntax error, unexpected ',', expecting ')'
>
>
>
Please guide me how to solve this. Thanks in advance. | 2015/07/07 | [
"https://Stackoverflow.com/questions/31266953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739770/"
] | This cannot be done directly in C#.
You can however implement it in verifiable CIL:
```
.method public hidebysig static bool Test<T>(!!T& a, !!T& b) cil managed
{
.maxstack 8
ldarg.0
ldarg.1
ceq
ret
}
```
**Tests**
```
int a = 4, b = 4, c = 5;
int* aa = &a; // unsafe needed for this
object o = a, p = o;
Console.WriteLine(Test(ref a, ref a)); // True
Console.WriteLine(Test(ref o, ref o)); // True
Console.WriteLine(Test(ref o, ref p)); // False
Console.WriteLine(Test(ref a, ref b)); // False
Console.WriteLine(Test(ref a, ref c)); // False
Console.WriteLine(Test(ref a, ref *aa)); // True
// all of the above works for fields, parameters and locals
```
**Notes**
This does not actually check for the same reference, but even more fine-grained in that it makes sure both are the same 'location' (or referenced from the same variable) too. This is while the 3rd line returns `false` even though `o == p` returns `true`. The usefulness of this 'location' test is very limited though. | >
>
> >
> > I know, that int is a value type but here it should pass references to the same object.
> >
> >
> >
>
>
>
Yes, the reference passed to the method are the same, but they are boxed *(converted to object/reference type)* in the `ReferenceEquals` method.
That is why the result of your test returns false, since you are comparing references of two different objects, *due to boxing*.
See: [Object.ReferenceEquals Method](https://msdn.microsoft.com/en-us/library/system.object.referenceequals(v=vs.110).aspx)
>
> When comparing value types. If `objA` and `objB` are **value types,
> they are boxed** before they are passed to the `ReferenceEquals`
> method. This means that if both `objA` and `objB` represent the **same
> instance** of a value type, the `ReferenceEquals` method nevertheless
> returns false
>
>
> |
3,721,999 | Following code is an example of text placed into a textarea from a database.
```
<textarea id="inputPane" cols="80" rows="40" class="pane">
<p>
some text here...
</p>
<p>
more text here...
</p>
</textarea>
```
using jQuery's .trim what is the actual jquery code to remove all leading and trailing whitespace and have the textarea display very similar to below?
```
<textarea id="inputPane" cols="80" rows="40" class="pane">
<p>some text here...</p>
<p>more text here...</p>
</textarea>
```
I've worked on this for hours with no success trying varying combinations with .trim
```
$('#inputPane')jQuery.trim(string);
``` | 2010/09/15 | [
"https://Stackoverflow.com/questions/3721999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335603/"
] | You could try something like this:
```
jQuery(function($) {
var pane = $('#inputPane');
pane.val($.trim(pane.val()).replace(/\s*[\r\n]+\s*/g, '\n')
.replace(/(<[^\/][^>]*>)\s*/g, '$1')
.replace(/\s*(<\/[^>]+>)/g, '$1'));
});
```
Which gives the result:
```
<p>some text here...</p>
<p>more text here...</p>
```
Though this may not be bulletproof, it should prove to be much faster/more efficient than creating elements from the HTML value of the textarea. | Try this:
```
var $input = $('#inputPane');
var $container = $('<div>').html( $input.val() );
$('*', $container).text( function(i,txt) {
return $.trim( txt );
});
$input.val( $container.html() );
```
It turns the content of the `textarea` into elements, walks through them and trims the content, then inserts the resulting HTML back into the `textarea`.
---
**EDIT:** Modified to use `.val()` instead of `.text()` as noted by @bobince |
586,984 | ```
\documentclass{article}
\usepackage[left=3cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage{listings}
\lstset{basicstyle=\ttfamily\footnotesize,breaklines=true,numbers=left,mathescape}
\begin{document}
\begin{lstlisting}
clear all;
clc;
j=1;
if j~=1
fprintf('j not equal to 1\n');
end
\end{lstlisting}
\end{document}
```
Why the tilde symbol in `if j~=1` on the top? How to make it in the center on the line text?
[](https://i.stack.imgur.com/GSxbK.png) | 2021/03/12 | [
"https://tex.stackexchange.com/questions/586984",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/163815/"
] | In fact the solution comes from <https://tex.stackexchange.com/a/130513/231952>, but it is part contained in a comment, so I thought it appropriate to summarize it here. (Other solutions here: [How to insert a nice tilde in a lstlisting?](https://tex.stackexchange.com/questions/17266/how-to-insert-a-nice-tilde-in-a-lstlisting.))
```
\documentclass{article}
\usepackage[left=3cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage{listings}
\lstset{basicstyle=\ttfamily\footnotesize,breaklines=true,numbers=left,mathescape}
\usepackage{url}
\usepackage{listings}
\lstset{literate={~}{{\raisebox{-.25em}{\textasciitilde}}}{1}}
\begin{document}
\begin{lstlisting}
clear all;
clc;
j=1;
if j~=1
fprintf('j not equal to 1\n');
end
\end{lstlisting}
\end{document}
```
[](https://i.stack.imgur.com/pvfL1.png) | THIS?
```
\documentclass{article}
\usepackage[left=3cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage{listings}
\lstset{basicstyle=\ttfamily\footnotesize,breaklines=true,numbers=left,mathescape}
\usepackage{url}
\usepackage{listings}
\lstset{literate={~}{{\raisebox{-.25em}{\textasciitilde}}}{1}}
\begin{document}
\begin{lstlisting}
clear all;
clc;
j=1;
if j\~=1
fprintf('j not equal to 1\n');
end
\end{lstlisting}
\end{document}
``` |
33,695,850 | Given two strings `str1` and `str2` as input, I need to determine whether `str2` occurs within `str1` or not.
Examples:
* Input #1: `occurs("JavaLadders","Java")`
* Output #1: `true`
* Input #2: `occurs("Problem Panel","Panes")`
* Output #2: `false`
In my function I took 2 Strings. In for loop I am checking each character position whether that character in `str1` matches in `str2`. If it does not match I made `p=0` and `count=0`. If it matches I increment my `count` as well as `p`.
I also checked whether `count` is equal to my `str2.length()`. If it is, I move out of the loop and return `true`, otherwise I return `false`.
```
public boolean occurs(String str1, String str2)
{
int l1=str1.length();
int l2=str2.length();
int p=0;
int count=0;
int j=0;
for(;j<l1;j++)
{
char ch1=str1.charAt(j);
char ch2=str2.charAt(p);
if(ch1==ch2)
{
p++;
count++;
}
else if(count==l2)
{
break;
}
else
{
p=0;
count=0;
}
}
if(l2==count)
return true;
else
return false;
}
```
But this test case fails:
* Input: `occurs('Trisect Institute', 'Trisect')`
* Output: `null`
* Expected output: `true`
What am I doing wrong? | 2015/11/13 | [
"https://Stackoverflow.com/questions/33695850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5294872/"
] | Your `else if(count==l2)` statement is in a wrong place. In your code, this condition does not check when `ch1 == ch2`. The following may help you:
```
public boolean occurs(String str1, String str2) {
int l1=str1.length();
int l2=str2.length();
int p=0;
int count=0;
int j=0;
for(;j<l1;j++) {
char ch1=str1.charAt(j);
char ch2=str2.charAt(p);
if(ch1==ch2) {
p++;
count++;
} else {
p=0;
count=0;
}
if(count==l2) {
break;
}
}
if(l2==count)
return true;
else
return false;
}
``` | There are plenty of things wrong with your code. However, I recommend using one of the built-in string functions that Java provides, like String.indexOf() or String.contains().
* If the first character doesn't match, you return either true or false.
* You don't have a return statement in your method (it shouldn't compile)
* You are checking on char index ranges and incrementing both of them if they are in the same range. This doesn't make sense. What are you trying to accomplish?
* You can use String.toLower() if you are doing a case insensitive match, before you start comparing
* If the first characters are out of range and different, it would skip checking altogether.
* There are no comments which explain what you're trying to attempt
I would at least try and fix some of these and print out the results each iteration of the loop (or use a debugger) to help you. |
25,673,599 | I'm making a calendar with events in Codeigniter, so I want do build a list of this events sorted by month and year.
In database, I have the list of events and I want to retrieve then by the field date, that uses the DATE datatype.
```
if($year != null and $month != null)
{
$this->db->where('date', '?');
}
$events = $this->db->get('agenda')->result();
```
Basically i have a yyyy-mm to compare with a yyyy-mm-dd.
Thank you and sorry for my English. | 2014/09/04 | [
"https://Stackoverflow.com/questions/25673599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3207788/"
] | Assuming that `$this->db->where()` makes a `AND field = value` try this.
```
$this->db->where("DATE_FORMAT(date,'%d')", $month);
$this->db->where("DATE_FORMAT(date,'%Y')", $year );
```
The `DATE_FORMAT()` function is a MYSQL function for manipulating/formating dates so this should equate to
```
WHERE
DATE_FORMAT(date,'%d') = '12'
AND DATE_FORMAT(date,'%Y') = '2014'
```
Or you could use
```
$this->db->where('MONTH(date)', $month);
$this->db->where('YEAR(date)', $year );
``` | That query should solve your problem!
```
SELECT * FROM table_name WHERE data_field_name >='01/10/2000'
```
or
```
SELECT * FROM table_name WHERE data_field_name between '01/01/2009' and '01/01/2010'; //FOR YEAR
```
or
```
SELECT * FROM table_name WHERE data_field_name between '01/01/2009' and '01/02/2009'; //FOR MONTH
``` |
36,722,987 | Im working on webpage that should average values in a given column based on the current year.
Ive got the following code:
```
public function getElecReadings(){
try {
$stmt = $this->dbconn->prepare("SELECT AVG(ElecUsage), DateAdded FROM elec_readings WHERE AccountNumber = '" . $_SESSION['user_session'] . "'");
$stmt->execute();
return $stmt;
} catch (Exception $e) {
}
}
```
As i understand that should select the average from all the values within the `ElecUsage` column. However i was wondering how i can select all the average values from the column based on the current year that were in. I know to get the current year i can do something along the lines of : `<?php echo date("Y"); ?>` which will echo out 2016.
My DateAdded column is stored as a date type. So today would be 2016-04-19. Is there any way to extract the 2016 from the column and apply it to the select statement and then display the averaged value in a textbox on my HTML page?
Thanks | 2016/04/19 | [
"https://Stackoverflow.com/questions/36722987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332088/"
] | You basically answered the question yourself:
```
$year = date("Y");
$year = "$year%";
$stmt = $this->dbconn->prepare("SELECT AVG(ElecUsage), DateAdded FROM
elec_readings WHERE AccountNumber = '" . $_SESSION['user_session'] . "'
AND DateAdded LIKE '$year'");
```
That will extract all the account numbers where the year is 2016-andsomething, which I think is what you want? | **its about your query. You have to select avg from the table where year(date) = 'current\_year'**
so your code could be like this :
```
public function getElecReadings(){
try {
$current_year = date('Y');
$stmt = $this->dbconn->prepare("SELECT AVG(ElecUsage),
DateAdded FROM elec_readings WHERE year(DateAdded) = '$current_year' and AccountNumber = '" .$_SESSION['user_session'] . "'");
$stmt->execute();
return $stmt;
} catch (Exception $e) {
}
}
```
**also you can use another query to extract every average for every year:**
```
SELECT AVG(ElecUsage), year(DateAdded) FROM elec_readings GROUP BY YEAR(DateAdded)
``` |
21,782,893 | I'm using the date filter to render a unix timestamp in a certain format. I've noticed the filter adds the local timezone to the output.
Is there any way to simply output the exact timestamp, without adding any timezone information?
Input:
```
talk.content.date_and_time = 1400167800
```
(is 05 / 15 / 14 @ 3:30:00pm UTC)
Code:
```
{{talk.content.date_and_time*1000 | date:'dd-M-yyyy H:mm Z'}}
```
Output:
```
15-5-2014 17:30 +0200
```
How can I make the output 15:30 instead of 17:30? | 2014/02/14 | [
"https://Stackoverflow.com/questions/21782893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453746/"
] | Since version `1.3.0` AngularJS introduced extra filter parameter `timezone`, like following:
```
{{ date_expression | date : format : timezone}}
```
But in versions `1.3.x` only supported timezone is `UTC`, which can be used as following:
```
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}
```
Since version `1.4.0-rc.0` AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):
```
{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}
```
[Here](https://docs.angularjs.org/api/ng/filter/date) you can find documentation of AngularJS date filters.
**NOTE:** this is working only with Angular 1.x
Here's [working example](https://plnkr.co/edit/Yy4yPL2RMyFcCZlCasGa?p=preview) | The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward [moment.js](http://momentjs.com/).
Borrowing from this [answer](https://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc#answer-6777470), you could do something like this without moment.js:
**controller**
```
var app1 = angular.module('app1',[]);
app1.controller('ctrl',['$scope',function($scope){
var toUTCDate = function(date){
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return _utc;
};
var millisToUTCDate = function(millis){
return toUTCDate(new Date(millis));
};
$scope.toUTCDate = toUTCDate;
$scope.millisToUTCDate = millisToUTCDate;
}]);
```
**template**
```
<html ng-app="app1">
<head>
<script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ctrl">
<div>
utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
</div>
<div>
local {{1400167800 | date:'dd-M-yyyy H:mm'}}
</div>
</div>
</body>
</html>
```
here's [plunker](http://plnkr.co/edit/eLwnLZReCy8HXtJyO84q?p=preview) to play with it
See also [this](https://stackoverflow.com/questions/20662140/using-angularjs-date-filter-with-utc-date?lq=1) and [this](https://stackoverflow.com/questions/20470139/angularjs-timestamp-to-formatted-utc-time-with-date-helper).
Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset. |
3,700,113 | In the past, I've only developed Java applications. This is my first time attempting an actual web app on my own, so pardon the painfully rookie question.
Should I add the **WEB-INF/web.xml** file to version control? It appears to be a generated file, so my instinct is to add it to the ignore list, but I thought I'd ask and make sure.
Thanks! | 2010/09/13 | [
"https://Stackoverflow.com/questions/3700113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164958/"
] | Generally, `web.xml` should be under version control. And it is not usually generated.
If you are using some "clever" utility to generate the web.xml, then don't put it in version control. But:
* your build process should include the generation as well - your app won't run without this file
* I'd advise against web.xml generation. At minimum there should be a template web.xml to which the generator appends. | it should be. it is where you do configure your web application. |
1,319,129 | i have tried to open some JPEG files in Delphi with TImage component. i also added the Jpeg unit. i can open most of jpg files and there is no problem.
but when i try to open some JPGs, the program just throw an exception.
i also tried to load that images in design mode, but there is some problem. in design mode the exception is:
*Access violation at address 402672A1 in module 'vcljpeg70.bpl'. Write of address 08E84000*
Why i cannot open that JPGs? they are not corrupted. i checked them in some tools like savantools EXIF viewer.
here is the URL of one of that images:
<http://xs842.xs.to/xs842/09340/backpic435.jpg>
Thanks so much
PS:
My Delphi version is 7. Borland Delphi 7 | 2009/08/23 | [
"https://Stackoverflow.com/questions/1319129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161640/"
] | The reason you may be encountering this problem is due to the file type. Delphi has issues displaying JPEG images that have been encoded using CMYK, rather than the default RGB encoding. CMYK is a format that is generally used for Print design, try and always encode your images to RGB format to avoid this issue with Delphi.
Patch for [Delphi jpeg.dcu](http://cc.embarcadero.com/item/19723)
Bye. | Check out the Free Image library for alternative JPEG support in Delphi if the native one has problems. Free Image is an open source lib that lets you work with JPEG/PNG/... from Delphi/BCB/and others. Very nice library IMHO.
<http://freeimage.sourceforge.net/> |
592,378 | I am working on a project where I need to drive two LEDs on a PCB (= PCB\_LED) which is 1 meter away from another PCB (= PCB\_MCU).
The PCB\_MCU includes a microcontroller with two LED drivers. Each LED driver is a constant current buck driver. Its output current depends on what the MCU asks it to output. The LED driver simply applies a PWM onto the cathode of the LED.
More info:
* The PWM is around 2 kHz
* The LED have a threshold voltage of approx. 3 V
* I would need 3 wires into the cable: 1 PWM for each LED and common VCC
I have several questions:
* Will it work?
* If so, is it EMC compliant?
* If no, it means that I need differential wires into the cable?
Do you think using an RS485 transceiver in both ends is enough? I have already done this to communicate between a master and some slaves but they were communicating using UARTs, it was not simple PWM.
Thanks :) | 2021/10/27 | [
"https://electronics.stackexchange.com/questions/592378",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/294827/"
] | **This is supposed to be a comment but got too long, so I decided to put as an answer.**
What I understood is, you have two PCBs, one having only the LEDs and the other having the MCU and the respective LED drivers for LEDs. So the LED drivers' outputs go to LEDs through a 1-m-long cable. *It is more preferable to see a diagram and schematic (if possible)*.
This cannot be simplified as "sending PWM signal through a 1-m cable", because there are switching currents flowing through the cables. *You should also indicate the maximum peak value of these currents in your question's body.*
A 1-m long cable can be a good quarter-wave monopole antenna for 75 MHz. Depending on the rise time of the PWM signal, the PWM signal will probably contain 75-MHz harmonics and these harmonics will be radiated. The amplitude of the radiation depends on the rise time and the peak value of the switched currents *(Switching 10 A current with 75 kHz PWM with very low duty cycle may be enough to disturb your radio from 1 meter of distance)*. Plus, any 75 MHz signals picked up by the cable may or may not disturb the drivers' performances. It's hard to say something about radiated immunity performance without knowing what brand/model/type LED drivers will you use.
Maybe you should move the buck converters and LEDs to PCB\_LED, and send low-voltage low-current PWM control signals from PCB\_MCU through buffers/low-impedance drivers. | Instead of a common VCC wire, consider a separate VCC for each LED. In this case the return current in each VCC wire will exactly match the current in its associated PWM wire, but in the opposite direction of course. Now the EMI can be greatly reduced by using twisted pairs of wire. Cat5 or Cat6 communication cable is inexpensive.
The truth is, simply twisting all three wires with a common VCC will likely help reduce EMI. |
56,427,934 | For app development I download and installed Flutter sdk along with its dependencies Android studio, Java. After installing all I came to an error
for checking `flutter doctor`. The following error came:
```
Android toolchain - develop for Android devices (Android SDK version 28.0.3)
X Android license status unknown.
Try re-installing or updating your Android SDK Manager.
See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.
```
Then after searching with the help of [Flutter Android license status unknown](https://stackoverflow.com/questions/55143752/flutter-android-license-status-unknown) I tried to update Android SDK with `PathToAndroidSDK --update` It again generates following error:
```
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 5 more
``` | 2019/06/03 | [
"https://Stackoverflow.com/questions/56427934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11593251/"
] | My first choice would be a `std::variant` (it is better then `std::optional` since it can provide extra information in case of error and this is always beneficial in the future):
```
usign ErrorType = int;
using ReturnType = std::variant<std::vector<int>, ErrorType>
ReturnType function() {
std::vector ans;
//do stuff
if (something happens)
return -1;
return ans;
}
```
If your error is quite rare and exception could be cough in deeper caller level then exception is also a good/better way:
```
class MyException : public std::exception {
public:
MyException(int errorCode) : exception("MyException"), errorCode(errorCode)
{}
int code() const { return errorCode; }
private:
int errorCode;
};
std::vector<int> function() {
std::vector ans;
//do stuff
if (something happens)
throw MyException{ -1 };
return ans;
}
```
Please remember that in C++ exceptions are design in such way that they are zero cost when nothing is thrown. Trade of is that when something exception is thrown unwinding a stack is extremely slow (on some cpp-con someone said that it is x40 slower, I didn't measure it). This is the reason use of `std::optional` or `std::variant` instead of exception can be so beneficial.
AFAIK standard comity is working on [new kind of exceptions](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf) mechanism which will behave like `std::variant` (similar how this is made in Swift). | You can use `std::optional` for it. |
1,949,592 | I have a query like the following:
```
SELECT t1.v3, t2.v2
FROM t1
INNER JOIN t2
ON t1.v1 = t2.v1
WHERE ISNULL(t1.DeleteFlag,'N') = 'N'
```
I have an index in place that I think should result in there being an Index Seek for the `= 'N'` part but instead I am seeing a very expensive Index Scan. Is it possible that the ISNULL is messing up the correct use of indexes? Does it even make sense to have an index on a column that will only have a few possible values (like `DeleteFlag` will)? | 2009/12/22 | [
"https://Stackoverflow.com/questions/1949592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226897/"
] | Yes, any function calls in your WHERE clause will likely make the index useless. Try to rewrite it so that the index can be used:
```
SELECT t1.v3, t2.v2
FROM t1
INNER JOIN t2
ON t1.v1 = t2.v1
WHERE NOT t1.DeleteFlag = 'Y'
```
The index makes sense if the number of results you expect from the query is much smaller than the total number of rows in the table. | 1) Does use of ISNULL turn a Seek into a Scan? Yes. Applying a function to a column in general makes the expression non SARG-able (not searchable). In order for an index to be considered for a Seek operation the engine needs to know what value to seek for, as a raw binary value. As soon as you apply a function to the column you are asking to search for the *result* of the function, so it has to evaluate the function on every row to see if the result happens to satisfy the condition.
2) Does it make sense to have an index on a column with very low selectivity (2-3 values)? Yes, but never as a standalone index expression. The index [tipping point](http://www.sqlskills.com/BLOGS/KIMBERLY/post/The-Tipping-Point-Query-Answers.aspx) will make a standalone index on a low selectivity column just a waste of space. But very low selectivity columns like bits and flags are very usefull as leftmost keys in an index, when composed with more keys. In your case, given that is deleted flag, it would make sense to be the first key of the clustered index since is expected that *every* query will specify the 'IsDeleted' condition.
I would also add that you should probably not have NULLs on a 'deleted' flag. |
73,220,323 | I want to extract two pieces of information from a list of filenames using regex.
The two numbers are always located just before the file extension and separated by a dash.
In the example filename below, I would aim for 10 and 11.
To get the digit just before the extension (so 11 in the example), I am using `\d+(?=.raw)` and it seems to work.
However, I struggle to get something similar for the number before (so 10 in this example).
```
D:\CDTFlatten02\20210730-HK-S-006-PLATE-flatten-sliced\20210730-HK-S-006-PLATE-flatten-10-11.raw\
```
The expression is to be used to create a new column in a pandas dataframe in the following way: `df['y'] = df['Filename'].apply(lambda x: re.findall('\d+(?=.raw)', x)[0])` | 2022/08/03 | [
"https://Stackoverflow.com/questions/73220323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12296100/"
] | The current latest version of `hiredis` 2.0 [provides](https://pypi.org/project/hiredis/2.0.0/#files) wheels for Python 3.6-3.9 but not 3.10 or later. Use lower version of Python.
Or install Microsoft Visual C++ 14.0 to compile C/C++ extensions. | The current version of redis does not support Python 3.10
Try using lower versions of python |
177,980 | My supervisor started the e-mail thread of welcoming me to the team/department. Several team members has already replied (including the boss of my supervisor so I'm extra nervous) with a brief but warm welcome message. I was wondering what is the best way to reply in this thread.
This is my first fully remote role so I am not that familiar with how it works yet.
Would a short reply like "Thanks for the warm welcome, I'm excited to be working with everyone and I'm looking forward meeting you in the upcoming weeks." or Should I be adding my professional background/main tasks of my role/hobbies/etc. ? | 2021/08/30 | [
"https://workplace.stackexchange.com/questions/177980",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/129196/"
] | >
> Would a short reply like "Thanks for the warm welcome, I'm excited to be working with everyone and I'm looking forward meeting you in the upcoming weeks."
>
>
>
Yes
>
> Should I be adding my professional background/main tasks of my role/hobbies/etc. ?
>
>
>
No.
That type of detail is "need/reason to know" and not for general consumption. Talk about your hobbies in a socially appropriate context (lunch, water cooler, etc) and talk about your professional background/role with the people you work with directly and only when this is actually relevant to the current topic. | >
> "Thanks for the warm welcome, I'm excited to be working with everyone and I'm looking forward meeting you in the upcoming weeks."
>
>
>
Your suggested reply is perfect. Stop fretting. |
1,692,206 | For brushing up my C, I'm writing some useful library code. When it came to reading text files, it's always useful to have a convenient tokenization function that does most of the heavy lifting (looping on `strtok` is inconvenient and dangerous).
When I wrote this function, I'm amazed at its intricacy. To tell the truth, I'm almost convinced that it contains bugs (especially with memory leaks in case of an allocation error). Here's the code:
```
/* Given an input string and separators, returns an array of
** tokens. Each token is a dynamically allocated, NUL-terminated
** string. The last element of the array is a sentinel NULL
** pointer. The returned array (and all the strings in it) must
** be deallocated by the caller.
**
** In case of errors, NULL is returned.
**
** This function is much slower than a naive in-line tokenization,
** since it copies the input string and does many allocations.
** However, it's much more convenient to use.
*/
char** tokenize(const char* input, const char* sep)
{
/* strtok ruins its input string, so we'll work on a copy
*/
char* dup;
/* This is the array filled with tokens and returned
*/
char** toks = 0;
/* Current token
*/
char* cur_tok;
/* Size of the 'toks' array. Starts low and is doubled when
** exhausted.
*/
size_t size = 2;
/* 'ntok' points to the next free element of the 'toks' array
*/
size_t ntok = 0;
size_t i;
if (!(dup = strdup(input)))
return NULL;
if (!(toks = malloc(size * sizeof(*toks))))
goto cleanup_exit;
cur_tok = strtok(dup, sep);
/* While we have more tokens to process...
*/
while (cur_tok)
{
/* We should still have 2 empty elements in the array,
** one for this token and one for the sentinel.
*/
if (ntok > size - 2)
{
char** newtoks;
size *= 2;
newtoks = realloc(toks, size * sizeof(*toks));
if (!newtoks)
goto cleanup_exit;
toks = newtoks;
}
/* Now the array is definitely large enough, so we just
** copy the new token into it.
*/
toks[ntok] = strdup(cur_tok);
if (!toks[ntok])
goto cleanup_exit;
ntok++;
cur_tok = strtok(0, sep);
}
free(dup);
toks[ntok] = 0;
return toks;
cleanup_exit:
free(dup);
for (i = 0; i < ntok; ++i)
free(toks[i]);
free(toks);
return NULL;
}
```
And here's simple usage:
```
int main()
{
char line[] = "The quick brown fox jumps over the lazy dog";
char** toks = tokenize(line, " \t");
int i;
for (i = 0; toks[i]; ++i)
printf("%s\n", toks[i]);
/* Deallocate
*/
for (i = 0; toks[i]; ++i)
free(toks[i]);
free(toks);
return 0;
}
```
Oh, and `strdup`:
```
/* strdup isn't ANSI C, so here's one...
*/
char* strdup(const char* str)
{
size_t len = strlen(str) + 1;
char* dup = malloc(len);
if (dup)
memcpy(dup, str, len);
return dup;
}
```
A few things to note about the code of the `tokenize` function:
1. `strtok` has the impolite habit of writing over its input string. To save the user's data, I only call it on a duplicate of the input. The duplicate is obtained using `strdup`.
2. `strdup` isn't ANSI-C, however, so I had to write one
3. The `toks` array is grown dynamically with `realloc`, since we have no idea in advance how many tokens there will be. The initial size is 2 just for testing, in real-life code I would probably set it to a much higher value. It's also returned to the user, and the user has to deallocate it after use.
4. In all cases, extreme care is taken not to leak resources. For example, if `realloc` returns NULL, it won't run over the old pointer. The old pointer will be released and the function returns. No resources leak when `tokenize` returns (except in the nominal case where the array returned to the user must be deallocated after use).
5. A `goto` is used for more convenient cleanup code, according to the [philosophy](http://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c/) that `goto` can be good in some cases (this is a good example, IMHO).
The following function can help with simple deallocation in a single call:
```
/* Given a pointer to the tokens array returned by 'tokenize',
** frees the array and sets it to point to NULL.
*/
void tokenize_free(char*** toks)
{
if (toks && *toks)
{
int i;
for (i = 0; (*toks)[i]; ++i)
free((*toks)[i]);
free(*toks);
*toks = 0;
}
}
```
I'd really like to discuss this code with other users of SO. What could've been done better? Would you recommend a difference interface to such a tokenizer? How is the burden of deallocation taken from the user? Are there memory leaks in the code anyway?
Thanks in advance | 2009/11/07 | [
"https://Stackoverflow.com/questions/1692206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] | You don't need to strdup() each token; you duplicate the input string, and could let strtok() chop that up. It simplifies releasing the resources afterwards, too - you only have to release the array of pointers and the single string.
I agree with those who say that you need a function to release the data - unless you change the interface radically and have the user provide the array of pointers as an input parameter, and then you would probably also decide that the user is responsible for duplicating the string if it must be preserved. That leads to an interface:
```
int tokenize(char *source, const char *sep, char **tokens, size_t max_tokens);
```
The return value would be the number of tokens found.
You have to decide what to do when there are more tokens than slots in the array. Options include:
* returning an error indication (negative number, likely -1), or
* the full number of tokens found but the pointers that can't be assigned aren't, or
* just the number of tokens that fitted, or
* one more than the number of tokens, indicating that there were more, but no information on exactly how many more.
I chose to return '-1', and it lead to this code:
```
/*
@(#)File: $RCSfile: tokenise.c,v $
@(#)Version: $Revision: 1.9 $
@(#)Last changed: $Date: 2008/02/11 08:44:50 $
@(#)Purpose: Tokenise a string
@(#)Author: J Leffler
@(#)Copyright: (C) JLSS 1987,1989,1991,1997-98,2005,2008
@(#)Product: :PRODUCT:
*/
/*TABSTOP=4*/
/*
** 1. A token is 0 or more characters followed by a terminator or separator.
** The terminator is ASCII NUL '\0'. The separators are user-defined.
** 2. A leading separator is preceded by a zero-length token.
** A trailing separator is followed by a zero-length token.
** 3. The number of tokens found is returned.
** The list of token pointers is terminated by a NULL pointer.
** 4. The routine returns 0 if the arguments are invalid.
** It returns -1 if too many tokens were found.
*/
#include "jlss.h"
#include <string.h>
#define NO 0
#define YES 1
#define IS_SEPARATOR(c,s,n) (((c) == *(s)) || ((n) > 1 && strchr((s),(c))))
#define DIM(x) (sizeof(x)/sizeof(*(x)))
#ifndef lint
/* Prevent over-aggressive optimizers from eliminating ID string */
const char jlss_id_tokenise_c[] = "@(#)$Id: tokenise.c,v 1.9 2008/02/11 08:44:50 jleffler Exp $";
#endif /* lint */
int tokenise(
char *str, /* InOut: String to be tokenised */
char *sep, /* In: Token separators */
char **token, /* Out: Pointers to tokens */
int maxtok, /* In: Maximum number of tokens */
int nulls) /* In: Are multiple separators OK? */
{
int c;
int n_tokens;
int tokenfound;
int n_sep = strlen(sep);
if (n_sep <= 0 || maxtok <= 2)
return(0);
n_tokens = 1;
*token++ = str;
while ((c = *str++) != '\0')
{
tokenfound = NO;
while (c != '\0' && IS_SEPARATOR(c, sep, n_sep))
{
tokenfound = YES;
*(str - 1) = '\0';
if (nulls)
break;
c = *str++;
}
if (tokenfound)
{
if (++n_tokens >= maxtok - 1)
return(-1);
if (nulls)
*token++ = str;
else
*token++ = str - 1;
}
if (c == '\0')
break;
}
*token++ = 0;
return(n_tokens);
}
#ifdef TEST
struct
{
char *sep;
int nulls;
} data[] =
{
{ "/.", 0 },
{ "/.", 1 },
{ "/", 0 },
{ "/", 1 },
{ ".", 0 },
{ ".", 1 },
{ "", 0 }
};
static char string[] = "/fred//bill.c/joe.b/";
int main(void)
{
int i;
int j;
int n;
char input[100];
char *token[20];
for (i = 0; i < DIM(data); i++)
{
strcpy(input, string);
printf("\n\nTokenising <<%s>> using <<%s>>, null %d\n",
input, data[i].sep, data[i].nulls);
n = tokenise(input, data[i].sep, token, DIM(token),
data[i].nulls);
printf("Return value = %d\n", n);
for (j = 0; j < n; j++)
printf("Token %d: <<%s>>\n", j, token[j]);
if (n > 0)
printf("Token %d: 0x%08lX\n", n, (unsigned long)token[n]);
}
return(0);
}
#endif /* TEST */
``` | Just a few things:
1. Using gotos is not intrinsically evil or bad, much like the preprocessor, they are often abused. In cases like yours where you have to exit a function differently depending on how things went, they are appropriate.
2. Provide a functional means of freeing the returned array. I.e. tok\_free(pointer).
3. Use the re-entrant version of strtok() initially, i.e. strtok\_r(). It would not be cumbersome for someone to pass an additional argument (even NULL if not needed) for that. |
7,340 | I sync email, contacts and calendar to my company's Exchange server. This morning all of my contacts are gone from my iPhone (iPhone 4, iOS 4.2.1). Facts that further explain:
* My contacts were good last night
* I haven't synched to my computer, updated any apps or changed any settings since then
* I'm getting email and my calendar entries are all good.
* I see all my contacts when I log into the web mail interface to the Exchange server
Is there a way to tell the iPhone to wise up and realize that it has screwed up its contacts? | 2011/01/30 | [
"https://apple.stackexchange.com/questions/7340",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/283/"
] | Maybe you've already tried this but I'll suggest it anyway.
Check Groups
------------
1. Open Contacts
2. Tap the arrow in the upper-left corner labelled Groups if it exists.
3. Ensure you have selected the right group of contacts.
Try Re-Sync
-----------
If you need to re-sync because the above did not work you could try this:
1. Open the Settings app
2. Open Accounts & Passwords (or the Mail section on older iOS).
3. Select the account causing problems. (Usually called Exchange.)
4. Turn Contacts off and tap ‘Delete From My iPhone’ when prompted.
5. Turn Contacts back on and tap ‘Sync’ when prompted. | Above trick worked perfectly for my iPhone 5S. Thank you very much. After my new carrier asked me to reset ALL on my phone, I had lost everything, Google contacts, emails, etc.
If you need to re-sync because the above did not work you could try this:
Open the Settings app
Open the Mail settings. (This is listed as Mail, Contacts, Calendars on older iPhones.)
Select the account causing problems. (Usually called Exchange.)
Turn Contacts off and tap Delete From My iPhone when prompted.
Turn Contacts back on and tap Sync when prompted. |
38,376,015 | So im trying to figure out if I can pass a intent extra from a custom adapter to an activity which then passes that intent extra to another activity?
Is something like that possible or is there a better way to do what I want to do? | 2016/07/14 | [
"https://Stackoverflow.com/questions/38376015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418948/"
] | ```
Activity A:
Intent intent = new Intent(A.this, B.class);
intent.putExtra("someString", "string");
startActivity(intent):
Activity B:
onCreate(...) {
String myString = getIntent().getStringExtra("someString");
MyAdapter myAdapter = new MyAdapter(B.this, myString);
}
MyAdapter :
Context myContext;
String myString;
MyAdapter(Context context, String string) {
this.myContext = context;
this.myString = string
}
```
Now you have the String from activity A into your adapter :) | I assume, that you know how to send intent extras to an activity. And what you are looking for is a way to forward that same intent to another activity. You can do it like this:
```
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtras(getIntent());
``` |
53,608,819 | I just updated my android studio to version 3.2.1 and also updated my gradle via android studio to latest version, but building project faces this error:
>
> Android resource compilation failed Output:
> D:\projects\myProject\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:2577:
> error: inner element must either be a resource reference or
> empty.
> D:\projects\myProject\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:2585:
> error: inner element must either be a resource reference or
> empty.
>
>
> Command:
> C:\Users\Hamed.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\ea639d8248f3ebb66b449dfd3b6a9a07\aapt2-3.2.1-4818971-windows\aapt2.exe
> compile --legacy \
> -o \
> D:\projects\myProject\app\build\intermediates\res\merged\debug \
> D:\projects\myProject\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
> Daemon: AAPT2 aapt2-3.2.1-4818971-windows Daemon #0
>
>
>
and In the line it says there is an error, this code exists:
>
>
> ```
> <item name="googledefaultpass" type="id">123456789</item>
>
> ```
>
>
What is wrong? As I searched the solution is [this](https://stackoverflow.com/a/52077501/9850245), but the structure is the same.
I have updated all my libraries.
app level gradle:
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '28.0.3'
defaultConfig {
applicationId "com.my.project"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "0.7"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [onesignal_app_id : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: "REMOTE"]
}
applicationVariants.all { variant ->
variant.resValue "string", "versionName", variant.versionName
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
jcenter()
}
dependencies {
implementation 'com.android.support:recyclerview-v7:27.1.1'
// implementation 'com.google.firebase:firebase-core:16.0.1'
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
// compile 'im.crisp:crisp-sdk:0.1.10'
implementation 'com.getkeepsafe.taptargetview:taptargetview:1.11.0'
implementation 'com.stephentuso:welcome:1.4.1'
implementation 'co.ronash.android:pushe-base:1.4.0'
implementation 'com.google.android.gms:play-services-gcm:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:customtabs:27.1.1'
// compile 'com.google.firebase:firebase-auth:16.0.2'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.code.gson:gson:2.8.2'
implementation('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
implementation 'com.android.volley:volley:1.1.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '28.+'
}
}
}
}
apply plugin: 'com.google.gms.google-services'
```
project level gradle:
```
repositories {
google()
maven { url 'https://maven.google.com' }
jcenter()
mavenCentral()
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.0.1'
}
}
allprojects {
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
---
**update**:
I invalidated cache and restarted Android studio, the problem solved, but I faced the following error:
```
> Could not find org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71.
> Searched in the following locations:
> https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.2.71/kotlin-stdlib-jdk8-1.2.71.pom
> https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.2.71/kotlin-stdlib-jdk8-1.2.71.jar
> https://maven.google.com/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.2.71/kotlin-stdlib-jdk8-1.2.71.pom
> https://maven.google.com/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.2.71/kotlin-stdlib-jdk8-1.2.71.jar
> Required by:
> project : > com.android.tools.build:gradle:3.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.build:builder:3.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.lint:lint-gradle-api:26.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.build:gradle-api:3.2.1
> project : > com.android.tools.build:gradle:3.2.1 > androidx.databinding:databinding-compiler-common:3.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.build:builder:3.2.1 >
> com.android.tools:sdk-common:26.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.build:builder:3.2.1 >
> com.android.tools:common:26.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.build:builder:3.2.1 >
> com.android.tools.build:manifest-merger:26.2.1
> project : > com.android.tools.build:gradle:3.2.1 > com.android.tools.build:builder:3.2.1 >
> com.android.tools:sdklib:26.2.1 > com.android.tools:repository:26.2.1
```
The point is that I am not using Kotlin at all. I added `classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71"` to gradle dependencies but the same error raises. I searched `Kotlin` in whole project, but there was nothing but some `replay_pid1632.log` files.
tnx | 2018/12/04 | [
"https://Stackoverflow.com/questions/53608819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9850245/"
] | In my case the problem was that I forgot to escape an apostrophe sign within an item of a `StringArray`.
So in my `strings.xml` I changed
```
<string-array name="questions">
<item>What's the weather today?</item>
</string-array>
```
to
```
<string-array name="questions">
<item>What\'s the weather today?</item>
</string-array>
```
And now it builds perfectly fine. | Try to add
```
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71'
```
inside project level gradle dependencies, and then add
```
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.71'
```
inside your app level gradle.
Maybe one of your libraries require kotlin plugin. |
29,923,370 | I have an issue with the following hierarchy in scala:
```
class ScalaGenericTest {
def getValue[A, B <: Abstract[A]](clazz: B): A = clazz.a
def call: String = {
val sub: Subclass = new Subclass
getValue(sub)
}
}
class Subclass extends Abstract[String] {
def a: String = "STRING"
}
abstract class Abstract[A] {
def a: A
}
```
The compiler doesn't seem to be able to bind the generic parameter A in the call to the getValue function -- I think it should be able to infer this from the definition of Subclass. The compile error is as follows:
>
> inferred type arguments [Nothing,Subclass] do not conform to method getValue's type parameter bounds [A,B <: Abstract[A]]
>
>
>
It works if I explicitly pass the generic type arguments to the method, i.e. `getValue[String,Subclass](sub)` but surely the compiler should be able to infer this?
The same hierarchy works fine in Java:
```
public class JavaGenericTest {
public <T,U extends Abstract<T>> T getValue(U subclass) {
return subclass.getT();
}
public String call(){
Subclass sub = new Subclass();
return getValue(sub);
}
private static class Subclass extends Abstract<String> {
String getT(){
return "STRING";
}
}
private static abstract class Abstract<T> {
abstract T getT();
}
}
```
I'm pretty new to Scala so there's probably some subtlety that I'm missing.
Thanks in advance for any help! | 2015/04/28 | [
"https://Stackoverflow.com/questions/29923370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4842531/"
] | It's a limitation in Scala's type inference. The issue is described in [SI-2272](https://issues.scala-lang.org/browse/SI-2272) (the example there uses implicits, but the same error occurs when using it explicitly). It's been closed as **won't fix**.
In that issue, Adriaan Moors advises to avoid constraints that have type variables on both sides. ie. `B <: Abstract[A]`. An easy work-around would be to avoid the second type parameter altogether.
```
def getValue[A](clazz: Abstract[A]): A = clazz.a
scala> val sub = new Subclass
sub: Subclass = Subclass@585cbda6
scala> getValue(sub)
res11: String = STRING
```
Additionally, Adriaan also provided a way of using an implicit `<:<` as another work around. To put it in the context of your example, it would look like:
```
def getValue[A, B](b: B)(implicit ev: B <:< Abstract[A]): B = b.a
```
Where an instance of `<:<` is provided implicitly through [Predef](http://www.scala-lang.org/api/current/index.html#scala.Predef$$$less$colon$less). | As addition to Justin's and m-z's answers, another way to make similar declaration keeping two type parameters:
```
def getValue[A, B](clazz: B)(implicit evidence: B <:< Abstract[A]): A = clazz.a
``` |
24,214,224 | Using STS, if I import the `"Rest Service"` Getting Started project using the latest Spring Boot and choose `"Run As Spring Boot App"`, it starts up, then immediately shuts down.
Looking at the debug logs, Spring is for some reason deciding the project is not a web application, but I have no idea why.
If I switch from Spring Boot `1.1.1.RELEASE` to `1.0.1.RELEASE`, the project works as expected and the default Tomcat embedded server is found.
I can't find anything in the `1.1.1` release notes that suggests there is a config change or anything?
**UPDATE: Steps to reproduce and log output**
I'm running STS 3.6.0.M1 and Spring 4.0.5 and Spring Boot 1.1.1. I can easily reproduce this by doing the following:
1. Import the REST Service Getting started app.
2. Select "Run as Spring Boot Project"
3. This is the output:
```
:: Spring Boot :: (v1.1.1.RELEASE)
2014-06-14 11:08:34.226 INFO 47728 --- [ main] hello.Application : Starting Application on localhost with PID 47728 (/Users/pdrummond/src/sts/gs-rest-service-complete/target/classes started by pdrummond in /Users/pdrummond/src/sts/gs-rest-service-complete)
2014-06-14 11:08:34.257 INFO 47728 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@802b249: startup date [Sat Jun 14 11:08:34 BST 2014]; root of context hierarchy
2014-06-14 11:08:34.680 INFO 47728 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-06-14 11:08:34.908 INFO 47728 --- [ main] hello.Application : Started Application in 0.917 seconds (JVM running for 1.351)
2014-06-14 11:08:36.397 INFO 47728 --- [ Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@802b249: startup date [Sat Jun 14 11:08:34 BST 2014]; root of context hierarchy
2014-06-14 11:08:36.398 INFO 47728 --- [ Thread-3] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
```
4. If I edit the pom and change the `spring-boot-starter-parent` to `1.0.1.RELEASE` it boots as expected.
**UPDATE 2: Added output from --debug command**
```
:: Spring Boot :: (v1.1.1.RELEASE)
2014-06-14 19:29:03.814 INFO 986 --- [ main] hello.Application : Starting Application on localhost with PID 986 (/Users/pdrummond/src/sts/gs-rest-service-complete/target/classes started by pdrummond in /Users/pdrummond/src/sts/gs-rest-service-complete)
2014-06-14 19:29:03.816 DEBUG 986 --- [ main] o.s.boot.SpringApplication : Loading source class hello.Application
2014-06-14 19:29:03.838 INFO 986 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@c163956: startup date [Sat Jun 14 19:29:03 BST 2014]; root of context hierarchy
2014-06-14 19:29:04.177 INFO 986 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-06-14 19:29:04.346 DEBUG 986 --- [ main] utoConfigurationReportLoggingInitializer :
=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches:
-----------------
PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
- @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)
JacksonAutoConfiguration
- @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)
JacksonAutoConfiguration#jacksonObjectMapper
- @ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found no beans (OnBeanCondition)
JmxAutoConfiguration
- @ConditionalOnClass classes found: org.springframework.jmx.export.MBeanExporter (OnClassCondition)
- SpEL expression on org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration: ${spring.jmx.enabled:true} (OnExpressionCondition)
JmxAutoConfiguration#mbeanServer
- @ConditionalOnMissingBean (types: javax.management.MBeanServer; SearchStrategy: all) found no beans (OnBeanCondition)
JmxAutoConfiguration#objectNamingStrategy
- @ConditionalOnMissingBean (types: org.springframework.jmx.export.naming.ObjectNamingStrategy; SearchStrategy: all) found no beans (OnBeanCondition)
HttpMessageConvertersAutoConfiguration
- @ConditionalOnClass classes found: org.springframework.http.converter.HttpMessageConverter (OnClassCondition)
HttpMessageConvertersAutoConfiguration#messageConverters
- @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.HttpMessageConverters; SearchStrategy: all) found no beans (OnBeanCondition)
HttpMessageConvertersAutoConfiguration.ObjectMappers
- @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)
HttpMessageConvertersAutoConfiguration.ObjectMappers#mappingJackson2HttpMessageConverter
- @ConditionalOnMissingBean (types: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; SearchStrategy: all) found no beans (OnBeanCondition)
Negative matches:
-----------------
MessageSourceAutoConfiguration
- Bundle found for spring.messages.basename: messages (MessageSourceAutoConfiguration.ResourceBundleCondition)
RabbitAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)
AopAutoConfiguration
- required @ConditionalOnClass classes not found: org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
BatchAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher,org.springframework.jdbc.core.JdbcOperations (OnClassCondition)
ElasticsearchRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.repository.ElasticsearchRepository (OnClassCondition)
JpaRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)
MongoRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)
RepositoryRestMvcAutoConfiguration
- not a web application (OnWebApplicationCondition)
SolrRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: org.apache.solr.client.solrj.SolrServer,org.springframework.data.solr.repository.SolrRepository (OnClassCondition)
ElasticsearchAutoConfiguration
- required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.client.TransportClientFactoryBean,org.springframework.data.elasticsearch.client.NodeClientFactoryBean (OnClassCondition)
ElasticsearchDataAutoConfiguration
- required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.core.ElasticsearchTemplate (OnClassCondition)
FlywayAutoConfiguration
- required @ConditionalOnClass classes not found: org.flywaydb.core.Flyway (OnClassCondition)
FreeMarkerAutoConfiguration
- required @ConditionalOnClass classes not found: freemarker.template.Configuration,org.springframework.ui.freemarker.FreeMarkerConfigurationFactory (OnClassCondition)
GroovyTemplateAutoConfiguration
- required @ConditionalOnClass classes not found: groovy.text.TemplateEngine (OnClassCondition)
HypermediaAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.hateoas.Resource (OnClassCondition)
IntegrationAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.integration.config.EnableIntegration (OnClassCondition)
JacksonAutoConfiguration.JodaModuleAutoConfiguration
- required @ConditionalOnClass classes not found: com.fasterxml.jackson.datatype.joda.JodaModule (OnClassCondition)
JacksonAutoConfiguration.Jsr310ModuleAutoConfiguration
- Required JVM version 1.8 or newer found 1.6 (OnJavaCondition)
DataSourceAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
DataSourceTransactionManagerAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
JmsAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate (OnClassCondition)
ActiveMQAutoConfiguration
- required @ConditionalOnClass classes not found: javax.jms.ConnectionFactory,org.apache.activemq.ActiveMQConnectionFactory (OnClassCondition)
HornetQAutoConfiguration
- required @ConditionalOnClass classes not found: javax.jms.ConnectionFactory,org.hornetq.api.jms.HornetQJMSClient (OnClassCondition)
JmxAutoConfiguration#mbeanExporter
- @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: current) found the following [mbeanExporter] (OnBeanCondition)
LiquibaseAutoConfiguration
- required @ConditionalOnClass classes not found: liquibase.integration.spring.SpringLiquibase (OnClassCondition)
DeviceDelegatingViewResolverAutoConfiguration
- not a web application (OnWebApplicationCondition)
DeviceResolverAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)
SitePreferenceAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor,org.springframework.mobile.device.site.SitePreferenceHandlerMethodArgumentResolver (OnClassCondition)
MongoAutoConfiguration
- required @ConditionalOnClass classes not found: com.mongodb.Mongo (OnClassCondition)
MongoDataAutoConfiguration
- required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.core.MongoTemplate (OnClassCondition)
HibernateJpaAutoConfiguration
- did not find HibernateEntityManager class (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)
ReactorAutoConfiguration
- required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)
RedisAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.data.redis.connection.jedis.JedisConnection,org.springframework.data.redis.core.RedisOperations,redis.clients.jedis.Jedis (OnClassCondition)
FallbackWebSecurityAutoConfiguration
- SpEL expression on org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration: !${security.basic.enabled:true} (OnExpressionCondition)
SecurityAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.security.authentication.AuthenticationManager (OnClassCondition)
FacebookAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.social.facebook.connect.FacebookConnectionFactory (OnClassCondition)
LinkedInAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.social.linkedin.connect.LinkedInConnectionFactory (OnClassCondition)
SocialWebAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.social.connect.web.ConnectController,org.springframework.social.config.annotation.SocialConfigurerAdapter (OnClassCondition)
TwitterAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.social.twitter.connect.TwitterConnectionFactory (OnClassCondition)
SolrAutoConfiguration
- required @ConditionalOnClass classes not found: org.apache.solr.client.solrj.SolrServer (OnClassCondition)
ThymeleafAutoConfiguration
- required @ConditionalOnClass classes not found: org.thymeleaf.spring4.SpringTemplateEngine (OnClassCondition)
VelocityAutoConfiguration
- required @ConditionalOnClass classes not found: org.apache.velocity.app.VelocityEngine,org.springframework.ui.velocity.VelocityEngineFactory (OnClassCondition)
DispatcherServletAutoConfiguration
- not a web application (OnWebApplicationCondition)
EmbeddedServletContainerAutoConfiguration
- not a web application (OnWebApplicationCondition)
ErrorMvcAutoConfiguration
- required @ConditionalOnClass classes not found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
MultipartAutoConfiguration
- required @ConditionalOnClass classes not found: javax.servlet.Servlet,javax.servlet.MultipartConfigElement (OnClassCondition)
ServerPropertiesAutoConfiguration
- not a web application (OnWebApplicationCondition)
WebMvcAutoConfiguration
- not a web application (OnWebApplicationCondition)
WebSocketAutoConfiguration
- required @ConditionalOnClass classes not found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat,org.springframework.web.socket.WebSocketHandler,org.apache.tomcat.websocket.server.WsSci (OnClassCondition)
2014-06-14 19:29:04.348 INFO 986 --- [ main] hello.Application : Started Application in 0.73 seconds (JVM running for 1.085)
2014-06-14 19:29:06.378 INFO 986 --- [ Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@c163956: startup date [Sat Jun 14 19:29:03 BST 2014]; root of context hierarchy
2014-06-14 19:29:06.379 INFO 986 --- [ Thread-3] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
``` | 2014/06/13 | [
"https://Stackoverflow.com/questions/24214224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/780271/"
] | Just add
```
spring.main.web-environment=true
```
in application.properties and restart. | In addition, you should check that you have at least one rest controller in your app (@RestController) and make sure you compile with `spring-boot-starter-tomcat`
```
providedRuntime ('org.springframework.boot:spring-boot-starter-tomcat')
``` |
1,250,933 | Let $V$ be a finite-dimensional vector space and let $W\_{1}, W\_{2}$ be subspaces of $V$. If $\dim (W\_{1} \cap W\_{2}) = \dim W\_{1}$, must $W\_{1} \subset W\_{2}$?
Since $\dim (W\_{1} \cap W\_{2}) = \dim W\_{1},$ every basis $\alpha \subset W\_{1} \cap W\_{2}$ has the same number of vectors as every basis $\beta \subset W\_{1}$. If $W\_{1} \not\subset W\_{2}$, then there is a $v \in W\_{1} \setminus W\_{2}.$ Hitherto I can only tell that $v \notin$ span$(\alpha)$ and cannot proceed. I would like to see how this can proceed. | 2015/04/25 | [
"https://math.stackexchange.com/questions/1250933",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/155328/"
] | Hint: if $A \subset B$ are vector spaces with $\dim A = \dim B < \infty$ then $A = B$ | No need to reason about bases here. The intersection $W\_1\cap W\_2$ of two subspaces is always a subspace of $W\_1$ (and also of $W\_2$ but that won't be used here). If in addition it has the same (finite) dimension as $W\_1$, then it must be all of $W\_1$, that is $W\_1\cap W\_2=W\_1$. But that means that $W\_1\subseteq W\_2$. |
21,386 | Do you honor [Programmers' Day](http://programmerday.info/FAQ.html "They speak English in 'What'?!"), the 256-th day of the year?
It'll fall on 13 September this year, being a non-leaping one and all that jazz. | 2009/09/11 | [
"https://meta.stackexchange.com/questions/21386",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/-1/"
] | No. I use a 0-based index for my days, so I celebrate Day 255. | Programmers day only exists one time in history: October 10th, 2010. Or in binary form 101010. It's quite simply the ultimate answer. |
30,109,554 | I have a tsv, file1, that is structured as follows:
```
col1 col2 col3
1 4 3
22 0 8
3 5
```
so that the last line would look something like `3\t\t5`, if it was printed out. I'd like to replace that empty string with 'NA', so that the line would then be `3\tNA\t5`. What is the easiest way to go about this using the command line? | 2015/05/07 | [
"https://Stackoverflow.com/questions/30109554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2516989/"
] | In these [docs](http://guides.rubyonrails.org/association_basics.html) you have:
>
> When are Objects Saved?
>
>
> When you assign an object to a has\_and\_belongs\_to\_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
>
>
> If you want to assign an object to a has\_and\_belongs\_to\_many association without saving the object, use the `collection.build` method.
>
>
>
Here is a good answer for Rails 3 that goes over some of the same issues
[Rails 3 has\_and\_belongs\_to\_many association: how to assign related objects without saving them to the database](https://stackoverflow.com/questions/26491920/rails-3-has-and-belongs-to-many-association-how-to-assign-related-objects-witho) | I know that this is a pretty old question, but I found a solution that works perfectly for me and hope it could save time to someone else:
```
class A
has_many :bs, class_name 'B'
end
class B
belongs_to :a, class_name: 'A'
end
a.bs.target.clear
new_bs.each {|new_b| a.bs.build new_b.attributes.except('created_at', 'updated_at', 'id') }
```
you will avoid autosave that Rails does when you do `a.bs = new_bs` |
39,682,143 | Ok, so we all know that you can do the following:
```
array.each{ |value|
puts value
}
```
What if, however, I want to start at element `n` instead of starting at the beginning; *i.e.* `n=0`. | 2016/09/25 | [
"https://Stackoverflow.com/questions/39682143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6554042/"
] | You can also do
`array.drop(n).each { |v| puts v }` | You can call a subarray with a range like this:
```
array[n..-1].each { |value| puts value }
```
Where n is the index you'd like to start at, and -1 will always point to the last index of an array. |
124,199 | I installed Magento 2.1 on my Centos 7 server, running Nginx 1.10.1, MariaDB 10.1 and PHP7 with SSL. In theory, everything installed just fine and after the installation I got no errors what-so-ever, and "systemctl status nginx" and "systemctl status php-fpm" both show that they should be working fine. But when I try to access my site in web browser, I get following:
>
> "There has been an error processing your request
>
>
> Exception printing is disabled by default for security reasons.
>
>
> Error log record number: 886472238215"
>
>
>
So I went to "usr/share/nginx/magento2/var/report" and opened that log number 886472238215:
```
a:4:{i:0;s:226:"Warning: SessionHandler::read(): open(/var/lib/php/session/sess_au56sith2u5dloibaakd9c3q06, O_RDWR) failed: Permission denied (13) in /usr/share/nginx/magento2/vendor/magento/framework/Session/SaveHandler/Native.php on line 22";i:1;s:6680:"#0 [internal function]: Magento\Framework\App\ErrorHandler->handler(2, 'SessionHandler:...', '/usr/share/ngin...', 22, Array)
#1 /usr/share/nginx/magento2/vendor/magento/framework/Session/SaveHandler/Native.php(22): SessionHandler->read('au56sith2u5dloi...')
#2 /usr/share/nginx/magento2/vendor/magento/framework/Session/SaveHandler.php(93): Magento\Framework\Session\SaveHandler\Native->read('au56sith2u5dloi...')
#3 [internal function]: Magento\Framework\Session\SaveHandler->read('au56sith2u5dloi...')
#4 /usr/share/nginx/magento2/vendor/magento/framework/Session/SessionManager.php(189): session_start()
#5 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Interceptor.php(146): Magento\Framework\Session\SessionManager->start()
#6 /usr/share/nginx/magento2/var/generation/Magento/Framework/Session/Generic/Interceptor.php(52): Magento\Framework\Session\Generic\Interceptor->___callPlugins('start', Array, Array)
#7 /usr/share/nginx/magento2/vendor/magento/framework/Session/SessionManager.php(130): Magento\Framework\Session\Generic\Interceptor->start()
#8 /usr/share/nginx/magento2/var/generation/Magento/Framework/Session/Generic/Interceptor.php(14): Magento\Framework\Session\SessionManager->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Framework\Session\Storage), Object(Magento\Framework\Stdlib\Cookie\PhpCookieManager), Object(Magento\Framework\Stdlib\Cookie\CookieMetadataFactory), Object(Magento\Framework\App\State))
#9 /usr/share/nginx/magento2/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93): Magento\Framework\Session\Generic\Interceptor->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Framework\Session\Storage), Object(Magento\Framework\Stdlib\Cookie\PhpCookieManager), Object(Magento\Framework\Stdlib\Cookie\CookieMetadataFactory), Object(Magento\Framework\App\State))
#10 /usr/share/nginx/magento2/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(89): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Magento\\Framewo...', Array)
#11 /usr/share/nginx/magento2/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Magento\\Framewo...')
#12 /usr/share/nginx/magento2/var/generation/Magento/Framework/Session/Generic/Proxy.php(84): Magento\Framework\ObjectManager\ObjectManager->get('Magento\\Framewo...')
#13 /usr/share/nginx/magento2/var/generation/Magento/Framework/Session/Generic/Proxy.php(207): Magento\Framework\Session\Generic\Proxy->_getSubject()
#14 /usr/share/nginx/magento2/vendor/magento/framework/Url.php(942): Magento\Framework\Session\Generic\Proxy->getSessionIdForHost('https://www......')
#15 /usr/share/nginx/magento2/vendor/magento/framework/Url.php(1096): Magento\Framework\Url->_prepareSessionUrl('https://www......')
#16 /usr/share/nginx/magento2/vendor/magento/module-store/App/FrontController/Plugin/RequestPreprocessor.php(78): Magento\Framework\Url->getRedirectUrl('https://www.......')
#17 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Chain/Chain.php(67): Magento\Store\App\FrontController\Plugin\RequestPreprocessor->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#18 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'install')
#19 /usr/share/nginx/magento2/vendor/magento/framework/Module/Plugin/DbStatusValidator.php(69): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#20 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Chain/Chain.php(67): Magento\Framework\Module\Plugin\DbStatusValidator->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#21 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'front-controlle...')
#22 /usr/share/nginx/magento2/vendor/magento/module-page-cache/Model/App/FrontController/VarnishPlugin.php(55): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#23 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Chain/Chain.php(67): Magento\PageCache\Model\App\FrontController\VarnishPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#24 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'front-controlle...')
#25 /usr/share/nginx/magento2/vendor/magento/module-page-cache/Model/App/FrontController/BuiltinPlugin.php(73): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#26 /usr/share/nginx/magento2/vendor/magento/framework/Interception/Interceptor.php(142): Magento\PageCache\Model\App\FrontController\BuiltinPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#27 /usr/share/nginx/magento2/var/generation/Magento/Framework/App/FrontController/Interceptor.php(26): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, Array)
#28 /usr/share/nginx/magento2/vendor/magento/framework/App/Http.php(135): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#29 /usr/share/nginx/magento2/vendor/magento/framework/App/Bootstrap.php(258): Magento\Framework\App\Http->launch()
#30 /usr/share/nginx/magento2/pub/index.php(37): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http))
#31 {main}";s:3:"url";s:1:"/";s:11:"script_name";s:10:"/index.php";}
```
And here is the content of /usr/share/nginx/magento2/vendor/magento/framework/Session/SaveHandler/Native.php
```
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Session\SaveHandler;
/**
* Php native session save handler
*/
class Native extends \SessionHandler
{
/**
* Workaround for php7 session_regenerate_id error
* @see https://bugs.php.net/bug.php?id=71187
*
* @param string $sessionId
* @return string
*/
public function read($sessionId)
{
return (string)parent::read($sessionId);
}
}
```
Can anyone tell me what the problem might be? | 2016/07/04 | [
"https://magento.stackexchange.com/questions/124199",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/41764/"
] | php package has some `pre|post` installation scenario in its `specfile`, and one of commands is:
```
......
%dir %attr(0770, root, apache) "/var/lib/php/session"
......
```
so im afraid that probably all your changes will be overwritten on the next php upgrade. no need to chmod or change owner anyway.
you have one option to properly fix it:
open your php-fpm pool config file `/etc/php-fpm.d/www.conf`
and change these lines at the bottom:
```
php_value[session.save_handler] = files
php_value[session.save_path] = /path/to/magento/var/session
```
or remove them and use `redis` or `memcached`. | The problem that user of php-fpm process do not have write access to /var/lib/php/session/\* files. Please find out username and user group and change access on folder
like
```
sudo chown -R www-data:www-data /var/lib/php/
```
or if it developer environment you can simple (**but not secure**) add access for all
```
sudo chmod -R 0777 /var/lib/php/
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.