date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/14
| 1,560 | 5,583 |
<issue_start>username_0: I have a map with a lot of sprites. I could add a material to the sprite with diffuse shading and than add lots of lights. But that won't give me the result I want. And is performance heavy.
---
Examples
--------
In the first image you can see that light is generated by torches. It's expanding its light at its best through 'open spaces' and it is stopped by blocks fairly quickly.
[](https://i.stack.imgur.com/8Sm4g.jpg)
---
Here is a great example of the top layer. We can see some kind of 2D directional light? Please note that the lighting inside the house is generated by torches again. The cave on the right side shows a better example of how light is handled. Also, note the hole in the background, this is generating some extra light into the cave. As if the light is really shining through the background there.
[](https://i.stack.imgur.com/ibtqE.jpg)
---
What I have
-----------
You can clearly see the issue here. Lights increase their intensity. And light creates a squared edge around some of the tiles for some reason. Also, lots of lights will cause performance issues very quickly.
[](https://i.stack.imgur.com/OZWtH.jpg)
---
Raycasting?
-----------
I read that you can somehow use raycasting? To target 'open space' or something? I have no experience with shaders or with lighting in games at all. I'd love a well-explained answer with how to achieve this Terraria/Starbound lighting effect. This does not mean I'm saying that raycasting is the solution.
---
Minecraft
---------
In Minecraft, light can travel for a certain amount of air blocks. It gradually fades to completely dark. In the Graphic settings you can enable `Smooth Lightning`, which will (obviously) smooth the lightning on the blocks.
I guess this is done with shaders, but I'm not sure. My guess is that this is performance heavy. But I'm thinking about air blocks (which are gameobjects) and maybe I have the wrong logic.
---
**Note:** I love a helpful answer, but please provide a link with a detailed explanation. Or provide an explanation with source code or links to the Unity docs in your answer. I wouldn't like to see theories worked out or something. I'd love to get an answer on how to implement this kind of lighting in Unity.
I'd also like to know if it's possible to *NOT* use a package from the Unity Marketplace.
---
Similar, but no good
--------------------
Take a look at similar posts with links to articles that cover the basics of raycasting. But no explanation on how to implement this in Unity and not the Terraria/Starbound effect I'd like to achieve:
[Make pixel lighting like terraria and starbound](https://stackoverflow.com/questions/41443130/make-pixel-lighting-like-terraria-and-starbound)
[How to achieve Terraria/Starbound 2d lighting?](https://stackoverflow.com/questions/31736654/how-to-achieve-terraria-starbound-2d-lighting)
---
Video impression
----------------
For example, take a look at this video for a really good impression on how 2d light works in Starbound:
<https://www.youtube.com/watch?v=F5d-USf69SU>
I know this is a bit more advanced, but also the point light generated by the player's flash light is stopped by blocks and let through by the open spaces.
---
Other help forums
-----------------
Also posted by me.
**Gamedev Exchange:** <https://gamedev.stackexchange.com/questions/155440/unity-2d-shader-lighting-like-terraria-or-starbound>
**Unity Forum:** <https://answers.unity.com/questions/1480518/2d-shader-lighting-like-terraria-or-starbound.html>
---<issue_comment>username_1: Apparently, there are several packages on [the Unity Asset Store](https://assetstore.unity.com/). Search for "2d lighting" or "2d shader". You can easily import the source code of these packages and test it in Unity yourself. If you like a package after testing, you can use it.
I highly advise you not to import it directly into an existing project. For your own sake, test it in a test environment (or a copy of your project) before including it into your project.
Upvotes: 0 <issue_comment>username_2: I can mention 2 main elements about 2d Dynamic Lighting for unity.
1. One of the main asset used for 2d lighting in unity essentials is [DDL light](https://assetstore.unity.com/packages/tools/particles-effects/2ddl-pro-2d-dynamic-lights-and-shadows-25933), with an official tutorial [here](https://learn.unity.com/tutorial/recorded-video-session-2d-essentials-pack).
2. Most importantly Unity itself is working on a Dynamic lighting system, currently in beta (for 2019.2). Unity introduced the package Lightweight RP for 2d lights [here](https://forum.unity.com/threads/experimental-2d-lights-and-shader-graph-support-in-lwrp.683623/) and there's a tutorial [here](https://www.youtube.com/watch?v=nkgGyO9VG54).
Upvotes: 3 [selected_answer]<issue_comment>username_3: [Here's my hacky solution](https://i.stack.imgur.com/t7HCm.png)
[GitHub Link](https://github.com/BigDaddyGameDev/Tile-Light-and-Shadows-Like-Terraria)
1. There's 2 cameras.
2. Empty tiles are filled in with white blocks (only camera 2 render this)
3. A gaussian blur is applied to the camera rendering the white blocks
4. SpriteLightKit blends the two cameras, darkening everything not covered by the white blur.
5. You can adjust the "light" penetration by changing the white tile's sprite's Pixels Per Unit.
Upvotes: 0
|
2018/03/14
| 826 | 3,332 |
<issue_start>username_0: I'm trying to make axios working with a request interceptor. However
before a request is made the interceptor is not triggered. What could be going wrong here? I've red already a lot about this problem but not
found a solution so far. Could use some help here! This is my code:
```js
import VueRouter from 'vue-router';
import Login from './components/Login.vue'
import Home from './components/Home.vue'
import axios from 'axios';
window.Vue = require('vue');
window.axios = axios.create({
baseURL: 'http://localhost:8080',
timeout: 10000,
params: {} // do not remove this, its added to add params later in the config
});
Vue.use(VueRouter);
// Check the user's auth status when the app starts
// auth.checkAuth()
const routes = [
{ path: '/', component: Login, name: 'login' },
{ path: '/home', component: Home, name: 'home', beforeEnter: requireAuth },
];
const router = new VueRouter({
routes // short for `routes: routes`
});
const app = new Vue({
router
}).$mount('#app');
function requireAuth (to, from, next) {
if (!loggedIn()) {
router.push('/');
} else {
next()
}
}
function loggedIn() {
return localStorage.token !== undefined;
}
axios.interceptors.request.use(function (config) {
alert('test');
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
```
When I use axios within another vue file:
```js
axios.get('users').then((data) => {
console.log(data);
});
```
The interceptor is not triggered!<issue_comment>username_1: You're calling the interceptor on the axios instance you imported, but it needs to be on the instances you created.
Calling `window.axios = axios.create()` is really bad style anyway and you should avoid it at all costs. If you want it to be globally available you should bind it to the Vue Prototype. Even better would be to move it out in another module:
```
const instance = axios.create({
baseURL: 'http://localhost:8080',
timeout: 10000,
params: {} // do not remove this, its added to add params later in the config
});
instance.interceptors.request.use(function (config) {
alert('test');
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default instance
```
If you really want it to be available everywhere without having to import it, consider wrapping my code from above inside a Vue plugin and let your Vue instance use it, as shown [here in the 4. comment](https://v2.vuejs.org/v2/guide/plugins.html).
Upvotes: 7 [selected_answer]<issue_comment>username_2: ```
axios.interceptors.response.use(async function (response) {
return response;
}, async function (error) {
if (error.response.status === 401) {
//call your api for refresh token
error.config.headers[
"Authorization"
] = `bearer ${token from your result}`;
return axios(error.config);
}
return Promise.reject(error);
});
```
By using above code you can automatically call the current api url.
Upvotes: 0
|
2018/03/14
| 278 | 1,054 |
<issue_start>username_0: please i am trying to search the all column that (dcountry ="France") as example, as illustrated in picture:

i try that code, but not work:
```
MyFirebase.db.child("Developer").orderByChild("dcountry")
.startAt("France")
.endAt("France"+ "\ufbff")
.addValueEventListener(object:ValueEventListener{
override fun onDataChange(p0: DataSnapshot?) {
```<issue_comment>username_1: You can do this:
```
MyFirebase.db.child("Developers").orderByChild("dcountry").equalTo("France").addValueEventListener(object:ValueEventListener{
```
which will give you all countries that are equal to france
Upvotes: 3 [selected_answer]<issue_comment>username_2: I have written query using kotlin. But it will help you
```
val query = FirebaseDatabase.getInstance()
.getReference()
.child("Developers")
.orderByChild("dcountry")
.equalTo("france")
.limitToFirst(50)
```
Upvotes: 0
|
2018/03/14
| 754 | 2,632 |
<issue_start>username_0: I am having a design issue here. I have the following below structure.
```
trait Table
object Table1 extends Table
object Table2 extends Table
// and so on till Table200
```
I have command line interface where the user specifies the table name that needs to be executed. So the problem I am having is instantiating the classes based on the table name(type String) specified by the user. I am looking for a solution without the use of reflection.<issue_comment>username_1: You can use some kind of "registry" if you want to avoid using reflection:
```
import scala.collection.mutable
object MyApp {
// Create some kind of "registry"
private val TableByName: mutable.Map[String, Table] = mutable.Map()
// Create a lookup method:
def lookup(name: String): Option[Table] = TableByName.get(name)
// Each table would register itself
trait Table {
TableByName.put(this.toString, this)
override def toString: String = this.getClass.getSimpleName.replace("$", "")
}
// Instantiate each object after declaring it, or else it won't "register"
object Table1 extends Table; Table1
object Table2 extends Table; Table2
// ...
def main(args: Array[String]): Unit = {
// Now we can lookup our table in the registry by name
val result: Option[Table] = lookup("Table2")
println(result)
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
scala> trait Table
// defined trait Table
scala> object Table1 extends Table
// defined object Table1
scala> object Table2 extends Table
// defined object Table2
scala> val name = "Table2"
// name: String = Table2
scala> val map = Map (1 -> Table1, 2 -> Table2)
// map: scala.collection.immutable.Map[Int,Table] = Map(1 -> Table1$@51549af8, 2 -> Table2$@394542f5)
scala> def getTable (s: String) : Option [Table] = map.get (s.replaceAll ("^Table", "").toInt)
// getTable: (s: String)Option[Table]
scala> getTable (name)
// res0: Option[Table] = Some(Table2$@394542f5)
```
Using an array would be similar:
```
val tblarr = Array[Table] (Table1, Table2)
val usertbl = tblarr(name.replaceAll ("^Table", "").toInt - 1)
```
or, with a dummy table at index 0, without the error prone -1 operation (easy to forget).
Upvotes: 1 <issue_comment>username_3: Try this
```
trait Table
class Table1 extends Table
class Table2 extends Table
object Table {
def apply (kind: String) = kind match {
case "Table1" => new Table1()
case "Table2" => new Table2()
}
}
Table("Table1")
```
I believe that you can read the input from the cli pass that value while creating the object.
Upvotes: 0
|
2018/03/14
| 1,544 | 7,721 |
<issue_start>username_0: Here is my Firebase structure
[](https://i.stack.imgur.com/7iMHr.png)
I'm trying to select all the IDs with the same date and populate a recycler view with it, here is my code snippet:
```
private void updateValues()
{
if(rAuth !=null && rUser!=null)
{
final String date="15/03/2018";
final DatabaseReference rRef =
FirebaseDatabase.getInstance().getReference()
.child("Users")
.child("Transactions");
rRef.child("Expense").addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot rSnap)
{
for(DataSnapshot d: rSnap.getChildren())
{
rRef.child(d.getKey())
.child("Date")
.addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(date.equals(dataSnapshot.getValue().toString()))
{
recordItems.add(new recordItems(iconGetter(d.child("Type").getValue().toString()),
d.child("Description").getValue().toString(),
d.child("Type").getValue().toString(),
d.child("Value").getValue().toString(),
d.child("Date").getValue().toString()));
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
initRecycler();
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
```
now since i'm trying to access DataSnapshot d from an inner class I need to make it final, but if I do that, I can't iterate it anymore. I am a bit stuck here since it's my first time using Firebase. I have only used SQL in the past.
recordItems is my model(is that what it's called?) class for storing and providing values to the recycler adapter
Is there a better way to do this? I need to sort these by date, I thought about restructuring the database but I would prefer if there was another way.
Forgive my messy code, I intend to fix it once I get it working. Thanks for any help in advance.<issue_comment>username_1: If you wanna retrieve all those `Expense` childs based on the given date
You need to declare your given `date` value as Global .
I would recommend you to use `addChildEventListener` and override all the methods.
Then, You have to create a `pojo class` for getting all those values in the form of an object.
Give this a try :
First create a class with the name :
```
ExpenseModel.java
```
paste this on it .
```
public class ExpenseModel {
String Date,Description,Type,Value;
public ExpenseModel(){
}
public ExpenseModel(String date, String description, String type, String value) {
Date = date;
Description = description;
Type = type;
Value = value;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
```
And The method should be something like this
```
final String date="15/03/2018";
private void updateValues()
{
if(rAuth !=null && rUser!=null)
{
final DatabaseReference rRef =
FirebaseDatabase.getInstance().getReference()
.child("Users")
.child("Transactions");
rRef.child("Expense").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ExpenseModel expenseModel = dataSnapshot.getValue(ExpenseModel.class);
assert expenseModel != null;
if(expenseModel.getDate().equals(date)){
// Add it to the recyclerView
// And call notifyDataSetChanged()
yourAdapter.add(expenseModel);
yourAdapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```
Hope this at least helps till some extent, let me know if you still faced any problem.
**Cheers**
Upvotes: 1 <issue_comment>username_2: First of all you should fix those code line and add the User-id:
```
final DatabaseReference rRef =
FirebaseDatabase.getInstance().getReference()
.child("Users")
.child("Transactions");
```
Should look like that:
```
final DatabaseReference rRef =
FirebaseDatabase.getInstance().getReference()
.child("Users")
.child(userId)
.child("Transactions");
```
Now, if you want to make your code more efficient you can get only the desired dates with the next query:
```
final Query refQuery =
FirebaseDatabase.getInstance().getReference()
.child("Users")
.child(userId)
.child("Transactions")
.child("Expense")
.orderByChild("Date").equalTo(date);
```
Then, you don't even need to call the `addListenerForSingleValueEvent` method, because Firebase Realtime-Database always retrieve all the children of the specified Reference.
So all you need is to add your Code line inside the foreach loop:
```
for (DataSnapshot d : dataSnapshot.getChildren()){
recordItems.add(new recordItems(iconGetter(d.child("Type").getValue().toString()),
d.child("Description").getValue().toString(),
d.child("Type").getValue().toString(),
d.child("Value").getValue().toString(),
d.child("Date").getValue().toString()));
}
```
And don't forget to notify yout adapter after adding all the new items to the list with `adapter.notifyDataSetChanged()` and of course after you called `initRecycler();` in the beginning of this whole code.
Hope I helped!
You are welcome to check my solution and tell if there are any problems
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,163 | 4,054 |
<issue_start>username_0: So I transform paragraph into a string and try to count letters but...
HTML:
```
example text a
```
JavaScript
```
function alert(){
var str = document.getElementById('text').outerHTML;
var counta = str.match(/a/g).length;
var countd = str.match(/d/g).length;
var county = str.match(/y/g).length;
document.getElementById("example").innerHTML= counta+ " " +countd+ " " + county;
}
```
I need to count every letter in a paragraph, but I have an issue. Like in the example below I would like to check counting for the letter "a", "d", "y". In my example, I don't have "y" letter and "d".
So why I have an output like 2 1 1?? Where I make a mistake??!!<issue_comment>username_1: You're getting the [outerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML), which includes the tag information (). That's why you have a d (in `id`).
Use [innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) to get the content between the tags. You may even want to use [innerText](https://caniuse.com/#feat=innertext) so it ignores tags inside, I modified your example to contain a to illustrate the point.
```js
function getCount(matchResult) {
return matchResult ? matchResult.length : 0;
}
var innerHTML = document.getElementById('text').innerHTML;
var counta = getCount(innerHTML.match(/a/g));
var countd = getCount(innerHTML.match(/d/g));
var county = getCount(innerHTML.match(/y/g));
document.getElementById("exampleInnerHTML").innerHTML = counta + " " + countd + " " + county;
var innerText = document.getElementById('text').innerText;
counta = getCount(innerText.match(/a/g));
countd = getCount(innerText.match(/d/g));
county = getCount(innerText.match(/y/g));
document.getElementById("exampleInnerText").innerHTML = counta + " " + countd + " " + county;
```
```html
example text a
Using innerHTML
---------------
Using innerText
---------------
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You get 2 1 1 because you are using `outerHTML`.
`outerHTML` will give you the entire tag and its contents, in this case `example text a` so you probably want to use `innerHTML` instead to only make the matching on the actual content.
Upvotes: 0 <issue_comment>username_3: First of all, you should use `innerHTML` instead of `outerHTML`.
Moreover, you should rename your function, because you are overwriting the JS `alert` function.
But the issue you are getting here is that `.match` returns `null` if no match if found. So you need to set a default value to your count variables.
Try something like this :
```
function count(){
var str = document.getElementById('text').innerHTML;
var matcha = str.match(/a/g);
var matchd = str.match(/d/g);
var matchy = str.match(/y/g);
var counta = matcha ? matcha.length : 0;
var countd = matchd ? matchd.length : 0;
var county = matchy ? matchy.length : 0;
document.getElementById("example").innerHTML= counta+ " " +countd+ " " + county;
}
```
Upvotes: 0 <issue_comment>username_4: Make sure you are only grabbing the text content of the element using .textContent or a similar JS library method (.outerHTML was pulling in your html tags and attributes). That should do the trick.
Using .innerHTML could be problematic, as that method will, like outerHTML, return any embedded HTML tags and attributes. For example, I added a span surrounding your text. Using .innerHTML on the element with the id of "text" would return the span tags along with the text. Using .textContent will return only the content of the text node.
```js
function alert(){
var str = document.getElementById("text").textContent;
console.log(str);
var counta = str.match(/a/g).length;
var countb = str.match(/b/g).length;
console.log(str.match(/a/g));
console.log(str.match(/b/g));
console.log(counta);
console.log(countb);
var newStr = document.getElementById("text").innerHTML;
console.log(newStr);
}
alert();
```
```html
an example text for the letters a and b
```
Upvotes: 0
|
2018/03/14
| 532 | 1,700 |
<issue_start>username_0: Consider the following cell array:
```
A={1:3,[20,40],100}
A =
1×3 cell array
{1×3 double} {1×2 double} {[100]}
```
I'd like a way to retrive the linear index of the values stored it, for example if I flatten the array using:
```
[A{:}]
ans =
1 2 3 20 40 100
```
I can see that the 4th linear index is `20` etc. So is there a way similar the matrix linear index that will give me for a cell array `A((4))` the value `20` in the example? (I of course just invented the `(())` notation for illustration purposes.<issue_comment>username_1: If you don't want to convert your cell array of matrices into a straight numerical matrix, it's hard to determine the linear index to a specific element of a specific matrix since you don't know the "full size" if your data.
You can retrieve elements of matrices within your cell arrays:
```
value = A{1,2}(1,1) % 20
```
That gets the the underlying value of the second cell in the first row of cells (`{1,2}`) and retrieve the element in the first row and column (`(1,1)`). If you want, you can rewrite the command so that it takes into account only a single dimension:
```
value = A{2}(1) % 20
```
Upvotes: 0 <issue_comment>username_2: There isn't a straightforward solution, as far as I know. Here's a way to achieve that. It works even if the inner arrays are not row vectors; in that case they are implicitly considered to be linearized.
```
A = {1:3,[20,40],100}; % data
ind = 4; % linear index into flattened data
s = [0 cumsum(cellfun(@numel, A))];
ind_outer = find(ind<=s, 1) - 1;
ind_inner = ind - s(ind_outer);
result = A{ind_outer}(ind_inner);
```
Upvotes: 4 [selected_answer]
|
2018/03/14
| 1,001 | 3,566 |
<issue_start>username_0: I want to use the [GetTempFileName](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364991(v=vs.85).aspx) function to generate a random file name but without creating the file itself when the function gets called. I want to use that function to use the name itself (and without the extension) so later I can create a folder with that particular name. Since there is no similar function that creates a folder, I just want to get the string that GetTempFileName creates to later on create a folder.
```
LPTSTR wzTemp = new TCHAR[MAX_PATH];
GetTempFileName(strTemp, 0, 0, wzTemp);
CString tempFolder;
tempFolder = wzTemp;
```
This is my attempt but right after GetTempFileName the file gets created.
Any idea how can I tweak this?<issue_comment>username_1: You can delete the file, remove the extension from the generated name, then create the folder.
Upvotes: 2 [selected_answer]<issue_comment>username_2: [GetTempFileName](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364991.aspx) is responsible for creating a file. If you want to create a unique directory instead, you have to write your own implementation. Using `GetTempFileName`, then deleting the file, and creating a directory with the same name in its place is doomed to fail, due to a [TOCTOU](https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use) race.
The standard solution to creating unique names is to use string representations of GUIDs. You can call [UuidCreate](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379205(v=vs.85).aspx), followed by [UuidToString](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379352.aspx) to get one.
If 36 characters is unwieldy in your situation, you would need to write your own implementation, based on a less unique algorithm (like the system time) and a retry strategy.
As an example, here is an implementation, that uses the string representation of the system time, represented as a 64-bit decimal number. That leads to a string representation, that is at most 19 characters wide.
```
#include
#include
#include
#include
std::wstring GetTempDir(std::wstring const& root\_dir) {
while (true) {
::SYSTEMTIME st{};
::GetSystemTime(&st);
::FILETIME ft{};
if (!::SystemTimeToFileTime(&st, &ft)) {
auto error\_code{ ::GetLastError() };
throw std::system\_error(error\_code, std::system\_category(),
"SystemTimeToFileTime()");
}
ULARGE\_INTEGER ft\_uli{ ft.dwLowDateTime, ft.dwHighDateTime };
auto dir\_name{ std::to\_wstring(ft\_uli.QuadPart) };
auto dir\_name\_full{ root\_dir + dir\_name };
if (::CreateDirectoryW(dir\_name\_full.c\_str(), nullptr)) {
return dir\_name\_full;
}
else {
auto error\_code{ ::GetLastError() };
if (error\_code != ERROR\_ALREADY\_EXISTS) {
throw std::system\_error(error\_code, std::system\_category(),
"CreateDirectoryW()");
}
}
}
}
```
This function returns the fully qualified path to the temporary directory it creates, or throws an exception if it cannot. It expects a string to the root directory including a trailing backslash. In case the directory already exists, it keeps trying, until a directory can be created.
Note in particular, that there is no race condition. If the function succeeds, the directory has been created.
It can be called as shown in the following sample:
```
int main() {
wchar_t path[MAX_PATH + 1]{};
::GetTempPathW(_countof(path), path);
auto temp_dir{ GetTempDir(path) };
std::wcout << L"Temporary directory created: " << temp_dir << std::endl;
}
```
Upvotes: 3
|
2018/03/14
| 466 | 1,566 |
<issue_start>username_0: I need to know if there is a way to create this part dynamically. Or, is it even possible? Using "Contians" will not work in this situation.
```
(x.Letter!= "a") && (x.Letter!= "b") && (x.Letter!= "e")
```
The "a", "b", "c" will be generated out of a ListBox using a for loop. There can be any number of items in the list box. That is why this must be dynamic.
```
MyList.RemoveAll(x => (x.Letter != "a") && (x.Letter!= "b") && (x.Letter!= "e"));
```<issue_comment>username_1: You're trying to make sure that nothing in that list is equal to `x.Letter`, so I'd construct the list of values you'd like to remove first, then use that.
I don't know what your `ListBox` looks like, but let's assume you can get the list of strings out of it like this:
```
List stuffToRemove = myListBox.Items.Select(x => x.Value).ToList();
```
You should just be able to use that list of strings in your LINQ statement:
```
MyList.RemoveAll(x => stuffToRemove.Contains(x.Letter));
```
---
If you actually intended to *keep* the stuff in the `ListBox`, then adjust it accordingly:
```
List stuffToKeep = myListBox.Items.Select(x => x.Value).ToList();
MyList.RemoveAll(x => !stuffToKeep.Contains(x.Letter));
```
Upvotes: 2 <issue_comment>username_2: You do not need to make it dynamic, because the structure of your condition is very regular: you check containment against all items. Hence you can do it like this:
```
var check = new List(itemsFromListBox);
MyList.RemoveAll(x => check.All(s => x.Letter != s));
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,384 | 5,196 |
<issue_start>username_0: I am having trouble figuring out how I can update the component with the new data from the database after the edit function has been run and the update to the database was successful.
I have tried doing `this.forceUpdate()` but that doesn't work. I heard about using `this.setState()` but I don't know how I would update it using that with the database as my classroom state is a JSON array.
I have been thinking and google-ing long and hard for days without any luck, so any advice or help with this problem would be greatly appreciated.
P.S. I am using MySQL for my Database. I don't know if that matters.
**App.js**
```
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
toggle: false,
toggleIdxArray: [],
classroom: [],
childflagged: '',
flagreason: '',
id: ''
};
this.eventHandler = this.eventHandler.bind(this);
this.logChange = this.logChange.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
logChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleEdit(event) {
event.preventDefault()
var data = {
childflagged: this.state.childflagged,
flagreason: this.state.flagreason,
id: this.state.id
}
fetch("/classroom/edit", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
if (data.affectedRows === 1) {
console.log('Edited Flag!'); //UPDATE COMPONENT FUNCTION OF SOME-SORT HERE
}
}).catch(function(err) {
console.log(err)
});
}
eventHandler(event, idx) {
let updatedArr = this.state.toggleIdxArray.slice();
let checkIdx = updatedArr.indexOf(idx);
if (checkIdx === -1) updatedArr.push(idx);
else updatedArr.splice(checkIdx, 1);
this.setState((prevState) => ({
toggleIdxArray: updatedArr
})
);
}
componentDidMount() {
fetch("/classroom")
.then(res => res.json())
.then(classroom => this.setState({ classroom }))
}
render() {
return (
Classroom
=========
{this.state.classroom.map((classroom, idx) =>
Child's Name: {classroom.childsname}
Parent's Phone Number: {classroom.parentsnumber}
this.eventHandler(e, idx)}>Edit Flags
View Results
View Profile
this.state.id = classroom.id} name="submit" value="Save Changes" />
)}
);
}
}
export default App;
```<issue_comment>username_1: You can trigger the component re-render by calling `setState` inside your `handleEdit` function, after the request finished and data returned:
```
handleEdit(event) {
....
fetch("/classroom/edit", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
if (data.affectedRows === 1) {
/** Calling setState here
* For example, if the data return is a classroom object,
* you can update the classroom property of the state to
* reflect it
*/
this.setState({classroom:[...this.state.classroom, data.classroom]});
}
})
....
}
```
Basically, a react component will re-render if:
1. Its props change.
2. Its `setState` function is called.
3. Its `forceUpdate` function is called.
More details about this topic can be found here: <https://reactjs.org/docs/state-and-lifecycle.html>
Upvotes: 1 <issue_comment>username_2: If you get back the data in a useful format after updating it on the database, just use setState with that data:
```
handleEdit(event) {
event.preventDefault()
var data = {
childflagged: this.state.childflagged,
flagreason: this.state.flagreason,
id: this.state.id
}
fetch("/classroom/edit", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
//Aside: because of the way promises work, this is the correct way to throw the error. Doing this you can catch it in the "catch" callback
Promise.reject(new Error("Bad response from server"));
}
return response.json();
}).then((data) => {
if (data.affectedRows === 1) {
console.log('Edited Flag!'); //UPDATE COMPONENT FUNCTION OF SOME-SORT HERE
//use data to set state
this.setState({ classroom: data });
}
}).catch(function(err) {
console.log(err)
});
}
```
Upvotes: 2 <issue_comment>username_3: I fixed this by using:
```
}.then((data) => {
console.log('Update Complete');
this.setState({ classroom: data })
})
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 517 | 1,672 |
<issue_start>username_0: I want to execute the following R chunk, but when I generate the PDF of the RMarkdown I don't want to include the Loading messages.
**Knitr Setup chunk**
`{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(progress=FALSE)`
**Load Packages**
```
```{r, warning=FALSE, results='hide',message='hide'}
x <- c("ggmap", "rgdal", "rgeos", "maptools", "dplyr", "tidyr", "tmap")
lapply(x, library, character.only = TRUE) # load the required packages
```
```
**Output I'm getting**
[enter image description here](https://i.stack.imgur.com/NkH0u.png)
-------------------------------------------------------------------
**Wanted Output**
Only the chunk in the pdf without messages of loading packages.<issue_comment>username_1: There is a base function `suppressPackageStartupMessages` that serves this purpose. Wrapping your expression will prevent the text from printing to the console.
```
x <- c("ggmap", "rgdal", "rgeos", "maptools", "dplyr", "tidyr", "tmap")
suppressPackageStartupMessages(lapply(x, library, character.only = TRUE))
```
Upvotes: 1 <issue_comment>username_2: The message option takes a logical argument (i.e., TRUE/FALSE): [See knitr documentation](https://yihui.name/knitr/options/#text-results).
This sould work:
```
```{r, warning=FALSE, results='hide',message=FALSE}
x <- c("ggmap", "rgdal", "rgeos", "maptools", "dplyr", "tidyr", "tmap")
lapply(x, library, character.only = TRUE) # load the required packages
```
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: I use the `pacman` library
```
pacman::p_load(ggmap, rgdal, rgeos, maptools, dplyr, tidyr, tmap)
```
Upvotes: 1
|
2018/03/14
| 397 | 1,218 |
<issue_start>username_0: These are the inputs I have:
```
ab_something#123
something else#15
zy_s0meth1ng third
nothing
```
The output I need is:
```
something
something else
s0meth1ng third
nothing
```
The closest I got was this `(?:.._|^)(.*)(?:#[0-9]*|$)` but this still captures the suffix.<issue_comment>username_1: There is a base function `suppressPackageStartupMessages` that serves this purpose. Wrapping your expression will prevent the text from printing to the console.
```
x <- c("ggmap", "rgdal", "rgeos", "maptools", "dplyr", "tidyr", "tmap")
suppressPackageStartupMessages(lapply(x, library, character.only = TRUE))
```
Upvotes: 1 <issue_comment>username_2: The message option takes a logical argument (i.e., TRUE/FALSE): [See knitr documentation](https://yihui.name/knitr/options/#text-results).
This sould work:
```
```{r, warning=FALSE, results='hide',message=FALSE}
x <- c("ggmap", "rgdal", "rgeos", "maptools", "dplyr", "tidyr", "tmap")
lapply(x, library, character.only = TRUE) # load the required packages
```
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: I use the `pacman` library
```
pacman::p_load(ggmap, rgdal, rgeos, maptools, dplyr, tidyr, tmap)
```
Upvotes: 1
|
2018/03/14
| 1,082 | 3,357 |
<issue_start>username_0: I am trying to read the lParam x and y coordinates from WM\_MOVE win32 message and getting strange values. I need to extract them from the lParam IntPtr somehow.
<https://msdn.microsoft.com/en-us/library/windows/desktop/ms632631(v=vs.85).aspx>
Thanks<issue_comment>username_1: Coordinates in Windows messages are often two signed 16-bit numbers packed into a 32-bit number.
Ideally you should extract these as signed numbers emulating the [`GET_X_LPARAM`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms632654(v=vs.85).aspx)/`GET_Y_LPARAM` macros:
```
IntPtr lparam = (IntPtr) 0xfffeffff; // -1 x -2 example coordinate
uint lparam32 = (uint) lparam.ToInt64(); // We want the bottom unsigned 32-bits
short x = (short) (((uint)lparam32) & 0xffff);
short y = (short) ((((uint)lparam32) >> 16) & 0xffff);
Console.WriteLine(string.Format("coordinates: {0} x {1}", x, y));
```
In the case of `WM_MOVE` you could also extract them as unsigned numbers (`ushort`) since the client area will never be negative.
Upvotes: 0 <issue_comment>username_2: .NET Reference source is a gold mine. In an internal [System.Windows.Forms.NativeMethods+Util class](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/NativeMethods.cs,e1ab28ba69954959,references) you will find these helpers, that talk the same as WM\_MOVE documentation (high-order word = HIWORD, low-order word = LOWORD, etc.)
```
public static int MAKELONG(int low, int high) {
return (high << 16) | (low & 0xffff);
}
public static IntPtr MAKELPARAM(int low, int high) {
return (IntPtr) ((high << 16) | (low & 0xffff));
}
public static int HIWORD(int n) {
return (n >> 16) & 0xffff;
}
public static int HIWORD(IntPtr n) {
return HIWORD( unchecked((int)(long)n) );
}
public static int LOWORD(int n) {
return n & 0xffff;
}
public static int LOWORD(IntPtr n) {
return LOWORD( unchecked((int)(long)n) );
}
public static int SignedHIWORD(IntPtr n) {
return SignedHIWORD( unchecked((int)(long)n) );
}
public static int SignedLOWORD(IntPtr n) {
return SignedLOWORD( unchecked((int)(long)n) );
}
public static int SignedHIWORD(int n) {
int i = (int)(short)((n >> 16) & 0xffff);
return i;
}
public static int SignedLOWORD(int n) {
int i = (int)(short)(n & 0xFFFF);
return i;
}
```
Upvotes: 1 <issue_comment>username_3: In addition to what username_2 already posted (which covers a number of standard macros), this method returns a `Point()` from a `message.LParam`.
>
> [MSDN suggests](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-mousemove) to use the `GET_X_LPARAM` and `GET_Y_LPARAM` macros
> (defined in `WindowsX.h`) to extract the coordinates, warning against
> the possible wrong results returned by the `LOWORD` and `HIWORD`
> macros (defined in `WinDef.h`), because those return unsigned
> integers.
>
>
>
These are the definitions of the suggested macros:
```
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
```
What's important is that these values must be signed, since secondary monitors return negative values as coordinates.
```
public static Point PointFromLParam(IntPtr lParam)
{
return new Point((int)(lParam) & 0xFFFF, ((int)(lParam) >> 16) & 0xFFFF);
}
```
Upvotes: 3
|
2018/03/14
| 273 | 994 |
<issue_start>username_0: I have a vsts build definition in which I try to set the PATH environment variable using PowerShell (and before I tried cmd) task, so that in a later vsTest task, the tests could run an exe from that path, however setting the PATH using the ps\cmd tasks doesn’t seem to work, I tried a few options such as:
```
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";" + $newPath, [EnvironmentVariableTarget]::User)
setx path " %newPath;%PATH%"
```
Any suggestions?<issue_comment>username_1: Set the process environment variable by calling [logging command](https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md) through PowerShell task:
For example:
```
Write-Host "##vso[task.setvariable variable=PATH;]${env:PATH};$newPath";
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: If you need to do this in a Linux pipeline you can do the following:
`- script: echo "##vso[task.setvariable variable=PATH]${PATH}:"`
Upvotes: 2
|
2018/03/14
| 206 | 739 |
<issue_start>username_0: I'm working with regex of python and I'm trying to get a match for what comes before a certain word. For example in the string "match.function" i'm only interested in the 'match'.
how should i write the regex?
thanks<issue_comment>username_1: Set the process environment variable by calling [logging command](https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md) through PowerShell task:
For example:
```
Write-Host "##vso[task.setvariable variable=PATH;]${env:PATH};$newPath";
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: If you need to do this in a Linux pipeline you can do the following:
`- script: echo "##vso[task.setvariable variable=PATH]${PATH}:"`
Upvotes: 2
|
2018/03/14
| 525 | 2,125 |
<issue_start>username_0: I am working on a console Hangman game in c#. I am trying to compare user inputted letter against the letters in the random word I have generated. Error i get is "Operator "==" cannot be applied to operands of type "string" and "char". What other ways could I go about doing this? Ive googled a lot but I haven't found any ideas.
```
public static void LetterChecker(string word)
{
int userGuesses = 6;
string userInputGuess;
while(userGuesses > 0)
{
Console.WriteLine("Please guess a letter");
userInputGuess = Console.ReadLine();
foreach(var letter in word)
{
if(userInputGuess == letter)
{
Console.WriteLine("this letter is in word, guess again");
}
else
{
Console.WriteLine("Incorrect guess");
userGuesses--;
}
}
}
}
```<issue_comment>username_1: Instead of using `Console.ReadLine` which reads an entire line, use `Console.ReadKey`:
>
> Obtains the next character or function key pressed by the user.
>
> The pressed key is displayed in the console window.
>
>
>
```
char userInputGuess;
...
Console.WriteLine("Please guess a letter");
userInputGuess = Console.ReadKey().KeyChar;
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: The return type of `Console.ReadLine()` is a string. By this your `userInputGuess` is of type string, and this is why you receive the error. With slight modification your code can work. Instead of:
```
if(userInputGuess == letter)
```
use:
```
if(userInputGuess[0] == letter)
```
This will read the first letter of your line. But as you may guess, this is not the best solution in this case.
The better approach would be to read only one letter from the console. Like this:
```
var userInputGuess = Console.ReadKey().KeyChar; (and get rid of the previous declaration)
```
The result of this is of type char, and you won't have a problem in the comparison.
Upvotes: 0
|
2018/03/14
| 616 | 2,047 |
<issue_start>username_0: I am having a bit of trouble reading data from a CSV file as an integer.
Here is an example of my CSV file:
```
Col1 Col2 Col3
Header Header Header
Header 1 1,000,000
BLANK 2 500,000
BLANK 3 200,000
```
What I am wanting to do is read in the data from 'Col3' (not including the header) as integers into a tuple.
Here is my code:
```
import csv
prizePoints = []
with open("csvfile.csv") as prizes:
next(prizes)
for row in prizes:
prizePoints.append(row)
```
When I try this, I get an error that says:
```
ValueError: invalid literal for int() with base 10: '"1'
```
Example of printed row:
```
['', '1', '1,000,000']
```
I think it is due to the values in 'Col3' having commas. However, I am unsure of how to fix this so any help would be greatly appreciated!
P.S. I can't change the format of the values for 'Col3' so that they do not have commas.<issue_comment>username_1: You've got multiple problems here.
* In your comprehension, you do `for row in prizes`. Since `prizes` is the file object, this consumes all of the remaining lines in the file, while you're processing the first row.
* The same thing also hides the `row` from the `csv.reader`.
* You're then `split`ing each `row`. If you did the `csv.reader` part right, the row would be a list, not a string, so there'd be nothing to split.
* Your CSV header appears to be two lines long. You don't skip the header. You're kind of getting lucky that the first error cancels this one out, so you never end up trying to process the header as an int.
* Then, finally, you'll get to the point where you try to call `int` on `1,000,000`. This one is pretty easy to solve. For a quick&dirty solution, you can just do `int(s.replace(',', '')`.
Upvotes: 2 <issue_comment>username_2: Consider using the `locale` module when parsing the number - this will help if you run into the problem where some regions switch the thousands and decimal separator
<https://stackoverflow.com/a/2954231/66349>
Upvotes: 0
|
2018/03/14
| 1,765 | 4,233 |
<issue_start>username_0: I have an array through whose contents I need to iterate and prep up a new array. I need to do this multiple times, and I don't need to keep the old data once I'm done with it within the inner loop.
Essentially:
```
double array[dim];
double temparray[dim];
/*initialise array*/
for(...){
for(...){
/*replace contents of temparray based on contents from array*/
}
array = temparray;
}
```
However, this code breaks:
```
error: assignment to expression with array type
array = temparray;
^
```
Any ideas?<issue_comment>username_1: The compiler is right, you cannot assign an array directly. You can initiate it directly and then loop through it to change it:
```
#include
double array[5] = {1, 2, 3, 4, 5};
double temparray[5] = {0, 0, 0, 0, 0};
void printArrays() {
for (int i = 0; i < 5; i++) {
printf("%f\n", array[i]);
}
for (int i = 0; i < 5; i++) {
printf("%f\n", temparray[i]);
}
}
void arrayCopy() {
for (int i = 0; i < 5; i++) {
array[i] = temparray[i];
}
}
int main() {
printf("Hello, Arrays!\n");
printArrays();
arrayCopy();
printf("Hello, Arrays!\n");
printArrays();
return 0;
}
```
There are many ways to illustrate it but I've tried to keep it simple above. It just replaces the elements of one array with another.
Upvotes: -1 <issue_comment>username_2: You can use a couple of helper pointers and swap their values, instead of copying the arrays every time.
So, if I've understood your intent, you can write something like this:
```
#include
void swap\_dptr(double \*\*a, double \*\*b)
{
double \*tmp = \*a;
\*a = \*b;
\*b = tmp;
}
#define dim 5
int main(void) {
double a[dim];
double b[dim] = {9, 8, 7, 6, 5};
double \*pa = a;
double \*pb = b;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < dim; ++j)
{
pa[j] = 1.0 - 0.5 \* pb[j];
printf("%10.6f", pa[j]);
}
puts("");
swap\_dptr(&pa, &pb);
}
return 0;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Maybe this is what you're after. The code uses the pointers `p1` and `p2` to point alternatively at `array1`/`array2` or `array2`/`array1` respectively.
```
#include
static void dump\_array(const char \*tag, int num, double \*data)
{
printf("%8s", tag);
for (int i = 0; i < num; i++)
printf(" %4.0f", data[i]);
putchar('\n');
}
int main(void)
{
int dim = 10;
double array1[dim];
double array2[dim];
for (int i = 0; i < dim; i++)
array1[i] = i;
double \*p1 = array1;
double \*p2 = array2;
dump\_array("p1:", dim, p1);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < dim; j++)
p2[j] = 2 \* (p1[j] + 2) + j;
dump\_array("p2:", dim, p2);
dump\_array("array1:", dim, array1);
dump\_array("array2:", dim, array2);
double \*tp = p1;
p1 = p2;
p2 = tp;
putchar('\n');
}
}
```
Sample output:
```
p1: 0 1 2 3 4 5 6 7 8 9
p2: 4 7 10 13 16 19 22 25 28 31
array1: 0 1 2 3 4 5 6 7 8 9
array2: 4 7 10 13 16 19 22 25 28 31
p2: 12 19 26 33 40 47 54 61 68 75
array1: 12 19 26 33 40 47 54 61 68 75
array2: 4 7 10 13 16 19 22 25 28 31
p2: 28 43 58 73 88 103 118 133 148 163
array1: 12 19 26 33 40 47 54 61 68 75
array2: 28 43 58 73 88 103 118 133 148 163
p2: 60 91 122 153 184 215 246 277 308 339
array1: 60 91 122 153 184 215 246 277 308 339
array2: 28 43 58 73 88 103 118 133 148 163
p2: 124 187 250 313 376 439 502 565 628 691
array1: 60 91 122 153 184 215 246 277 308 339
array2: 124 187 250 313 376 439 502 565 628 691
```
Upvotes: 2 <issue_comment>username_4: You cannot directly assign the array to another array. For this problem you have 2 option first one is by using pointer and assign the pointer to other pointer. And second is by using loop and assign the value to another array one by one.
```
#include
void main(){
int array[100],temparray[100];
int i,n;
scanf("%d", &n); // size of array
for(i=0;i
```
The above code is just a small example of achieving the goal.
Upvotes: 0
|
2018/03/14
| 1,826 | 4,356 |
<issue_start>username_0: I want to scape to html some json in request but it doesn´t work, I get an error when decoding json
```
import (
"html/template"
"encoding/json"
"net/http"
"io"
"io/ioutil"
"log"
)
func anyFunction(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
ri, wo := io.Pipe()
go template.HTMLEscape(wo, body)
var t []customStruct
json.NewDecoder(ri).Decode(t) //error: Invalid character:'&' looking for beginning of object key string
...
}
```
The json coming from the client it´s valid because I´m using "JSON.stringify(data)"
Go 1.9.4<issue_comment>username_1: The compiler is right, you cannot assign an array directly. You can initiate it directly and then loop through it to change it:
```
#include
double array[5] = {1, 2, 3, 4, 5};
double temparray[5] = {0, 0, 0, 0, 0};
void printArrays() {
for (int i = 0; i < 5; i++) {
printf("%f\n", array[i]);
}
for (int i = 0; i < 5; i++) {
printf("%f\n", temparray[i]);
}
}
void arrayCopy() {
for (int i = 0; i < 5; i++) {
array[i] = temparray[i];
}
}
int main() {
printf("Hello, Arrays!\n");
printArrays();
arrayCopy();
printf("Hello, Arrays!\n");
printArrays();
return 0;
}
```
There are many ways to illustrate it but I've tried to keep it simple above. It just replaces the elements of one array with another.
Upvotes: -1 <issue_comment>username_2: You can use a couple of helper pointers and swap their values, instead of copying the arrays every time.
So, if I've understood your intent, you can write something like this:
```
#include
void swap\_dptr(double \*\*a, double \*\*b)
{
double \*tmp = \*a;
\*a = \*b;
\*b = tmp;
}
#define dim 5
int main(void) {
double a[dim];
double b[dim] = {9, 8, 7, 6, 5};
double \*pa = a;
double \*pb = b;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < dim; ++j)
{
pa[j] = 1.0 - 0.5 \* pb[j];
printf("%10.6f", pa[j]);
}
puts("");
swap\_dptr(&pa, &pb);
}
return 0;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Maybe this is what you're after. The code uses the pointers `p1` and `p2` to point alternatively at `array1`/`array2` or `array2`/`array1` respectively.
```
#include
static void dump\_array(const char \*tag, int num, double \*data)
{
printf("%8s", tag);
for (int i = 0; i < num; i++)
printf(" %4.0f", data[i]);
putchar('\n');
}
int main(void)
{
int dim = 10;
double array1[dim];
double array2[dim];
for (int i = 0; i < dim; i++)
array1[i] = i;
double \*p1 = array1;
double \*p2 = array2;
dump\_array("p1:", dim, p1);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < dim; j++)
p2[j] = 2 \* (p1[j] + 2) + j;
dump\_array("p2:", dim, p2);
dump\_array("array1:", dim, array1);
dump\_array("array2:", dim, array2);
double \*tp = p1;
p1 = p2;
p2 = tp;
putchar('\n');
}
}
```
Sample output:
```
p1: 0 1 2 3 4 5 6 7 8 9
p2: 4 7 10 13 16 19 22 25 28 31
array1: 0 1 2 3 4 5 6 7 8 9
array2: 4 7 10 13 16 19 22 25 28 31
p2: 12 19 26 33 40 47 54 61 68 75
array1: 12 19 26 33 40 47 54 61 68 75
array2: 4 7 10 13 16 19 22 25 28 31
p2: 28 43 58 73 88 103 118 133 148 163
array1: 12 19 26 33 40 47 54 61 68 75
array2: 28 43 58 73 88 103 118 133 148 163
p2: 60 91 122 153 184 215 246 277 308 339
array1: 60 91 122 153 184 215 246 277 308 339
array2: 28 43 58 73 88 103 118 133 148 163
p2: 124 187 250 313 376 439 502 565 628 691
array1: 60 91 122 153 184 215 246 277 308 339
array2: 124 187 250 313 376 439 502 565 628 691
```
Upvotes: 2 <issue_comment>username_4: You cannot directly assign the array to another array. For this problem you have 2 option first one is by using pointer and assign the pointer to other pointer. And second is by using loop and assign the value to another array one by one.
```
#include
void main(){
int array[100],temparray[100];
int i,n;
scanf("%d", &n); // size of array
for(i=0;i
```
The above code is just a small example of achieving the goal.
Upvotes: 0
|
2018/03/14
| 776 | 2,946 |
<issue_start>username_0: VSCode is complaining about the use of `va_start` in the following *currently working* function.
```
void _log(int level, const char *format, ...)
{
va_list arglist;
va_start(arglist, format);
writelog(level, format, arglist);
}
```
After searching around, I found a reference to the standard that appears to indicate VSCode is correct and the code will result in undefined behavior.
>
> 18.10/3 ...The parameter parmN is the identifier of the rightmost parameter in the variable parameter list of the function definition (the one just before the ...). If the parameter parmN is declared with a function, array, or reference type, or with a type that is not compatible with the type that results when passing an argument for which there is no parameter, the behavior is undefined.
>
>
>
I tried to find examples of how others handled similar functionality. I found several blogs and several code samples recreating `printf`, using implementations similar to the one above. Are these examples also incorrect?
**What is the appropriate way to write a `printf`-like function without resulting in undefined behavior?**<issue_comment>username_1: So I'm running into this too and it confuses me when working with build output. I believe its a bug (I've registered one here: <https://github.com/Microsoft/vscode-cpptools/issues/1720>).
I found a maybe horrible work around using special preprocessor logic for `__INTELLISENSE__` builds (necessary if a platform can't support Intellisense natively, but vscode is cross platform so....).
Here's the workaround:
```
#if __INTELLISENSE__
#undef va_start(arg, va)
#define va_start(arg, va)
#undef va_end(va)
#define va_end(va)
#undef va_copy(va0, va1)
#define va_copy(arg0, va1)
#define __INT_MAX__ 0x7fffffff
#endif
```
I had issues with the definition of `__INT_MAX__` as well.
If you're desperate this will get these errors out of the way.
Hopefully someone will figure out an actual solution, or at least one that doesn't require custom code.
Thanks,
Adrian
Upvotes: 2 <issue_comment>username_2: I know this is a 5 years old question, this reply is only for who run in to this issue in the future. I'm using latest version of VS Code at the time of posting btw.
The issue is likely caused by incorrect settings in c\_cpp\_properties, if you don't have one in your project, then it will use the default. You need set compilerPath and intelliSenseMode to gcc instead of clang.
```
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c17",
"cppStandard": "c++14",
"intelliSenseMode": "linux-gcc-x64",
"configurationProvider": "ms-vscode.makefile-tools"
}
],
"version": 4
}
```
Upvotes: 1
|
2018/03/14
| 1,113 | 3,788 |
<issue_start>username_0: I have the following:
```
import sqlite3
# connecting to the database
conn = sqlite3.connect("illness.db")
question_data = [
{
"question1": "Have you consumed Alcoholic drinks in the last 24 hours?t",
"choices": {"a": "Yes", "b": "No"},
"answer": "a"
},
{
"question2": "Another Question",
"choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"},
}
]
q = (question_data)
print(q.get('question1'))
answer = input(q.get('choices')).lower()
if answer == q.get('answer'):
c = conn.execute("SELECT illnessID, illness, illnessinfo from illnesses WHERE illness = 'Alcohol Misuse'")
else:
print("Okay Next question.")
```
This corresponds to:
```
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS illnesses(illnessID PRIMARY KEY, illness VARCHAR(30), illnessinfo VARCHAR(50))")
c.execute("CREATE TABLE IF NOT EXISTS symptoms(symptomID PRIMARY KEY, symptom VARCHAR(50))")
def data_entry():
c.execute("INSERT INTO illnesses(illnessID, illness , illnessinfo) VALUES(1,'Flu','Influenza - Common Cold.')")
c.execute("INSERT INTO illnesses(illnessID, illness , illnessinfo) VALUES(2,'Acne','Skin Condition')")
c.execute("INSERT INTO illnesses(illnessID, illness , illnessinfo) VALUES(3,'Alcohol Misuse','Hangover')")
c.execute("INSERT INTO symptoms (symptomID,symptom) VALUES(1,'Headache')")
c.execute("INSERT INTO symptoms (symptomID,symptom) VALUES(2,'Spots')")
c.execute("INSERT INTO symptoms (symptomID,symptom) VALUES(3,'Breathing problems')")
```
So there I have a minimal DB and a form of a questionnaire which I'm trying to have questions relate to answers inside the DB which then tell me which illness it is then print that out into a text file. However I am new to all this and i'm trying to figure it all out and I'm honestly just really stuck and unsure where to go from here. Any help at all from this would be appreciated.
EDIT: The error message I get is: `object has no attribute 'get'`<issue_comment>username_1: So I'm running into this too and it confuses me when working with build output. I believe its a bug (I've registered one here: <https://github.com/Microsoft/vscode-cpptools/issues/1720>).
I found a maybe horrible work around using special preprocessor logic for `__INTELLISENSE__` builds (necessary if a platform can't support Intellisense natively, but vscode is cross platform so....).
Here's the workaround:
```
#if __INTELLISENSE__
#undef va_start(arg, va)
#define va_start(arg, va)
#undef va_end(va)
#define va_end(va)
#undef va_copy(va0, va1)
#define va_copy(arg0, va1)
#define __INT_MAX__ 0x7fffffff
#endif
```
I had issues with the definition of `__INT_MAX__` as well.
If you're desperate this will get these errors out of the way.
Hopefully someone will figure out an actual solution, or at least one that doesn't require custom code.
Thanks,
Adrian
Upvotes: 2 <issue_comment>username_2: I know this is a 5 years old question, this reply is only for who run in to this issue in the future. I'm using latest version of VS Code at the time of posting btw.
The issue is likely caused by incorrect settings in c\_cpp\_properties, if you don't have one in your project, then it will use the default. You need set compilerPath and intelliSenseMode to gcc instead of clang.
```
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c17",
"cppStandard": "c++14",
"intelliSenseMode": "linux-gcc-x64",
"configurationProvider": "ms-vscode.makefile-tools"
}
],
"version": 4
}
```
Upvotes: 1
|
2018/03/14
| 1,566 | 5,172 |
<issue_start>username_0: I´m trying to learn Redux, so: I'm going through Action creators, actions, reducers, dispatchers...
Now, I´m trying to learn how to generate x-state based on other states. For the case, names and hobbies.
I've the types, const: `NAMES` and `HOBBIES` which are used by my action creators which return them as type and a payload, example: { type: HOBBIES, request: payload }
Then I have my reducer file where I switch by an action for both cases (and the default one)
I dispatch from my main file, App.js and access to those states as props.
```
function mapStateToProps(state) {
return {
names: state.names,
hobbies: state.hobbies
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ grabNames, grabHobbies }, dispatch);
}
export default connect(mapStateToProps,mapDispatchToProps)(myApp);
```
I´m using combineReducers (index.js)
```
const rootReducer = combineReducers({
names: namereducer,
hobbies: hobbyreducer
});
```
Currently I have the following redux State.
```
names: [
{name: "A", id: "1"},
{name: "B", id: "2"},
{name: "C", id: "3"}
]
```
and
```
hobbies: [
{basedId: "1", hobby: "cooking"},
{basedId: "2" hobby: "reading"},
{basedId: "3" hobby: "gaming"},
{basedId: "1" hobby: "reading"}
]
```
The result should be an array of objects containing the hobby for each `basedId`, following of course the good practices of Redux.
```
result: [
{name: "A", id: "1", hobby: ["cooking", "reading"]},
{name: "B", id: "2", hobby: "reading"},
{name: "C", id: "3", hobby: "gaming"}
]
```
The thing is that I never went beyond simple maps and [...state, action.data];
I tried to find a solution to this but I could not. I really appreciate any help as I'm quite new.<issue_comment>username_1: I would argue not to generate a new state out of your already stored data, since you would be storing the same (but modified) data twice. Rather perform this data manipulation and construct your `result` object when you need it.
Having said that, here's your answer with a bit of **ES6** spice:
```
names.map(name => (
{ ...name, hobby: hobbies.filter(hobby => hobby.basedId === name.id).map(hobby => hobby.hobby) }
))
```
Upvotes: 0 <issue_comment>username_2: One of the redux principle is "Single source of truth".
it means do not duplicate data, its more efficient and prevents many bugs and problems.
But if you just want to share data between two reducers you can do
by usingusing [redux thunk middleware](https://www.npmjs.com/package/redux-thunk)
Basically you can read data from other reducers states before the action is launched with the dispatch.
**Simple action**:
```
function myAction() {
return {
type: DO_SOMTHING
};
}
```
**Action with thunk**
```
function myAction() {
return (dispatch, getState) => {
// get state contains all existing reducers states
const { reducerTwo } = getState();
dispatch({
type: DO_SOMTHING,
data: reducerTwo.prop
});
};
}
```
Upvotes: 1 <issue_comment>username_3: This is a perfect use case for [reselect](https://github.com/reactjs/reselect). Your code will basically look like this:
```js
import { createSelector } from 'reselect';
const namesSelector = state => state.names;
const hobbiesSelector = state => state.hobbies;
const combineNamesAndHobbies = (names, hobbies) =>
names.map(name => ({
...name,
hobby: hobbies.filter(hobby => hobby.basedId === name.id)
.map(hobby => hobby.hobby)
}));
const resultSelector = createSelector(
[namesSelector, hobbiesSelector],
combineNamesAndHobbies
);
function mapStateToProps(state) {
return {
names: namesSelector(state),
hobbies: hobbiesSelector(state),
result: resultSelector(state)
}
}
```
This will result in your `myApp` component having these `props`:
```js
{
names: [
{ name: "A", id: "1" },
{ name: "B", id: "2" },
{ name: "C", id: "3" }
],
hobbies: [
{ basedId: "1", hobby: "cooking" },
{ basedId: "2", hobby: "reading" },
{ basedId: "3", hobby: "gaming" },
{ basedId: "1", hobby: "reading" }
],
result: [
{ name: "A", id: "1", hobby: ["cooking", "reading"] },
{ name: "B", id: "2", hobby: ["reading"] },
{ name: "C", id: "3", hobby: ["gaming"] }
]
}
```
Note that `hobby` will always be an array, which I'd consider best practice. (But you should name it `hobbies` instead.)
Upvotes: 3 [selected_answer]<issue_comment>username_4: I agree with @username_3. By using [reselect](https://github.com/reactjs/reselect) you avoid recomputing the generated state if none of the related state changes, useful if the selector function is called a lot of times, like in a render loop, so you don't need to manually optimize this part.
To reduce the code needed you can also try [redux-named-reducers](https://github.com/mileschristian/redux-named-reducers) and write the selector like this instead:
```
const resultSelector = createSelector(
[namesModule.names, hobbiesModule.hobbies],
combineNamesAndHobbies
);
```
This adds a little overhead computation in exchange for the shortcut
Upvotes: 0
|
2018/03/14
| 526 | 2,074 |
<issue_start>username_0: After update API (27) in Android OREO this code is no longer working:
```
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() {document.getElementById(\"imPage\").style.display='none';})()");
}
```
I have also tried with:
```
webView.loadUrl(
"javascript:(function() { " +
"document.addEventListener(\"DOMContentLoaded\", function(event) {" +
"document.getElementById(\"imPage\").style.display='none';" +
"});" +
"})()");
```
Element not hiding and debug return:
```
I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'style' of null", source: mywebsite/ (1)
```
So I think the `javascript` is injected before loading page, this explains why the line is 1, because I have other code called after loading page is finished but this code is called when page is white, not loaded.<issue_comment>username_1: `document.getElementById(\"imPage\")` must be returning `null`.
So there is either no `imPage`element or you haven't loaded the page at the time.
I would suggest moving your entire js code into
```
document.addEventListener("DOMContentLoaded", function(event) {
//insert here
});
```
Upvotes: 1 <issue_comment>username_2: You have to enable Javascript Seetings like below :-
```
view.getSettings().setJavaScriptEnabled(true); //Yes you have to do it
```
Upvotes: -1 <issue_comment>username_3: In my own project I have been using `evaluateJavascript(script,null)` in onPageFinished to hide html elements. `view.loadUrl()` Should work the same way.
If you don't need the function be called at later time you could simplify your JS string and instead of `\"` try using `'`.
```
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:document.getElementById('imPage').style.display='none';");}
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 803 | 3,000 |
<issue_start>username_0: I am receiving this error in Android Studio:
```
Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
```
With this app gradle file:
```
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 26
buildToolsVersion "26.0.3"
defaultConfig {
applicationId "com.example.android.kotlintest"
minSdkVersion 23
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation "com.android.support:appcompat-v7:$supportVersion"
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation "com.android.support:design:$supportVersion"
implementation "com.android.support:support-v13:$supportVersion"
testCompile 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.github.bumptech.glide:glide:3.8.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
}
repositories {
mavenCentral()
}
```
Also, the `$supportVersion` is = `'26.+'`
I cannot figure out what configuration is causing this. I have tried clean & rebuild, and I added `multiDexEnabled true` and nothing has worked.
Any help would be greatly appreciated!<issue_comment>username_1: `document.getElementById(\"imPage\")` must be returning `null`.
So there is either no `imPage`element or you haven't loaded the page at the time.
I would suggest moving your entire js code into
```
document.addEventListener("DOMContentLoaded", function(event) {
//insert here
});
```
Upvotes: 1 <issue_comment>username_2: You have to enable Javascript Seetings like below :-
```
view.getSettings().setJavaScriptEnabled(true); //Yes you have to do it
```
Upvotes: -1 <issue_comment>username_3: In my own project I have been using `evaluateJavascript(script,null)` in onPageFinished to hide html elements. `view.loadUrl()` Should work the same way.
If you don't need the function be called at later time you could simplify your JS string and instead of `\"` try using `'`.
```
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:document.getElementById('imPage').style.display='none';");}
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,231 | 3,606 |
<issue_start>username_0: This is a common, basic task, so it would be good to know an appropriate way to do this. A similar program in C++ might look like this ([ref](https://www.geeksforgeeks.org/command-line-arguments-in-c-cpp/)):
```
#include
using namespace std;
int main(int argc, char\*\* argv)
{
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
}
```
In this example, we are printing out each of the arguments on the command line. So that running the programming like `./main.exe asdf 1234 bob` would give:
```
./main.exe
asdf
1234
bob
```<issue_comment>username_1: This is very similar to the same kind of program in C, with a few differences related to constraints and linear types. The constraints are straightforward once set up:
```
(*
Run patscc -o hello hello.dats
*)
#include "share/atspre_staload.hats"
implement main0{n}
(argc, argv): void = {
fun echoArgs{i:nat | i < n}
(ii: int(i), argv: !argv(n)): void = {
val () = println!("arg ", ii, " is ", argv[ii])
val () = if ii + 1 < argc then echoArgs(ii + 1, argv)
}
val () = echoArgs(0, argv)
}
```
Since we need to access the contents of `argv`, we have to change the view of its viewtype by supplying the linear-dependent type `!argv(n)`; the `!` [corresponds](http://ats-lang.sourceforge.net/DOCUMENT/ATS2TUTORIAL/HTML/ATS2TUTORIAL-BOOK-onechunk.html#linlist) to the bang in [linear logic](https://www.quora.com/What-is-linear-logic) indicating that values of that type are still available after the function call; the (`n`) just means `argv` is a string array of size `n`. We have to guarantee the index `i` into the array is less than the size `n` of the array.
Upvotes: 2 <issue_comment>username_2: Here is a combinator-based style:
```
#include "share/atspre_staload.hats"
#include "share/atspre_staload_libats_ML.hats"
implement
main0(argc, argv) = let
//
val args = listize_argc_argv(argc, argv)
//
in
list0_foreach(args, lam(arg) => println!(arg))
end // end of [main0]
```
Upvotes: 1 <issue_comment>username_3: Probably, the more common desire is to get flags and arguments from the command line, to change program behavior. For this, you can just use getopt (or with slightly more complexity but a much nicer CLI interface, GNU getopt). These functions do basically everything for you.
For a somewhat silly example:
```
#include "share/atspre_staload.hats"
%{^
#include
%}
extern fun getopt{n:int}(argc: int, argv: !argv(n), flags: string): int = "mac#"
val trad = ref(false)
val color = ref(false)
val progname = ref("hello4")
fn get\_progname{n:int}(argc: int(n), argv: !argv(n)): void =
if argc > 0 then
!progname := argv[0]
implement main0(argc, argv) = (
get\_progname(argc, argv);
process\_args(argc, argv);
case+ (!trad, !color) of
| (true, true) => println!("\033[31;1mhello world\033[0m")
| (true, false) => println!("hello world")
| (false, true) => println!("\033[31;1mHello, world!\033[0m")
| (false, false) => println!("Hello, modern world!")
) where {
fn usage(): void = (
fprintln!(stderr\_ref, "usage: ", !progname, " [-htc]");
exit(1);
)
fun process\_args{n:int}(argc: int, argv: !argv(n)): void =
let
val r = getopt(argc, argv, "htc")
in
if r >= 0 then (
ifcase
| r = 'h' => usage()
| r = 't' => (!trad := true; process\_args(argc, argv))
| r = 'c' => (!color := true; process\_args(argc, argv))
| \_ => (println!("fell through with: ", $UNSAFE.cast{char}(r)); usage())
)
end
}
```
Usage:
```
$ ./hello4
Hello, modern world!
$ ./hello4 -t
hello world
$ ./hello4 -c
Hello, world! <-- this is red
```
Upvotes: 1
|
2018/03/14
| 301 | 1,169 |
<issue_start>username_0: Sorry for confusing you with the terms. I may not be explaining correctly.
I have created a new field called Request Title (refname:SAM.OI.Requesttitle) and my Work Item Type name is Request Details.
Note: Not using refname System.Title.
Please see below screen shot. for my custom WIT.. Entered Test Request Title is not displayed next to the New Request Details 3\*:... if you see for default Task WIT entered Task Title is displayed next to New Task 2\*: Task Title.
Help me on how to fix to show the Request title Next to Request Details.
<issue_comment>username_1: There is no way to show the Request title Next to Request Details. Only the default Title can be shown there.
You could use the default Title field and add label `Request Title` to it, in this way, you will get the behavior you want:
[](https://i.stack.imgur.com/FJbuK.png)
Upvotes: 0 <issue_comment>username_2: Added a Rule to Title Field Definition to Copy the Request title value to Title. It is working as expected.
Upvotes: 1
|
2018/03/14
| 270 | 963 |
<issue_start>username_0: I am currently using the below code to define an array from the active workbook
```
Dim MyRangeArray As Variant
MyRangeArray = Array(Sheet1.Range("A4:N19"), Sheet2.Range("A4:N19"))
```
I want this array to reference data from another workbook instead of the workbook which has the code. The result i am looking for is:
```
MyRangeArray= Array(Wb1.sheets.RangeX,wb2.sheets.rangeX)
```
Can somebody help?<issue_comment>username_1: There is no way to show the Request title Next to Request Details. Only the default Title can be shown there.
You could use the default Title field and add label `Request Title` to it, in this way, you will get the behavior you want:
[](https://i.stack.imgur.com/FJbuK.png)
Upvotes: 0 <issue_comment>username_2: Added a Rule to Title Field Definition to Copy the Request title value to Title. It is working as expected.
Upvotes: 1
|
2018/03/14
| 333 | 1,110 |
<issue_start>username_0: For example we have class `a` and `b`, and following is the markup
```css
body {
position: relative;
}
.b {
position: absolute;
top: 0px;
}
```
```html
This is class a
class b
```
Is there a way so that the part of class `a` that is being overlapped by class `b` can be hidden completely?<issue_comment>username_1: Maybe a background to the `.b`. Since there is no relation between both elements, I don't think there is another way.
```css
body {
margin: 0;
}
.b {
position: absolute;
top: 0px;
background: #fff;
}
```
```html
This is class a
class b
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I'm not sure I fully understand the question... but if your goal is to make "b" fully opaque in covering up "a", then you might get the flexibility you're looking for by using the :before and :after pseudo-elements to act like separate layers of "b."
<https://css-tricks.com/pseudo-element-roundup/>
Or if you're just having trouble getting "b" to be on top of "a", make sure that "b" has a z-depth greater than a.
Upvotes: 0
|
2018/03/14
| 1,291 | 4,381 |
<issue_start>username_0: I would like to print a string representing a Date, using a specific timezone, locale, and display options.
Which one of these should I use?
1. [Intl.DateTimeFormat.prototype.format](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/format)
2. [Date.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)
It seems like they return identical results.
```js
const event = new Date(1521065710000);
const options = {
day: 'numeric',
month: 'long',
weekday: 'short',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short',
timeZone: 'America/Los_Angeles',
};
console.log(event.toLocaleString('en-US', options));
// "Wed, March 14, 3:15 PM PDT"
console.log(new Intl.DateTimeFormat('en-US', options).format(event));
// "Wed, March 14, 3:15 PM PDT"
```<issue_comment>username_1: This is very close to being off–topic as opinion based, but here goes anyway.
>
> Which one of these should I use?
>
>
>
*Date.prototype.toLocaleString* was originally solely implementation dependent and varied quite a bit across browsers. When support for the Intl object was added (ECMAScript 2015, ed 6) then *toLocaleString* was allowed to support the same options. While support isn't mandated by ECMA-262, probably all current implementations support it.
Note that this did not remove the allowed implementation variability, it just provided some formatting options based on language, region and dialect (and also timezone options based on the [IANA time zone database](https://www.iana.org/time-zones) identifiers and values).
The Intl object (and hence *toLocaleString*) is based on [ECMA-402](https://tc39.github.io/ecma402/#intl-object), which doesn't strictly specify formatting, so there is still some room for implementations to differ. The biggest differences are in regard to timezone names (for which there is no standard) and placement of commas, spaces, etc.
However, for most practical purposes, whether you use the Intl object or *toLocaleString* is up to you, I don't think there's any technical reason to prefer one over the other. While the results for both should be identical for a particular implementation, don't expect the resulting string to be **exactly** identical across implementations or to conform to a particular format for a given [BCP 47 language tag](https://www.rfc-editor.org/rfc/rfc5646).
Upvotes: 6 [selected_answer]<issue_comment>username_2: The Internationalisation API [isn't supported](https://caniuse.com/#feat=internationalization) in all browsers just yet - notably, IE10 and below and UC Browser for Android 11.8. If you want to support those browsers, use ToLocaleString. (Though if the Internationalisation API isn't supported, what ToLocalString returns is implementation-dependent.)
Intl.DateTimeFormat.prototype.format is designed for the use of formatting large groups of Dates - rather than setting the locale and options every time, you set them once and use the resulting format function from then on.
Upvotes: 2 <issue_comment>username_3: Addition to points that others issued, I saw a difference with ***default formats (options)***:
```js
const event = new Date(1521065710000)
//const o = options
console.log(event.toLocaleString('en-US' /*, o*/)) // "3/15/2018, 1:45:10 AM"
console.log(new Intl.DateTimeFormat('en-US' /*, o*/).format(event)) // "3/15/2018"
```
Tested on Chrome v72 - v85 / Node v14.
Upvotes: 3 <issue_comment>username_4: If you re-use the same format a lot of times, re-using `Intl.DateTimeFormat` object seems to be better from a performance perspective.
```js
const format = {
weekday: 'long',
month: 'long',
day: '2-digit',
};
const dateTimeFormat = new Intl.DateTimeFormat('en', format);
const start1 = performance.now();
for (let i = 0; i < 10000; i++) dateTimeFormat.format(new Date());
console.log('re-use Intl.DateTimeFormat', performance.now() - start1);
const start2 = performance.now();
for (let i = 0; i < 10000; i++) new Date().toLocaleString('en', format);
console.log('use toLocaleString', performance.now() - start2);
```
When I run this snippet in Chrome 105, it gives me a result like this:
```
re-use Intl.DateTimeFormat 17.299999952316284
use toLocaleString 876.0999999046326
```
Upvotes: 2
|
2018/03/14
| 995 | 3,086 |
<issue_start>username_0: I'd like my parent div to expand the height of the content, as my content will be dynamic. However, the content must be (I think) positioned absolutely so they can overlap each other vertically.
I've concluded I'll have to use JS to find the offset from the top to the bottom of the last element in the container, then set the height to that.
I'm currently doing something like this:
```
var lastElement = document.getElementById('three');
var bounds = lastElement.getBoundingClientRect();
var bottomOffset = bounds.top + $("#three").height();
$("#container").height(bottomOffset);
```
However this is clunky within my application, and the application of the height is not instantaneous, leading to a sluggy site.
Is there a better way?
```js
var lastElement = document.getElementById('three');
var bounds = lastElement.getBoundingClientRect();
var bottomOffset = bounds.top + $("#three").height();
$("#container").height(bottomOffset);
```
```css
body,
html {
height: 100% padding: 0;
margin: 0;
}
.absolute {
display: inline-block;
position: absolute;
background-color: blue;
width: 100px;
height: 100px;
}
#two {
top: 80px;
left: 120px
}
#three {
top: 160px;
left: 240px;
}
#container {
position: relative;
width: 100%;
;
background-color: yellow;
;
}
```
```html
```
[View on JSFiddle](https://jsfiddle.net/d815x4h1/)<issue_comment>username_1: Perhaps taking out the `getBoundingClientRect()` function, using jQuery instead might speed it up and simplify it a bit.
```js
var lastElement = $('#three');
var bottomOffset = lastElement.offset().top + lastElement.height();
$("#container").height(bottomOffset);
```
```css
body,
html {
height: 100% padding: 0;
margin: 0;
}
.absolute {
display: inline-block;
position: absolute;
background-color: blue;
width: 100px;
height: 100px;
}
#two {
top: 80px;
left: 120px
}
#three {
top: 160px;
left: 240px;
}
#container {
position: relative;
width: 100%;
;
background-color: yellow;
;
}
```
```html
```
Upvotes: 0 <issue_comment>username_2: You can accomplish your result without any JS, but instead use CSS `margin` around the boxes to get the same result.
For the horizontal margin you can also use percentages (by request of OP).
For the vertical margins this will give unexpected results, since the percentage will still reference the **[width of the container (under "Property Values")](https://www.w3schools.com/cssref/pr_margin-top.asp), not the height**.
```css
html,body {height:100%; padding:0; margin:0;}
.container {
background-color: yellow;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 2%;
background-color: blue;
}
.box.one {margin-top:0; margin-bottom:160px;}
.box.two {margin-top:80px; margin-bottom:80px;}
.box.three {margin-top:160px; margin-bottom:0;}
```
```html
```
**pixel-margin: <https://jsfiddle.net/xzq64tsh/>**
**percent-margin: <https://jsfiddle.net/xzq64tsh/3/>**
Upvotes: 1
|
2018/03/14
| 703 | 2,508 |
<issue_start>username_0: I am trying to package(maven package) and run(java -jar file.jar) a project that contains both java and kotlin code. I have followed the tutorial at: <https://michaelrice.com/2016/08/hello-world-with-kotlin-and-maven/>
`kotlin source src/main/kotlin
java source src/main/java`
the file I am trying to run is located in `src/main/kotlin/THEFILE.kt`
After succesfull packaging trying to run the jar I get an error `Error: Could not find or load main class THEFILEKt`
What can be the reason for this and how to fix it?
Thanks in advance!!!
Pom.xml includes a necessary kotlin plugins and dependency:
```
org.jetbrains.kotlin
kotlin-stdlib-jdk8
${kotlin.version}
org.springframework.boot
spring-boot-maven-plugin
org.jetbrains.kotlin
kotlin-maven-plugin
${kotlin.version}
compile
compile
compile
src/main/java
src/main/kotlin
test-compile
test-compile
test-compile
1.8
org.apache.maven.plugins
maven-compiler-plugin
default-compile
none
default-testCompile
none
java-compile
compile
compile
java-test-compile
test-compile
testCompile
compile
compile
compile
testCompile
test-compile
testCompile
org.apache.maven.plugins
maven-jar-plugin
2.6
true
THEFILEKt
org.apache.maven.plugins
maven-assembly-plugin
2.6
make-assembly
package
single
THEFILEKt
jar-with-dependencies
```<issue_comment>username_1: There are some issues when you have both java and kotlin code. I noticed the following -
* If I had a folder called src/main/java, then the main class needed to be written in Java.
* If I had a folder called src/main/kotlin, then the main class needed to be written in kotlin.
I did not try with both java and kotlin source folders.
I would suggest that you move all your java code to the kotlin folder. It will still work. Perhaps when there is a java folder, it expects the main class to be in java? Not sure.
Upvotes: 1 <issue_comment>username_2: I had the same problem until I deleted maven-compiler-plugin. pom.xml build block:
```
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-surefire-plugin
false
org.projectlombok
lombok-maven-plugin
1.16.8.0
generate-sources
delombok
org.jetbrains.kotlin
kotlin-maven-plugin
${kotlin.version}
compile
process-sources
compile
src/main/java
src/main/kotlin
target/generated-sources/annotations
test-compile
test-compile
test-compile
src/test/java
src/test/kotlin
1.8
```
Upvotes: -1
|
2018/03/14
| 550 | 1,836 |
<issue_start>username_0: How to write a SQL statement (in SQL Server) to get a row with minimum value based on two columns?
For example:
```
Type Rank Val1 val2
------------------------------
A 6 486.57 38847
B 6 430 56345
C 5 390 99120
D 5 329 12390
E 4 350 11109
E 4 320 11870
```
The SQL statement should return the last row in above table, because it has min value for Rank, and Val1.<issue_comment>username_1: I'm assuming that **Type** is the primary key for your table, and that you only want a row that has both the lowest Val1 and lowest Val2 (so if one row has the lowest Val1, but not the lowest Val2, this returns no data). I'm not sure about these assumptions, but your question could probably be clarified a bit.
Here's the code:
```
SELECT
*
FROM
Table1
WHERE
Type IN
(
SELECT
Type
FROM
Table1
GROUP BY
Type
HAVING
MIN(Val1) AND MIN(val2)
)
```
Upvotes: 0 <issue_comment>username_2: Something like this:
```
select *
from Table1
where rank = (select min(rank) from Table1)
and Val1 = (select min(Val1)
from Table1
where rank = (select min(rank) from Table1))
```
Or this, if you like a simple life:
```
select top 1 *
from Table1
order by rank asc, Val1 asc
```
Upvotes: 1 <issue_comment>username_3: ```
with cte as (
select *, row_number() over (order by rank, val1) as rn
from dbo.yourTable
)
select *
from cte
where rn = 1;
```
The idea here is that I'm assigning a 1..n enumeration to the rows based on rank and, in the case of ties, Val1. I return the row that takes the value of 1. If there is the possibility of a tie, use `rank()` instead of `row_number()`.
Upvotes: 1
|
2018/03/14
| 2,298 | 10,228 |
<issue_start>username_0: I am trying to write an AppleScript to be triggered by hotkey in Keyboard Maestro on MacOS
What I want to do, and please do not suggest **ANYTHING ELSE**, **such as hide all**, or hide functionality. I am looking for **minimize all** open windows functionality, ***including the animation***.
I can already do hide all.
So what I want to do is **iterate** **all** open windows, and **trigger** the menu option **Window -> Minimize** or if possible trigger minimize in a different manner.
Here is what I have so far but it is not fully working, **only partially**:
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
---activate
tell menu bar item "Window" of menu bar 1
click menu item "Minimize" of menu 1
end tell
end tell
delay 1
end repeat
```
Note, some applications will have a **Minimise without a z for Minimize.** . Would be good if the solution triggered some global minimize action **rather** than go through the **menu** **system**.<issue_comment>username_1: I believe I was able to at least get a working version from the one above.
I think I got some errors when the menu minimize did not exist, so I added try catch for that, and a fallback to hide.
This script should work:
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
try
tell menu bar item "Window" of menu bar 1
try
click menu item "Minimize" of menu 1
on error
try
click menu item "Minimise" of menu 1
on error
--- Optional, fallback
set visible to false
end try
end try
end tell
on error
--- Optional, fallback
set visible to false
end try
end tell
delay 0.005
end repeat
```
Upvotes: 0 <issue_comment>username_1: Another slower solution found online:
```
tell application "System Events"
repeat with appProc in (every application process whose visible is true)
click (first button of every window of appProc whose role description is "minimize button")
end repeat
end tell
```
Upvotes: 1 <issue_comment>username_2: Here is my original answer to your proposed problem, that was stated ought to work in fairly recent(*ish*) versions of MacOS:
```
use application "System Events"
set _P to a reference to (every process whose class of windows contains window)
set _W to a reference to (windows of _P whose value of attribute "AXMinimized" is false)
set value of attribute "AXMinimized" of _W to true
```
What I could have added was that, if we plug the value of each variable into the next line where it's referenced, and (for simplicity) choose to ignore the filtering used against the processes and windows, it becomes apparent that those four lines will evaluate at compile time to this single line of code:
```
tell application "System Events" to set value of attribute "AXMinimized" of windows of processes to false
```
However, you (the OP) reported that it was slow and not always reliable, and likely didn't use an iterative method but a recursive one.
I'm awaiting details of the circumstances under which the script above was found not to be reliable.
You asked whether I could produce code of a similarly-iterative nature/structure to [one of your proposed methods](https://stackoverflow.com/a/49338952/9051006).
This is the script that blends the functionality of my original script with the code structure taken from yours:
```
use application "System Events"
get the name of every application process whose class of windows contains window
repeat with P in the result
get (every window of process (contents of P) whose value of attribute "AXMinimized" is false)
repeat with W in the result
set the value of attribute "AXMinimized" of (contents of W) to true
end repeat
end repeat
```
Just as your script does, the one here explicitly iterates through all of the application processes retrieved against a filter (the filter in yours is the property `visible` for each `process`, whilst the filter in mine is collection of `window` objects of each `process`). You are free to change if you feel the need to.
However, once inside the `repeat` loop that iterates through the `processes`, what your script neglected to do was to iterate through every window that belongs to the each process. This is why you needed the fallback statement that sets the `visible` property to `false`, which is simply hiding the application process (something you explicitly stated in your OP that you did **not** want to do).
Without the `visible` property being set, the only other action performed is clicking the `Minimize` menu item **once** for each process. This will trigger the *front* window (i.e. the one that currently has focus) of that application process to minimise, but all other windows belonging to it remain unaffected, meaning only **one** window for each application process will get minimised. The rest are all just hidden by the visibility toggle.
The remedy for this was to set up a second `repeat` loop nested inside the first, which iterates through all the windows of a specific process retrieved against a filter (which, as before, I chose to be the `AXMinimized` attribute).
Then it's just a simple matter of setting the `AXMinimized` attribute for each window to `true`.
As you pointed out, one advantage of your script is that it appears to minimise the windows faster than mine. From what I can tell, it appears, for **some** reason, that the actual minimise *animation* is swifter when triggered using the menu than when triggered through the setting of an attribute value. So I then went ahead and created a script that doesn't try and set the attributes of the windows, but instead uses your mechanism of clicking the `Minimize` menu item:
```
use application "System Events"
set _P to a reference to (every application process whose visible is true)
repeat with P in (_P as list)
set frontmost of P to true
set _M to (a reference to menu 1 of menu bar item "Window" of menu bar 1 of P)
set _minimise to (a reference to menu item "Minimise" of _M)
set _minimize to (a reference to menu item "Minimize" of _M)
set _W to windows of P
set n to count _W
if n > 0 then perform action "AXRaise" of _W's front item
repeat n times
if (_minimize exists) and (_minimize is enabled) then
click _minimize
else if (_minimise exists) and (_minimise is enabled) then
click _minimise
end if
end repeat
end repeat
```
This script is essentially the reworked version of yours, using the same filtering criteria for its processes (`whose visible is false`) and clicking the menu item `Minimize` (or `Minimise`) to minimise the windows. It contains both the outside `repeat` loop for the `processes`, and the inside `repeat` loop for the `windows`.
Honestly, it's hard to say which appears to minimise windows more swiftly than the other, so I'll let you be the judge of that.
However, recalling what you stated in your original brief, you specifically asked:
* For a *"global* minimize *action rather than [to] go through the menu system"*;
* Not to offer other suggestions *"such as 'hide all', or 'hide' functionality. I am looking for [a] 'minimize-all-open-windows' functionality"*;
* To *"[include] the animation."*
Being frank about it, there's still only one solution that satisfies all of these criteria, and that's the original answer that I posted. Other solutions you found either don't work or rely on hiding the application windows; the last contribution I provided above works, but utilises the menu items, which is not your ideal method; and the script before that, which first demonstrated the nesting of two `repeat` loops in order to iterate through both processes **and** windows can be demonstrated through inductive reasoning to be an identical script to my original solution, which, despite not have explicit iterative statements you're used to seeing in a programming language, **does** still iterate through the `process` and `window` objects behind the scenes.
You can, of course, choose whichever method you wish, as it is your project and your ultimate satisfaction that is important in the creation of a tool that you'll be the one utilising from day-to-day. But, to give my honest and final opinion on the best method to achieve what you're setting out to do, I would strongly suggest you choose the compacted form of my first answer, which is this very elegant and simple line of code:
```
tell application "System Events" to set value of attribute "AXMinimized" of windows of processes to false
```
Upvotes: 2 <issue_comment>username_1: **Another working example, best so far.**
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
try
tell menu bar item "Window" of menu bar 1
try
click menu item "Minimize" of menu 1
on error
try
click menu item "Minimise" of menu 1
end try
end try
end tell
end try
delay 0.1
set visible to false
end tell
end repeat
```
Upvotes: -1 [selected_answer]
|
2018/03/14
| 2,378 | 10,097 |
<issue_start>username_0: Say I have 3 lists of the same dimensions which contains elements of velocity, distance and time.
```
V = [1, 2, 3, 4, -5, 4, 3, 2, 1]
D = [10, 9, 8, 7, 6, 5, 4, 3, 2]
T = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
If I want to find the minimum velocity in my V list I can just do
```
np.amin(V)
```
and I will get 5 in this case. But then how do I go about printing/getting/returning my value of D and T at that specific V? I have tried something like this
```
def MAXVTIME(VELOCITY, DISTANCE, TIME):
for i, (VELOCITY, DISTANCE, TIME) in enumerate(zip(VELOCITY, DISTANCE, TIME)):
if VELOCITY == np.amin(VELOCITY):
return VELOCITY.i(np.amin(VELOCITY))
```
but I can't get it to work. I need my function to be able to input 3 lists of velocity, distance and time, choose the smallest velocity value, and return the velocity, distance and time at that value.
Think of this as a person falling down, its smallest speed will be its maximum velocity(taking downwards as negative), and the distance is decreasing while time is ticking.<issue_comment>username_1: I believe I was able to at least get a working version from the one above.
I think I got some errors when the menu minimize did not exist, so I added try catch for that, and a fallback to hide.
This script should work:
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
try
tell menu bar item "Window" of menu bar 1
try
click menu item "Minimize" of menu 1
on error
try
click menu item "Minimise" of menu 1
on error
--- Optional, fallback
set visible to false
end try
end try
end tell
on error
--- Optional, fallback
set visible to false
end try
end tell
delay 0.005
end repeat
```
Upvotes: 0 <issue_comment>username_1: Another slower solution found online:
```
tell application "System Events"
repeat with appProc in (every application process whose visible is true)
click (first button of every window of appProc whose role description is "minimize button")
end repeat
end tell
```
Upvotes: 1 <issue_comment>username_2: Here is my original answer to your proposed problem, that was stated ought to work in fairly recent(*ish*) versions of MacOS:
```
use application "System Events"
set _P to a reference to (every process whose class of windows contains window)
set _W to a reference to (windows of _P whose value of attribute "AXMinimized" is false)
set value of attribute "AXMinimized" of _W to true
```
What I could have added was that, if we plug the value of each variable into the next line where it's referenced, and (for simplicity) choose to ignore the filtering used against the processes and windows, it becomes apparent that those four lines will evaluate at compile time to this single line of code:
```
tell application "System Events" to set value of attribute "AXMinimized" of windows of processes to false
```
However, you (the OP) reported that it was slow and not always reliable, and likely didn't use an iterative method but a recursive one.
I'm awaiting details of the circumstances under which the script above was found not to be reliable.
You asked whether I could produce code of a similarly-iterative nature/structure to [one of your proposed methods](https://stackoverflow.com/a/49338952/9051006).
This is the script that blends the functionality of my original script with the code structure taken from yours:
```
use application "System Events"
get the name of every application process whose class of windows contains window
repeat with P in the result
get (every window of process (contents of P) whose value of attribute "AXMinimized" is false)
repeat with W in the result
set the value of attribute "AXMinimized" of (contents of W) to true
end repeat
end repeat
```
Just as your script does, the one here explicitly iterates through all of the application processes retrieved against a filter (the filter in yours is the property `visible` for each `process`, whilst the filter in mine is collection of `window` objects of each `process`). You are free to change if you feel the need to.
However, once inside the `repeat` loop that iterates through the `processes`, what your script neglected to do was to iterate through every window that belongs to the each process. This is why you needed the fallback statement that sets the `visible` property to `false`, which is simply hiding the application process (something you explicitly stated in your OP that you did **not** want to do).
Without the `visible` property being set, the only other action performed is clicking the `Minimize` menu item **once** for each process. This will trigger the *front* window (i.e. the one that currently has focus) of that application process to minimise, but all other windows belonging to it remain unaffected, meaning only **one** window for each application process will get minimised. The rest are all just hidden by the visibility toggle.
The remedy for this was to set up a second `repeat` loop nested inside the first, which iterates through all the windows of a specific process retrieved against a filter (which, as before, I chose to be the `AXMinimized` attribute).
Then it's just a simple matter of setting the `AXMinimized` attribute for each window to `true`.
As you pointed out, one advantage of your script is that it appears to minimise the windows faster than mine. From what I can tell, it appears, for **some** reason, that the actual minimise *animation* is swifter when triggered using the menu than when triggered through the setting of an attribute value. So I then went ahead and created a script that doesn't try and set the attributes of the windows, but instead uses your mechanism of clicking the `Minimize` menu item:
```
use application "System Events"
set _P to a reference to (every application process whose visible is true)
repeat with P in (_P as list)
set frontmost of P to true
set _M to (a reference to menu 1 of menu bar item "Window" of menu bar 1 of P)
set _minimise to (a reference to menu item "Minimise" of _M)
set _minimize to (a reference to menu item "Minimize" of _M)
set _W to windows of P
set n to count _W
if n > 0 then perform action "AXRaise" of _W's front item
repeat n times
if (_minimize exists) and (_minimize is enabled) then
click _minimize
else if (_minimise exists) and (_minimise is enabled) then
click _minimise
end if
end repeat
end repeat
```
This script is essentially the reworked version of yours, using the same filtering criteria for its processes (`whose visible is false`) and clicking the menu item `Minimize` (or `Minimise`) to minimise the windows. It contains both the outside `repeat` loop for the `processes`, and the inside `repeat` loop for the `windows`.
Honestly, it's hard to say which appears to minimise windows more swiftly than the other, so I'll let you be the judge of that.
However, recalling what you stated in your original brief, you specifically asked:
* For a *"global* minimize *action rather than [to] go through the menu system"*;
* Not to offer other suggestions *"such as 'hide all', or 'hide' functionality. I am looking for [a] 'minimize-all-open-windows' functionality"*;
* To *"[include] the animation."*
Being frank about it, there's still only one solution that satisfies all of these criteria, and that's the original answer that I posted. Other solutions you found either don't work or rely on hiding the application windows; the last contribution I provided above works, but utilises the menu items, which is not your ideal method; and the script before that, which first demonstrated the nesting of two `repeat` loops in order to iterate through both processes **and** windows can be demonstrated through inductive reasoning to be an identical script to my original solution, which, despite not have explicit iterative statements you're used to seeing in a programming language, **does** still iterate through the `process` and `window` objects behind the scenes.
You can, of course, choose whichever method you wish, as it is your project and your ultimate satisfaction that is important in the creation of a tool that you'll be the one utilising from day-to-day. But, to give my honest and final opinion on the best method to achieve what you're setting out to do, I would strongly suggest you choose the compacted form of my first answer, which is this very elegant and simple line of code:
```
tell application "System Events" to set value of attribute "AXMinimized" of windows of processes to false
```
Upvotes: 2 <issue_comment>username_1: **Another working example, best so far.**
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
try
tell menu bar item "Window" of menu bar 1
try
click menu item "Minimize" of menu 1
on error
try
click menu item "Minimise" of menu 1
end try
end try
end tell
end try
delay 0.1
set visible to false
end tell
end repeat
```
Upvotes: -1 [selected_answer]
|
2018/03/14
| 2,389 | 10,176 |
<issue_start>username_0: I don't do much with VB and need some help to count/tally up the number of instances of a given value.
Data is in Column A and sorted by the value so all results are together just need a ongoing count till value changes or cell is blank.
Example of Sheet

```
Sub Rec_Label()
Path = "%UserProfile%"
Set ws = CreateObject("WScript.Shell")
fullpath = ws.ExpandEnvironmentStrings(Path)
'Create lines for number of labels based on Column "G"
ActiveSheet.Copy Before:=ActiveSheet
Application.ScreenUpdating = False
Dim vRows As Long, v As Long
On Error Resume Next
Dim ir As Long, mrows As Long, lastcell As Range
Set lastcell = Cells.SpecialCells(xlLastCell)
mrows = lastcell.Row
For ir = mrows To 2 Step -1
If Not IsNumeric(Cells(ir, 7)) Then
Cells(ir, 1).EntireRow.Delete
ElseIf Cells(ir, 1).Value > 1 Then
v = Cells(ir, 1).Value - 1
Rows(ir + 1).Resize(v).Insert Shift:=xlDown
Rows(ir).EntireRow.AutoFill Rows(ir). _
EntireRow.Resize(rowsize:=v + 1), xlFillCopy
ElseIf Cells(ir, 1).Value < 1 Then
Cells(ir, 1).EntireRow.Delete
End If
Next ir
'Fill-in Count based on column A
```<issue_comment>username_1: I believe I was able to at least get a working version from the one above.
I think I got some errors when the menu minimize did not exist, so I added try catch for that, and a fallback to hide.
This script should work:
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
try
tell menu bar item "Window" of menu bar 1
try
click menu item "Minimize" of menu 1
on error
try
click menu item "Minimise" of menu 1
on error
--- Optional, fallback
set visible to false
end try
end try
end tell
on error
--- Optional, fallback
set visible to false
end try
end tell
delay 0.005
end repeat
```
Upvotes: 0 <issue_comment>username_1: Another slower solution found online:
```
tell application "System Events"
repeat with appProc in (every application process whose visible is true)
click (first button of every window of appProc whose role description is "minimize button")
end repeat
end tell
```
Upvotes: 1 <issue_comment>username_2: Here is my original answer to your proposed problem, that was stated ought to work in fairly recent(*ish*) versions of MacOS:
```
use application "System Events"
set _P to a reference to (every process whose class of windows contains window)
set _W to a reference to (windows of _P whose value of attribute "AXMinimized" is false)
set value of attribute "AXMinimized" of _W to true
```
What I could have added was that, if we plug the value of each variable into the next line where it's referenced, and (for simplicity) choose to ignore the filtering used against the processes and windows, it becomes apparent that those four lines will evaluate at compile time to this single line of code:
```
tell application "System Events" to set value of attribute "AXMinimized" of windows of processes to false
```
However, you (the OP) reported that it was slow and not always reliable, and likely didn't use an iterative method but a recursive one.
I'm awaiting details of the circumstances under which the script above was found not to be reliable.
You asked whether I could produce code of a similarly-iterative nature/structure to [one of your proposed methods](https://stackoverflow.com/a/49338952/9051006).
This is the script that blends the functionality of my original script with the code structure taken from yours:
```
use application "System Events"
get the name of every application process whose class of windows contains window
repeat with P in the result
get (every window of process (contents of P) whose value of attribute "AXMinimized" is false)
repeat with W in the result
set the value of attribute "AXMinimized" of (contents of W) to true
end repeat
end repeat
```
Just as your script does, the one here explicitly iterates through all of the application processes retrieved against a filter (the filter in yours is the property `visible` for each `process`, whilst the filter in mine is collection of `window` objects of each `process`). You are free to change if you feel the need to.
However, once inside the `repeat` loop that iterates through the `processes`, what your script neglected to do was to iterate through every window that belongs to the each process. This is why you needed the fallback statement that sets the `visible` property to `false`, which is simply hiding the application process (something you explicitly stated in your OP that you did **not** want to do).
Without the `visible` property being set, the only other action performed is clicking the `Minimize` menu item **once** for each process. This will trigger the *front* window (i.e. the one that currently has focus) of that application process to minimise, but all other windows belonging to it remain unaffected, meaning only **one** window for each application process will get minimised. The rest are all just hidden by the visibility toggle.
The remedy for this was to set up a second `repeat` loop nested inside the first, which iterates through all the windows of a specific process retrieved against a filter (which, as before, I chose to be the `AXMinimized` attribute).
Then it's just a simple matter of setting the `AXMinimized` attribute for each window to `true`.
As you pointed out, one advantage of your script is that it appears to minimise the windows faster than mine. From what I can tell, it appears, for **some** reason, that the actual minimise *animation* is swifter when triggered using the menu than when triggered through the setting of an attribute value. So I then went ahead and created a script that doesn't try and set the attributes of the windows, but instead uses your mechanism of clicking the `Minimize` menu item:
```
use application "System Events"
set _P to a reference to (every application process whose visible is true)
repeat with P in (_P as list)
set frontmost of P to true
set _M to (a reference to menu 1 of menu bar item "Window" of menu bar 1 of P)
set _minimise to (a reference to menu item "Minimise" of _M)
set _minimize to (a reference to menu item "Minimize" of _M)
set _W to windows of P
set n to count _W
if n > 0 then perform action "AXRaise" of _W's front item
repeat n times
if (_minimize exists) and (_minimize is enabled) then
click _minimize
else if (_minimise exists) and (_minimise is enabled) then
click _minimise
end if
end repeat
end repeat
```
This script is essentially the reworked version of yours, using the same filtering criteria for its processes (`whose visible is false`) and clicking the menu item `Minimize` (or `Minimise`) to minimise the windows. It contains both the outside `repeat` loop for the `processes`, and the inside `repeat` loop for the `windows`.
Honestly, it's hard to say which appears to minimise windows more swiftly than the other, so I'll let you be the judge of that.
However, recalling what you stated in your original brief, you specifically asked:
* For a *"global* minimize *action rather than [to] go through the menu system"*;
* Not to offer other suggestions *"such as 'hide all', or 'hide' functionality. I am looking for [a] 'minimize-all-open-windows' functionality"*;
* To *"[include] the animation."*
Being frank about it, there's still only one solution that satisfies all of these criteria, and that's the original answer that I posted. Other solutions you found either don't work or rely on hiding the application windows; the last contribution I provided above works, but utilises the menu items, which is not your ideal method; and the script before that, which first demonstrated the nesting of two `repeat` loops in order to iterate through both processes **and** windows can be demonstrated through inductive reasoning to be an identical script to my original solution, which, despite not have explicit iterative statements you're used to seeing in a programming language, **does** still iterate through the `process` and `window` objects behind the scenes.
You can, of course, choose whichever method you wish, as it is your project and your ultimate satisfaction that is important in the creation of a tool that you'll be the one utilising from day-to-day. But, to give my honest and final opinion on the best method to achieve what you're setting out to do, I would strongly suggest you choose the compacted form of my first answer, which is this very elegant and simple line of code:
```
tell application "System Events" to set value of attribute "AXMinimized" of windows of processes to false
```
Upvotes: 2 <issue_comment>username_1: **Another working example, best so far.**
```
tell application "System Events"
set currentProcesses to name of every application process whose visible = true
end tell
repeat with tmpProcess in currentProcesses
tell application "System Events" to tell process tmpProcess
set frontmost to true
try
tell menu bar item "Window" of menu bar 1
try
click menu item "Minimize" of menu 1
on error
try
click menu item "Minimise" of menu 1
end try
end try
end tell
end try
delay 0.1
set visible to false
end tell
end repeat
```
Upvotes: -1 [selected_answer]
|
2018/03/14
| 262 | 1,016 |
<issue_start>username_0: When declaring a variable as dynamic:
```
dynamic var myProperty: Bool = true
```
is there any advantage or change in behavior by also adding the @objc marker?
```
@objc dynamic var myProperty: Bool = true
```<issue_comment>username_1: In Swift 4, `dynamic` variables will give a compilation error if they do not have the `@objc` attribute on them. So, you could say the ability to compile is an advantage of adding `@objc`.
Upvotes: 2 [selected_answer]<issue_comment>username_2: See Apple's documentation itself. It states
>
> Declarations marked with the dynamic modifier must also be explicitly marked with the @objc attribute unless the @objc attribute is implicitly added by the declaration’s context. For information about when the @objc attribute is implicitly added. See [Declaration Attributes](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Attributes.html#//apple_ref/doc/uid/TP40014097-CH35-ID348)
>
>
>
Upvotes: 0
|
2018/03/14
| 447 | 1,810 |
<issue_start>username_0: In my controller I have a loop that iterates through an arraylist and displays the attributes belonging to each object in the arraylist and I am wondering what should I put in my thymeleaf code because at the moment it is only displaying the information of the first object in the arraylist.
My Controller class
```
@GetMapping("/allSubjects")
public String shoSubjects(@ModelAttribute("subject") @Valid UserRegistrationDto userDto, BindingResult result, Model model) {
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
User user = userRepository.findByEmailAddress(email);
ArrayList subjects = new ArrayList();
for(Subject sub:user.getSubject())
{
subjects.add(sub.getSubjectName());
}
model.addAttribute("subjects", subjects);
if(!subjects.isEmpty()) {
for(int i = 0; i
```
My html class
```
<>Subject: ####
```
//I have this for each attribute I have just not added it in for this post.<issue_comment>username_1: In Swift 4, `dynamic` variables will give a compilation error if they do not have the `@objc` attribute on them. So, you could say the ability to compile is an advantage of adding `@objc`.
Upvotes: 2 [selected_answer]<issue_comment>username_2: See Apple's documentation itself. It states
>
> Declarations marked with the dynamic modifier must also be explicitly marked with the @objc attribute unless the @objc attribute is implicitly added by the declaration’s context. For information about when the @objc attribute is implicitly added. See [Declaration Attributes](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Attributes.html#//apple_ref/doc/uid/TP40014097-CH35-ID348)
>
>
>
Upvotes: 0
|
2018/03/14
| 487 | 1,629 |
<issue_start>username_0: I've just started to practice and I cant find any info. Why is "o" defined as blank and later reappearing in other line of code as different.Thank you in advance.
```js
function TriangleOfStars() {
for (var i = 1; i <= 10; i++) {
var o = "";
for (var j = 1; j <= i; j++) {
o += "*"
}
console.log(o);
}
}
TriangleOfStars();
```<issue_comment>username_1: Here goes some information:
[Variable initalization:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)
```
var o="";
```
[Assignment operators:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators)
```
o += "*"
```
Upvotes: 0 <issue_comment>username_2: The third line is defining the variable o as an empty string (as you mentioned). The fifth line is adding an asterisk. That is what the += sign means. So every time it reaches line 5, an asterisk will be appended to the string.
As said in the comment by username_3, it is useful to look at the console because that way you can see the result is a triangle pointing upwards. That will help you to understand it.
Upvotes: 3 [selected_answer]<issue_comment>username_3: For every iteration in the outer for loop, `o` is defined as empty. The inner loop will concatinate a `*` to `o` to build up a line of `*` based on the outer for loop like this:
```
* // i = 1
** // i = 2
*** // i = 3
**** // i = 4
***** // i = 5
****** // i = 6
******* // i = 7
******** // i = 8
********* // i = 9
********** // i = 10
```
Upvotes: 1
|
2018/03/14
| 422 | 1,728 |
<issue_start>username_0: I have a problem when rotating my Android App after doing some basic interactions, I keep getting a null error;
```
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
```
Whilst I know what the error means, I cannot see any reason why it would happen when rotating the device (happens both on my physical dev device and in the emulator). The code its complaining about is (which is in my onAttach method in a fragment);
```
TextView totalMatchGoals = (TextView) getView().findViewById(R.id.txtResInfoGoals);
```
Does rotating the device cause the view to refresh? Even then I can't think why that would cause problems.
All help is appreciated.<issue_comment>username_1: Do your checking inside `onCreateView()` after inflating the layout, or `onViewCreated()`, when views actually exist.
Upvotes: 0 <issue_comment>username_2: If you have not configured your AndroidManifest.xml to do otherwise, Android will destroy and recreate your whole activity when an orientation change is detected.
When recreating the activity, onAttach is called before the view is populated, as per: <https://developer.android.com/reference/android/app/Fragment.html>
If you want to handle the orientation change in the code of your activity, add the following:
AndroidManifest.xml
In your Activity class, override this method to deal with the orientation change:
```
@Override
public void onConfigurationChanged(Configuration newConfig) {}
```
More info:
* <https://developer.android.com/guide/topics/resources/runtime-changes.html>
* <http://code.hootsuite.com/orientation-changes-on-android/>
Upvotes: -1
|
2018/03/14
| 885 | 2,952 |
<issue_start>username_0: I want to have two names for the same atom in Prolog:
```
player(thomas).
player(william).
teamOfPlayer(thomas, redSocks).
teamOfPlayer(william, redSocks).
tom :- thomas.
will :- william.
teamOfPlayer(will, X).
```
I'd like to be able to refer to William using "william" atom and using "will" atom.
I know I could use a functor to define nicknames:
```
nick(tom, thomas).
nick(will, william).
```
and then,
```
nick(tom,X), teamOfPlayer(X, Y).
```
But I'd like to avoid all this verbosity.<issue_comment>username_1: Implementation specific facilities are available for this purpose - and much more. Indeed, given that identity it's 'at heart' of logic, rewriting rules to fit different identification strategies is not an uncommon problem.
In SWI-Prolog, you can use the [expansion hooks](http://www.swi-prolog.org/pldoc/man?section=progtransform), more specifically [goal\_expansion](http://www.swi-prolog.org/pldoc/doc_for?object=goal_expansion/2)/2.
In your module, add near the end-of-file (just a convention, though)
```
:- multifile user:goal_expansion/2.
user:goal_expansion(will, william).
user:goal_expansion(tom, thomas).
```
*edit*
Sorry, I didn't debugged my suggestion, and it turns out to be incorrect.
A possible correction could be:
```erlang
alias(will,william).
alias(tom,thomas).
:- multifile user:goal_expansion/2.
user:goal_expansion(player(X), player(Y)) :-
alias(X,Y).
user:goal_expansion(teamOfPlayer(X,T), teamOfPlayer(Y,T)) :-
alias(X,Y).
```
We could make the overloading rules more generic, but the problem is deeply rooted in language core. Atoms carry the fundamental property (from the relational data model viewpoint) of **identity**, then we can 'overload' an atom only in **specific** contexts.
Upvotes: 3 <issue_comment>username_2: You can define whether something IS A something else
```
player(tom) :- !.
player(thomas) :- player(tom), !.
```
Now Prolog can see that if a player is named `thomas` or `tom`, the goal is met, so they are treated as the same person.
Your first solution is preferable though, as `nick(tom,X), teamOfPlayer(X, Y).` is much less specific and therefore much more extensible and easier to maintain as you're not changing existing code, you're just adding new facts to the knowledge base.
By defining both rules, you give Prolog two ways to answer for X.
```
%is X a member of team Y?
isPartOfTeam(X,Y) :- teamOfPlayer(X,Y).
isPartOfTeam(X,Y) :- nick(X, Z), teamOfPlayer(Z, Y).
```
By defining these general rules, X can be solved by either finding a team in the fact `teamOfPlayer(X,Y)` directly, or by trying *every single nickname you've defined for a specific instance of X*. That's where the power of Prolog comes in. You can have 10000 nicknames for 1 guy and Prolog will go through a process called backtracking to choicepoints to check them all through these two simple rules defined above.
Upvotes: 1 [selected_answer]
|
2018/03/14
| 1,577 | 4,614 |
<issue_start>username_0: Suppose we have a list `cid = [1,1,1,2,2]`. The goal is loop over the list and each time replace the element at the cursor position with each one from a pool of candidates. The pool is all other elements not equal to the one in focus plus one more which is not contained in `cid`. For example for `cid = [1,1,1,2,2]`I want to end up with:
```
[[2 1 1 2 2]
[3 1 1 2 2]
[1 2 1 2 2]
[1 3 1 2 2]
[1 1 2 2 2]
[1 1 3 2 2]
[1 1 1 1 2]
[1 1 1 3 2]
[1 1 1 2 1]
[1 1 1 2 3]]
```
What I have written is:
```
arr = np.empty((0, len(cid)), int)
m = max(cid)
# Loop over the list
for i, j in enumerate(cid):
# make a pool of candidates
pool = set([x for x in cid if x != j])
# add a new element
pool.add(m+1)
# construct the new list
for idx in pool:
a = cid[:i] + [idx] + cid[i+1 :]
arr = np.append(arr, np.array([a]), axis=0)
print(arr)
```
Is there a better way to write this please? A real case scenario involves a list of length around 3000 containing almost 50 different integers (quite likely not sequential)<issue_comment>username_1: Instead of making a new set of candidates each time, create a master set before you enter the loop. Each iteration, simply remove the unwanted element to get a set for that index position.
Also, I think you can clean up the replacement logic a *little*. I tried using a product that would keep the head and tail constant and iterate through the desired index position, but that's not very readable. I finally settled on essentially your own handling, but actually replacing the desired element each time and then appending a copy:
```
cid = [1, 1, 1, 2, 2]
master = set(cid + [max(cid)+1])
solution = []
for idx, val in enumerate(cid):
print(idx, val)
cand = master - {val}
for elem in cand:
cid[idx] = elem
solution.append(cid[:])
print(solution)
cid[idx] = val
```
Output (line breaks inserted manually):
```
[[2, 1, 1, 2, 2],
[3, 1, 1, 2, 2],
[1, 2, 1, 2, 2],
[1, 3, 1, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 3, 2, 2],
[1, 1, 1, 1, 2],
[1, 1, 1, 3, 2],
[1, 1, 1, 2, 1],
[1, 1, 1, 2, 3]]
```
Upvotes: 2 <issue_comment>username_2: This will get the same output as the other answers, and as the OP, but the combination of numpy replacement and memoizing previously seen results can get a faster result on large inputs. When I tried the originally given code it took ~0.25 seconds when the given `cid` was `range(50)`, the timing results of different input `cid` on the code below is shown below. The given code is a lot faster than the originally given code, but how much depends on the given `cid`. The distribution of the input will matter, the more times you see a particular input the more that memoizing will help you :)
It's noted in the code, but when you get to large inputs you should probably start to break up the arrays being calculated and write them out somehow.
Also, from rough timing analysis it looks like most of the time goes into creating the `array` variable with `np.ones`. The actual replacement using numpy is quite fast. Hooray numpy :)
```
import numpy as np
cid = [1, 1, 1, 2, 2]
# cid = range(600) # ~0.23 seconds
# cid = range(100) * 6 # ~0.08 seconds
# cid = range(100) * 30 # ~1.1 seconds
# cid = range(300) * 10 # MemoryError
# Or whatever extra element you want
extra_element = max(cid) + 1
# By putting the set into an array format the pool[pool != j] step below
# becomes very fast
pool = np.array(list(set(cid)) + [extra_element])
# This is the number of available candidates to replace any individual element
num_available = len(pool) - 1
# Memoize results we've seen before
seen_elements = {}
# Create an array to hold the output. It's possible that this can get too
# large to hold in memory all at once, so you might want to consider breaking
# this up (maybe create a new array each for loop and then write it somewhere?)
array = np.ones((len(cid) * num_available, len(cid)), dtype=int) * np.array(cid)
# Replace the operational range each loop with the saved value, or populate
# the saved value as necessary
for i, j in enumerate(cid):
lower_bound = i * num_available
upper_bound = i * num_available + num_available
try:
array[lower_bound:upper_bound, i] = seen_elements[j]
except KeyError:
seen_elements[j] = pool[pool != j]
array[lower_bound:upper_bound, i] = seen_elements[j]
print array
[[2 1 1 2 2]
[3 1 1 2 2]
[1 2 1 2 2]
[1 3 1 2 2]
[1 1 2 2 2]
[1 1 3 2 2]
[1 1 1 1 2]
[1 1 1 3 2]
[1 1 1 2 1]
[1 1 1 2 3]]
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 525 | 1,737 |
<issue_start>username_0: I would like to select the label "`Autres méthode de paiement`" by using jQuery:
Here is a JSFiddle example: <https://jsfiddle.net/0dnd6qj4/>
```html
- Autres méthode de paiement
```<issue_comment>username_1: Need to select the label with jQuery? No problem. Use the tag selector, like this:
```
$("label")
```
Please check the API for more information:
<https://api.jquery.com/element-selector/>
Upvotes: -1 <issue_comment>username_2: You can use [**`:contains()` pseudo-class**](https://api.jquery.com/contains-selector/) in conjunction with the [`label` element/tag selector](https://api.jquery.com/element-selector/):
```js
$("label:contains('Autres méthode de paiement')")
```
If you have some specific data from the that is nested inside the (such as its `id` or a unique `name` attributes), you could use the [**`:has()` pseudo-class**](https://api.jquery.com/has-selector/):
```js
$("label:has(input[name='payment'])")
```
Demo below.
```js
console.log('using :contains()', $("label:contains('Autres méthode de paiement')")[0])
console.log('using :has()', $("label:has(input[name='payment'])")[0])
console.log('without jquery',
[].filter.call(document.querySelectorAll('label'), function(e) {
return e.textContent.includes('Autres méthode de paiement');
})[0]
);
```
```html
- Autres méthode de paiement
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You could target it by the nested input.
```
$('input').filter('[name="payment"]').closest('label');
```
Upvotes: 0 <issue_comment>username_4: I think you dont use label correctly...
```
Autres méthode de paiement
```
Then you can access the label like:
```
$("label[for='payment']")
```
Upvotes: 0
|
2018/03/14
| 504 | 1,622 |
<issue_start>username_0: I have tried a few things to try to get this to work. I was looking at this --
[Laravel Blade - pass variable via an @include or @yield](https://stackoverflow.com/questions/33938362/laravel-blade-pass-variable-via-an-include-or-yield) -- question about how to pass variables between blades but I can't seem to get it to work!
I have a view calling my header view (in /resources/views/layouts/frontendbasic.blade.php):
```
@include('common/head', array('url'=>'www.url.com'))
```
And in the header blade (in /resources/views/common/head.blade.php) I am calling that variable like this:
```
```
And I get the error:
```
Undefined variable: url
(View: ...\resources\views\common\head.blade.php)
(View: ...\resources\views\common\head.blade.php)
(View: ...\resources\views\common\head.blade.php)
```
I am wondering what I am doing wrong?<issue_comment>username_1: The correct thing is to pass a variable through the controller:
```
return view('view.path', [
'url' => 'www.url.com'
]);
```
however, try as below:
```
@include('common.head', ['url' => 'www.url.com'])
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: there are many way to done this. you can also use "compact" and "with" function for pass variable into blade in controller and blade also.
in controller
```
$info = 23; /* variable you want to pass into blade */
return view('view.path',compact('info'));
OR
return view('view.path')->with('info'=>$info);
```
in view
```
@include('view.path',compact('variable_name'));
OR
@include('view.path')->with('key' => $value);
```
Upvotes: 2
|
2018/03/14
| 1,319 | 3,628 |
<issue_start>username_0: I have a task to update a scala array like this:
```
val input = Seq[2, 1, 5, 4, 5, 1, 8, 4]
```
`input` is the array which needs to be updated. `label` is the index from which the elements in the array should be updated accordingly.
The updated rule for the elements is
```
new_value = the_current_value + value_of_last_labeled_elements
```
For example, if
```
val label = Seq(2)
```
then the desired result should be
```
input = Seq(2,1,5,4,5,1,8,4)
output = Seq(2,1,5,9,10,6,13,9)
```
There could be multiple labels:
```
val label = Seq(2,5)
```
Then the desired results should be:
```
input = Seq(2,1,5,4,5,1,8,4)
output = Seq(2,1,5,9,10,6,9,5)
```
The fifth element 5 was changed to 6, due to last labeled element is 5. From the sixth element, their values was updated by adding 1, due to the fifth elements is 1 in the original array.
I found this task can be easily handled in Java, by using two pointers in the loop. However, I have no idea how Scala could handle this.<issue_comment>username_1: ```
scala> def shiftFromIndexBy (input: List[Int], toShiftFrom: List[Int], shiftBy: Int = 0) : List [Int] = (input, toShiftFrom) match {
| case (Nil, _) => Nil
| case (x :: xs, Nil) => input.map (_ + shiftBy)
| case (x :: xs, y:: ys) => if (y == 0) x + shiftBy :: shiftFromIndexBy (xs, ys.map (_ - 1), x) else
| x + shiftBy :: shiftFromIndexBy (xs, toShiftFrom.map(_ - 1), shiftBy)
| }
shiftFromIndexBy: (input: List[Int], toShiftFrom: List[Int], shiftBy: Int)List[Int]
scala> shiftFromIndexBy (input, label)
res19: List[Int] = List(2, 1, 5, 9, 10, 6, 13, 9)
scala> shiftFromIndexBy (input, List (2, 5))
res20: List[Int] = List(2, 1, 5, 9, 10, 6, 9, 5)
```
There are 3 cases, the last one with two subcases.
* Case 0: Input is empty. Done.
* Case 1: Input is valid, but no more shiftings will come from the index list, which is empty. Then perform the addition of the carried value to the rest of the List - done.
* Case 2a: We have values in the index list. If the first one is zero, we have to finally shift the first input value by the number carried. We get this first value x as new shiftBy value. The indexes have to decrease by one.
* Case 2b: The first index isn't zero, so we keep adding the old shiftBy-value, decreasing the index values in the rest of the list.
For large numbers of input and few index values, calculating the number of values to transform with the shiftBy value at once and decreasing the index values at once, could be considered. But first make things work, then make them fast.
For convenience I used Lists, not Seq for implementing.
Upvotes: 2 <issue_comment>username_2: I wanted to see if I could do it without recursion (and, of course, without pointers).
```
def updateAfterIndex(input:Seq[Int], label: Seq[Int]): Seq[Int] = {
if (label.isEmpty) input
else {
val pad = Seq.fill(label.head + 1)(0) ++
(label :+ input.length - 1).sliding(2)
.flatMap { case Seq(a, b) => Seq.fill(b - a)(input(a)) }
input.zip(pad).map(t => t._1 + t._2)
}
}
```
It seems to work even for many examples of bad `label` content, e.g. an index out of range or in wrong order.
```
updateAfterIndex(Seq(2,1,5,4,5,1,8,4), Seq()) //res0: Seq[Int] = List(2, 1, 5, 4, 5, 1, 8, 4)
updateAfterIndex(Seq(2,1,5,4,5,1,8,4), Seq(2)) //res1: Seq[Int] = List(2, 1, 5, 9, 10, 6, 13, 9)
updateAfterIndex(Seq(2,1,5,4,5,1,8,4), Seq(2,5)) //res2: Seq[Int] = List(2, 1, 5, 9, 10, 6, 9, 5)
updateAfterIndex(Seq(2,1,5,4), Seq(5,2)) //res3: Seq[Int] = List(2, 1, 5, 4)
```
Upvotes: 1
|
2018/03/14
| 894 | 2,878 |
<issue_start>username_0: I'm trying to update the Table `LIQUIDITYACCOUNT` using the field `QUANTITY` which belongs to the table `STOCKACCOUNT`. Both tables have foreign key CLIENT\_ID.
```
update
lq
set
lq.AMOUNT = lq.AMOUNT + ( st.QUANTITY % @num) * @rompu
from
LIQUIDITYACCOUNT lq
inner join STOCKACCOUNT st on
lq.CLIENT_ID = st.CLIENT_ID
and
st.TITRE_ID = @id_titre
and
st.QUANTITY > 0
```
The table `STOCKACCOUNT` contains informations about `STOCKS` hold by a customer while the table `LIQUIDITYACCOUNT` contains information about cash money.
If the result of the subquery contains one row, it work. But it doesn't for multiple rows. And in this generally the case in my project since any customer can hold many shares of different stocks.
How can I make it work when the subquery returns multiple rows.<issue_comment>username_1: So the primary key on your lq table can be pk. Then the SQL for updating lq.AMOUNT with this logic is:
```
UPDATE
lq
SET
lq.AMOUNT = sq.newvalue
FROM
(
SELECT
lq.AMOUNT + ( st.QUANTITY % @num) * @rompu AS newvalue,
lq.pk
FROM
LIQUIDITYACCOUNT lq
INNER JOIN
STOCKACCOUNT st
ON
lq.CLIENT_ID = st.CLIENT_ID
AND
st.TITRE_ID = @id_titre
AND
st.QUANTITY > 0
) AS sq
WHERE
lq.pk = sq.pk
```
Upvotes: 0 <issue_comment>username_2: Purpose of the update seems odd but here it is
```
update lq
set lq.AMOUNT = lq.AMOUNT + stt.qty * @rompu
from LIQUIDITYACCOUNT lq
join ( select st.CLIENT_ID, sum(st.QUANTITY % @num) as qty
from STOCKACCOUNT st
where st.TITRE_ID = @id_titre
and st.QUANTITY > 0
group
by st.CLIENT_ID
) stt
on stt.CLIENT_ID = lq.CLIENT_ID
```
Upvotes: 1 <issue_comment>username_3: [@username_1](https://stackoverflow.com/users/3097559/username_1), [@username_2](https://stackoverflow.com/users/607314/username_2) and [@Dai](https://stackoverflow.com/users/159145/dai) thank you so much indeed. I have found a solution using `cursor` and `while` loop. Below is the code.
```
declare @id_client as varchar(50)
declare @amount as money
declare liq_cursor cursor for
SELECT
lq.AMOUNT + ( st.QUANTITY % @num) * @rompu AS newvalue,
lq.CLIENT_ID
FROM
LIQUIDITYACCOUNT lq
INNER JOIN
STOCKACCOUNT st
ON
lq.CLIENT_ID = st.CLIENT_ID
AND
st.TITRE_ID = @id_titre
AND
st.QUANTITY > 0
OPEN liq_cursor
FETCH NEXT FROM liq_cursor into @amount,@id_client
---
WHILE @@FETCH_STATUS=0
BEGIN
update LIQUIDITYACCOUNT set AMOUNT=@amount,
DATEMODIF=GETDATE()
where CLIENT_ID=@id_client
FETCH NEXT FROM liq_cursor into @amount,@id_client
END
close liq_cursor
deallocate liq_cursor
```
Upvotes: 0
|
2018/03/14
| 1,068 | 3,914 |
<issue_start>username_0: I am setting up a simple Nextjs boilerplate but can't seem to get the styled-components to work. In my file Header.tsx:
```
// Core Module Imports
import Link from "next/link";
import * as React from "react";
// Styled-Component Imports
import styled from "../theme/theme";
class Header extends React.Component {
render() {
return (
About Us
);
}
}
const StyledHeader = styled(Header)`
width: 100vw;
height: 10vh;
background: #2a2c39;
color: #ff0000;
link-style: none;
`;
export default StyledHeader;
```
As you can see, I set up a simple Header component and then below I used styled() to define my css. In my file Index.tsx:
```
// Core Module Imports
import * as React from "react";
import StyledHeader from "../components/Header";
class Index extends React.Component {
render() {
return (
Test Change
Example Div
);
}
}
export default Index;
```
Obviously I am doing something wrong because it is not working and all I get it an unstyled link. Can anyone point me in the right direction?<issue_comment>username_1: You need to pass `this.props.className` into the root element of `Header` so the styled wrapper can pass a generated class name in:
```
class Header extends React.Component {
render() {
return (
About Us
);
}
}
```
Upvotes: 2 <issue_comment>username_2: For anyone that sees this and has a similar issue, check out this:
<https://github.com/zeit/next.js/issues/1942#issuecomment-313925454>
Fixed my issue.
>
> Hey guys. At version 3.0.1-beta.13+, you could set passHref to Link (as a boolean property) to expose its href to styled-components (or any other library that wraps its tag).
>
>
>
```
const StyledLink = styled.a`
color: red;
background: blue;
`
export default ({ href, name }) => (
{name}
)
```
There are solutions in the GitHub issue for people using `next-routes`.
Upvotes: 3 [selected_answer]<issue_comment>username_3: **TL;DR:**
Create a `_document.js` file in your `/pages` folder and paste this in. It should work immediately
```
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
),
}
} finally {
sheet.seal()
}
}
}
```
**If you want styled-components to work automatically on every page/component**, you "can create a ServerStyleSheet and add a provider to your React tree, that accepts styles via a context API." In Nextjs, you would do so by adding it to your `_document.js` file...
You can read about it more if you follow these links:
1. [Styled-Components: SSR Documentation](https://styled-components.com/docs/advanced#server-side-rendering)
2. [Nextjs: Customer Render
Page](https://nextjs.org/docs/advanced-features/custom-document#customizing-renderpage)
Thankfully there's already a working example you can use from the styled-components people themselves!
Check it out here: <https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js>
Upvotes: 1 <issue_comment>username_4: I don't know if this is what you're searching for but **styling a Next Link** is pretty easy
```
import Link from 'next/link'
const StyledLink = styled(Link)`
text-decoration: none;
color: white;
`
```
and then use it like
```
{route.name}
```
Upvotes: 1
|
2018/03/14
| 3,702 | 9,657 |
<issue_start>username_0: I understand that normal function pointer contain the start address of the function being pointed to so when a normal function pointer is used, we just jump to the stored address. But what does a pointer to an object member function contain?
Consider:
```
class A
{
public:
int func1(int v) {
std::cout << "fun1";
return v;
}
virtual int func2(int v) {
std::cout << "fun2";
return v;
}
};
int main(int argc, char** argv)
{
A a;
int (A::*pf)(int a) = argc > 2 ? &A::func1 : &A::func2;
static_assert(sizeof(pf) == (sizeof(void*), "Unexpected function size");
return (a.*pf)(argc);
}
```
In the above program, the function pointer can take its value from either a virtual function (that needs to be accessed via the vtable) or a normal class member (that is implemented as a normal function with an implicit `this` as a first argument.)
So what is the value stored in my pointer to member function and how does the compiler get things to work as expected?<issue_comment>username_1: GCC [documents](http://gcc.gnu.org/onlinedocs/gcc/Bound-member-functions.html) that PMFs are implemented as structs that know how to compute the value of `this` and make any vtable lookup.
Upvotes: 0 <issue_comment>username_2: This of course depends on the compiler and the target architecture, and there is more than one single way to do it. But I'll describe how it works on the system I use most, g++ for Linux x86\_64.
g++ follows the [Itanium C++ ABI](https://itanium-cxx-abi.github.io/cxx-abi/abi.html), which describes a lot of the details of one way various C++ features including virtual functions can be implemented behind the scenes for most architectures.
The ABI says this about pointers to member functions, in section 2.3:
>
> A pointer to member function is a pair as follows:
>
>
> **ptr**:
>
>
> For a non-virtual function, this field is a simple function pointer. ... For a virtual function, it is 1 plus the virtual table offset (in bytes) of the function, represented as a `ptrdiff_t`. The value zero represents a NULL pointer, independent of the adjustment field value below.
>
>
> **adj**:
>
>
> The required adjustment to `this`, represented as a `ptrdiff_t`.
>
>
> It has the size, data size, and alignment of a class containing those two members, in that order.
>
>
>
The +1 to ptr for a virtual function helps detect whether or not the function is virtual, since for most platforms all function pointer values and vtable offsets are even. It also makes sure a null member function pointer has a distinct value from any valid member function pointer.
The vtable / vptr setup for your class `A` will work something like this C code:
```
struct A__virt_funcs {
int (*func2)(A*, int);
};
struct A__vtable {
ptrdiff_t offset_to_top;
const std__typeinfo* typeinfo;
struct A__virt_funcs funcs;
};
struct A {
const struct A__virt_funcs* vptr;
};
int A__func1(struct A*, int v) {
std__operator__ltlt(&std__cout, "fun1");
return v;
}
int A__func2(struct A*, int v) {
std__operator__ltlt(&std__cout, "fun2");
return v;
}
extern const std__typeinfo A__typeinfo;
const struct A__vtable vt_for_A = { 0, &A__typeinfo, { &A__func2 } };
void A__initialize(A* a) {
a->vptr = &vt_for_A.funcs;
}
```
(Yes, a real name mangling scheme would need to do something with function parameter types to allow for overloading, and more things since the `operator<<` involved is actually a function template specialization. But that's beside the point here.)
Now let's look at the assembly I get for your `main()` (with options `-O0 -fno-stack-protector`). My comments are added.
```
Dump of assembler code for function main:
// Standard stack adjustment for function setup.
0x00000000004007e6 <+0>: push %rbp
0x00000000004007e7 <+1>: mov %rsp,%rbp
0x00000000004007ea <+4>: push %rbx
0x00000000004007eb <+5>: sub $0x38,%rsp
// Put argc in the stack at %rbp-0x34.
0x00000000004007ef <+9>: mov %edi,-0x34(%rbp)
// Put argv in the stack at %rbp-0x40.
0x00000000004007f2 <+12>: mov %rsi,-0x40(%rbp)
// Construct "a" on the stack at %rbp-0x20.
// 0x4009c0 is &vt_for_A.funcs.
0x00000000004007f6 <+16>: mov $0x4009c0,%esi
0x00000000004007fb <+21>: mov %rsi,-0x20(%rbp)
// Check if argc is more than 2.
// In both cases, "pf" will be on the stack at %rbp-0x30.
0x00000000004007ff <+25>: cmpl $0x2,-0x34(%rbp)
0x0000000000400803 <+29>: jle 0x400819
// if (argc <= 2) {
// Initialize pf to { &A\_\_func2, 0 }.
0x0000000000400805 <+31>: mov $0x4008ce,%ecx
0x000000000040080a <+36>: mov $0x0,%ebx
0x000000000040080f <+41>: mov %rcx,-0x30(%rbp)
0x0000000000400813 <+45>: mov %rbx,-0x28(%rbp)
0x0000000000400817 <+49>: jmp 0x40082b
// } else { [argc > 2]
// Initialize pf to { 1, 0 }.
0x0000000000400819 <+51>: mov $0x1,%eax
0x000000000040081e <+56>: mov $0x0,%edx
0x0000000000400823 <+61>: mov %rax,-0x30(%rbp)
0x0000000000400827 <+65>: mov %rdx,-0x28(%rbp)
// }
// Test whether pf.ptr is even or odd:
0x000000000040082b <+69>: mov -0x30(%rbp),%rax
0x000000000040082f <+73>: and $0x1,%eax
0x0000000000400832 <+76>: test %rax,%rax
0x0000000000400835 <+79>: jne 0x40083d
// int (\*funcaddr)(A\*, int); [will be in %rax]
// if (is\_even(pf.ptr)) {
// Just do:
// funcaddr = pf.ptr;
0x0000000000400837 <+81>: mov -0x30(%rbp),%rax
0x000000000040083b <+85>: jmp 0x40085c
// } else { [is\_odd(pf.ptr)]
// Compute A\* a2 = (A\*)((char\*)&a + pf.adj); [in %rax]
0x000000000040083d <+87>: mov -0x28(%rbp),%rax
0x0000000000400841 <+91>: mov %rax,%rdx
0x0000000000400844 <+94>: lea -0x20(%rbp),%rax
0x0000000000400848 <+98>: add %rdx,%rax
// Compute funcaddr =
// (int(\*)(A\*,int)) (((char\*)(a2->vptr))[pf.ptr-1]);
0x000000000040084b <+101>: mov (%rax),%rax
0x000000000040084e <+104>: mov -0x30(%rbp),%rdx
0x0000000000400852 <+108>: sub $0x1,%rdx
0x0000000000400856 <+112>: add %rdx,%rax
0x0000000000400859 <+115>: mov (%rax),%rax
// }
// Compute A\* a3 = (A\*)((char\*)&a + pf.adj); [in %rcx]
0x000000000040085c <+118>: mov -0x28(%rbp),%rdx
0x0000000000400860 <+122>: mov %rdx,%rcx
0x0000000000400863 <+125>: lea -0x20(%rbp),%rdx
0x0000000000400867 <+129>: add %rdx,%rcx
// Call int r = (\*funcaddr)(a3, argc);
0x000000000040086a <+132>: mov -0x34(%rbp),%edx
0x000000000040086d <+135>: mov %edx,%esi
0x000000000040086f <+137>: mov %rcx,%rdi
0x0000000000400872 <+140>: callq \*%rax
// Standard stack cleanup for function exit.
0x0000000000400874 <+142>: add $0x38,%rsp
0x0000000000400878 <+146>: pop %rbx
0x0000000000400879 <+147>: pop %rbp
// Return r.
0x000000000040087a <+148>: retq
End of assembler dump.
```
But then what's the deal with the member function pointer's `adj` value? The assembly added it to the address of `a` before doing the vtable lookup and also before calling the function, whether the function was virtual or not. But both cases in `main` set it to zero, so we haven't really seen it in action.
The `adj` value comes in when we have multiple inheritance. So now suppose we have:
```
class B
{
public:
virtual void func3() {}
int n;
};
class C : public B, public A
{
public:
int func4(int v) { return v; }
int func2(int v) override { return v; }
};
```
The layout of an object of type `C` contains a `B` subobject (which contains another vptr and an `int`) and then an `A` subobject. So the address of the `A` contained in a `C` is not the same as the address of the `C` itself.
As you might be aware, any time code implicitly or explicitly converts a (non-null) `C*` pointer to an `A*` pointer, the C++ compiler accounts for this difference by adding the correct offset to the address value. C++ also allows converting from a pointer to member function of `A` to a pointer to member function of `C` (since any member of `A` is also a member of `C`), and when that happens (for a non-null member function pointer), a similar offset adjustment needs to be made. So if we have:
```
int (A::*pf1)(int) = &A::func1;
int (C::*pf2)(int) = pf1;
```
the values within the member function pointers under the hood would be `pf1 = { &A__func1, 0 };` and `pf2 = { &A__func1, offset_A_in_C };`.
And then if we have
```
C c;
int n = (c.*pf2)(3);
```
the compiler will implement the call to the member function pointer by adding the offset `pf2.adj` to the address `&c` to find the implicit "this" parameter, which is good because then it will be a valid `A*` value as `A__func1` expects.
The same thing goes for a virtual function call, except that as the disassembly dump showed, the offset is needed both to find the implicit "this" parameter and to find the vptr which contains the actual function code address. There's an added twist to the virtual case, but it's one which is needed for both ordinary virtual calls and calls using a pointer to member function: The virtual function `func2` will be called with an `A*` "this" parameter since that's where the original overridden declaration is, and the compiler won't in general be able to know if the "this" argument is actually of any other type. But the definition of override `C::func2` expects a `C*` "this" parameter. So when the most derived type is `C`, the vptr within the `A` subobject will point at a vtable which has an entry pointing not at the code for `C::func2` itself, but at a tiny "thunk" function, which does nothing but subtract `offset_A_in_C` from the "this" parameter and then pass control to the actual `C::func2`.
Upvotes: 4 [selected_answer]
|
2018/03/14
| 1,083 | 4,217 |
<issue_start>username_0: I've set up an application stack running on Google Kubernetes Engine + Google Cloud SQL. When developing locally, I would like my application to connect to a postgres database server running *outside* the cluster to simulate the production environment.
It seems that the way to do this is by defining an external endpoint as described here: [Minikube expose MySQL running on localhost as service](https://stackoverflow.com/questions/43354167/minikube-expose-mysql-running-on-localhost-as-service)
Unfortunately, I am not able to specify "127.0.0.1" as the Endpoint IP address:
```
kubectl apply -f kubernetes/local/postgres-service.yaml
service "postgres-db" unchanged
The Endpoints "postgres-db" is invalid: subsets[0].addresses[0].ip:
Invalid value: "127.0.0.1": may not be in the loopback range (127.0.0.0/8)
```
So I am forced to bind postgres to my actual machine address.
It seems like there MUST be a way to map a port from my localhost into the local kubernetes cluster, but so far I can't find a way to do it.
Anybody know the trick? Or alternatively, can someone suggest an alternative solution which doesn't involve running postgres inside the cluster?<issue_comment>username_1: Mysql server should connect to private IP, and that private IP can be used in application.
Prefer way is to create kubernetes service+endpoint pointing to Mysql Server IP.
Upvotes: -1 <issue_comment>username_2: There is a potential solution for this called [Telepresence](https://www.telepresence.io/) which allows to have a local workload to be proxied into the cluster as if it were actualy run within that kube cluster.
Upvotes: 2 <issue_comment>username_3: May not be an answer for Minikube, but I ended up here so I share what I did for Kubernetes in Docker for Mac.
I added a service like this for PostgreSQL:
```
kind: Service
apiVersion: v1
metadata:
name: postgres
namespace: default
spec:
type: ExternalName
# https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds
externalName: host.docker.internal
ports:
- name: port
port: 5432
```
My application was able to connect to the locally running postgres server with this setup using the domain name `postgres`. The Postgres server can listen to `127.0.0.1` with this setup.
Upvotes: 4 <issue_comment>username_4: K8s Native Approach
===================
I had similar issues with developing cloud-native software directly inside Kubernetes. We took a look at tools like Telepresence and Skaffold, too but they are hard to configure and very time-consuming.
That's why I built the DevSpace CLI together with a colleague: <https://github.com/covexo/devspace>
Feel free to take a look and try it out. It will solve issues like yours by allowing you to easily run all your workloads directly inside Kubernetes while still being able to program with your desktop tools (local terminal, IDE, git etc).
Alternative: Minikube networking
================================
As you are using minikube, you should take a look as the answers to this question: [Routing an internal Kubernetes IP address to the host system](https://stackoverflow.com/questions/42268814/routing-an-internal-kubernetes-ip-address-to-the-host-system)
Alternative: Tunneling
======================
You could also use local tunneling with tools like ngrok: <https://ngrok.com/> (simply start it locally and connect to your ngrok address from anywhere)
Upvotes: 1 <issue_comment>username_5: Faced a similar situation on Mac . My Postgresdb is running locally. What I did was to pass the credentials of the db as environment variables. Pay special attention to the HOST variable that composes the string to connect to the db.
```
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
labels:
app: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: app-container
image:
ports:
- containerPort: 8080
env:
- name: POSTGRES\_USER
value:
- name: POSTGRES\_PASSWORD
value:
- name: HOST
value: docker.for.mac.host.internal
- name: POSTGRES\_DB
value:
```
Upvotes: 0
|
2018/03/14
| 1,539 | 5,448 |
<issue_start>username_0: Why does the code snippet below print out `0`? However, `i` is correctly updated to `1` without the `for` loop.
```
package main
import (
"fmt"
"time"
)
func main() {
var i uint64
go func() {
for {
i++
}
}()
time.Sleep(time.Second)
fmt.Println(i)
}
```
**Solution 1**
```
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var i uint64
ch := make(chan bool)
go func() {
for {
select {
case <-ch:
return
default:
i++
}
}
}()
time.Sleep(time.Second)
ch <- true
fmt.Println(i)
}
```
**Solution 2**
```
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var i uint64
var mx sync.Mutex
go func() {
for {
mx.Lock()
i++
mx.Unlock()
}
}()
time.Sleep(time.Second)
mx.Lock()
fmt.Println(i)
mx.Unlock()
}
```
**Solution 3**
```
package main
import (
"fmt"
"runtime"
"sync/atomic"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
var i uint64
go func() {
for {
atomic.AddUint64(&i, 1)
runtime.Gosched()
}
}()
time.Sleep(time.Second)
fmt.Println(atomic.LoadUint64(&i))
}
```<issue_comment>username_1: It's not "correctly" updated without the for loop, it's just randomly updated before you print it.
In go playgorund this ends with:
```
process took too long
Program exited.
```
See: <https://play.golang.org/p/qKd-CdLt3uK>
When starting the go routine the scheduler will decide when to switch the context between the execution of the go routine and the main function. In addition the go-routine is stopped when the main function ends.
What you want to do is some Synchronisation between your go routine and your main loop, since both are accessing a shared variable `i`.
Best practice here would be to use channels, sync.Mutex or sync.WaitGroup.
You can add some delay to your for loop, to give up some CPU for the main function:
```
go func() {
for {
i++
time.Sleep(1 * time.Millisecond)
}
}()
```
This will pint some value around 1000, but it's still not reliable.
Upvotes: 0 <issue_comment>username_2: Running this in the go playground, it times out, which slightly surprises me because, as username_1 says, the infinite for loop should be terminated upon exit from `main`. It seems that the go playground waits for all goroutines to complete before exiting. I imagine the reason you see 0 is to do with bad multithreading here. The for loop is continually updating `i` at the same time as `i` is read by main, and the results are unpredictable. I'm not sure what you are trying to demonstrate, but you would need a mutex here or a channel to read and update `i` safely on different threads.
Upvotes: 1 <issue_comment>username_3: You have a race condition. The results are undefined.
```
package main
import (
"fmt"
"time"
)
func main() {
var i uint64
go func() {
for {
i++
}
}()
time.Sleep(time.Second)
fmt.Println(i)
}
```
Output:
```
$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00c0000a2010 by main goroutine:
main.main()
/home/peter/src/racer.go:18 +0x95
Previous write at 0x00c0000a2010 by goroutine 6:
main.main.func1()
/home/peter/src/racer.go:13 +0x4e
Goroutine 6 (running) created at:
main.main()
/home/peter/src/racer.go:11 +0x7a
==================
66259553
Found 1 data race(s)
exit status 66
$
```
---
Reference: [Introducing the Go Race Detector](https://blog.golang.org/race-detector)
Upvotes: 3 [selected_answer]<issue_comment>username_4: Necessary reading for understanding - [The Go Memory Model](https://golang.org/ref/mem)
>
> The Go memory model specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine.
>
>
>
Whenever you have 2 or more concurrent goroutines accessing same memory and one of them modifying memory (like `i++` in your example) you need to have some sort of synchronization: [mutex](https://golang.org/ref/mem#tmp_8) or [channel](https://golang.org/ref/mem#tmp_7).
Something like this would be smallest modification necessary to your code:
```golang
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var (
mu sync.Mutex
i uint64
)
go func() {
for {
mu.Lock()
i++
mu.Unlock()
}
}()
time.Sleep(time.Second)
mu.Lock()
fmt.Println(i)
mu.Unlock()
}
```
Oh and official [Advice](https://golang.org/ref/mem#tmp_1):
>
> If you must read the rest of this document to understand the behavior of your program, you are being too clever. **Don't be clever.**
>
>
>
:) have fun
Upvotes: 2
|
2018/03/14
| 418 | 1,531 |
<issue_start>username_0: In Objective-C, I would use the following code to identify an instance of a class and the function being called in the console.
```
NSLog(@"[DMLOG - %@] %@", NSStringFromSelector(_cmd), self);
```
This would return something like the console out below, where I would get an instance ID to track different instances of an object.
```
[DMLOG - prepForInput]
```
How can I get both the instance ID and the function being called within Swift? I've tried the following to get the ID in Swift but it only provides the class name and no instance ID value? Any suggestions would be appreciated.
```
print("[DBG] Init: \(self)")
```<issue_comment>username_1: I just ran a quick test using the following:
```
print("\(self) \(#function) - Count \(count)")
```
I got the following result:
```
viewWillAppear - Count 3
```
I would give that a try and see if it helps.
Upvotes: 0 <issue_comment>username_2: To get current function name use `#function` literal.
As for instance ID, looks like you have two options:
1. Inherit from `NSObject` (UIKit classes inherit it anyways) so that class instances would have instance IDs:
```
class MyClass: NSObject {
override init() {
super.init()
print("[DBG: \(#function)]: \(self)")
}
}
```
2. If your class does not inherit from `NSObject` you can still identify your instances by memory address:
```
class Jumbo {
init() {
print("[DBG: \(#function)]: \(Unmanaged.passUnretained(self).toOpaque())")
}
}
```
Upvotes: 5 [selected_answer]
|
2018/03/14
| 594 | 2,167 |
<issue_start>username_0: The `java.nio.ByteBuffer` class has a `ByteBuffer.array()` method, however this returns an array that is the size of the buffer's capacity, and not the used capacity. Due to this, I'm having some issues.
I have a ByteBuffer which I am allocating as some size and then I am inserting data to it.
```
ByteBuffer oldBuffer = ByteBuffer.allocate(SIZE);
addHeader(oldBuffer, pendingItems);
newBuffer.flip();
oldBuffer.put(newBuffer);
// as of now I am sending everything from oldBuffer
send(address, oldBuffer.array());
```
How can I just send what is being used in `oldBuffer`. Is there any one liner to do this?<issue_comment>username_1: You can flip the buffer, then create a new array with the remaining size of the buffer and fill it.
```java
oldBuffer.flip();
byte[] remaining = new byte[oldBuffer.remaining()];
oldBuffer.get(remaining);
```
Another way in a one liner with `flip()` and [Arrays.copyOf](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(byte[],%20int))
```java
oldBuffer.flip();
Arrays.copyOf(oldBuffer.array(), oldBuffer.remaining());
```
And without `flip()`
```java
Arrays.copyOf(oldBuffer.array(), oldBuffer.position());
```
Also like EJP said, if you have access to the `send(..)` method, you can add a size and offset argument to the `send()` method, and avoid the need to create and fill a new array.
Upvotes: 4 [selected_answer]<issue_comment>username_2: The `position()` of the buffer indicates that the amount of *used* data in the buffer.
So create a byte array of that size.
Next go to the position 0 of the buffer, since you have to read data from there. `rewind()` does this.
Then use the `get()` method to copy the buffer data into the array.
```
byte[] data = new byte[buffer.position()];
buffer.rewind();
buffer.get(data);
```
Also note that `buffer.array()` works only if the `buffer.hasArray()` returns true. So check for `hasArray()`before calling it. Otherwise, `buffer.array()` will throw any of the following exception.
1. `UnsupportedOperationException` - when calling it on direct buffer.
2. `ReadOnlyBufferException` - if the buffer is read-only.
Upvotes: 2
|
2018/03/14
| 2,633 | 7,217 |
<issue_start>username_0: I am trying to use RSelenium with Docker, and everything appears to be working, except that I cannot see the firefox browser. I don't think there is anything in my code requiring it to be headless, but that must be the case. Is there a way to make it viewable like it was when using `RSelenium::startServer()` ?
I installed docker via the instructions in this article, <https://www.raynergobran.com/2017/01/rselenium-mac-update/>
I went to terminal and typed in: `docker run -d -p 4445:4444 selenium/standalone-firefox` without issue.
I go to R and run this code:
```
library(RSelenium)
remDr <- remoteDriver(port=4445L, browserName = "firefox")
remDr$open()
remDr$getStatus()
remDr$navigate("https://www.google.com/")
remDr$getCurrentUrl()
```
The output from the last command is as expected:
```
[[1]]
[1] "https://www.google.com/"
```
When looking at the output after `remDr$open()`, headless is set to false:
```
[1] "Connecting to remote server"
$`moz:profile`
[1] "/tmp/rust_mozprofile.EQnMfPLPKS4l"
$rotatable
[1] FALSE
$timeouts
$timeouts$implicit
[1] 0
$timeouts$pageLoad
[1] 300000
$timeouts$script
[1] 30000
$pageLoadStrategy
[1] "normal"
$`moz:headless`
[1] FALSE
$`moz:accessibilityChecks`
[1] FALSE
$acceptInsecureCerts
[1] FALSE
$browserVersion
[1] "58.0.2"
$platformVersion
[1] "4.9.60-linuxkit-aufs"
$`moz:processID`
[1] 741
$browserName
[1] "firefox"
$platformName
[1] "linux"
$`moz:webdriverClick`
[1] TRUE
$webdriver.remote.sessionid
[1] "bfa2d87a-67d3-4e5e-838b-e6894a90dd5c"
$id
[1] "bfa2d87a-67d3-4e5e-838b-e6894a90dd5c"
```
Again, the browser is not viewable on my screen but I'd like it to be.
I am running El Capitan 10.11.6.
Thank you for your help.<issue_comment>username_1: I think the issue seems to with your expectations to see the browser. You are launching the browser inside a docker container. The docker container doesn't have a UI, the browser is launched inside the container instance and not on your machine which initiates the call
The default `selenium/standalone-firefox` doesn't allow viewing of the browser. If you need to view the browser then you need to use the `selenium/standalone-firefox-debug` image. This image hosts VNC at port `5900` of the container. You will run it using below
```
docker run -d -p 4445:4444 -p 5900:5900 selenium/standalone-firefox-debug
```
Then you will execute your code and connect to `127.0.0.1:5900` using a VNC Viewer. It will ask for a password which is `<PASSWORD>` by default.
Then you will see the browser in that VNC
[](https://i.stack.imgur.com/6FFrS.png)
The above is the result of running the code you had in question
Upvotes: 3 <issue_comment>username_2: Here is a Dockerfile which may be useful to you <https://github.com/jessfraz/dockerfiles/blob/master/chrome/stable/Dockerfile>
inlined here for convenience:
```
# Run Chrome in a container
#
# docker run -it \
# --net host \ # may as well YOLO
# --cpuset-cpus 0 \ # control the cpu
# --memory 512mb \ # max memory it can use
# -v /tmp/.X11-unix:/tmp/.X11-unix \ # mount the X11 socket
# -e DISPLAY=unix$DISPLAY \
# -v $HOME/Downloads:/home/chrome/Downloads \
# -v $HOME/.config/google-chrome/:/data \ # if you want to save state
# --security-opt seccomp=$HOME/chrome.json \
# --device /dev/snd \ # so we have sound
# --device /dev/dri \
# -v /dev/shm:/dev/shm \
# --name chrome \
# jess/chrome
#
# You will want the custom seccomp profile:
# wget https://raw.githubusercontent.com/jfrazelle/dotfiles/master/etc/docker/seccomp/chrome.json -O ~/chrome.json
# Base docker image
FROM debian:sid
LABEL maintainer "<NAME> "
ADD https://dl.google.com/linux/direct/google-talkplugin\_current\_amd64.deb /src/google-talkplugin\_current\_amd64.deb
# Install Chrome
RUN apt-get update && apt-get install -y \
libcanberra-gtk\* \
apt-transport-https \
ca-certificates \
curl \
gnupg \
hicolor-icon-theme \
libgl1-mesa-dri \
libgl1-mesa-glx \
libpango1.0-0 \
libpulse0 \
libv4l-0 \
fonts-symbola \
--no-install-recommends \
&& curl -sSL https://dl.google.com/linux/linux\_signing\_key.pub | apt-key add - \
&& echo "deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list \
&& apt-get update && apt-get install -y \
google-chrome-stable \
--no-install-recommends \
&& dpkg -i '/src/google-talkplugin\_current\_amd64.deb' \
&& apt-get purge --auto-remove -y curl \
&& rm -rf /var/lib/apt/lists/\* \
&& rm -rf /src/\*.deb
# Add chrome user
RUN groupadd -r chrome && useradd -r -g chrome -G audio,video chrome \
&& mkdir -p /home/chrome/Downloads && chown -R chrome:chrome /home/chrome
COPY local.conf /etc/fonts/local.conf
# Run Chrome as non privileged user
USER chrome
# Autorun chrome
ENTRYPOINT [ "google-chrome" ]
CMD [ "--user-data-dir=/data" ]
```
Additionally, this project <https://github.com/sameersbn/docker-browser-box>
Inlined Dockerfile for convenience.
```
FROM sameersbn/ubuntu:14.04.20170123
ENV TOR_VERSION=6.5 \
TOR_FINGERPRINT=0x4E2C6E8793298290
RUN wget -q -O - "https://dl-ssl.google.com/linux/linux_signing_key.pub" | sudo apt-key add - \
&& echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \
&& mkdir ~/.gnupg \
&& gpg --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys ${TOR_FINGERPRINT} \
&& gpg --fingerprint ${TOR_FINGERPRINT} | grep -q "Key fingerprint = EF6E 286D DA85 EA2A 4BA7 DE68 4E2C 6E87 9329 8290" \
&& apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y xz-utils file locales dbus-x11 pulseaudio dmz-cursor-theme curl \
fonts-dejavu fonts-liberation hicolor-icon-theme \
libcanberra-gtk3-0 libcanberra-gtk-module libcanberra-gtk3-module \
libasound2 libglib2.0 libgtk2.0-0 libdbus-glib-1-2 libxt6 libexif12 \
libgl1-mesa-glx libgl1-mesa-dri libstdc++6 nvidia-346 \
gstreamer-1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav \
google-chrome-stable chromium-browser firefox \
&& update-locale LANG=C.UTF-8 LC_MESSAGES=POSIX \
&& mkdir -p /usr/lib/tor-browser \
&& wget -O /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz \
&& wget -O /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc \
&& gpg /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc \
&& tar -Jvxf /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz --strip=1 -C /usr/lib/tor-browser \
&& ln -sf /usr/lib/tor-browser/Browser/start-tor-browser /usr/bin/tor-browser \
&& rm -rf /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz \
&& rm -rf ~/.gnupg \
&& rm -rf /var/lib/apt/lists/*
COPY scripts/ /var/cache/browser-box/
COPY entrypoint.sh /sbin/entrypoint.sh
COPY confs/local.conf /etc/fonts/local.conf
RUN chmod 755 /sbin/entrypoint.sh
ENTRYPOINT ["/sbin/entrypoint.sh"]
```
Upvotes: 1
|
2018/03/14
| 2,257 | 6,549 |
<issue_start>username_0: I have a problem with my Angular 4, Firebase, AngularFire ionic app with observable that makes firebase request.
The problem is that the first time i click on the view the cards doesn't load, but if i went to other page and come back and i click again then the images loads with no problem but the first time i clic after ionic serve the cards never loads.
I have 2 providers, the first provider is called from view controller gdm1.ts and the call is:
```
constructor(
private dbCards: CardsProvider,
...
){...}
...
ionViewDidLoad() {
this.cards = this.dbCards.loadcards(9);
}
```
This call the first provider cards.ts:
```
constructor(private dbhDb: FirebaseDbProvider) {}
...
loadcards(colnumber)
{
this.dbhDb.getCards().first().subscribe(cards=>{
this.cards = cards[colnumber].cards;
});
return this.cards;
}
```
And cards.ts call the second provider firebase-db.ts:
```
constructor(
public afDB: AngularFireDatabase,
public auth: AuthProvider
) {...}
...
getCards(){
return this.afDB.list('/cards');;
}
```<issue_comment>username_1: I think the issue seems to with your expectations to see the browser. You are launching the browser inside a docker container. The docker container doesn't have a UI, the browser is launched inside the container instance and not on your machine which initiates the call
The default `selenium/standalone-firefox` doesn't allow viewing of the browser. If you need to view the browser then you need to use the `selenium/standalone-firefox-debug` image. This image hosts VNC at port `5900` of the container. You will run it using below
```
docker run -d -p 4445:4444 -p 5900:5900 selenium/standalone-firefox-debug
```
Then you will execute your code and connect to `127.0.0.1:5900` using a VNC Viewer. It will ask for a password which is `secret` by default.
Then you will see the browser in that VNC
[](https://i.stack.imgur.com/6FFrS.png)
The above is the result of running the code you had in question
Upvotes: 3 <issue_comment>username_2: Here is a Dockerfile which may be useful to you <https://github.com/jessfraz/dockerfiles/blob/master/chrome/stable/Dockerfile>
inlined here for convenience:
```
# Run Chrome in a container
#
# docker run -it \
# --net host \ # may as well YOLO
# --cpuset-cpus 0 \ # control the cpu
# --memory 512mb \ # max memory it can use
# -v /tmp/.X11-unix:/tmp/.X11-unix \ # mount the X11 socket
# -e DISPLAY=unix$DISPLAY \
# -v $HOME/Downloads:/home/chrome/Downloads \
# -v $HOME/.config/google-chrome/:/data \ # if you want to save state
# --security-opt seccomp=$HOME/chrome.json \
# --device /dev/snd \ # so we have sound
# --device /dev/dri \
# -v /dev/shm:/dev/shm \
# --name chrome \
# jess/chrome
#
# You will want the custom seccomp profile:
# wget https://raw.githubusercontent.com/jfrazelle/dotfiles/master/etc/docker/seccomp/chrome.json -O ~/chrome.json
# Base docker image
FROM debian:sid
LABEL maintainer "<NAME> "
ADD https://dl.google.com/linux/direct/google-talkplugin\_current\_amd64.deb /src/google-talkplugin\_current\_amd64.deb
# Install Chrome
RUN apt-get update && apt-get install -y \
libcanberra-gtk\* \
apt-transport-https \
ca-certificates \
curl \
gnupg \
hicolor-icon-theme \
libgl1-mesa-dri \
libgl1-mesa-glx \
libpango1.0-0 \
libpulse0 \
libv4l-0 \
fonts-symbola \
--no-install-recommends \
&& curl -sSL https://dl.google.com/linux/linux\_signing\_key.pub | apt-key add - \
&& echo "deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list \
&& apt-get update && apt-get install -y \
google-chrome-stable \
--no-install-recommends \
&& dpkg -i '/src/google-talkplugin\_current\_amd64.deb' \
&& apt-get purge --auto-remove -y curl \
&& rm -rf /var/lib/apt/lists/\* \
&& rm -rf /src/\*.deb
# Add chrome user
RUN groupadd -r chrome && useradd -r -g chrome -G audio,video chrome \
&& mkdir -p /home/chrome/Downloads && chown -R chrome:chrome /home/chrome
COPY local.conf /etc/fonts/local.conf
# Run Chrome as non privileged user
USER chrome
# Autorun chrome
ENTRYPOINT [ "google-chrome" ]
CMD [ "--user-data-dir=/data" ]
```
Additionally, this project <https://github.com/sameersbn/docker-browser-box>
Inlined Dockerfile for convenience.
```
FROM sameersbn/ubuntu:14.04.20170123
ENV TOR_VERSION=6.5 \
TOR_FINGERPRINT=0x4E2C6E8793298290
RUN wget -q -O - "https://dl-ssl.google.com/linux/linux_signing_key.pub" | sudo apt-key add - \
&& echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \
&& mkdir ~/.gnupg \
&& gpg --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys ${TOR_FINGERPRINT} \
&& gpg --fingerprint ${TOR_FINGERPRINT} | grep -q "Key fingerprint = EF6E 286D DA85 EA2A 4BA7 DE68 4E2C 6E87 9329 8290" \
&& apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y xz-utils file locales dbus-x11 pulseaudio dmz-cursor-theme curl \
fonts-dejavu fonts-liberation hicolor-icon-theme \
libcanberra-gtk3-0 libcanberra-gtk-module libcanberra-gtk3-module \
libasound2 libglib2.0 libgtk2.0-0 libdbus-glib-1-2 libxt6 libexif12 \
libgl1-mesa-glx libgl1-mesa-dri libstdc++6 nvidia-346 \
gstreamer-1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav \
google-chrome-stable chromium-browser firefox \
&& update-locale LANG=C.UTF-8 LC_MESSAGES=POSIX \
&& mkdir -p /usr/lib/tor-browser \
&& wget -O /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz \
&& wget -O /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc \
&& gpg /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc \
&& tar -Jvxf /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz --strip=1 -C /usr/lib/tor-browser \
&& ln -sf /usr/lib/tor-browser/Browser/start-tor-browser /usr/bin/tor-browser \
&& rm -rf /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz \
&& rm -rf ~/.gnupg \
&& rm -rf /var/lib/apt/lists/*
COPY scripts/ /var/cache/browser-box/
COPY entrypoint.sh /sbin/entrypoint.sh
COPY confs/local.conf /etc/fonts/local.conf
RUN chmod 755 /sbin/entrypoint.sh
ENTRYPOINT ["/sbin/entrypoint.sh"]
```
Upvotes: 1
|
2018/03/14
| 2,138 | 6,156 |
<issue_start>username_0: I have a node js app that gets me a another site's html source into a variable (result.body)
I want to get the value of an input tag.
```
```
I have tried using jsdom like this:
```
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(result.body);
console.log("dom ********************");
console.log(dom);
var session = dom.window.document.getElementById('#session').value;
```
I get the following in console:
```
dom ********************
JSDOM {}
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
TypeError: Cannot read property 'getElementById' of undefined
```<issue_comment>username_1: I think the issue seems to with your expectations to see the browser. You are launching the browser inside a docker container. The docker container doesn't have a UI, the browser is launched inside the container instance and not on your machine which initiates the call
The default `selenium/standalone-firefox` doesn't allow viewing of the browser. If you need to view the browser then you need to use the `selenium/standalone-firefox-debug` image. This image hosts VNC at port `5900` of the container. You will run it using below
```
docker run -d -p 4445:4444 -p 5900:5900 selenium/standalone-firefox-debug
```
Then you will execute your code and connect to `127.0.0.1:5900` using a VNC Viewer. It will ask for a password which is `secret` by default.
Then you will see the browser in that VNC
[](https://i.stack.imgur.com/6FFrS.png)
The above is the result of running the code you had in question
Upvotes: 3 <issue_comment>username_2: Here is a Dockerfile which may be useful to you <https://github.com/jessfraz/dockerfiles/blob/master/chrome/stable/Dockerfile>
inlined here for convenience:
```
# Run Chrome in a container
#
# docker run -it \
# --net host \ # may as well YOLO
# --cpuset-cpus 0 \ # control the cpu
# --memory 512mb \ # max memory it can use
# -v /tmp/.X11-unix:/tmp/.X11-unix \ # mount the X11 socket
# -e DISPLAY=unix$DISPLAY \
# -v $HOME/Downloads:/home/chrome/Downloads \
# -v $HOME/.config/google-chrome/:/data \ # if you want to save state
# --security-opt seccomp=$HOME/chrome.json \
# --device /dev/snd \ # so we have sound
# --device /dev/dri \
# -v /dev/shm:/dev/shm \
# --name chrome \
# jess/chrome
#
# You will want the custom seccomp profile:
# wget https://raw.githubusercontent.com/jfrazelle/dotfiles/master/etc/docker/seccomp/chrome.json -O ~/chrome.json
# Base docker image
FROM debian:sid
LABEL maintainer "<NAME> "
ADD https://dl.google.com/linux/direct/google-talkplugin\_current\_amd64.deb /src/google-talkplugin\_current\_amd64.deb
# Install Chrome
RUN apt-get update && apt-get install -y \
libcanberra-gtk\* \
apt-transport-https \
ca-certificates \
curl \
gnupg \
hicolor-icon-theme \
libgl1-mesa-dri \
libgl1-mesa-glx \
libpango1.0-0 \
libpulse0 \
libv4l-0 \
fonts-symbola \
--no-install-recommends \
&& curl -sSL https://dl.google.com/linux/linux\_signing\_key.pub | apt-key add - \
&& echo "deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list \
&& apt-get update && apt-get install -y \
google-chrome-stable \
--no-install-recommends \
&& dpkg -i '/src/google-talkplugin\_current\_amd64.deb' \
&& apt-get purge --auto-remove -y curl \
&& rm -rf /var/lib/apt/lists/\* \
&& rm -rf /src/\*.deb
# Add chrome user
RUN groupadd -r chrome && useradd -r -g chrome -G audio,video chrome \
&& mkdir -p /home/chrome/Downloads && chown -R chrome:chrome /home/chrome
COPY local.conf /etc/fonts/local.conf
# Run Chrome as non privileged user
USER chrome
# Autorun chrome
ENTRYPOINT [ "google-chrome" ]
CMD [ "--user-data-dir=/data" ]
```
Additionally, this project <https://github.com/sameersbn/docker-browser-box>
Inlined Dockerfile for convenience.
```
FROM sameersbn/ubuntu:14.04.20170123
ENV TOR_VERSION=6.5 \
TOR_FINGERPRINT=0x4E2C6E8793298290
RUN wget -q -O - "https://dl-ssl.google.com/linux/linux_signing_key.pub" | sudo apt-key add - \
&& echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \
&& mkdir ~/.gnupg \
&& gpg --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys ${TOR_FINGERPRINT} \
&& gpg --fingerprint ${TOR_FINGERPRINT} | grep -q "Key fingerprint = EF6E 286D DA85 EA2A 4BA7 DE68 4E2C 6E87 9329 8290" \
&& apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y xz-utils file locales dbus-x11 pulseaudio dmz-cursor-theme curl \
fonts-dejavu fonts-liberation hicolor-icon-theme \
libcanberra-gtk3-0 libcanberra-gtk-module libcanberra-gtk3-module \
libasound2 libglib2.0 libgtk2.0-0 libdbus-glib-1-2 libxt6 libexif12 \
libgl1-mesa-glx libgl1-mesa-dri libstdc++6 nvidia-346 \
gstreamer-1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav \
google-chrome-stable chromium-browser firefox \
&& update-locale LANG=C.UTF-8 LC_MESSAGES=POSIX \
&& mkdir -p /usr/lib/tor-browser \
&& wget -O /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz \
&& wget -O /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc https://www.torproject.org/dist/torbrowser/${TOR_VERSION}/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc \
&& gpg /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz.asc \
&& tar -Jvxf /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz --strip=1 -C /usr/lib/tor-browser \
&& ln -sf /usr/lib/tor-browser/Browser/start-tor-browser /usr/bin/tor-browser \
&& rm -rf /tmp/tor-browser-linux64-${TOR_VERSION}_en-US.tar.xz \
&& rm -rf ~/.gnupg \
&& rm -rf /var/lib/apt/lists/*
COPY scripts/ /var/cache/browser-box/
COPY entrypoint.sh /sbin/entrypoint.sh
COPY confs/local.conf /etc/fonts/local.conf
RUN chmod 755 /sbin/entrypoint.sh
ENTRYPOINT ["/sbin/entrypoint.sh"]
```
Upvotes: 1
|
2018/03/14
| 324 | 1,267 |
<issue_start>username_0: I wanna stop ballerina program in the middle of some logic. How can I stop a running program in ballerina using code?
I'm looking for something equivalent to System.exit(0) in java.<issue_comment>username_1: You could throw a runtime exception.
Upvotes: 1 <issue_comment>username_2: I believe you are writing a program with a main function. Unfortunately its not available with Ballerina, you can request that feature by creating an issue in Github repository [1].
As @werner has suggested throwing an error would be a workaround as following code.
```
import ballerina.io;
function main(string[] args) {
int count = 0;
while (true) {
io:println(count);
if (count == 5) {
error err = {message:"Stop the program"};
throw err;
}
count = count + 1;
}
}
```
[1] <https://github.com/ballerina-lang/ballerina/issues>
Upvotes: 3 <issue_comment>username_3: I think there is no need for a System.exit sort of function in Ballerina. This is because, if you started your process via a main function, then getting that function to complete will result in the program exiting. If there are services running, then it is a bad idea to have a System.exit in service code.
Upvotes: 1
|
2018/03/14
| 1,038 | 2,198 |
<issue_start>username_0: I would like to know what is a best practice or a neat code if I have a very complex format recorded in Excel. For example
```
bad_format = c(1969*,--1979--,1618, 19.42, 1111983, 1981, 1-9-3-2, 1983,
“1977”,“1954”, “1943”, 1968, 2287 BC, 1998, ..1911.., 1961)
```
There are all sort of issues some years are recorded as string, others are incorrectly stored such as 1111983 (3 extra 1), other in BC etc.
The output should like this:
```
correct_format = c(1969,1979, 1618, 1942, 1983, 1981, 1932, 1983, 1977,
1954, 1943, 1968, -2287, 1998, 1911, 1961)
```
I have no idea as how to approach this task or have the capability to write a code in r that could solve it, but I hope someone might have an idea as how to write a neat code which could find these issues and correct it.<issue_comment>username_1: I agree with @thelatemail, but perhaps this is a start?
```
bad_format = c("1969*","--1979--","1618", "19.42", "1111983", "1981", "1-9-3-2", "1983",
"“1977”","“1954”", "“1943”", "1968", "2287 BC", "1998", "..1911..", "1961")
# Step 1: Remove trailing/leading characters
# Anchor digits to start with either 1 or 2
ss <- gsub("^.*([12]\\d\\d\\d).*$", "\\1", bad_format)
# Step 2: Remove "dividing" non-digit characters
ss <- gsub("\\D", "", ss);
#[1] "1969" "1979" "1618" "1942" "1983" "1981" "1932" "1983" "1977" "1954"
#[11] "1943" "1968" "2287" "1998" "1911" "1961"
```
Upvotes: 1 <issue_comment>username_2: First set `BC` to TRUE if the string ends in `"BC"` and FALSE otherwise. Then remove non-digits and convert to numeric giving `digits`. Finally use modulo to take the last 4 digits multiplying by -1 if `BC` is TRUE and +1 otherwise.
```
bad_format <- c("1969*", "--1979--", "1618", "19.42", "1111983", "1981",
"1-9-3-2", "1983", "1977", "1954", "1943", "1968", "2287 BC", "1998",
"..1911..", "1961")
BC <- grepl("BC$", bad_format)
digits <- as.numeric(gsub("\\D", "", bad_format))
ifelse(BC, -1, 1) * (digits %% 10000)
```
giving:
```
[1] 1969 1979 1618 1942 1983 1981 1932 1983 1977 1954 1943 1968
[13] -2287 1998 1911 1961
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 685 | 3,203 |
<issue_start>username_0: I am trying to verify an Admin created a user through password-reset-challenge using AWS Cognito generated a temporary password and I can't find the way or an example on how to use a temporary password and set new passwords for new users in javascript.<issue_comment>username_1: The Amazon Cognito developer guide provides an example of authenticating with a temporary password and handling the `newPasswordRequired` condition:
```
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: [...],
onFailure: [...],
mfaRequired: [...],
newPasswordRequired: function(userAttributes, requiredAttributes) {
// User was signed up by an admin and must provide new
// password and required attributes, if any, to complete
// authentication.
// userAttributes: object, which is the user's current profile. It will list all attributes that are associated with the user.
// Required attributes according to schema, which don’t have any values yet, will have blank values.
// requiredAttributes: list of attributes that must be set by the user along with new password to complete the sign-in.
// Get these details and call
// newPassword: <PASSWORD> that user <PASSWORD>
// attributesData: object with key as attribute name and value that the user has given.
cognitoUser.completeNewPasswordChallenge(newPassword, attributesData, this)
}
});
```
Excerpted from the guide here: <https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-identity-user-pools-javascript-example-authenticating-admin-created-user.html>
Note that the third argument to `completeNewPasswordChallenge` in the example is `this`, i.e., the object with the handler functions. This is because `completeNewPasswordChallenge` requires `onSuccess` and `onFailure` handlers, and you can often use the same handlers as you would for the `authenticateUser` result.
Upvotes: 4 [selected_answer]<issue_comment>username_2: I did go through the document you referred to. I do not understand what should be '`attributesData`'. Below is what I have done till now.
```
var authenticationData = {
Username : email,
Password : <PASSWORD>,
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
console.log('idToken + ' + result.idToken.jwtToken);// User authentication was successful
},
onFailure: function(err) {
alert(err);// User authentication was not successful
},
newPasswordRequired: function(userAttributes, requiredAttributes) {
userAttributes: authenticationData;
requiredAttributes: email;
var newPassword: <PASSWORD>;
// attributesData: object with key as attribute name and value that the user has given.
cognitoUser.completeNewPasswordChallenge(newPassword, attributesData, this)
}
});
```
Upvotes: 0
|
2018/03/14
| 1,569 | 5,367 |
<issue_start>username_0: I just started getting into programming and I have been trying to solve this puzzle, but unfortunately I couldn't find any answers related to this anywhere, so here it goes:
1) Given n numbers (using prompt), show the highest and lowest numbers of the set.
```
var highest = 0, **lowest = 0**;
while(true) {
var num = prompt("Input a number");
if(num == 0) {break;}
if(num < 0) {
alert("Input a valid number.");
}
if(num > highest) {
highest = num;
}
**if(num < lowest) {
lowest = num**
}
}
document.write("The highest number is: " + highest + "
");
document.write("The lowest number is: " + lowest);
```
I know that the code is wrong, probably with the variable lowest, so I would be much obliged if someone helped me.<issue_comment>username_1: One idea is to maybe set the lowest to a large number, but I think an even better idea is to leave them undefined.. Because if say the user types 0 on first input, you have a state that indicates such.
Below is your example code modified with a few tweaks, and extra sanity checks.
```js
var highest, lowest;
while(true) {
var num = parseInt(prompt("Input a number, 0 - when done"), 10);
if(num < 0 || isNaN(num)) {
alert("Input a valid number.");
continue;
}
if(num === 0) {break;}
if(highest === undefined || num > highest) {
highest = num;
}
if(lowest === undefined || num < lowest) {
lowest = num;
}
}
if (lowest === undefined) {
document.write("No Numbers given");
} else {
document.write("The highest number is: " + highest + "
");
document.write("The lowest number is: " + lowest);
}
```
---
Alternatively, you can let the user leave the input-field empty in order to see the results:
```js
var highest,lowest;
while (true) {
var num = parseInt(prompt("Input a number. Leave empty to see results"));
if (isNaN(num)) {break;}
else if (num < 0) {alert("Negative values are not allowed");}
else {
if (num>highest || highest==undefined) {highest = num;}
if (num");
document.write("The lowest number is: "+(lowest!=undefined?lowest:"-"));
```
Upvotes: 1 <issue_comment>username_2: You probably want to set `lowest` to the highest possible number to start with, and then also parse the prompt as an integer, and ensure that it's a valid number:
```
var highest = 0, lowest = Number.MAX_VALUE;
while(true) {
var num = parseInt(prompt("Input a number"));
if(num == 0) {
break;
}
if(num < 0 || isNaN(num)) {
alert("Input a valid number.");
continue;
}
if(num > highest) {
highest = num;
}
if(num < lowest) {
lowest = num;
}
}
document.write("The highest number is: " + highest + "
");
document.write("The lowest number is: " + lowest);
```
Upvotes: 0 <issue_comment>username_3: * You need to convert to number every entered value, so you can use the object `Number` never use `parseInt` because this `4hhrh` will be converted to `4`.
* To avoid invalid values like letters, use the function `isNaN`.
* When an entered value is invalid, execute the statement `continue`.
* This statement gets the lowest value `lowest = num < lowest ? num : lowest;`.
```js
var highest = 0,
lowest = Number.MAX_VALUE;
while (true) {
var num = Number(prompt("Input a number"));
if (num == 0) {
break;
}
if (isNaN(num) || num < 0) {
alert("Input a valid number.");
continue
}
lowest = num < lowest ? num : lowest;
if (num > highest) {
highest = num;
}
}
document.write("The highest number is: " + highest + "
");
document.write("The lowest number is: " + lowest);
```
Upvotes: 1 [selected_answer]<issue_comment>username_4: Since you use zero to end, simply add a check for zero before you compare to `highest` and `lowest`. Also you should parse the value from string to number:
```js
var highest = 0, lowest = 0;
while (true) {
var num = parseInt(prompt("Input a number, 0 - when done"), 10);
if (num == 0) {
break;
}
if (num < 0 || isNaN(num)) {
alert("Input a valid number.");
continue;
}
if (highest == 0 || num > highest) {
highest = num;
}
if (lowest == 0 || num < lowest) {
lowest = num;
}
}
document.write("The highest number is: " + highest + "
");
document.write("The lowest number is: " + lowest);
```
Upvotes: 0 <issue_comment>username_5: You need to use a keyword (`var`, `let`, `const`) to every time you declare a new variable so you need `var lower = 0` and you'll need a semi colon separating your two declarations. Also you asterisks below are breaking the If statement. The following should work:
```
let highest = 0; let lowest = 999999;
while(true) {
let num = prompt("Input a number");
if(num == 0) {break;}
if(num < 0) {
alert("Input a valid number.");
}
if(num > highest) {
highest = num;
}
if(num < lowest) {
lowest = num;
}
}
document.write("The highest number is: " + highest + "
");
document.write("The lowest number is: " + lowest);
```
Also, `lowest` can't be set to 0 since you'll never have a number lower than that in your program. I set it to 99999 but you would need to use whatever your upper bound is or perhaps `null`.
Furthermore, consider researching the difference between `var`, `let` and `const`.
Upvotes: 2
|
2018/03/14
| 2,222 | 8,464 |
<issue_start>username_0: Imagine I have something that looks like this:
```
Stream stream = Stream.of(2,1,3,5,6,7,9,11,10)
.distinct()
.sorted();
```
The javadocs for both `distinct()` and `sorted()` say that they are "stateful intermediate operation". Does that mean that internally the stream will do something like create a hash set, add all the stream values, then seeing `sorted()` will throw those values into a sorted list or sorted set? Or is it smarter than that?
In other words, does `.distinct().sorted()` cause java to traverse the stream twice or does java delay that until a terminal operation is performed (such as `.collect`)?<issue_comment>username_1: Acording to the javadoc both [distinct](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--) and [sorted](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--) methods are stateful intermediate operations.
The [StreamOps](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps) says the following about this operations:
>
> Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream. As a result, under parallel computation, some pipelines containing stateful intermediate operations may require multiple passes on the data or may need to buffer significant data.
>
>
>
But the collect of the stream, happens only in the terminal operation (e.g. `toArray`, `collect` or `forEach`), both operations are processed in the pipeline and the data flows through it. Still, one important thing to note is the order in which this operations are executed, the javadoc of the `distinct()` method says:
>
> For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made.
>
>
>
---
For sequential streams, when this stream is sorted, the only element checked is the previous, when is not sorted a [HashSet](https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html) is used internally instead, for this reason executing `distinct` after `sort` results in a better performance.
(note: as commented by Eugene the performance gain may be tiny in this secuential streams, specially when the code is hot, but still avoids the creation of that extra temporal `HashSet`)
Here you can see more about the order of `distinct` and `sort`:
[Java Streams: How to do an efficient "distinct and sort"?](https://stackoverflow.com/questions/43806467/java-streams-how-to-do-an-efficient-distinct-and-sort)
---
By the other hand, for parallel streams the [doc](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps) says:
>
> Preserving stability for distinct() in parallel pipelines is relatively expensive (requires that the operation act as a full barrier, with substantial buffering overhead), and stability is often not needed. Using an unordered stream source (such as generate(Supplier)) or removing the ordering constraint with BaseStream.unordered() may result in significantly more efficient execution for distinct() in parallel pipelines, if the semantics of your situation permit.
>
>
>
A [full barrier operation](https://stackoverflow.com/questions/35189387/parallel-processing-with-infinite-stream-in-java) means that:
>
> All the upstream operations must be performed before the downstream can start. There are only two full barrier operations in Stream API: .sorted() (every time) and .distinct() (in ordered parallel case).
>
>
>
For this reason, when using parallel streams the opposite order is normally better (as long as the current stream is unordered), that is the use of `distinct` before `sorted`, because sorted can start to receive elements while distinct is being processed.
Using the opposite order, first sorting (an unordered parallel stream) and then using distinct, puts a barrier in both, first all elements have to be processed (flow) for `sort`, then all for `distinct`.
Here is an example:
```java
Function process = name ->
idx -> {
TimeUnit.SECONDS.sleep(ThreadLocalRandom
.current().nextInt(3)); // handle exception or use
// LockSupport.parkNanos(..) sugested by username_2
System.out.println(name + idx);
};
```
The below function receives a name, and retuns a int consumer that sleeps from 0-2 seconds and then prints.
```java
IntStream.range(0, 8).parallel() // n > number of cores
.unordered() // range generates ordered stream (not sorted)
.peek(process.apply("B"))
.distinct().peek(process.apply("D"))
.sorted().peek(process.apply("S"))
.toArray(); // terminal operation
```
This will print, Mix of B's and D's and then all S's (no barrier in `distinct`).
If you change the order of `sorted` and `distinct`:
```
// ... rest
.sorted().peek(process.apply("S"))
.distinct().peek(process.apply("D"))
// ... rest
```
This will print, all B's then all S's and then all D's (barrier in `distinct`).
If you want to try even more add an `unordered` after `sorted` again:
```java
// ... rest
.sorted().unordered().peek(process.apply("S"))
.distinct().peek(process.apply("D"))
// ... rest
```
This will print, All B's and then a mix of S's and D's (no barrier in `distinct` again).
---
Edit:
Changed a little the code to a better explanation and use of `ThreadLocalRandom.current().nextInt(3)` as sugested.
Upvotes: 3 <issue_comment>username_2: You have asked a loaded question, implying that there had to be a choice between two alternatives.
The stateful intermediate operations have to store data, in some cases up to the point of storing all elements before being able to pass an element downstream, but that doesn’t change the fact that this work is deferred until a terminal operation has been commenced.
It’s also not correct to say that it has to “traverse the stream twice”. There are entirely different traversals going on, e.g. in the case of `sorted()`, first, the traversal of the source filling on internal buffer that will be sorted, second, the traversal of the buffer. In case of `distinct()`, no second traversal happens in the sequential processing, the internal `HashSet` is just used to determine whether to pass an element downstream.
So when you run
```
Stream stream = Stream.of(2,1,3,5,3)
.peek(i -> System.out.println("source: "+i))
.distinct()
.peek(i -> System.out.println("distinct: "+i))
.sorted()
.peek(i -> System.out.println("sorted: "+i));
System.out.println("commencing terminal operation");
stream.forEachOrdered(i -> System.out.println("terminal: "+i));
```
it prints
```none
commencing terminal operation
source: 2
distinct: 2
source: 1
distinct: 1
source: 3
distinct: 3
source: 5
distinct: 5
source: 3
sorted: 1
terminal: 1
sorted: 2
terminal: 2
sorted: 3
terminal: 3
sorted: 5
terminal: 5
```
showing that nothing happens before the terminal operation has been commenced and that elements from the source immediately pass the `distinct()` operation (unless being duplicates), whereas all elements are buffered in the `sorted()` operation before being passed downstream.
It can further be shown that `distinct()` does not need to traverse the entire stream:
```
Stream.of(2,1,1,3,5,6,7,9,2,1,3,5,11,10)
.peek(i -> System.out.println("source: "+i))
.distinct()
.peek(i -> System.out.println("distinct: "+i))
.filter(i -> i>2)
.findFirst().ifPresent(i -> System.out.println("found: "+i));
```
prints
```none
source: 2
distinct: 2
source: 1
distinct: 1
source: 1
source: 3
distinct: 3
found: 3
```
As explained and demonstrated by [<NAME>’s answer](https://stackoverflow.com/a/49291012/2711488), the amount of buffering may change with ordered parallel streams, as partial results must be adjusted before they can get passed to downstream operations.
Since these operations do not happen before the actual terminal operation is known, there are more optimizations possible than currently happen in OpenJDK (but may happen in different implementations or future versions). E.g. `sorted().toArray()` may use and return the same array or `sorted().findFirst()` may turn into a `min()`, etc.
Upvotes: 4 [selected_answer]
|
2018/03/14
| 2,388 | 9,166 |
<issue_start>username_0: I need help getting two ImageViews to collide, I looked around on this website and many youtube videos and think I have found one solution to my problem. I found some code from another person post,
[how to detect when a ImageView is in collision with another ImageView?](https://stackoverflow.com/questions/24600378/how-to-detect-when-a-imageview-is-in-collision-with-another-imageview?answertab=active#tab-top)
and I'm just wondering where I should place that code in my program because when it's at the bottom i try to log.d to show if I was succesful on trying to detect whether the imageViews collided and nothing shows. Anyways here is my code and the code I used from the other question is at the very bottom and used as a comment. YOUR HELP IS EXTREMELY APPRECIATED, THANK YOU IF YOU HELPED ME!
Main.java
```
package com.example.admin.basketball;
import android.graphics.Point;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//Layout
private RelativeLayout myLayout = null;
//Screen Size
private int screenWidth;
private int screenHeight;
//Position
private float ballDownY;
private float ballDownX;
//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Images
private ImageView net = null;
private ImageView ball = null;
//for net movement along x-axis
float x;
float y;
//points
private int points = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLayout = (RelativeLayout) findViewById(R.id.myLayout);
//score
final TextView score = (TextView) findViewById(R.id.score);
//imageviews
net = (ImageView) findViewById(R.id.net);
ball = (ImageView) findViewById(R.id.ball);
//retrieving screen size
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
//move to out of screen
ball.setX(-80.0f);
ball.setY(screenHeight + 80.0f);
//start timer
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
changePos();
}
});
}
}, 0, 20);
}
public void changePos() {
//down
ballDownY += 10;
if (ball.getY() > screenHeight) {
ballDownX = (float) Math.floor((Math.random() * (screenWidth -
ball.getWidth())));
ballDownY = -100.0f;
}
ball.setY(ballDownY);
ball.setX(ballDownX);
//make net follow finger
myLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
MainActivity.this.x = event.getX();
y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
net.setX(MainActivity.this.x);
net.setY(y);
}
return true;
}
});
}
}
/*
private boolean viewsOverlap(ImageView net, ImageView ball) {
int[] net_coords = new int[2];
net.getLocationOnScreen(net_coords);
int net_w = net.getWidth();
int net_h = net.getHeight();
Rect net_rect = new Rect(net_coords[0], net_coords[1], net_coords[0] +
net_w, net_coords[1] + net_h);
int[] ball_coords = new int[2];
ball.getLocationOnScreen(ball_coords);
int ball_w = ball.getWidth();
int ball_h = ball.getHeight();
Rect ball_rect = new Rect(ball_coords[0], ball_coords[1], ball_coords[0]
+ ball_w, ball_coords[1] + ball_h);
return net_rect.intersect(ball_rect) || net_rect.contains(ball_rect) ||
ball_rect.contains(net_rect);
}*/
```<issue_comment>username_1: Let me give you an example how I implemented working collision detection in only 10 rows of code. It is not exactly the same problem but it can give you an idea how to manipulate objects based on coordinates.
```
// update the canvas in order to display the game action
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
int xx = 200;
int yy = 0;
if (persons != null) {
synchronized (persons) {
Iterator iterate = persons.iterator();
while (iterate.hasNext()) {
Person p = iterate.next();
if (p.getImage() != 0) {
bitmap = BitmapFactory.decodeResource(getResources(), p.getImage()); //load a character image
// Draw the visible person's appearance
if(xx > canvas.getWidth())
xx = 0;
canvas.drawBitmap(bitmap, xx , canvas.getHeight()- bitmap.getHeight() , null);
// Draw the name
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
canvas.save();
paint.setStrokeWidth(1);
paint.setColor(Color.WHITE);
paint.setTextSize(50);
canvas.drawText(p.name, (float)(xx+0.25\*bitmap.getWidth()), (float) (canvas.getHeight() ), paint);
xx += bitmap.getWidth()\*0.75;
}
}
}
}
canvas.save(); //Save the position of the canvas.
canvas.restore();
//Call the next frame.
invalidate();
}
}
```
In the above code, I just check if `xx` collides with an array of other images, then I just update `xx` accordingly. You are welcome to check out my [open source repository](http://github.com/montao/adventure) with this code.
Upvotes: -1 <issue_comment>username_2: Collision detction and score increase ;-)
=========================================
```
public class MainActivity extends AppCompatActivity
{
//Layout
private RelativeLayout myLayout = null;
//Screen Size
private int screenWidth;
private int screenHeight;
//Position
private float ballDownY;
private float ballDownX;
//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Images
private ImageView net = null;
private ImageView ball = null;
//score
private TextView score = null;
//for net movement along x-axis
public float x = 0;
public float y = 0;
//points
private int points = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
this.myLayout = (RelativeLayout) findViewById(R.id.myLayout);
this.score = (TextView) findViewById(R.id.score);
this.net = (ImageView) findViewById(R.id.net);
this.ball = (ImageView) findViewById(R.id.ball);
//retrieving screen size
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
//move to out of screen
this.ball.setX(-80.0f);
this.ball.setY(screenHeight + 80.0f);
//Error here
/*//Run constantly
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
Render();
}
}, 100); //100 is miliseconds interval than sleep this process, 1000 miliseconds is 1 second*/
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(100);
runOnUiThread(new Runnable() {
@Override
public void run(){Render();}});}
}catch (InterruptedException e) {}}};
t.start();
}
public void Render()
{
changePos();
if(Collision(net, ball))
{
points++; //You dont need findView Textview score for that exists in OnCreate Method
this.score.setText("Score:" + points);
}
}
public void changePos()
{
//down
ballDownY += 10;
if (ball.getY() > screenHeight) {
ballDownX = (float) Math.floor((Math.random() * (screenWidth - ball.getWidth())));
ballDownY = -100.0f;
}
ball.setY(ballDownY);
ball.setX(ballDownX);
//make net follow finger
myLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
x = event.getX();
y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
net.setX(x);
net.setY(y);
}
return true;
}
});
public boolean Collision(ImageView net, ImageView ball)
{
Rect BallRect = new Rect();
ball.getHitRect(BallRect);
Rect NetRect = new Rect();
net.getHitRect(NetRect);
return BallRect.intersect(NetRect);
}
}
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 558 | 1,840 |
<issue_start>username_0: Wondering is following code ever possible in Haskell?
```
equal :: a -> b -> Bool
equal a b = a == b
```<issue_comment>username_1: No, the type of `(==)` requires its arguments to be of the same type
```
(==) :: Eq a => a -> a -> Bool
```
You ask if it's possible (to test equality between different types), yes it is possible but not something you'd normally do. You can use [`Typeable`](https://hackage.haskell.org/package/base-4.10.1.0/docs/Type-Reflection.html) to witness that `a` and `b` are the same type but you need a `Typeable` constraint on both of them (and `Eq` constraint on either)
```
{-# Language ScopedTypeVariables #-}
{-# Language TypeApplications #-}
{-# Language ConstraintKinds #-}
{-# Language GADTs #-}
import Type.Reflection
type Equal a b = (Eq a, Typeable a, Typeable b)
equal :: forall a b. Equal a b => a -> b -> Bool
equal x y =
case eqTypeRep (typeRep @a) (typeRep @b) of
-- In this branch, `a' and `b' are the SAME type
-- so `(==)' works
Just HRefl -> x == y
-- Values of different types are never equal
Nothing -> False
```
so the following works
```
>> equal 10 'a'
False
>> equal 'X' 'a'
False
>> equal 'X' 'X'
True
```
Make sure you understand why we only constrain one of `Eq a`/`Eq b` and it doesn't matter which one.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Despite the fact `Eq` won't allow you to define that function due to `==`'s signature, you can define your own typeclass:
```
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
class Eqq a b where
eqq :: a -> b -> Bool
-- Just an example of a possible instance for general types
instance Eqq a b where
eqq a b = True
```
And then,
```
equal :: (Eqq a b) => a -> b -> Bool
equal a b = a `eqq` b
```
Upvotes: 2
|
2018/03/14
| 553 | 1,960 |
<issue_start>username_0: Consider the following code:
```
const log = ({a,b=a}) => console.log(a,b);
log({a:'a'})
```
The variable `b` is assigned the value `a`. This does work when transpiling it to es5, but I am not entirely sure if this is valid es6 syntax.
Am I allowed to do this kind of default value assignment in a destructured object?<issue_comment>username_1: ```
const log = ({a,b=a}) => console.log(a,b);
log('a')
```
is syntactically valid but semantically invalid, since you are trying to destructure a string primitive, which gets boxed into a temporary `String` object wrapper, and tries to get both `a` and `b` properties, which are always `undefined` since the wrapper object is temporary and only created for the sake of the operation triggering the boxing itself.
Thus you have `undefined, undefined` when you call it.
The destructuring operation with defaults could be semantically valid
in your case with a call like this:
```
const log = ({a,b=a}) => console.log(a,b);
log({a: 'a'}) // a,a
```
**UPD:**
But beware that order of supplying default value matters, so this won't
work
```
const log = ({a=b,b}) => console.log(a,b);
log({a: 'a'}) // error
```
because destructuring happens after argument object initialization and is evaluated from left to right, thus `b` is not yet destructured and known by the time we destructure `a` to try to reference it in case `a` is undefined.
Upvotes: 1 <issue_comment>username_2: >
> Am I allowed to do this kind of default value assignment in a destructured object?
>
>
>
Yes. The destructuring expression is evaluated from left to right, and you can use variables that are already initialised from properties in the default initialiser expressions of later properties.
Remember that it desugars to
```
const log = (o) => {
var a = o.a;
var b = o.b !== undefined ? o.b : a;
// ^ a is usable here
console.log(a,b);
};
```
Upvotes: 0
|
2018/03/14
| 778 | 2,889 |
<issue_start>username_0: How to run [Psiphon](https://www.psiphon3.com) from command line (to connect to a proxy server) and make it be applied to curl only (keeping other programs' connections un-proxy-ed)?
**Purpose:**
I'm using a script (written in perl) that uses **curl** by calling CMD command lines to perform web requests. I am looking for using Psiphon also via CMD command line, this way the script could call CMD command lines to connect to a server and use curl through Psiphon proxy.
**Note:**
I need Psiphon proxy to be working for **curl** only, keeping my other programs' connections normal as is.
**My attempt for solution:**
I've noticed that Psiphon uses an executable `psiphon-tunnel-core.exe`. I tried to run this executable file from CMD it tells me `{"data":{"data":{"message":"configuration file is required"},"noticeType":"Error","showUser":false,"timestamp":"2018-03-11T21:24:27.441Z"}`<issue_comment>username_1: Open `cmd` and type:
```
psiphon-tunnel-core.exe -help
```
You should be prompted the following:
```
Usage of C:\Users\dell\Desktop\test\psiphon-tunnel-core.exe:
-config string
configuration input file
-formatNotices
emit notices in human-readable format
-homepages string
homepages notices output file
-listenInterface string
bind local proxies to specified interface
-notices string
notices output file (defaults to stderr)
-rotating string
rotating notices output file
-rotatingFileSize int
rotating notices file size (default 1048576)
-rotatingSyncFrequency int
rotating notices file sync frequency (default 100)
-serverList string
embedded server entry list input file
-v print build information and exit
-version
print build information and exit
```
Upvotes: 0 <issue_comment>username_2: I just like to add something from above. Since you need Psiphon proxy to be working for curl only, the easiest way is start Psiphon3 main application (whichever command you want), then use proxifier/proxycap/freecap/widecap...to control which application uses your local proxy, or just use curl' --proxy flag (i.e. --proxy 127.0.0.1:8080). Be sure you followed the SkipProxySettings registry instructions here: <https://psiphon.ca/en/faq.html>
For the cmd query, in <https://github.com/Psiphon-Labs/psiphon-tunnel-core>, there's a simple script to run the consoleclient (psiphon-tunnel-core). Try placing the "consoleclient" in the Psiphon3 "Roaming" folder and run it from there. Be sure that your http proxy port is the same as in the config file. Configuration infos are found here in case you need it: <https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#Config>. The rest is all up to the user, but it's not recommended. (And even if this works, you still need to control the proxy for curl "only".)
Upvotes: 1
|
2018/03/14
| 513 | 1,939 |
<issue_start>username_0: I am applying Decision Tree to a data set, using sklearn
In Sklearn there is a parameter to select the depth of the tree -
dtree = DecisionTreeClassifier(max\_depth=10).
My question is how the max\_depth parameter helps on the model.
how does high/low max\_depth help in predicting the test data more accurately?<issue_comment>username_1: `max_depth` is what the name suggests: The maximum depth that you allow the tree to grow to. The deeper you allow, the more complex your model will become.
For training error, it is easy to see what will happen. If you increase `max_depth`, training error will always go down (or at least not go up).
For testing error, it gets less obvious. If you set `max_depth` *too high*, then the decision tree might simply overfit the training data without capturing useful patterns as we would like; this will cause testing error to increase. But if you set it *too low*, that is not good as well; then you might be giving the decision tree too little flexibility to capture the patterns and interactions in the training data. This will also cause the testing error to increase.
There is a nice golden spot in between the extremes of too-high and too-low. Usually, the modeller would consider the `max_depth` as a hyper-parameter, and use some sort of grid/random search with cross-validation to find a good number for `max_depth`.
Upvotes: 5 [selected_answer]<issue_comment>username_2: **if you are interested in the best precision according to max\_depth you can look at this**
```
L = []
for i in range(1,n):
dtree = DecisionTreeClassifier(max_depth=i)
dtree.fit(X_train,y_train)
y_pred = dtree.predict(X_test)
L.append(round(accuracy_score(y_test,y_pred),4))
print(L.index(max(L)))
print(max(L))
```
* 'n' it's up to you to look at the value you don't want to exceed
to avoid overfitting I advise you not to increase this value too much\*
Upvotes: 2
|
2018/03/14
| 356 | 1,164 |
<issue_start>username_0: How can I bind a property only when a variable is set to `true`?
```html
{{ icon }}
{{ title }}
export default {
name: 'list-tile-text-icon',
props: ['icon', 'title', 'route'],
data: () => ({
isItemSelected: false
}),
created() {
this.isItemSelected = window.location.href === this.route;
}
}
```
On line 4 I need to bind in `:color="$primaryColor"` only when the `isItemSelected` variable is equal to `true`.<issue_comment>username_1: The values used in `v-bind` are JavaScript **expressions**, thus you can use the [Conditional (ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator):
```html
```
*Note*: I'm calling it `v-bind` because `:` is just a shorthand to `v-bind`. I.e. `:color=""` is the same as `v-bind:color=""`
Upvotes: 4 [selected_answer]<issue_comment>username_2: [Vue class and style binding doc](https://v2.vuejs.org/v2/guide/class-and-style.html#ad)
this is the offical document about vue class and style binding,
detail:
```
```
then write the style you want
```
.someClassYouDefine {
color: $primaryColor;
}
```
Upvotes: 1
|
2018/03/14
| 1,603 | 3,973 |
<issue_start>username_0: I have the following `reprex` list of 10 sample matrices:
```r
# Sample of 10 3*3 matrices
z1 <- matrix(101:104, nrow = 2, ncol = 2)
z2 <- matrix(201:204, nrow = 2, ncol = 2)
z3 <- matrix(301:304, nrow = 2, ncol = 2)
z4 <- matrix(401:404, nrow = 2, ncol = 2)
z5 <- matrix(501:504, nrow = 2, ncol = 2)
z6 <- matrix(601:604, nrow = 2, ncol = 2)
z7 <- matrix(701:704, nrow = 2, ncol = 2)
z8 <- matrix(801:804, nrow = 2, ncol = 2)
z9 <- matrix(901:904, nrow = 2, ncol = 2)
z10 <- matrix(1001:1004, nrow = 2, ncol = 2)
# Combine all matrices into a single list
za <- list(z1, z2, z3, z4, z5, z6, z7, z8, z9, z10)
```
What we would like is to take `za` as an input and obtain `2 2*2 matrices` called an `upper_quantile` and `lower_quantile` matrices.
Essentially this is to take the above list of 10 matrices and take the upper 97.5% quantile for the **corresponding entries**. And the same for the lower 2.5% quantile.
In this case we can **manually** construct the `upper_quantile` matrix for this example as follows:
```r
upper_quantile <- matrix(data = c(quantile(x = seq(101, 1001, by = 100), probs = 0.975),
c(quantile(x = seq(102, 1002, by = 100), probs = 0.975)),
c(quantile(x = seq(103, 1003, by = 100), probs = 0.975)),
c(quantile(x = seq(104, 1004, by = 100), probs = 0.975)))
, nrow = 2
, ncol = 2
, byrow = FALSE)
upper_quantile
#> [,1] [,2]
#> [1,] 978.5 980.5
#> [2,] 979.5 981.5
```
I would like to understand how to do this using `purrr` or `tidyverse` tools as I have been trying to avoid cumbersome loops on lists and would like to adjust to dimensions automatically.
Could anyone please assist?<issue_comment>username_1: Here's a slightly clunky method which at least keeps everything in one pipe. It assumes that all the matrices are the same dimension, which needs to be true else the desired output doesn't make much sense. Working with matrices in `purrr` is always a little odd. The approach is basically to use `flatten` to make it easy to group the cells in the order we want, which is one column per location. That lets us map across columns to produce another vector, and then put that vector back into the right matrix. Might need some testing for larger matrices than 2x2.
The other approach I thought about was using `cross` to make a list of all index combinations, and then mapping through and creating the matrix cell by cell analogous to your example. Can attempt that if desired.
```r
library(tidyverse)
z1 <- matrix(101:104, nrow = 2, ncol = 2)
z2 <- matrix(201:204, nrow = 2, ncol = 2)
z3 <- matrix(301:304, nrow = 2, ncol = 2)
z4 <- matrix(401:404, nrow = 2, ncol = 2)
z5 <- matrix(501:504, nrow = 2, ncol = 2)
z6 <- matrix(601:604, nrow = 2, ncol = 2)
z7 <- matrix(701:704, nrow = 2, ncol = 2)
z8 <- matrix(801:804, nrow = 2, ncol = 2)
z9 <- matrix(901:904, nrow = 2, ncol = 2)
z10 <- matrix(1001:1004, nrow = 2, ncol = 2)
# Combine all matrices into a single list
za <- list(z1, z2, z3, z4, z5, z6, z7, z8, z9, z10)
quant_mat <- function(list, p){
dim = ncol(list[[1]]) * nrow(list[[1]])
list %>%
flatten_int() %>%
matrix(ncol = dim, byrow = TRUE) %>%
as_tibble() %>%
map_dbl(quantile, probs = p) %>%
matrix(ncol = ncol(list[[1]]))
}
quant_mat(za, 0.975)
#> [,1] [,2]
#> [1,] 978.5 980.5
#> [2,] 979.5 981.5
quant_mat(za, 0.025)
#> [,1] [,2]
#> [1,] 123.5 125.5
#> [2,] 124.5 126.5
```
Created on 2018-03-14 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0).
Upvotes: 3 [selected_answer]<issue_comment>username_2: This should do the trick for a single quantile using tidyverse:
```
tibble(za) %>%
mutate(za = map(za, ~ data.frame(t(flatten_dbl(list(.)))))) %>%
unnest(za) %>%
summarize_all(quantile, probs = .975) %>%
matrix(ncol = 2)
```
Upvotes: 0
|
2018/03/14
| 850 | 3,169 |
<issue_start>username_0: A data collection app that used `LocationManager` directly was updated to use `FusedLocationProviderApi`. With `LocationManager`, most devices quickly report 5m accuracy or better when collecting location. With `FusedLocationProviderApi`, the best accuracy ever reported is 10m.
I have just installed a location demo app and see the same behavior (<https://github.com/will-quast/android-location-demo>). In the Fused Location activity, if I only show GPS location, the accuracy changes as I get a better view of the sky and it can go down to 2m. If I only show fused, I get the same point as reported by `LocationManager`. This makes sense -- I have Android set to use GPS only for location and priority is set to `PRIORITY_HIGH_ACCURACY` so I expect the two points to always be the same. But the best accuracy ever displayed is 10m with the fused provider.
**Why does the fused provider never report an accuracy less than 10m?** Is this documented somewhere? Is there any way around it or should `LocationManager` always be used when a sense of accuracy is needed?
`FusedLocationProviderClient` is not currently an option because it requires an update to Google Play and this app is used in resource-constrained areas where a Google Play update is prohibitively large. It would still be useful to know whether it does report sub-10m accuracies. It also never reports an accuracy below 10m with Android settings set to use GPS only.
**Edit 4/9 -** Related questions:
* [Dramatic shift in location accuracy distribution starting February 15](https://stackoverflow.com/questions/49656301/dramatic-shift-in-location-accuracy-distribution-starting-february-15#)
* [Wierd and very unexpected issue with location.getAccuracy()](https://stackoverflow.com/questions/49238599/wierd-and-very-unexpected-issue-with-location-getaccuracy)
* [FusedLocationApi Performance Issue: Accuracy seems capped at 10.0 meters](https://stackoverflow.com/questions/49044731/fusedlocationapi-performance-issue-accuracy-seems-capped-at-10-0-meters)
* [Cordova geolocation accuracy gets capped at 10 meters](https://stackoverflow.com/questions/49348489/cordova-geolocation-accuracy-gets-capped-at-10-meters)<issue_comment>username_1: No. It is best effort only. No guarantee.
If you have a good devices, and in a location which has large number of Android user. (which for example, SSID database will become more accurate), it can go to 2-3m accuracy.
Otherwise, mixing location information from different source will have a larger variance, and result as lower accuracy.
e.g.
Source A accuracy is 5m.
Source B accuracy is 15m.
Using Source A alone of course accuracy is 5m.
But if mixed A and B, the accuracy of course will be >= 5m.
(consider adding noise to clean data)
Upvotes: 1 <issue_comment>username_2: This was confirmed as a Google Play Services bug [on the Google issue tracker](https://issuetracker.google.com/u/0/issues/79189573). A fix that allows accuracies down to 3m is projected for Play Services 13.4.0. It's unclear why it will be capped at 3m rather than using the accuracy reported by the raw location source.
Upvotes: 1 [selected_answer]
|
2018/03/14
| 2,798 | 10,420 |
<issue_start>username_0: I'm trying to use Eclipse write Spring boot application, however it encounter the following error:
```
** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.
2018-03-15 12:16:19.833 WARN 30196 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: URL [jar:file:/home/billcyz/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.0.0.RELEASE/spring-boot-autoconfigure-2.0.0.RELEASE.jar!/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration.class]; nested exception is java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration due to org/springframework/dao/DataAccessException not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
2018-03-15 12:16:19.847 ERROR 30196 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: URL [jar:file:/home/billcyz/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.0.0.RELEASE/spring-boot-autoconfigure-2.0.0.RELEASE.jar!/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration.class]; nested exception is java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration due to org/springframework/dao/DataAccessException not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.scanCandidateComponents(ClassPathScanningCandidateComponentProvider.java:454) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:316) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:275) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:132) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:284) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:241) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:198) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:166) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:316) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:693) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at SampleController.main(SampleController.java:8) [classes/:na]
Caused by: java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration due to org/springframework/dao/DataAccessException not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:55) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:109) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:88) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:71) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isConditionMatch(ClassPathScanningCandidateComponentProvider.java:515) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isCandidateComponent(ClassPathScanningCandidateComponentProvider.java:498) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.scanCandidateComponents(ClassPathScanningCandidateComponentProvider.java:431) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
... 20 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.getMatchOutcome(DataSourceAutoConfiguration.java:148) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
... 26 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.DataAccessException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_151]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_151]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_151]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_151]
... 28 common frames omitted
```
Here is the current dependency package used in this app:
```
org.springframework.boot
spring-boot-starter-parent
2.0.0.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
```
The same config works on another computer, but error happens when I moved to another work environment. Does this problem related to Maven? I doubt it is using other configs.<issue_comment>username_1: You may need to add more control to your component scans.
Each package component scan can trigger additional component scans.
You can controler this in the main applicaton class.
Spring says, "We recommend that you locate your main application class in a root package".
Here is an example how to controller your component scans.
```
@SpringBootApplication
@ComponentScan(basePackages = {
"com.webTemplate.config.web", // MVC @Configuration
"com.webTemplate.config.security", // Security @Configuration
"com.webTemplate.config.jpa", // Database @Configuration -> does Entity Scan and Repository scan
"com.webTemplate.service", // Service scan @Service
"com.webTemplate.controler", // Controller scan @Controller
})
public class WebTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(WebTemplateApplication.class, args);
}
}
```
Upvotes: 1 <issue_comment>username_2: The reason for this error was probably your *Application* class located in the default package. Try putting classes **into the certain package** (could be like com.invoices, us.cars, it.shoeshop). For example:
```
package com.invoices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
Upvotes: 4
|
2018/03/14
| 589 | 2,330 |
<issue_start>username_0: i am new with NDK , and would like some help from you. I am trying to run this [Project](https://github.com/ayuso2013/face-recognition-as) but it keeps me showing the Error `Invalid DT_NEEDED entry "../../lib/lipopencv_core.so"`. This may be happening because i am using the .so files compiled by someone else and storing these files in the `jniLibs/armeabi-v7a` folder directly and calling it in the java class with the `System.loadLibrary("opencv_java");`
After reading about this problem([#177](https://github.com/android-ndk/ndk/issues/177)) i discovered that the file had to be compiled with the `-soname` argument .
But how i do this?
Need to make a Android.mk for this? Or a CmakeList.txt?
I already have installed NDK, Cmake and LLDB.
Ty<issue_comment>username_1: You may need to add more control to your component scans.
Each package component scan can trigger additional component scans.
You can controler this in the main applicaton class.
Spring says, "We recommend that you locate your main application class in a root package".
Here is an example how to controller your component scans.
```
@SpringBootApplication
@ComponentScan(basePackages = {
"com.webTemplate.config.web", // MVC @Configuration
"com.webTemplate.config.security", // Security @Configuration
"com.webTemplate.config.jpa", // Database @Configuration -> does Entity Scan and Repository scan
"com.webTemplate.service", // Service scan @Service
"com.webTemplate.controler", // Controller scan @Controller
})
public class WebTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(WebTemplateApplication.class, args);
}
}
```
Upvotes: 1 <issue_comment>username_2: The reason for this error was probably your *Application* class located in the default package. Try putting classes **into the certain package** (could be like com.invoices, us.cars, it.shoeshop). For example:
```
package com.invoices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
Upvotes: 4
|
2018/03/14
| 553 | 2,197 |
<issue_start>username_0: The code below works, but I would like to know if there is a way to optimize it. The if..else statement has redundant code. I'm not familiar enough with array.reduce / array.map { } yet.
I have two arrays containing characters. I would like to count the number of deletions necessary in either/both arrays so they contain the same characters.
["a", "b"]
["a", "b", "c", "d", "e"]
would require 3 deletions.
```
var aArray = ["a", "b", "c"]
var bArray = ["a", "b", "c", "d", "e", "f", "g", "h"]
var newArray = [String]()
if aArray.count >= bArray.count {
for i in 0..
```<issue_comment>username_1: You may need to add more control to your component scans.
Each package component scan can trigger additional component scans.
You can controler this in the main applicaton class.
Spring says, "We recommend that you locate your main application class in a root package".
Here is an example how to controller your component scans.
```
@SpringBootApplication
@ComponentScan(basePackages = {
"com.webTemplate.config.web", // MVC @Configuration
"com.webTemplate.config.security", // Security @Configuration
"com.webTemplate.config.jpa", // Database @Configuration -> does Entity Scan and Repository scan
"com.webTemplate.service", // Service scan @Service
"com.webTemplate.controler", // Controller scan @Controller
})
public class WebTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(WebTemplateApplication.class, args);
}
}
```
Upvotes: 1 <issue_comment>username_2: The reason for this error was probably your *Application* class located in the default package. Try putting classes **into the certain package** (could be like com.invoices, us.cars, it.shoeshop). For example:
```
package com.invoices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
Upvotes: 4
|
2018/03/14
| 1,900 | 7,049 |
<issue_start>username_0: It defaults to my safari but would like to change it to chrome. I looked in preferences, but there doesn't seem to be an option for that. Any ideas?<issue_comment>username_1: If you are using the live server extension <https://github.com/ritwickdey/vscode-live-server> it has this setting:
>
> liveServer.settings.CustomBrowser:
>
>
> To change your system's default
> browser. Default value is "Null" [String, not null]. (It will open
> your system's default browser.) Available Options : chrome
> chrome:PrivateMode firefox firefox:PrivateMode microsoft-edge
>
>
>
Upvotes: 0 <issue_comment>username_2: If you had installed globally your live-server while using npm package, you can easily start your live-server on the browser of your choice by passing browser option on your launching command:
On your terminal type :`live-server --browser=BROWSER_NAME`
Eg:
`live-server --browser=firefox,
live-server --browser=safari`
and some macbooks accepts
`live-server --browser='Google Chrome'` for google chrome while others
`live-server --browser=google-chrome`
NB:For mac `live-server --browser=chrome` will throw an error
Upvotes: 1 <issue_comment>username_3: Go to **Files** > **Prefrences** > **Settings**
From Default User settings choose `LiveServer Config`
Inside it click on pen icon to the left on `liveServer.settings.CustomBrowser` select `chrome`.
Upvotes: 6 <issue_comment>username_4: You can do it in 2 steps:-
1) In `package.json` under `scripts` section create a key value as `"devserver": "live-server --browser=Chrome"`.
2) In terminal run `npm run devserver`
This will open application in chrome.
Upvotes: 1 <issue_comment>username_5: This is how I did it on MacOS (you have to hit the gear, then select "Configure Extension Settings")
[](https://i.stack.imgur.com/CRFzB.png)
Upvotes: 3 <issue_comment>username_6: 1. Go into settings. Shortcut: hold command then comma on mac.
2. In the top search bar search: liveServer.settings.CustomBrowser
3. You will see: Live Server > Settings: Custom Browser
4. In the drop down menu select whatever browser you want e.g. chrome or chrome:PrivateMode etc..
or
1. Open settings.json file
2. Type or copy and paste the following in the next line: "liveServer.settings.CustomBrowser": "chrome"
3. Make sure that there is a comma after the code in the previous line.
e.g.
```
"editor.formatOnSave": true,
"liveServer.settings.CustomBrowser": "chrome"
```
Upvotes: 5 <issue_comment>username_7: How to customize your non-traditional browser in "liveServer"?
==============================================================
1. Go to `Files > Preferences > Settings` and search `.json` and click on `settings.json` file
2. or press **`SHIFT + CTRL + P`** and tab `Preferences: Open Settings (JSON)`
3. Write on JSON file
`"liveServer.settings.AdvanceCustomBrowserCmdLine":` To set your any favorite browser (Eg: Chrome Canary, Firefox Nightly) using advance Command Line. (You can specify full path of your favorite custom browser).
* This setting will override `"CustomBrowser"` and `"ChromeDebuggingAttachment"` settings.
* Default Value is null
* Examples:
+ chrome --incognito --headless --remote-debugging-port=9222
+ C:\Program Files\Firefox Developer Edition\firefox.exe --private-window
Check out my [photo](https://i.stack.imgur.com/vs6uu.png) or see this [link on GitHub](https://github.com/ritwickdey/vscode-live-server/blob/master/docs/settings.md) for more details.
>
> Note: Either use `"AdvanceCustomBrowserCmdLine"` or `"CustomBrowser"`. If
> you use both, `"AdvanceCustomBrowserCmdLine"` has higher priority.
>
>
>
Upvotes: 2 <issue_comment>username_8: On Mac, via VS Code menu:
Code > Preferences > Settings > type `browser` in the Search settings box at the top
Upvotes: 0 <issue_comment>username_9: open the visual studio and go to
`file - preferences - extension` - right-click over Live server setting icon - then choose
edit in setting JSON
then you will find that sentence
`"liveServer.settings.AdvanceCustomBrowserCmdLine": ""`
just put your browser name between the double quotes
Upvotes: 0 <issue_comment>username_10: **liveServer.settings.CustomBrowser**:To change your system's default browser.
* Default value is null [String, not null]. (It will open your system's default browser.)
* Available Options :
+ Chrome
+ chrome:PrivateMode
+ firefox
+ firefox:PrivateMode
+ microsoft-edge
+ blisk
Not enough? need more? open an/a issue/pull request on github. For now, use `liveServer.settings.AdvanceCustomBrowserCmdLine` settings (see below).
* **`liveServer.settings.AdvanceCustomBrowserCmdLine`**:To set your any favorite browser (Eg: Chrome Canary, Firefox Nightly) using advance Command Line. (You can specify full path of your favorite custom browser).
* This setting will override CustomBrowser and ChromeDebuggingAttachment settings.
* Default Value is null
* **Examples**:
* `chrome --incognito --headless --remote-debugging-port=9222`
* `C:\Program Files\Firefox Developer Edition\firefox.exe --private-window //Remove --Private-windows for normal Window`
* **Note**: Either use AdvanceCustomBrowserCmdLine or CustomBrowser. If you use both, AdvanceCustomBrowserCmdLine has higher priority.
Upvotes: 0 <issue_comment>username_11: I was also looking for this, while trying to change to Google Chrome Dev.
And discovered you can practically change to any browser you want, just type the name of the app on your settings.json
Example:
```
"liveServer.settings.CustomBrowser": "Google Chrome Dev"
```
Upvotes: 2 <issue_comment>username_12: * Click windows+i
* Choose Apps
* Choose default apps
* Change (web browser ) to chrome (by change anyway)
Upvotes: 1 <issue_comment>username_13: Thanks! to above answers. On Mac select VS and press [**command + ,**] or from menubar choose **code->Preferences->Settings**. It will open the Settings tab and enter **live server config** in search bar follow the steps given below
[](https://i.stack.imgur.com/z9WDS.png)
Upvotes: 4 <issue_comment>username_14: ### steps (change default browser for *open with Live Server*)
1. Go to [**File** > **Prefrences** > **Settings**](https://i.stack.imgur.com/LJb70.png)
2. Copy and paste `liveServer.settings.CustomBrowser` into the *Search settings* bar
3. Find the setting: *Live Server › Settings: Custom Browser*
4. Choose **chrome** or **chrome:PrivateMode** from the [dropdown menu](https://i.stack.imgur.com/NdmsH.png)
Next time you **Open with Live Server** or **Go live**, the extension will automatically open with Chrome (no need to restart VSCode).
Upvotes: 1 <issue_comment>username_15: Open live server in Google Chrome Canary [MacOS]
`"liveServer.settings.AdvanceCustomBrowserCmdLine": "/Applications/Google Chrome Canary.app"`
Past this line in setting.json in place of `"liveServer.settings.CustomBrowser": "<-default browser->"`
Upvotes: 0
|
2018/03/14
| 364 | 1,161 |
<issue_start>username_0: I'm trying to do npm install for firebase but I keep running into errors...
I tried with npm version 5.6.0 and 5.7.1
I even tried installing assert-plus but that also failed (similar error to below). Any suggestions?
```
vagrant [polaris]> npm install firebase
npm ERR! path /vagrant/polaris/node_modules/grpc/node_modules/dashdash/node_modules/assert-plus/package.json.2882240414
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open '/vagrant/polaris/node_modules/grpc/node_modules/dashdash/node_modules/assert-plus/package.json.2882240414'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2018-03-14T23_28_13_938Z-debug.log
```<issue_comment>username_1: One quick suggestion. Delete your node\_modules folder and do a fresh 'npm install'.
Upvotes: 0 <issue_comment>username_2: You should use `npm install -g firebase-tools` instead of `npm install -g firebase`. After that, you'll be able to initialize your project on your PC.
Upvotes: 1
|
2018/03/14
| 991 | 2,583 |
<issue_start>username_0: I'm trying to replace the `panel.smooth` for argument `panel` in `pairs()` with a regression line drawing function instead of lowess line, with no success.
I tried to create function `reg` and place it for argument `panel` but that does not work? Any fix?
```
reg <- function(x, y) abline(lm(y~x)) # made to draw regression line instead of lowess line
panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y))
txt <- format(c(r, 0.123456789), digits = digits)[1]
txt <- paste0(prefix, txt)
text(0.5, 0.5, txt, cex = 1.1, font = 4)
}
#EXAMPLE OF USE:
pairs(USJudgeRatings[1:5], panel = panel.smooth, # replace HERE for panel.smooth #
cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)
```<issue_comment>username_1: You never used your function `reg`. I slightly modified `reg` to take a color argument. Instead of using `panel.smooth` (which gives the loess curve) I modified it to use the linear model and your reg function.
```
reg <- function(x, y, col) abline(lm(y~x), col=col)
panel.lm = function (x, y, col = par("col"), bg = NA, pch = par("pch"),
cex = 1, col.smooth = "red", span = 2/3, iter = 3, ...) {
points(x, y, pch = pch, col = col, bg = bg, cex = cex)
ok <- is.finite(x) & is.finite(y)
if (any(ok)) reg(x[ok], y[ok], col.smooth)
}
pairs(USJudgeRatings[1:5], panel = panel.lm,
cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2,
font.labels = 2, lower.panel = panel.cor)
```
[](https://i.stack.imgur.com/9kdb4.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: You need to define the scatterplot in `reg` along with the `lm` fit line.
```
reg <- function(x, y, ...) {
points(x,y, ...)
abline(lm(y~x))
}# made to draw regression line instead of lowess line
panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y))
txt <- format(c(r, 0.123456789), digits = digits)[1]
txt <- paste0(prefix, txt)
text(0.5, 0.5, txt, cex = 1.1, font = 4)
}
#EXAMPLE OF USE:
pairs(USJudgeRatings[1:5], upper.panel = reg, # replace HERE for panel.smooth #
cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)
```
[](https://i.stack.imgur.com/dwXhp.png)
Upvotes: 2
|
2018/03/14
| 861 | 2,149 |
<issue_start>username_0: I'm trying to add all the values of an object into one variable for the total, but I seem to be concatenating them instead?
```
binance.depth("BNBBTC", (error, depth, symbol) => {
a = 0;
for (value in depth.bids){
a += value;
};
console.log(a);
});
```
This is the output:
```
00.001081000.001080900.001080800.001080200.001080000.001079700.001079600.001079100
```
Any help would be much appreciated<issue_comment>username_1: You never used your function `reg`. I slightly modified `reg` to take a color argument. Instead of using `panel.smooth` (which gives the loess curve) I modified it to use the linear model and your reg function.
```
reg <- function(x, y, col) abline(lm(y~x), col=col)
panel.lm = function (x, y, col = par("col"), bg = NA, pch = par("pch"),
cex = 1, col.smooth = "red", span = 2/3, iter = 3, ...) {
points(x, y, pch = pch, col = col, bg = bg, cex = cex)
ok <- is.finite(x) & is.finite(y)
if (any(ok)) reg(x[ok], y[ok], col.smooth)
}
pairs(USJudgeRatings[1:5], panel = panel.lm,
cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2,
font.labels = 2, lower.panel = panel.cor)
```
[](https://i.stack.imgur.com/9kdb4.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: You need to define the scatterplot in `reg` along with the `lm` fit line.
```
reg <- function(x, y, ...) {
points(x,y, ...)
abline(lm(y~x))
}# made to draw regression line instead of lowess line
panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y))
txt <- format(c(r, 0.123456789), digits = digits)[1]
txt <- paste0(prefix, txt)
text(0.5, 0.5, txt, cex = 1.1, font = 4)
}
#EXAMPLE OF USE:
pairs(USJudgeRatings[1:5], upper.panel = reg, # replace HERE for panel.smooth #
cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)
```
[](https://i.stack.imgur.com/dwXhp.png)
Upvotes: 2
|
2018/03/14
| 685 | 2,436 |
<issue_start>username_0: I've run into a weird problem with Visual Studio 2017 (Enterprise, version 15.5.2) that I can only replicate on one specific machine. The problem doesn't occur on other development machines.
Given a file `foo.resources.json` with the following contents:
```js
{
"FooReparatur": "Reparatur",
"FooVerlust": "Verlust",
"FooWema": "Wema"
}
```
Applying the quick action `Sort Properties` results in the keys being in the wrong order:
```js
{
"FooReparatur": "Reparatur",
"FooWema": "Wema",
"FooVerlust": "Verlust"
}
```
The configured language for Visual Studio is English, there is no schema selected for the given file. The configured language for Windows is Estonian, but the sorting order is wrong by that alphabet as well.
I checked for any funny unicode characters or anything similar via a hexdump, but found nothing of the like either. As mentioned before, the file sorts correctly on all other machines.
I've tried disabling all the (default) extensions the installation has, but that doesn't resolve the problem either.
I've looked through most of the settings for both general text editing and the specific file type, but I can't find a setting that could cause this. What could be the issue? How can I debug this further?<issue_comment>username_1: This is a property of Estonian collation where 'V' and 'W' are treated as the same character. Hence, the next character that differs will be the significant one. As can be demonstrated by this C# code using .Net.
```
var words1 = new[] { "FooR", "FooVer", "FooWem" };
var words2 = new[] { "FooR", "FooVa", "FooWb" };
var estonianCultureInfo = new System.Globalization.CultureInfo("et-EE");
var estonianComparer = StringComparer.Create(estonianCultureInfo, false);
var sortedWords = words1.OrderBy(x => x, estonianComparer);
foreach (var word in sortedWords)
{
Console.WriteLine(word);
}
Console.WriteLine("[-----]");
sortedWords = words2.OrderBy(x => x, estonianComparer);
foreach (var word in sortedWords)
{
Console.WriteLine(word);
}
```
Output:
```
FooR
FooWem
FooVer
[-----]
FooR
FooVa
FooWb
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try to use this plugin to sort :
<https://marketplace.visualstudio.com/items?itemName=richie5um2.vscode-sort-json>
If dosn't work, try to install again the visual studio and choose language English to test if it work
Good Chance.
Upvotes: 0
|
2018/03/14
| 509 | 2,029 |
<issue_start>username_0: I'm trying to make a shooter game with different enemy and I'm trying to kill a boss with multiple hits but I can't see how I can do it. Can anyone explain it to me please?<issue_comment>username_1: The problem is that you're keeping track of the boss's health inside of `projectileDidCollideWithBoss`, but you're setting the boss's health to 10 every time you call the function (which means the lowest it will ever get is 9). You need to keep track of `monsterhp` outside of the function and just decrement it each time you call that collision function. You could do as <NAME> suggested and make the boss a subclass of SKSpriteNode with a health property. You could also make monsterhp a property of the scene, but your scene will start to get messy fast if you need to do that kind of thing a lot, so subclassing SKSpriteNode would be a better solution in the long term.
Upvotes: 2 <issue_comment>username_2: **Removal**:
Recommended common method is: when you detect that a node should be removed (from collision detection code) add it to a removal list, and remove every object in this list either in `didFinishUpdate` or `update`.
**Data management**:
Now if you need to attach some data to a node, subclass its type and add appropriate properties and methods.
Upvotes: 1 <issue_comment>username_3: to update my answer i just created a variable who represent life of the boss
```
var vieboss = 10
```
and i also created a function who setup the kill of the boss or not
```
func bossdead(projectile: Projectile!,boss1 : Boss!) {
print("Hit boss")
projectile.physicsBody?.isDynamic = false
projectile.physicsBody?.categoryBitMask = 0
projectile.removeFromParent()
vieboss1 -= 1
if (vieboss1 == 0) {
monstersDestroyed += 10
boss1.physicsBody?.isDynamic = false
boss1.physicsBody?.categoryBitMask = 0
boss1.removeFromParent()
}
}
```
and call the function bossdead when the projectile hit the boss
Upvotes: 1 [selected_answer]
|
2018/03/14
| 681 | 2,257 |
<issue_start>username_0: How can I write an SQL query to find those authors who has co-authored some paper together.
schema :
```
Authors (
authorID,
firstName,
);
Papers (
paperID,
title,
);
PaperbyAuthor (
authorID FOREIGN KEY REFERENCES Authors,
paperID FOREIGN KEY REFERENCES Papers
);
```<issue_comment>username_1: If you want the authors who co-authored a specific paper, try:
```
SELECT a.authorID, a.firstName
FROM Authors a
INNER JOIN PaperbyAuthor pa ON pa.authorID = a.authorID
INNER JOIN Papers p ON p.paperID = pa.paperID
WHERE p.paperID = 1000;
```
Change the value 1000 to ID of the paper that you want. If you want to find the paper by title, change the last line to:
```
WHERE p.title = 'The Best Paper';
```
Upvotes: 0 <issue_comment>username_2: This will list all the Authors with their PaperID for Authors that have worked on a paper together.
```
SELECT PA.paperID, GROUP_CONCAT(A.firstName separator ',') FROM PaperbyAuthor PA
INNER JOIN Authors A ON PA.authorID = A.authorID
WHERE paperID IN (SELECT paperID FROM PaperbyAuthor PA
GROUP BY paperID
HAVING COUNT(*) > 1)
```
You can also join the table with Papers if you need to see the title of the paper.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Are you just looking for pairs of authors?
```
select distinct min(authorID), max(authorID)
from PapersByAuthor pa
group by paperID
having count(authorID) = 2
```
Upvotes: 0 <issue_comment>username_4: This will give you every pair of authors twice: if John and Joe co-write a paper, there will be entries for
```
CoAuthor1 CoAuthor2 JointPapers
JOHN JOE 1
JOE JOHN 1
```
The code is:
```
SELECT
a1.firstName AS CoAuthor1,
a2.firstName AS CoAuthor2,
l.JointPapers
FROM
(
SELECT
pba1.authorID AS CoAuthorID1,
pba2.authorID AS CoAuthorID2,
COUNT(*) AS JointPapers
FROM
PaperByAuthor AS pba1
LEFT JOIN
PaperByAuthor AS pba2
ON
pba1.paperID = pba2.paperID
GROUP BY
pba1.authorID,
pba2.authorID
) AS l
LEFT JOIN
Authors AS a1
ON
l.CoAuthorID1 = a1.authorID
LEFT JOIN
Authors AS a2
ON
l.CoAuthorID2 = a2.authorID
```
Upvotes: 1
|
2018/03/14
| 886 | 3,406 |
<issue_start>username_0: I'm submitting a form to a Lambda function deployed by serverless, here's the yml:
```
functions:
hello:
handler: handler.hello
events:
- http: POST hello
```
Now my hello function is:
```
module.exports.hello = (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Go Se222rverless v1.0! Your function executed successfully!',
input: event,
}),
};
callback(null, response);
};
```
I can see on the output that the variables were passed, but they are stored in the event.body property as such:
```
"body":"email=test%40test.com&password=<PASSWORD>"
```
Now I can access this string, but I can't read individual variables from it, unless I do some regex transformation which, I believe, would not be the case in such a modern stack such as serverless/aws.
What am I missing? How do I read the individual variables?<issue_comment>username_1: You can use a the Node [`querystring`](https://nodejs.org/docs/latest-v9.x/api/querystring.html) module to parse the POST body.
Upvotes: 1 [selected_answer]<issue_comment>username_2: The handler documentation for the various programming models implies that the event type from the API Gateway is a low level stream. That means you have to use other methods to extract the body content from the POST.
[Input Format](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format)
```
{
"resource": "Resource path",
"path": "Path parameter",
"httpMethod": "Incoming request's method name"
"headers": {Incoming request headers}
"queryStringParameters": {query string parameters }
"pathParameters": {path parameters}
"stageVariables": {Applicable stage variables}
"requestContext": {Request context, including authorizer-returned key-value pairs}
"body": "A JSON string of the request payload."
"isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}
```
Dotnet
[Only the System.IO.Stream type is supported as an input parameter by default.](https://docs.aws.amazon.com/lambda/latest/dg/dotnet-programming-model-handler-types.html)
Python
[event](https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html) – This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type.
Upvotes: 0 <issue_comment>username_3: It looks like your Serverless endpoint is receiving data with `Content-Type: application/x-www-form-urlencoded`. You could update the request to use JSON data instead to access the post variables the same way you would other JavaScript objects.
Assuming this isn't an option; you could still access your post body data using the node querystring module to parse the body of the request, here is an example:
```
const querystring = require('querystring');
module.exports.hello = (event, context, callback) => {
// Parse the post body
const data = querystring.parse(event.body);
// Access variables from body
const email = data.email;
...
}
```
Just remember if some of the parameters in the post body use names that are invalid JavaScript object identifiers to use the square bracket notation, e.g.:
```
const rawMessage = data['raw-message'];
```
Upvotes: 3
|
2018/03/14
| 1,185 | 3,554 |
<issue_start>username_0: I am trying to do use a "clip path" on an image with a rounded path. I know there is a possibility to use svg clip paths, but I thought its not possible making it really responsive - so I decided to use the svg graphic on the div underneath the image - but I still have problems with mobile views, because only the left side of the svg is shown.
[](https://i.stack.imgur.com/58Izj.png)
Can you please help me to find a better solution for this? I'm open for every solution, even it may be a totally different (and maybe better) approach. I made a fiddle to play around and to understand the problem, if you drag the preview window to a mobile view you'll see what I mean:
<https://jsfiddle.net/Lrtgr858/16/>
```css
html,
body {
background-color: #F7F7F7;
padding: 0;
overflow-x: hidden;
}
.svg-image-clip {
overflow: hidden;
top: -90px;
position: relative;
display: block;
width: 120%;
height: auto;
content: '';
background-image: url(https://svgshare.com/i/5r3.svg);
background-size: cover;
height: 200px;
left: 60%;
transform: translateX(-60%);
-webkit-transform: translateX(-60%);
-moz-transform: translateX(-60%);
}
.fullsize-image-div {
width: 100%;
height: 300px;
background-image: url(http://fs1.directupload.net/images/180315/vlz5bgwm.jpg);
background-size: cover;
display: flex;
align-items: center;
justify-content: center;
}
.fullsize-image-div h1 {
color: white;
font-size: 3rem;
}
```
```html
Hello, this is a test.
======================
```<issue_comment>username_1: You have many options and there is no need for you to do an svg element, I'll provide 2.
**1.** You can use a pseudo element where you can have a border radius on the bottom sides only and give the border some white color... the reason I bring this first one up is it will work everywhere:
Example:
```
.fullsize-image-div:before {
content: "";
position: absolute;
bottom: -100px;
left: 50%;
margin-left: -900px;
height: 1000px;
width: 1600px;
border-radius: 100%;
border: 100px solid #fff;
}
```
I use your fiddle to just change some things. The sizing is just me duping it but you can edit it as you please:
[**FIDDLE**](https://jsfiddle.net/Lrtgr858/21/)
**2.** If you want modern CSS3 `clip-path`: This can easily be done with `ellipse()`:
```
clip-path: ellipse(100% 98% at 50% 0%);
```
I also added some `vw` for sizing/font so it can be more fluid when responsive but please note this will not work in IE(clip-path)...again you can edit as you please:
[**Codepen**](https://codepen.io/anon/pen/YaqLVe)
p.s. I like using codepen :)
Upvotes: 0 <issue_comment>username_2: You can achieve this using `clip-path`.
There is no need `svg-image-clip` this element. Remove this from your code.
Add `clip-path: ellipse(75% 100% at 50% 0%);` to `.fullsize-image-div`.
**Here is the working code**
```css
html,
body {
background-color: #F7F7F7;
padding: 0;
overflow-x: hidden;
}
.fullsize-image-div {
width: 100%;
height: 300px;
background-image: url(http://fs1.directupload.net/images/180315/vlz5bgwm.jpg);
background-size: cover;
display: flex;
align-items: center;
justify-content: center;
clip-path: ellipse(85% 100% at 50% 0%);
}
.fullsize-image-div h1 {
color: white;
font-size: 3rem;
}
```
```html
Hello, this is a test.
======================
```
Upvotes: 4 [selected_answer]
|
2018/03/14
| 1,318 | 4,133 |
<issue_start>username_0: I have done several searches on this but sadly due to the type of query I am after it invariably gives me PHP answers.
I will revert to code to generate the script but the more I think about it I know there *must* be a simplier way to do it in a single query which will be much faster.
My Code:
```
SELECT DISTINCT
se.mailingID AS "mailingID",
(
SELECT
SUM(l.averageReadTime)
FROM
eventlog AS l
INNER JOIN sends as s ON l.mailingIDKey=s.id
WHERE
s.TFPIDSanitised=se.TFPIDSanitised
AND
l.averagerEadtIme!="-1"
AND
l.averageReadTime!="(none)"
) AS "Total",
(
SELECT
SUM(l.averageReadTime)
FROM
eventlog AS l
INNER JOIN recipients AS r ON l.recipientKey=r.id
INNER JOIN devices AS d ON r.commonDeviceKey=d.id
INNER JOIN sends AS s ON l.mailingIDKey=s.id
WHERE
d.name="AOL Mail"
AND
s.mailingID=se.mailingID
AND
l.averageReadTime!="-1"
AND
l.averageReadTime!="(none)"
) AS "AOL Mail",
...
[repeat for all email app types]
...
(
SELECT
SUM(l.averageReadTime)
FROM
eventlog AS l
INNER JOIN recipients AS r ON l.recipientKey=r.id
INNER JOIN devices AS d ON r.commonDeviceKey=d.id
INNER JOIN sends AS s ON l.mailingIDKey=s.id
WHERE
d.name="AOL Desktop"
AND
s.mailingID=se.mailingID
AND
l.averageReadTime!="-1"
AND
l.averageReadTime!="(none)"
) AS "AOL Desktop"
FROM sends AS se
WHERE
(
se.sendDateTime BETWEEN '2018-01-01 00:00:00' AND '2018-01-15 23:59:59'
);
```
As you can see it is a monster of a query.
I am already considering removing one of the inner joins (the device name and just search on the devices.id bypassing the need for a 3rd JOIN).
What I am after, is to perform some sort of a loop within the query:
So its like (not real code I know)
```
SELECT LOOP (devices)
where device.id=recipients.commonDeviceKey
AS device.name
```
Is anything like this at all for mysql at all? I am going round in a loop (the irony of this is not lost on me) as mysql and loop do not bring up relevant answers.<issue_comment>username_1: You have many options and there is no need for you to do an svg element, I'll provide 2.
**1.** You can use a pseudo element where you can have a border radius on the bottom sides only and give the border some white color... the reason I bring this first one up is it will work everywhere:
Example:
```
.fullsize-image-div:before {
content: "";
position: absolute;
bottom: -100px;
left: 50%;
margin-left: -900px;
height: 1000px;
width: 1600px;
border-radius: 100%;
border: 100px solid #fff;
}
```
I use your fiddle to just change some things. The sizing is just me duping it but you can edit it as you please:
[**FIDDLE**](https://jsfiddle.net/Lrtgr858/21/)
**2.** If you want modern CSS3 `clip-path`: This can easily be done with `ellipse()`:
```
clip-path: ellipse(100% 98% at 50% 0%);
```
I also added some `vw` for sizing/font so it can be more fluid when responsive but please note this will not work in IE(clip-path)...again you can edit as you please:
[**Codepen**](https://codepen.io/anon/pen/YaqLVe)
p.s. I like using codepen :)
Upvotes: 0 <issue_comment>username_2: You can achieve this using `clip-path`.
There is no need `svg-image-clip` this element. Remove this from your code.
Add `clip-path: ellipse(75% 100% at 50% 0%);` to `.fullsize-image-div`.
**Here is the working code**
```css
html,
body {
background-color: #F7F7F7;
padding: 0;
overflow-x: hidden;
}
.fullsize-image-div {
width: 100%;
height: 300px;
background-image: url(http://fs1.directupload.net/images/180315/vlz5bgwm.jpg);
background-size: cover;
display: flex;
align-items: center;
justify-content: center;
clip-path: ellipse(85% 100% at 50% 0%);
}
.fullsize-image-div h1 {
color: white;
font-size: 3rem;
}
```
```html
Hello, this is a test.
======================
```
Upvotes: 4 [selected_answer]
|
2018/03/14
| 750 | 2,834 |
<issue_start>username_0: **CommentsCollection**
```
class CommentsCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
```
**CommentsController**
```
public function index()
{
$post = Post::find(1);
return ['post'=> $post, 'comments' => new CommentsCollection(Comment::paginate(1))];
}
```
**Response**
```
"comments": {
"data": [
{
"id": 1,
"content": "First comment",
"post_id": 6,
"account_id": 1,
"created_at": "2018-03-07 02:50:33",
"updated_at": "2018-03-07 02:50:34"
}
]
}
```
This happens when resource with use of `::collection` method or even ResourceCollection returned as a part of the array.
If we're going to remove array and return pure collection:
`return new CommentsCollection(Comment::paginate(1))`
everything is going to work fine and response will include **meta** and **links**.
Why does API Resource (using `collection` method or ResourceCollection) doesn't include pagination information when returned in array?<issue_comment>username_1: I have checked it locally and yes you are right it don't return the meta and links. So I have a solution which is working. Create a Post resource. And a resouce controller for your posts. Then on the single post api where you need comments, just return your comments explicitly.
```
class PostsResource extends Resource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'comments' => Comment::paginate(5)
];
}
}
```
So your controller code for the show which means the single post will be like this:
```
public function show($id)
{
return new PostsResource(Post::find($id));
}
```
Upvotes: 0 <issue_comment>username_2: I notice result of resource collection must return individually to work correctly
```
return ItemMiniResource::collection(
$items->paginate(10)
);
```
It's works perfectly, but
```
$data['items'] = ItemMiniResource::collection(
$items->paginate(10)
);
return $data
```
not include paginate links
Upvotes: 2 <issue_comment>username_3: i have encountered this problem and found a solution check the following link for a detailed description of the solution
<https://laracasts.com/discuss/channels/laravel/paginate-while-returning-array-of-api-resource-objects-to-the-resource-collection?reply=575401>
in short check the following code snippet that solve the problem
```
$data = SampleModel::paginate(10);
return ['key' => SampleModelResource::collection($data)->response()->getData(true)];
```
Upvotes: 3
|
2018/03/14
| 323 | 997 |
<issue_start>username_0: I want to use ViewBag value in JQuery. Does anyone provide me some idea how to do that.
```
//My code
Cost@ViewBag.Cost
//JQuery
var original = $("#spCost").val;
```
I also tried:
```
var original = '@ViewBag.Cost';
```
But, currently, it is showing no value in `original`.
Please help me.<issue_comment>username_1: At the end of your view, write something similar to this -
```
var original = @ViewBag.Cost;
alert(original);
```
OR
```
var original = @Html.Raw(@ViewBag.Cost);
alert("Text is: " + original.Text);
```
or if you want to use the viewbag value in a separate .js file, then create a js file something similar to this
```
var newJSFile = (function(my){
my.CostFromView = 0;
//Your code
}(newJSFile || {}));
```
and then at the end of your view,
```
$(function(){
newJSFile.CostFromView = @ViewBag.Cost;
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
var val = parseInt(@ViewBag.Cost);
```
Upvotes: 1
|
2018/03/14
| 387 | 1,200 |
<issue_start>username_0: I wrote the below JPQL.
```sql
select e.name from emp e where e.date = nvl(:date,select max(date) from emp e where e.id=1);
```
When I pass the date value, it should run the JPQL with the given date value. If I don't pass any date value then the JPQL should run with `max(date)`.
But getting an exception `inconsistent datatypes`.
Observations :
If I change the query to :
```sql
select e.name from emp e where e.date = :date
```
It is working fine. But when I use `nvl` I'm getting the exception.<issue_comment>username_1: At the end of your view, write something similar to this -
```
var original = @ViewBag.Cost;
alert(original);
```
OR
```
var original = @Html.Raw(@ViewBag.Cost);
alert("Text is: " + original.Text);
```
or if you want to use the viewbag value in a separate .js file, then create a js file something similar to this
```
var newJSFile = (function(my){
my.CostFromView = 0;
//Your code
}(newJSFile || {}));
```
and then at the end of your view,
```
$(function(){
newJSFile.CostFromView = @ViewBag.Cost;
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
var val = parseInt(@ViewBag.Cost);
```
Upvotes: 1
|
2018/03/14
| 741 | 2,604 |
<issue_start>username_0: I have the following models:
```
class Venue(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000, null=True, blank=True)
streetaddress1 = models.CharField(max_length=150)
streetaddress2 = models.CharField(max_length=150 ,null=True, blank=True)
approved = models.BooleanField(default=False)
declined = models.BooleanField(default=False)
eventplannerstaff = models.BooleanField(default=False)
declineddate = models.DateField(null=True, blank=True)
declineddatestring = models.CharField(max_length=50, blank=True, null=True)
declinereason = models.CharField(max_length=200, blank=True, null=True)
class Room(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
name = models.CharField(max_length=100, null=True, blank=True)
online = models.BooleanField(default=False)
description = models.CharField(max_length=1000, blank=True, null=True)
privateroom = models.BooleanField(default=False)
semiprivateroom = models.BooleanField(default=False)
seatedcapacity = models.CharField(max_length=10, null=True, blank=True)
standingcapacity = models.CharField(max_length=10, null=True, blank=True)
```
I have a REST endpoint with a delete method.
I am trying to delete a room. A room is tied to a venue. I am not deleting the room directly as I want to expose the venue in this method. The permission code isn't written yet, but I will be wanting to see if the user has the permissions to mess around with the venues room.
The delete method is working but it is not actually deleting the rooms from the database. What am I doing wrong?
```
def delete(self, request, *args, **kwargs):
venuepk = kwargs.get('venuepk', None)
venue = get_object_or_404(Venue, pk=venuepk)
venuerooms = venue.room_set.all()
roompk = kwargs.get('roompk')
roomobject = None
for room in venuerooms:
if room.pk == roompk:
roomobject = Room.objects.get(pk=roompk)
roomobject.delete()
roomobject.save()
return Response({})
return Response(status.HTTP_404_NOT_FOUND)
```<issue_comment>username_1: Actually you recreate them:
```
roomobject.delete()
roomobject.save()
```
First line delete the room, second line saves them again with the same ID.
If you want to delete them, only call `.delete()`
Upvotes: 1 [selected_answer]<issue_comment>username_2: Remove
```
roomobject.save()
```
It writes back the object to the db.
Upvotes: 1
|
2018/03/15
| 417 | 1,370 |
<issue_start>username_0: The issue I have is that when I parse a JSON string, which correctlyreturns an array of elements, I try to push a new element to the array with empty values.
The problem here is:
```
console.log('addons ', this.categories[this.editingId - 1].addons);
console.log('parsed ', JSON.parse(this.categories[this.editingId - 1].addons));
console.log('pushed ', JSON.parse(this.categories[this.editingId - 1].addons).push({name:'', price:''}));
```
>
> addons is [{"name":"Peppers","price":50},{"name":"Pepperoni","price":150},{"name":"Chicken","price":250},{"name":"Cheese","price":150},{"name":"Broccoli","price":100},{"name":"Corn","price":75},{"name":"Extra Sauce","price":250},{"name":"Extra Meat","price":350}]
>
>
>
that the last argument returns an integer for the length of the array when it should log the array with the newly pushed element to it.
How can I successfully push to the array?
A minimal example is displayed here:
<https://jsfiddle.net/L5p0ueqe/1/><issue_comment>username_1: Actually you recreate them:
```
roomobject.delete()
roomobject.save()
```
First line delete the room, second line saves them again with the same ID.
If you want to delete them, only call `.delete()`
Upvotes: 1 [selected_answer]<issue_comment>username_2: Remove
```
roomobject.save()
```
It writes back the object to the db.
Upvotes: 1
|
2018/03/15
| 1,293 | 4,239 |
<issue_start>username_0: I'm plotting image outline points [using this threshold method](https://stackoverflow.com/questions/7011801/image-outline-points-generator), but my outline has straight line segments. I want to plot the angle to the vertical at each point, so I really need curves.
I can get smooth curves using a convex hull.

The image was generated as follows:
```
B = bwboundaries(BW3);
outline = B{1,1};
plot(outline(:,2),outline(:,1),'r.','LineWidth',1)
K = convhull(outline(:,2),outline(:,1));
plot(outline(K,2),outline(K,1),'b+--','LineWidth',1)
```
But how can I "fill in the gaps" between the convex hull points? I want a point on the blue curve for every red point.
I tried to achieve this using interp1:
```
outline2 = outline;
outline2(:,2)=interp1(outline(K,1),outline(K,2),outline(:,1),'spline');
```
but got the following error:
"Error using griddedInterpolant
The grid vectors must contain unique points."
I assume it's because the outline forms a loop, not a unique x point for each y. Is there a different way to fill in those missing points using a spline?
I'm also open to other ideas for finding a smooth edge.
Thanks for any help!<issue_comment>username_1: Since your image seems smooth and well sampled, I would suggest that you find, for each edge pixel, the sub-pixel location of the true edge. With this we remove the need for the convex hull, which might be useful for your particular image, but does't generalize to arbitrary shapes.
Here is some code to accomplish what I suggest.
```
% A test image in the range 0-1, the true edge is assumed to be at 0.5
img = double(gaussianedgeclip(60-rr));
% Get rough outline
p = bwboundaries(img>0.5);
p = p{1,1};
% Refine outline
n = size(p,1);
q = p; % output outline
for ii=1:n
% Find the normal at point p(ii,:)
if ii==1
p1 = p(end,:);
else
p1 = p(ii-1,:);
end
if ii==n
p2 = p(1,:);
else
p2 = p(ii+1,:);
end
g = p2-p1;
g = (g([2,1]).*[-1,1])/norm(g);
% Find a set of points along a line perpendicular to the outline
s = p(ii,:) + g.*linspace(-2,2,9)';
% NOTE: The line above requires newer versions of MATLAB. If it
% fails, use bsxfun or repmat to compute s.
v = interp2(img,s(:,2),s(:,1));
% Find where this 1D sample intersects the 0.5 point,
% using linear interpolation
if v(1)<0.5
j = find(v>0.5,1,'first');
else
j = find(v<0.5,1,'first');
end
x = (v(j-1)-0.5) / (v(j-1)-v(j));
q(ii,:) = s(j-1,:) + (s(j,:)-s(j-1,:))*x;
end
% Plot
clf
imshow(img,[])
hold on
plot(p(:,2),p(:,1),'r.','LineWidth',1)
plot(q(:,2),q(:,1),'b.-','LineWidth',1)
set(gca,'xlim',[68,132],'ylim',[63,113])
```
[](https://i.stack.imgur.com/WOEHo.png)
The first line, that generates the test image, requires [DIPimage](http://www.diplib.org), but the rest of the code uses only standard MATLAB functions, except `bwboundaries`, which you were using also and is from the Image Processing Toolbox.
The output set of points, `q`, is not sampled at integer x or y. That is a whole lot more complicated to accomplish.
Also, sorry for the one-letter variables... :)
Upvotes: 3 [selected_answer]<issue_comment>username_2: Find the initial outline with Marching Squares (<https://en.wikipedia.org/wiki/Marching_squares#Isoline>).
Then if you want a good estimate of the derivatives, fit an interpolating Cubic Spline (<https://en.wikipedia.org/wiki/Spline_interpolation#Algorithm_to_find_the_interpolating_cubic_spline>).
Here there is a little technicality: it seems that you want the slope at the centers of the pixels. But the spline obtained from marching cubes will pass through known point the edges and not through the centers. You can
* project the center point to the nearest point on the spline (unfortunately requiring the solution of a higher degree polynomial);
* implicitize the cubic arc and compute the gradient of the implicit function.
If your accuracy requirements are not stringent, you may probably do by just using the segment direction in the tagreted pixel.
Upvotes: 1
|
2018/03/15
| 1,270 | 4,639 |
<issue_start>username_0: I have been trying to create a slideshow on one of the web pages I've been creating. I have created a div with a unique class name that is targeted in order to change the background image using JavaScript. So far, I have been able to do the following:
1. Capture the div where I want to change the background image by using the querySelector
2. Attempted to change the background image of said div using JavaScript
I have been debugging this function using DevTools, yet I cannot figure out why the image won't change. Any idea what is happening here? I have included snippets of the code below. Thank you.
HTML
```
❮
❯
```
CSS
```
.content-one-right {
grid-column: col-start 7 / span 6;
height: 60vh;
}
.inner-content-one-right {
height: 90%;
width: 90%;
}
.slideshow-container {
height: 100%;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
background-image: url('../images/home-slideshow/home1.jpg');
background-repeat: no-repeat;
background-size: cover;
}
.prev, .next {
cursor: pointer;
color: #FFF;
font-weight: bold;
font-size: 1em;
border-radius: 0 3px 3px 0;
}
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
```
JavaScript
```
var slideshowIndex = 0;
function transitionSlides(n) {
var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
slideshowIndex += n;
if(slideshowIndex < 0) {
slideshowIndex = images.length-1;
}
else if (slideshowIndex >= images.length) {
slideshowIndex = 0;
}
var getContainer = document.getElementsByClassName('slideshow-container')[0];
var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";
getContainer.style.backgroundImage = imageToChange;
}
```<issue_comment>username_1: I think the problem is in how you are trying to change the background image. The first time you set it, you are setting it in the stylesheet. You are using a CSS property there.
Later, you try to change it using the `.style` property of the element. These aren't the same thing. From [this page](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style):
>
> The style property is not useful for completely learning about the
> styles applied on the element, since it represents only the CSS
> declarations set in the element's inline style attribute, not those
> that come from style rules elsewhere, such as style rules in the
> section, or external style sheets.
>
>
>
To clarify, try this in your console on this very page: `document.querySelectorAll('input[type="submit"]')[3].style`
This grabs the blue button at the bottom of the page that says "Post Your Answer". It's pretty clearly got a blue background that is set in the CSS. But that CSSDeclaration object in your console has only *empty* values. That's because it only reflects the *inline* styles, not the styles you applied with CSS.
Fun, right? With that knowledge, I think you can choose one way or the other to make your slideshow happen the way you expect. It's probably easiest to not use background image at all, though. I think it's conventional to have an `img` tag there and use javascript to set the `src` attribute.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You're running into the same issue as seen [in this post](https://stackoverflow.com/questions/17378199/uncaught-referenceerror-function-is-not-defined-with-onclick). There's good information provided there too. When running your code in JSFiddle, it just throws the following exception: `transitionSlides is not defined.` Remove the onclick handler and use `addEventListener()` instead. It would be best to use ID's for your prev and next buttons but this will work:
HTML:
```
❮
❯
```
JavaScript:
```
var slideshowIndex = 0;
document.getElementsByClassName('prev')[0].addEventListener("click", function() {
transitionSlides(-1);
}, false);
document.getElementsByClassName('next')[0].addEventListener("click", function() {
transitionSlides(1);
}, false);
function transitionSlides(n) {
var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
slideshowIndex += n;
if(slideshowIndex < 0) {
slideshowIndex = images.length-1;
}
else if (slideshowIndex >= images.length) {
slideshowIndex = 0;
}
var getContainer = document.getElementsByClassName('slideshow-container')[0];
var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";
getContainer.style.backgroundImage = imageToChange;
}
```
Upvotes: 0
|
2018/03/15
| 955 | 3,662 |
<issue_start>username_0: I am working on a windows forms app and trying to connect to a sharepoint site. I do not have sharepoint installed on my PC so from my googling I have leant that I must use client side code.
When I right click references in my project and go to add reference the only one that has Sharepoint is
>
> Microsoft.Sharepoint.FirefoxPlugin
>
>
>
I do not believe that is what I am after. How do I get the client side DLLs required to connect to sharepoint from my windows form app?
**EDIT**
I tried following the guide in this link, but I do not have the .dll located in this location as the link shows
>
> Add the following assemblies from hive 15 (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI).
>
>
>
<https://www.c-sharpcorner.com/article/sharepoint-client-object-modal-csom/><issue_comment>username_1: I think the problem is in how you are trying to change the background image. The first time you set it, you are setting it in the stylesheet. You are using a CSS property there.
Later, you try to change it using the `.style` property of the element. These aren't the same thing. From [this page](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style):
>
> The style property is not useful for completely learning about the
> styles applied on the element, since it represents only the CSS
> declarations set in the element's inline style attribute, not those
> that come from style rules elsewhere, such as style rules in the
> section, or external style sheets.
>
>
>
To clarify, try this in your console on this very page: `document.querySelectorAll('input[type="submit"]')[3].style`
This grabs the blue button at the bottom of the page that says "Post Your Answer". It's pretty clearly got a blue background that is set in the CSS. But that CSSDeclaration object in your console has only *empty* values. That's because it only reflects the *inline* styles, not the styles you applied with CSS.
Fun, right? With that knowledge, I think you can choose one way or the other to make your slideshow happen the way you expect. It's probably easiest to not use background image at all, though. I think it's conventional to have an `img` tag there and use javascript to set the `src` attribute.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You're running into the same issue as seen [in this post](https://stackoverflow.com/questions/17378199/uncaught-referenceerror-function-is-not-defined-with-onclick). There's good information provided there too. When running your code in JSFiddle, it just throws the following exception: `transitionSlides is not defined.` Remove the onclick handler and use `addEventListener()` instead. It would be best to use ID's for your prev and next buttons but this will work:
HTML:
```
❮
❯
```
JavaScript:
```
var slideshowIndex = 0;
document.getElementsByClassName('prev')[0].addEventListener("click", function() {
transitionSlides(-1);
}, false);
document.getElementsByClassName('next')[0].addEventListener("click", function() {
transitionSlides(1);
}, false);
function transitionSlides(n) {
var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
slideshowIndex += n;
if(slideshowIndex < 0) {
slideshowIndex = images.length-1;
}
else if (slideshowIndex >= images.length) {
slideshowIndex = 0;
}
var getContainer = document.getElementsByClassName('slideshow-container')[0];
var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";
getContainer.style.backgroundImage = imageToChange;
}
```
Upvotes: 0
|
2018/03/15
| 870 | 3,413 |
<issue_start>username_0: When `Span` was announced, I wanted to use it in a parser for my toy programming language. (Actually, I'd probably store a `Memory`, but that's beside the point.)
However, I have grown used to switching on strings:
```
switch (myString) {
case "function":
return TokenType.Function;
// etc.
}
```
Switching on a `Span` won't work, and allocating a String to compare against kind of defeats the purpose of using a Span.
Switching to using if-else statements would result in the same problem.
So, is there a way to efficiently to this? Does `ToString()` on a `Span` not allocate?<issue_comment>username_1: Calling `ToString()` would cause an allocation because strings are immutable but something you could consider is using the various [MemoryExtensions Class](https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions?view=netcore-2.1) methods to perform the comparison. So you could leave your source code being parsed in a `Span` and use code such as the following:
```
System.ReadOnlySpan myString = "function test();".AsSpan();
if (myString.StartsWith("function".AsSpan()))
Console.WriteLine("function");
```
That will cause an intermediate string allocation for each token (the myString allocation was just to demonstrate) but you could initialize the token table as a once-off operation outside the token parser method. Also you might want to take a look into the `Slice` method as an efficient way to move through the code as you're parsing it.
And thanks to [username_2](https://stackoverflow.com/users/11683/gserg) for pointing out among other things that .NET Core can handle the implicit conversion from `string` to `ReadOnlySpan` so you can ommit the `AsSpan()` if using .NET Core.
Upvotes: 2 <issue_comment>username_2: [`System.MemoryExtensions`](https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions) contains methods that compare contents of `Span`s.
Working with .NET Core that supports implicit conversions between `String` and `ReadOnlySpan`, you would have:
```
ReadOnlySpan myString = "function";
if (MemoryExtensions.Equals(myString, "function", StringComparison.Ordinal))
{
return TokenType.Function;
}
else if (MemoryExtensions.Equals(myString, "...", StringComparison.Ordinal))
{
...
}
```
I'm calling the `MemoryExtensions.Equals` explicitly here because that way it is happy with the implicit conversion of the string literal (e.g. `"function"`) to a `ReadOnlySpan` for comparison purposes. If you were to call this extension method in an object-oriented way, you would need to explicitly use `AsSpan`:
```
if (myString.Equals("function".AsSpan(), StringComparison.Ordinal))
```
---
If you are particularly attached to the `switch` statement, you could abuse the pattern matching feature to smuggle the comparisons in, but that would not look very readable or even helpful:
```
ReadOnlySpan myString = "function";
switch (myString)
{
case ReadOnlySpan s when MemoryExtensions.Equals(s, "function", StringComparison.Ordinal):
return TokenType.Function;
break;
case ReadOnlySpan s when MemoryExtensions.Equals(s, "...", StringComparison.Ordinal):
...
break;
}
```
---
If you are not using .Net Core and had to [install](https://stackoverflow.com/a/47321870/11683) the System.Memory NuGet package separately, you would need to append `.AsSpan()` to each of the string literals.
Upvotes: 5
|
2018/03/15
| 830 | 2,588 |
<issue_start>username_0: I have the following object:
```
{ name: ["Jimmy","Jill"], age: [23, 42], location: { city: ["LA", "NYC"] }
```
For every object key there is an array value with 2 entries (always). What I'm trying to do is to recreate the object by plucking the 2nd item in the arrays. But I want this to happen recursively. So the output would be:
```
{ name: "Jill", age: 42, location: { city: "NYC" }
```
I have tried iterating through the object using `Object.keys()` but this doesn't appear to give me nested keys. I was wondering if there was a more elegant way to tackle this?
Many thanks in advance.<issue_comment>username_1: Is this considered okay? This only works if we assume every prop would either be an Array of a plain Object.
```js
let o = { name: ["Jimmy","Jill"], age: [23, 42], location: { city: ["LA", "NY"] }}
function rec(obj) {
for (let key in obj) {
if (obj[key] instanceof Array) {
obj[key] = obj[key][1]
} else {
obj[key] = rec(obj[key])
}
}
return obj
}
rec(o)
console.dir(o)
```
Or even this? (allows existence of array that contains objects and plain primitive entries)
```js
let o = {
primitive: 10,
name: ["Jimmy","Jill"],
age: [23, 42],
location: {
city: ["LA", "NY"],
test: [
{prop1: ['1', '2']},
{prop2: ['A', 'B']}
]
}
}
function rec(obj) {
if (obj instanceof Array) {
return rec(obj[1])
} else if (obj instanceof Object) {
for (let key in obj) {
obj[key] = rec(obj[key])
}
return obj
} else {
return obj
}
}
rec(o)
console.dir(o)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Late to the party, but here's a "functional" option to consider. Would need to be modified to accommodate any edge cases.
```
const reducer = input =>
Object.entries(input).reduce(
(acc, [key, value]) =>
value instanceof Array ? { ...acc, ...{ [key]: value[1] } } : { ...acc, ...reducer(value) },
{}
);
const input = { name: ["Jimmy", "Jill"], age: [23, 42], location: { city: ["LA", "NYC"] } };
const reduced = reducer(input);
console.log(reduced); // Output: { name: 'Jill', age: 42, city: 'NYC' }
```
Upvotes: 0 <issue_comment>username_3: Might be easier to filter during parsing:
```js
j = '{ "name": ["Jimmy","Jill"], "age": [23, 42], "location": { "city": ["LA", "NYC"] }}'
o = JSON.parse(j, (k, v) => v.constructor === Array ? v.pop() : v)
console.log( o )
```
Upvotes: 1
|
2018/03/15
| 988 | 3,249 |
<issue_start>username_0: I have been setting up some tests with Nightwatch. I ran the following basic test on their website.
```
module.exports = {
'Search on google': (browser) => {
browser
.url('http://www.google.com')
.waitForElementVisible('body', 1000)
.setValue('input[type=text]', 'nightwatch')
.waitForElementVisible('button[name=btnG]', 1000)
.click('button[name=btnG]')
.pause(1000)
.assert.containsText('#main', 'Night Watch')
.end()
},
after: (browser) => {
browser.end()
}
};
```
And got the following error:
`Timed out while waiting for element to be visible for 1000 milliseconds. - expected "visible" but got: "not visible"`
My first attempt at correcting was to change `.waitForElementVisible('button[name=btnG]', 1000)` to 10000 but still ended up getting `Timed out while waiting for element to be visible for 10000 milliseconds. - expected "visible" but got: "not visible"`.
Inspecting the google search button showed me that the button name was actually btnK so I tested that but it didn't work either returning `expected "visible" but got: "not found"`.
Very stumped and not sure where to go from here. Anyone have an idea?<issue_comment>username_1: Is this considered okay? This only works if we assume every prop would either be an Array of a plain Object.
```js
let o = { name: ["Jimmy","Jill"], age: [23, 42], location: { city: ["LA", "NY"] }}
function rec(obj) {
for (let key in obj) {
if (obj[key] instanceof Array) {
obj[key] = obj[key][1]
} else {
obj[key] = rec(obj[key])
}
}
return obj
}
rec(o)
console.dir(o)
```
Or even this? (allows existence of array that contains objects and plain primitive entries)
```js
let o = {
primitive: 10,
name: ["Jimmy","Jill"],
age: [23, 42],
location: {
city: ["LA", "NY"],
test: [
{prop1: ['1', '2']},
{prop2: ['A', 'B']}
]
}
}
function rec(obj) {
if (obj instanceof Array) {
return rec(obj[1])
} else if (obj instanceof Object) {
for (let key in obj) {
obj[key] = rec(obj[key])
}
return obj
} else {
return obj
}
}
rec(o)
console.dir(o)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Late to the party, but here's a "functional" option to consider. Would need to be modified to accommodate any edge cases.
```
const reducer = input =>
Object.entries(input).reduce(
(acc, [key, value]) =>
value instanceof Array ? { ...acc, ...{ [key]: value[1] } } : { ...acc, ...reducer(value) },
{}
);
const input = { name: ["Jimmy", "Jill"], age: [23, 42], location: { city: ["LA", "NYC"] } };
const reduced = reducer(input);
console.log(reduced); // Output: { name: 'Jill', age: 42, city: 'NYC' }
```
Upvotes: 0 <issue_comment>username_3: Might be easier to filter during parsing:
```js
j = '{ "name": ["Jimmy","Jill"], "age": [23, 42], "location": { "city": ["LA", "NYC"] }}'
o = JSON.parse(j, (k, v) => v.constructor === Array ? v.pop() : v)
console.log( o )
```
Upvotes: 1
|
2018/03/15
| 826 | 2,602 |
<issue_start>username_0: I am making a rota spreadsheet in Excel 2016 and would like a formula tied to a dropdown list to ignore an "Annual Leave" item in the list rather than do a calculation.
I have a drop down called "start time" and one called "finish time". So for example I choose a start time from `5:30am` and a finish time of `4:00pm`, the formula in the next cell is `=SUM(G7-H7)*-24`, so it would change from `0.00` to `10.50` to reflect the hours worked.
I would like to be able to add "annual Leave" to the drop down lists and have the formula ignore it completely, so that the formula would give `0:00`. Is this possible?<issue_comment>username_1: Is this considered okay? This only works if we assume every prop would either be an Array of a plain Object.
```js
let o = { name: ["Jimmy","Jill"], age: [23, 42], location: { city: ["LA", "NY"] }}
function rec(obj) {
for (let key in obj) {
if (obj[key] instanceof Array) {
obj[key] = obj[key][1]
} else {
obj[key] = rec(obj[key])
}
}
return obj
}
rec(o)
console.dir(o)
```
Or even this? (allows existence of array that contains objects and plain primitive entries)
```js
let o = {
primitive: 10,
name: ["Jimmy","Jill"],
age: [23, 42],
location: {
city: ["LA", "NY"],
test: [
{prop1: ['1', '2']},
{prop2: ['A', 'B']}
]
}
}
function rec(obj) {
if (obj instanceof Array) {
return rec(obj[1])
} else if (obj instanceof Object) {
for (let key in obj) {
obj[key] = rec(obj[key])
}
return obj
} else {
return obj
}
}
rec(o)
console.dir(o)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Late to the party, but here's a "functional" option to consider. Would need to be modified to accommodate any edge cases.
```
const reducer = input =>
Object.entries(input).reduce(
(acc, [key, value]) =>
value instanceof Array ? { ...acc, ...{ [key]: value[1] } } : { ...acc, ...reducer(value) },
{}
);
const input = { name: ["Jimmy", "Jill"], age: [23, 42], location: { city: ["LA", "NYC"] } };
const reduced = reducer(input);
console.log(reduced); // Output: { name: 'Jill', age: 42, city: 'NYC' }
```
Upvotes: 0 <issue_comment>username_3: Might be easier to filter during parsing:
```js
j = '{ "name": ["Jimmy","Jill"], "age": [23, 42], "location": { "city": ["LA", "NYC"] }}'
o = JSON.parse(j, (k, v) => v.constructor === Array ? v.pop() : v)
console.log( o )
```
Upvotes: 1
|
2018/03/15
| 630 | 2,129 |
<issue_start>username_0: I have the following code. What it does is that on click of an `li`, the dropdown for it will slide down. If another `li` beside it is clicked, another drop down menu slides down then the previous drop down slides back up.
However, if I were to click on the same `li` to "open" and "close" it, then the drop down menu will just slide down on first click, then on second click to try and "close" it, it will slide right back down again.
So the issue is that if I click on a parent link and click on it again immediately after, the drop down menu slides up, then down again. It doesn't stay "closed" or doesn't toggle.
Here is my code:
```js
$(".dropdown").click(function() {
$("li > ul").slideUp();
$('li > ul').not($(this).children("ul").slideToggle("swing"));
});
```
```html
- [Parent Link](#)
* + [dropdown link](/)
+ [dropdown link](/)
+ [dropdown link](/)
```<issue_comment>username_1: I dont know how is your html and css codes but this can give idea.
```js
$(".dropdown").click(function () {
$(".dropdown > ul").slideUp();
$(this).find("ul").slideDown();
})
```
```css
li.dropdown > ul{
display:none;
}
```
```html
* test1
+ testa
+ testb
* test2
+ testc
+ testd
```
Upvotes: 1 <issue_comment>username_2: If I understand correctly, you'd like click parent link to slide down all child menus, when click one child menu, slide it up, then slide down others.
Please see the comment of below codes for the details:
```js
$(".dropdown > ul").click(function(e) {
$("li > ul").slideUp(); //slide up the menu which user clicked
$('li > ul').not($(this)).slideDown(); //slide down other menu except the one user clicked
$(this).children("ul").slideToggle("swing");
e.stopPropagation(); //prevents the click event from bubbling up the DOM tree
});
$(".dropdown").click(function(e) {
$("li > ul").slideDown(); //slide down for all child ul
});
```
```html
- [Parent Link](#)
* + [dropdown link A](/)
+ [dropdown link A](/)
+ [dropdown link A](/)
* + [dropdown link B](/)
+ [dropdown link B](/)
+ [dropdown link B](/)
```
Upvotes: 0
|
2018/03/15
| 381 | 1,348 |
<issue_start>username_0: I am trying to write the line:
`const reg = new RegExp('\.js$');`
but my VSCode deletes the `\` from my regex on save. Is this a setting, or some issue with a plugin? Searched online, but wasn't finding any relevant answers.
For reference, plugins installed are:
- Angular v5 Snippets
- Beautify
- CodeMetrics
- Debugger for Chrome
- EditorConfig for VSCode
- npm
- npm Intellisense
- Prettier
- TSLint
- vscode-icons<issue_comment>username_1: Whether this will fix your problem or not, I'm not sure, but that regex should be:
```
const reg = new RegExp('\\.js$');
```
Since you're doing the regex as a string, you need to double your backslashes to represent a single backslash.
Or you could do:
```
const reg = /\.js$/;
```
It could be that VSCode is deleting the backslash the way you originally wrote this because it's an invalid escape.
Upvotes: 3 [selected_answer]<issue_comment>username_2: The offender is **Prettier**. If `formatOnSave` is activated in the editor/user settings
```
// Set the default
"editor.formatOnSave": true,
// Enable per-language
"[javascript]": {
"editor.formatOnSave": true
}
```
it will remove `\` in strings if it is not part of a valid escape sequence.
A valid escape sequence like `\\` or `\n` is not affected. So, this is actually in your best interest.
Upvotes: 3
|
2018/03/15
| 1,560 | 3,411 |
<issue_start>username_0: So I currently have a function that outputs sound barrier for the input height.
```
def soundbarier (y):
if 0 < y < 1524:
S = 340.3
elif 1524 < y < 3048:
S = 334.4
elif 3048 < y < 4572:
S = 328.4
elif 4572 < y < 6096:
S = 322.2
elif 6096 < y < 7620:
S = 316.0
elif 7620 < y < 9144:
S = 309.6
elif 9144 < y < 10668:
S = 303.6
elif 10668 < y < 12192:
S = 295.4
else:
S = 294.5
return (float(S))
```
I want to shorten it using a dictionary but I can't get it to work.
```
def SOUND(y):
return {
0 < float(y) < 1524: 340.3,
1524 < y < 3048: 334.4,
3048 < y < 4572: 328.4,
4572 < y < 6096: 322.2,
6096 < y < 7620: 316.0,
7620 < y < 9144: 309.6,
9144 < y < 10668: 303.6,
10668 < y < 12192: 295.4
}.get(y, 9)
print(SOUND(1500))
```
I don't really want any default values. How could I make it work? I basically need the function to output S for a certain Y within a range.<issue_comment>username_1: One general solution is to use [`numpy.digitize`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html) combined with a dictionary.
Note this doesn't deal with edge cases where your input is on a boundary, in which case [floating point approximations](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) may need careful attention.
```
import numpy
def SOUND(y):
bins = np.array([0, 1524, 3048, 4572, 6096, 7620, 9144, 10668, 12192])
values = np.array([340.3, 334.4, 328.4, 322.2, 316.0, 309.6, 303.6, 295.4])
d = dict(enumerate(values, 1))
return d[int(np.digitize(y, bins))]
SOUND(7200) # 316.0
```
Upvotes: 1 <issue_comment>username_2: [Mathemagic by @Tim](https://stackoverflow.com/questions/49289685/turning-a-function-with-multiple-if-else-statement-into-a-dictionary#comment85582568_49289685).
```
consts = [340.3, 334.4, 328.4, 322.2, 316.0, 309.6, 303.6, 295.4, 295.5]
def soundbarrier(y):
return consts[
-1 if (not (0 < y < 12192) or y % 1524 == 0) else y // 1524
]
```
```
In [1]: soundbarrier(1500)
Out[1]: 340.3
In [2]: soundbarrier(10000)
Out[2]: 303.6
In [3]: soundbarrier(100)
Out[3]: 340.3
In [4]: soundbarrier(1524)
Out[4]: 295.5
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: There is no built-in syntax for this, but you can implement it efficiently with 'bisect', which finds location of a number in a list for you.
```
def soundbar(y):
barrier_dict = {
1524: 340.0,
3048: 334.4,
4572: 328.4,
float('inf'): 0
}
height, barrier = zip(*sorted(barrier_dict.items()))
return barrier[bisect(height, y)]
print 1000, '->', soundbar(1000)
print 2000, '->', soundbar(2000)
print 2500, '->', soundbar(2500)
print 10000, '->', soundbar(10000)
```
outputs:
```
1000 -> 340.0
2000 -> 334.4
2500 -> 334.4
10000 -> 0
```
Upvotes: 2 <issue_comment>username_4: The problem with your code is that python will evaluate the keys in your dictionary to True/False.
How about creating a mapping table(ie a dictionary of tuples to values) like this:
```
sound_barrier = { (0, 1524): 340.3, (1524, 3048): 334.4, (3048, 4572): 328.4, ... }
def get_mapping(table, value):
for k in table:
if k[0] < value < k[1]:
return table[k]
get_mapping(sound_barrier, 2000)
```
Upvotes: 0
|
2018/03/15
| 878 | 3,104 |
<issue_start>username_0: I tried to do something similar today. I was surprised it didn't compile.
```
struct Test {
// v----- Remove me to compile
// /*
static constexpr auto get_test1 = [](Test const& self) {
return self.test; // error, Test is incomplete
};
// */
// Handwritten version of the lambda
struct {
constexpr auto operator() (Test const& self) const {
return self.test; // ok
}
}
static constexpr get_test2{};
int test;
};
```
[Live example](https://godbolt.org/g/rQ21WU)
It says that the `Test` type is incomplete in the scope. Yet the handwritten version of the lambda does indeed work. What is the technical reason for that? Is it an oversight in the standard, or is there a specific wording that makes `Test` incomplete in the lambda?<issue_comment>username_1: This is what I could find:
>
> §5.1.2 Lambda expressions [expr.prim.lambda]
>
>
> 5. [...] [ Note: Names referenced in the lambda-declarator are looked up in the context in which the lambda-expression appears. —end note ]
> 6. The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator, but for purposes of name lookup
> (3.4), [...] the compound-statement is considered in the context of
> the lambda-expression.
>
>
>
If I am not misreading the standard this means that `Test` and `self` both in the parameter as well in the body are looked/considered in the context of the lambda, which is the class scope in which `Test` is incomplete.
As for why it is allowed with the nested class:
>
> §9.2 Class members [class.mem]
>
>
> 2. A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the classspecifier . Within the
> class member-specification, the class is regarded as complete within
> function bodies, default arguments, using-declarations introducing
> inheriting constructors (12.9), exception-specification s, and
> brace-or-equal-initializer s for non-static data members (including
> such things in nested classes). Otherwise it is regarded as incomplete
> within its own class member-specification.
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: I think that your compiler is correct. `Test` is still incomplete. The processing of such a data member’s initializer (which is what requires the type to be complete) is not deferred until the end of the class definition.
I couldn't find the part of the Standard that deals with this issue, but I remember it was raised as a National Body comment of the C++17 draft (US 24, [P0488R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0488r0.pdf)):
>
> The current specification prohibits `constexpr static` data members that are of the same type as the
> enclosing class.
>
>
> Example:
>
>
>
> ```
> struct A {
> int val;
> static constexpr A cst = { 42 }; // error
> };
>
> ```
>
>
Apparently, lifting completely the restriction may have caused some breaking changes so that the comment "did not increase consensus".
Upvotes: 0
|
2018/03/15
| 401 | 1,552 |
<issue_start>username_0: I am using last version of PGP Guzzle HTTP... Very simple test done :
```
use GuzzleHttp\Client;
$client = new Client();
$res = $client->post('https://MYAPI/cards/XXX/credit',[
'headers' => ['Authorization' => 'Token MYTOKEN'],
'json' => [
"amount" => 10,
"reason" => "Because"
]
]);
var_dump($res);
```
returned a Exception:
```
GuzzleHttp\Exception\ClientException : Client error: `POST
https://MYAPI/cards/XXX/credit` resulted in a `405 Method Not Allowed`
response:
{"detail":"Méthode \"GET\" non autorisée."}
```
Any idea ? the REST API server I am calling is made with Django DRF. But this is nonsense to think it might be incompatible....
Thanxs for any idea.<issue_comment>username_1: You get very clear error that the server doesn't accept POST request. I don't know, is it right or not. If have control over the server also, you check the code there, maybe it's just a bug in it.
Basically you cannot talk about compatibility or incompatibility, because it's just simple HTTP and it works. You can have an issue either in communications between you and the server developers or a bug in the server.
Upvotes: 1 <issue_comment>username_2: Well, it was neither Guzzle nor DRF whiche failed.... only one parameter in DRF urls that does not accept trailing / in rest entry points....
simply adding / after the credit url and everything worked fine....
Strange behaviour somehow for DRF to display this kind of misleading error message .
Upvotes: 0
|
2018/03/15
| 517 | 1,673 |
<issue_start>username_0: I'm trying to learn how to use Retrofit2, and this is the URL I have to generate:
`(baseUrl)/repositories?q=language:Python&sort=stars&page=1`
This is the method I'm using:
```
Call> javaRepos(
@Query("language") String language,
@Query("sort") String sort,
@Query("page") int page
);
```
and this is how I'm calling it:
`Call> call = client.javaRepos("Python", "stars", 1);`
However, this is the url my code generates:
`(baseUrl)/repositories?language=Python&sort=stars&page=1`
The differences are:
* the `q=` is missing;
* `language` is followed by a `=` instead of a `:`
How can I generate the correct url using `@Query` parameters (or any other way, actually)?<issue_comment>username_1: You need to use Path annotation according to this link : <https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Path.html>
```
@GET("repositories?q=language:{lang}&sort={sort}&page={page}")
Call> javaRepos(@Path(value = "lang") String lang, @Path(value = "sort") String sort, @Path(value = "page") int page);
```
Upvotes: -1 <issue_comment>username_2: Looks like you're misinterpreting the query string of your desired url.
`q=language:Python&sort=stars&page=1` should be broken down into three key-value pairs:
* `q` - `language:Python`
* `sort` - `stars`
* `page` - `1`
Note that the first key is `q` and not `language`.
With that in mind, your method should look like this (and you'll have to pass `"language:Python"` instead of just `"Python"` as the first argument).
```
Call> javaRepos(
@Query("q") String language,
@Query("sort") String sort,
@Query("page") int page
);
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 993 | 3,156 |
<issue_start>username_0: Still learning web dev so here is my question. I am wondering why when using a container class at the very beginning of my layout, and when adding a row with two Col-md-6 columns, the content extends past the container. The two columns with the forms inside extend past the jumbotron on both sides. Just confused. I think if I add an another container it would even it all out. Just dont know why that would be needed.
```js
var toggle = function(){
var exists = document.querySelector("#existButton");
console.log(exists.innerHTML);
if(exists.classList.contains("btn-warning")){
exists.classList.remove("btn-warning");
exists.classList.add("btn-info");
exists.innerHTML = "copy";
//document.getElementById("#existButton").innerHTML = 'check'
} else {
exists.classList.remove("btn-info");
exists.classList.add("btn-warning");
exists.innerHTML="check";
//document.getElementById("#existButton").innerHTML = 'copy'
}
}
```
```css
body{
/*background: repeating-linear-gradient(
to right,
#050210,
#050210 50px,
#271f41 50px,
#271f41 100px
)*/
background-image: url(images/body_background.png);
}
.jumbotron {
margin-bottom: 0;
background-color: #cbd0d3;
}
.container .jumbotron{
border-radius: 0px;
}
.navbar{
margin-bottom: 0;
background-color: #44abe2;
margin-top: 30px;
}
.navbar-default .navbar-nav>li>a {
color: white;
}
.navbar .navbar-default {
border-radius: 0px;
}
.navbar-default .navbar-brand{
color: white;
}
.automatic {
background-color: #6e8a99;
padding-bottom: 40px;
border-bottom-left-radius: 6px;
}
.manual {
background-color: #83929a;
padding-bottom: 40px;
border-bottom-right-radius: 6px;
}
#ml-2{
padding-right:0;
}
```
```html
Mailbox Creator
[Brand](#)
* [Mailbox Management](#)
[User Mailbox Management](#)
[Resource Mailbox Management](#)
[Mailbox Update Management](#)
* Hello Username
Mailbox Creator Pro
===================
#### Automatic
Account Name
Create
Does account have email?
Check
#### Manual
Email
Account
Create
Email exist?
[Check](#)
Copy
```<issue_comment>username_1: You need to use Path annotation according to this link : <https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Path.html>
```
@GET("repositories?q=language:{lang}&sort={sort}&page={page}")
Call> javaRepos(@Path(value = "lang") String lang, @Path(value = "sort") String sort, @Path(value = "page") int page);
```
Upvotes: -1 <issue_comment>username_2: Looks like you're misinterpreting the query string of your desired url.
`q=language:Python&sort=stars&page=1` should be broken down into three key-value pairs:
* `q` - `language:Python`
* `sort` - `stars`
* `page` - `1`
Note that the first key is `q` and not `language`.
With that in mind, your method should look like this (and you'll have to pass `"language:Python"` instead of just `"Python"` as the first argument).
```
Call> javaRepos(
@Query("q") String language,
@Query("sort") String sort,
@Query("page") int page
);
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 575 | 2,041 |
<issue_start>username_0: I am trying to execute this code and it shows 'NoSuchElementException' this error.
So can anyone help me for this ?
Code:
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver= webdriver.Chrome()
page=driver.get("http://www.awgp.org")
banner_tell=driver.find_element_by_Link_text('Tell Me More')
banner_tell.click()
```<issue_comment>username_1: I think all you need to do is give link text in uppercase but this link is dynamic as the banner auto-slides to the next one.
You should come up with another locator to click on exactly the locator you want to click. Otherwise you might get `ElementNotVisibleException` if the banner is changed.
```
banner_tell=driver.find_element_by_link_text('TELL ME MORE')
```
Upvotes: 1 <issue_comment>username_2: try with xpath
```
banner_tell= driver.find_element_by_xpath("//*[contains(text(),'TELL ME MORE')]")
```
Upvotes: 0 <issue_comment>username_3: Seems you were almost near however the `function()` should have been :
```
find_element_by_link_text()
```
To click on the button with text as **TELL ME MORE** you have to induce [WebDriverWait](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.wait.html#module-selenium.webdriver.support.wait) with [expected\_conditions](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#module-selenium.webdriver.support.expected_conditions) clause [`element_to_be_clickable`](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.element_to_be_clickable) as follows :
```
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "TELL ME MORE"))).click()
```
Upvotes: 0
|