qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
44,672,854 | I want to set the condition using `AND` and `OR` in `WHERE` clause. But the problem is AND condition is not setting to all other `OR` Condition
ex:
```
SELECT
Item,
Name,
Brand,
Date,
StoreID
FROM
Item
WHERE
Date between '01-01-2017' and '30-01-2017'
OR Brand = 'Nike' or Brand = 'Jhonson' OR Brand = 'Polo'
```
>
> In my scenario I cannot use IN to select multiple Brand. So I want to set all Date filter to all the brands. How can I achieve it.
>
>
>
Thanks | 2017/06/21 | [
"https://Stackoverflow.com/questions/44672854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734785/"
] | We have two Scenario here as follows
```
SELECT
Item,
Name,
Brand,
Date,
StoreID
FROM
Item
WHERE
Date between '01-01-2017' and '30-01-2017'
OR (Brand = 'Nike' or Brand = 'Jhonson' OR Brand = 'Polo')
SELECT
Item,
Name,
Brand,
Date,
StoreID
FROM
Item
WHERE
Date between '01-01-2017' and '30-01-2017'
AND (Brand = 'Nike' or Brand = 'Jhonson' OR Brand = 'Polo')
``` | ```
SELECT
Item,
Name,
Brand,
Date,
StoreID
FROM
Item
WHERE
Date between '01-01-2017' and '30-01-2017'
AND ( Brand = 'Nike' or Brand = 'Jhonson' OR Brand = 'Polo')
```
It can be right with your result. |
22,342,450 | I am doing a project on spring MVC with maven.I pass my data using Ajax to the controller.it is ok..but when i call the function for delete,i got org.hibernate.MappingException: Unknown entity: java.lang.Integer . below my codes..waiting for your reply
web.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>AccPerSpring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AccPerSpring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
spring-context.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable @Controller annotation support -->
<mvc:annotation-driven />
<!-- Map simple view name such as "test" into /WEB-INF/views/test.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
<context:component-scan base-package="com.gerrytan.pizzashop"/>
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<!-- <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="username" value="root"/>
<property name="password" value="kca@fnpl#12"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.gerrytan.pizzashop</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
```
Accountsconttroller .java
```
package com.gerrytan.pizzashop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
@Controller
@RequestMapping(value="/account")
public class AccountsController {
@Autowired
private AccountService accountService;
@Autowired
private AccountDAO accountDao;
private Accounts accounts;
@RequestMapping(value="/list",method = RequestMethod.GET,produces="application/json")
@ResponseBody
public String getAllAccounts(ModelMap model){
model.addAttribute("count",accountDao.getRowCount());
model.addAttribute("allAddress",accountDao.getAccounts());
String json= new Gson().toJson(model);
return json;
}
@RequestMapping(value="/delete",method=RequestMethod.POST,produces="application/json")
@ResponseBody
public ModelMap deleteRow(ModelMap model,@RequestParam(value = "id", required = true) int id) {
System.out.println(id);
accountDao.delete(id);
model.addAttribute("messageKey", "1");
model.addAttribute("id", id);
return model;
}}
```
implimentation.java
```
@Override
public void delete(int id) {
getCurrentSession().delete(id);
System.out.println("fgfgfgfgf");
}
```
my error is when iam calling the function delete from controller | 2014/03/12 | [
"https://Stackoverflow.com/questions/22342450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3011943/"
] | Notice the hibernate method `getCurrentSession().delete(Object obj)`, not just give an `id` as parameter.
```
@Override
public void delete(int id) {
Account accounts = new Accounts();
// hibernate deletes objects by the primary key
accounts.setId(id);
getCurrentSession().delete(accounts);
}
``` | The `getCurrentSession()` method would return an implementation of the `session` interface. Looking up the [javadocs](http://docs.jboss.org/hibernate/orm/3.6/javadocs/) from 3.6 and further for Hibernate.
It supports 2 methods for deletion
```
void delete(Object object)
Remove a persistent instance from the datastore.
void delete(String entityName, Object object)
Remove a persistent instance from the datastore.
```
In your `accountsDAO.delete()` method, you are passing in a String `id` to the delete method.
You would have to fetch the `Account` that you want to delete and pass the `Account` object for deletion. What Jiang mentioned would work too. |
40,728,432 | I need help making a php function. I want to create a function that removes everything before a specific word or character in a string. I know how to do that part, but I am new to making a function out of it, and I need to add an option to it... for example. If I have this string...
```
$str="I like to eat cheese, crackers and ham";
```
And I want to remove everything before the word cheese I could use this...
```
if(($pos=strpos($str,'cheese'))!== false) $str=substr($str,$pos);
```
and I'd end up with
>
> cheese, crackers and ham
>
>
>
if I want to include the word cheese in the removal, I could use...
```
if(($pos=strpos($str,'cheese'))!== false) $str=substr($str,$pos+6);
```
the +6 at the end is the length of the word "cheese". I would get...
>
> , crackers and ham
>
>
>
I'd like to be able to use a function called remove\_before to get my new string, like this...
```
$str=remove_before("cheese",$str,0);
```
The 3rd variable would indicate if you also want to remove the word you're looking for. A zero here would mean, remove everything before the word cheese and a 1 would mean remove the word cheese AND everything before it.
Thank you. | 2016/11/21 | [
"https://Stackoverflow.com/questions/40728432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067447/"
] | What you're looking for is something like this:
```
<?php
function remove_before($needle, $haystack, $removeNeedle=false) {
$pos = strpos($haystack, $needle);
if (($pos !== false)) {
return substr($haystack, $pos + (strlen($needle) * $removeNeedle));
}
return $haystack; // if word not found, return full string.
}
$needle = "cheese";
$haystack = "I like to eat cheese, crackers and ham";
echo remove_before($needle, $haystack, false);
?>
```
`$pos + (strlen($needle)*$removeNeedle)` $removeNeedle is a boolean, meaning its value is either 1 or 0. if you multiply by 1, then value is value, if you multiply by 0, value is 0. so basically, you multiply the length of needle by 1 or 0.
The boolean at the end, is optional, as its default value is false.
The code is written by me, and is free of use to anyone, without limit. | ```
<?php
$str = "I like to eat cheese, crackers and ham";
function remove_before($needle, $haystack, $include = false)
{
$pos = strpos($haystack, $needle);
if ($pos !== false) {
if (!$include) {
$pos += strlen($needle);
}
return substr($haystack, $pos, strlen($haystack));
}
return null;
}
echo remove_before('cheese', $str, true);
echo remove_before('cheese', $str);
> cheese, crackers and ham
> , crackers and ham
```
Take a look at the documentation for creating functions <http://php.net/manual/en/functions.user-defined.php>
But also look at the documentation for passing arguments to functions <http://php.net/manual/en/functions.arguments.php>
What you want to pay attention to in the second link is passing default arguments. This allows for you to set a default value for an $arg that when it isn't set manually, defaults to the defined value. This allows for PHP to mock the function overloading of other languages.
Also it is important to do some sort of error checking inside of your function, depending on the defaults set, where my example just assumes that the user will pass a boolean value. |
19,527,898 | I ran into a pointer dereferencing problem.
In C, &a means the address of a. If a is a pointer ,then &a simply means the address of that pointer.
So if we have:
```
char ptr [] = "abcd"
```
ptr should be a pointer pointing to the first character, which is 'a'. therefore,
```
&ptr
```
should be the address of ptr, which is different than the address of 'a'. However, when I tried the following code I got really confused:
```
int main()
{
char a [] = "abcd";
printf("0x%X 0x%X", a, &a);
}
Output: 0xBF7E62AB 0xBF7E62AB
```
Can someone explain why a and &a have the same value? Based on my understanding they should be different. thanks in advance | 2013/10/22 | [
"https://Stackoverflow.com/questions/19527898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391850/"
] | >
> So if we have: `char ptr [] = "abcd"`, ptr should be a pointer pointing to the first character.
>
>
>
**No. Not at all.**
`ptr` is an **array.** And **an array is not a pointer.**
Indeed, if you declared `ptr` as a real pointer, then you would get the expected behavior:
```
const char *ptr = "abcd";
printf("ptr = %p, &ptr = %p\n", (void *)ptr, (void *)&ptr);
```
As to why the address of the array is the same as the address of its first element: it's quite logical. The array represents a contiguous sequence of elements. The address of the array is where the array begins in memory. It begins where its first element begins. So, the address of the first element is (rather "can be" -- the standard does not mandate this behavior) the same as the address of the array itself.
```
+-----------+-----------+- - - -
| element 1 | element 2 |
+-----------+-----------+- - - -
^ start of array
^ start of first element
``` | `char a[] = "abcd"` does not declare a pointer `a` to `"abcd"` but an array. Even if an array can decay to a pointer, it is a different type for which `&a` and `a` yield the same address.
Basically `a` yields the address to the first element of the array, so it is equivalent to `&a` (and to `&a[0]`). |
40,029,839 | So i'm having trouble finding the index of the first vowel in a string. This is the code I came up with but its not returning anything.
Its supposed to return the index of the first vowel for example if the string was "Hello World" it should return 1 because the index of the first vowel is 'e'. If there is no vowel in the given string it should return -1.
```
public class Vowel
{
public static int isVowel(String s)
{
int a = -1;
for(int i = 0; i < s.length(); i++)
{
if("aeiouAEIOU".indexOf(i) >= 0)
{
a = i;
}
}
return a;
}
}
``` | 2016/10/13 | [
"https://Stackoverflow.com/questions/40029839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7015821/"
] | Utilize a private static method to check if a certain character is a vowel:
```
public static int firstVowelPos(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (isVowel(c))
return s.indexOf(c);
}
return -1;
}
private static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
```
If you don't need to check for vowels anywhere else in your code, this can be simplified by moving the vowel checking into your conditional statement:
```
public static int firstVowelPos(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ("AEIOUaeiou".indexOf(c) != -1)
return s.indexOf(c);
}
return -1;
}
``` | The reason why your method isn't returning anything is because it's checking for the index of an integer within a string of all vowels. What you should do is check the character at i within s, see if it's a vowel, and then return that index.
Also, I would recommend renaming your method to something like "indexFirstVowel". Below is a possible solution if you want to try it:
```
public class Vowel
{
public static void main(String[] args)
{
int x = indexFirstVowel("Hello World");
}
public static int indexFirstVowel(String s)
{
for(int i = 0; i < s.length(); i++)
{
switch(s.charAt(i))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return i;
default:
break;
}
}
return -1;
}
}
``` |
23,568,084 | I'm doing [this tutorial](http://tutorials.jumpstartlab.com/projects/blogger.html#i3%3a-tagging) and am stuck in the Tagging part. Basically I have articles that can have a list of tags. As one article can has multiple tags and vice versa, there is an additional `taggings` model, through which this association is modelled. Here are the models:
```
class Article < ActiveRecord::Base
has_many :comments
has_many :taggings
has_many :tags, through: :taggings
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :article
end
```
and the migrations:
```
def change
create_table :articles do |t|
t.string :title
t.text :body
t.timestamps
end
create_table :tags do |t|
t.string :name
t.timestamps
end
create_table :taggings do |t|
t.references :tag, index: true
t.references :article, index: true
t.timestamps
end
```
There's also an `article_controller` with (amongst others):
```
def create
@article = Article.new(article_params)
@article.save
redirect_to article_path(@article)
end
```
Now, as the tutorial suggets, when I try to create a new `tag` with the rails console for an article, I get a `NoMethodError` for a `nil:NilClass`:
```
head :011 > Article.first.tags.create(name: "tag")
Article Load (0.5ms) SELECT "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT 1
(0.2ms) begin transaction
SQL (0.8ms) INSERT INTO "tags" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", ...], ["name", "tag"], ["updated_at", ...]]
SQL (2.1ms) INSERT INTO "taggings" ("article_id", "created_at", "tag_id", "updated_at") VALUES (?, ?, ?, ?) [["article_id", 1], ["created_at", ...], ["tag_id", 7], ["updated_at", ...]]
(0.6ms) rollback transaction
NoMethodError: undefined method `name' for nil:NilClass
```
So it seems to me, as if the `tag` entry is created, as well as the correct `taggings` entry, but apparently at some point it struggles to find the correct `tag`, hence the error. Am I right? How can I fix this?
I found a lot of questions on SO regarding this kind of error, but each was caused by some problem I couldn't relate to mine...
UPDATE:
`reloading` or restarting the rails console has no effect.
Here is the error backtrace, with *path* as `~/.rvm/gems/ruby-head/gems/activerecord-4.0.4/lib/active_record`:
```
from path/associations/has_many_association.rb:81:in `cached_counter_attribute_name'
from path/associations/has_many_association.rb:77:in `has_cached_counter?'
from path/associations/has_many_association.rb:85:in `update_counter'
from path/associations/has_many_through_association.rb:66:in `insert_record'
from path/associations/collection_association.rb:463:in `block (2 levels) in create_record'
from path/associations/collection_association.rb:367:in `add_to_target'
from path/associations/collection_association.rb:461:in `block in create_record'
from path/associations/collection_association.rb:152:in `block in transaction'
from path/connection_adapters/abstract/database_statements.rb:213:in `block in transaction'
from path/connection_adapters/abstract/database_statements.rb:221:in `within_new_transaction'
from path/connection_adapters/abstract/database_statements.rb:213:in `transaction'
from path/transactions.rb:209:in `transaction'
from path/associations/collection_association.rb:151:in `transaction'
from path/associations/collection_association.rb:460:in `create_record'
from path/associations/collection_association.rb:121:in `create'
from path/associations/collection_proxy.rb:260:in `create'
from (irb):14
from ~/.rvm/gems/ruby-head/gems/railties-4.0.4/lib/rails/commands/console.rb:90:in `start'
from ~/.rvm/gems/ruby-head/gems/railties-4.0.4/lib/rails/commands/console.rb:9:in `start'
from /.rvm/gems/ruby-head/gems/railties-4.0.4/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23568084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3344078/"
] | Upgrade to Rails 4.0.13 (or later) or downgrading to Ruby 2.1.1 solves the problem. | FYI, I can confirm this is an issue with ActiveRecord and Ruby 2.2. I was using ActiveRecord 3.2 and since changing to the 3-2-stable branch, the issue is gone. I believe this is fixed now in 4.x branches. I have raised an issue for this at <https://github.com/rails/rails/issues/18991>. |
8,273 | Betrayal at House on the Hill features character pentagons with 4 traits that can increase or decrease and are marked by clips.

I find (at least with my copy) that the clips slip and slide too easily; we often lose track of our stats.
We've tried blu-tack but we aren't sure if that will damage the cardboard. We've tried writing them down but we still lose track as the stat tracker isn't always told/listening.
So is there a better way to keep track of traits? Preferably an improvement on the clips. | 2012/09/02 | [
"https://boardgames.stackexchange.com/questions/8273",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/2133/"
] | My friend inserted a small slither of black electrical tape inside the slider. This tightened the grip when applied and was invisible to the eye. I still find the sliders too short to align with the number, but this at least keeps them attached firmly! | I use 8 sided dice by each trait. It's easy to see and keep track, but I like the paper clip suggestion. |
64,338,446 | I am trying to make a video chat platform and I can not work out how to detect if a user does not have a webcam available and if they don't, it sets the video feed to a static image or name and profile picture.
here is my current way of getting the webcam:
```
navigator.mediaDevices.getUserMedia(with_video).then((stream) => {
addVideoStream(myVideo, stream);
myPeer.on('call', (call) => {
call.answer(stream);
const video = document.createElement('video');
call.on('stream', (userVideoStream) => {
addVideoStream(video, userVideoStream);
});
});
socket.on('user-connect', (userId) => {
connectToNewUser(userId, stream);
join.play();
});
});
```
addVideoStream:
```
function addVideoStream(video, stream) {
video.srcObject = stream;
video.addEventListener('loadedmetadata', () => {
video.play();
});
videoGrid.append(video);
}
``` | 2020/10/13 | [
"https://Stackoverflow.com/questions/64338446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11583514/"
] | You do not need to add the steps between 1 and 2 seperately, the third argument of the range function lets you the the step size, here 1/16.
The steps between 1 and 2 are not integers, they are float numbers. Unfortunately Pythons `.range()` is unable to handle that natively. One option is to use numpys arange() which can handle float steps.
To print each value of a list you can use a `*` in front of the list. This tells the print command that it shall print each value in the list instead of the whole list.
since you want a new line for each value you can also set the seperator parameter of the print function: `sep="\n"`. This means each line is seperated by "\n" which is a linebreak in python console.
```
import numpy as np
print(*np.arange(1, 2, 1/16), sep="\n")
```
output:
```
1.0
1.0625
1.125
1.1875
1.25
1.3125
1.375
1.4375
1.5
1.5625
1.625
1.6875
1.75
1.8125
1.875
1.9375
``` | You can use numpy's arange function as already suggested, or you can use a while loop like in the example below.
The problem with python's range funtions is that it only accepts integers as arguments.
```
x = 1/16
import numpy as np
for i in np.arange(1,2,x):
print(i)
value = 1.0
while value < 2:
print(value)
value = value + x
``` |
60,628,832 | Scenario
--------
I was running into some trouble trying to assign values from a command into a variable in a makefile. Using backtick notation seems to work fine, but as soon as I use the more modern `$(pwd)` notation, the value of the variable returns nothing.
```sh
$ cat Makefile
FOO=moo
BAR=$(pwd)
BAZ=`pwd`
all: foo bar baz
foo:
@echo foo:$(FOO)';'
bar:
@echo bar:$(BAR)';'
baz:
@echo baz:$(BAZ)';'
$ make all
foo:moo;
bar:;
baz:/home/mazunki;
```
As you can see, FOO and BAZ work as expected. But not BAR.
Problem
-------
Let's look at my problem now, by adding some more examples. I'm skipping the echoing, as you get the idea.
```sh
$ cat Makefile
SHELL=/bin/env bash
FOO=dog
BAR=$(pwd)
BAZ=`pwd`
QUZ=`$(FOO)`/cat
ZOT=`\`FOO\``/owl
BIM=`$(BAZ)`/rat
BAM=`\`BAZ\``/pig
BUM=`BUM`/fox
all: foo bar baz quz zot bim bam bum
# targets for all the things
$ make
foo:dog;
bar:;
baz:/home/mazunki;
bash: dog: command not found
quz:/cat;
bash: FOO: command not found
zot:/owl;
bim:pwd/rat;
bash: BAZ: command not found
bam:/pig;
bash: BAZ: command not found
bum:/fox;
```
I really had hopes for BIM. But sadly, it only return the command which I wanted to run instead. I tried adding another layer of `$()` and/or ```` to it, but the result is an empty output instead.
My desired output is what I'd get from running `echo -n $(pwd)/rat` in Bash. None of my tested examples allow me to do this. I want to be able to do this, as some of the commands I use for my preface variables are based on initial settings, as such:
```sh
# User settings
ROOT=`pwd`
SRCPATH=$(ROOT)/src/
OBJPATH=$(ROOT)/objects/
# Scripting
SRCFILES=`find $(SRCPATH) -name '*.ext' -printf '%p '`
OBJFILES=`find $(SRCPATH) -name '*.ext' -printf '$(OBJPATH)/%p ' | sed 's/^$(SRCPATH)/^$(OBJPATH)//g; s/.ext;/.obj;/g; s/;$//g'`
```
It might look kind of a convoluted scenario, but I'm doing this for two main reasons: I want it to be highly configurable, without having to edit the commands themselves, and also because I want to learn how to make Makefiles properly. | 2020/03/11 | [
"https://Stackoverflow.com/questions/60628832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4440053/"
] | Make doesn't support backticks. Makefiles are not shell scripts. However, makefiles do *run* shell scripts, and shell scripts support backticks. You wrote this:
```
$ cat Makefile
FOO=moo
BAR=$(pwd)
BAZ=`pwd`
all: foo bar baz
foo:
@echo foo:$(FOO)';'
bar:
@echo bar:$(BAR)';'
baz:
@echo baz:$(BAZ)';'
$ make all
foo:moo;
bar:;
baz:/home/mazunki;
```
The variable assignments simply create variables containing those literal strings, so `FOO` contains the string `moo`, `BAR` contains the string `$(pwd)`, and `BAZ` contains the string `pwd`.
Make only substitutes variables that start with `$` (maybe you can already see why your makefile doesn't work as you wanted). Nothing else is special to make. So when make runs the recipe for `foo`, it will replace the make variable `$(FOO)` with its value `moo` and runs the shell command `echo foo:moo';'`. When make runs the recipe for `baz` it replaces `$(BAZ)` with `pwd` and runs the shell command:
```
echo baz:`pwd`';'
```
and the *shell* (not make) will expand the backticks for you.
When make runs the recipe for `bar`, though, it will replace `$(BAR)` with the value `$(pwd)` which is another make variable, which will be expanded, and this make variable `pwd` is not set, so make expands this to the empty string and runs the shell command `echo bar:';'`.
If you want to use the new-style `$(...)` syntax for shell scripts you *must* escape the `$` so make doesn't treat it as a make variable. You have to write:
```
BAR=$$(pwd)
```
then it will work as you expect.
You should really read <https://www.gnu.org/software/make/manual/html_node/Reference.html> and the associated pages. | To expand on answer <https://stackoverflow.com/a/60628899> by <https://stackoverflow.com/users/1899640>, adding a working example:
```
SHELL=/bin/env bash
FOO=$(shell pwd)
BAR=$(FOO)/src
BUZ=ext
all: foo bar baz
foo:
@echo foo:$(FOO)';' # returns /home/mazunki
bar:
@echo bar:$(BAR)';' # returns /home/mazunki/src
baz:
find $(BAR) -name '*.$(BUZ)' # returns all files /home/mazunki/src/**/*.ext
``` |
32,313 | I have a linear regression model that is used to forecast the 'afluent natural energy' (ANE) of some region.
The predictors for this model are:
* the previous month ANE (`ANE0`)
* the previous month rain volume (`PREC0`)
* the current month forecast for rain volume (`PREC1`)
We have 7 years of historical data for all of these variables, for each month. The current model just runs a OLS linear regression. I feel there's a lot of improvements to be done, but i'm not a time series specialist.
The first thing I notice is that the predictors are highly correlated (multicollinearity).
I'm not certain of the impacts of multicollinearity on prediction confidence.
I decided to try a time series approach, so I ran a ACF and PACF on the historic data:
The ACF shows a sine wave pattern, and the PACF has a spike at 1 and 2. So I tried both `ARIMA (2, 0, 0)` and `ARIMA(2,0,1)` to predict 20 periods ahead.
The ARIMA(2,0,1) shows good results, but I'm not certain as to how to compare it to the linear regression model.
What's the best way to test the performance of these model? I'm using R as analysis tool (together with the `forecast` package). | 2012/07/15 | [
"https://stats.stackexchange.com/questions/32313",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/12626/"
] | The best way to test out of sample prediction is to do a pseudo out of sample forecasting experiment. Use about 75 percent of the data to train the models, make the prediction, record the forecast error, update the information set, and repeat. At the end, you can use all of the forecast errors to get the mean-squared forecast error (MSFE). The model with the lowest MSFE is the best predictor. In general the out-of-sample (OOS) r-squared can help you compare a model to some benchmark.
$$\text{OOS } R^2 = 1 - \frac{MSFE\_{model}}{MSFE\_{benchmark}}$$
If the OOS r-squared is greater than zero, the model beats the benchmark. A typical choice for the benchmark is the historical mean. The higher the OOS r-squared, the better.
A couple of other thoughts: If you're not sure which model to choose, just average the forecasts from both models. Average forecasts usually perform better than individual forecasts. Also, since your time series looks like a sine wave you may want to check for seasonality and use seasonal time series models. | If you have data beyond the range of the fit to test the forecasts then that would be good to compare the models. If you don't have that then fit criteria that don't require nested models and penalize for overparameterization would be best. I recommend using information criteria for that (versions of AIC or BIC). But if both models seem to have virtues you might consider a combined model such as a harmonic regression, which fits a sine wave plus autoregressive residuals. |
49,925,748 | I am trying to switch my remote from HTTPS to SSH. First I verify that it started out as HTTPS. I run:
`$ git remote get-url origin`
result: `https://<repo>.git`
I then run `$ git remote set-url origin git@github.com:<repo>.git`
Then I run so set the remote URL that I want:
`$ git remote get-url origin`
and it STILL returns `https://<repo>.git`!
...however, if I run:
`git config --get remote.origin.url`
Then I get back the expected url of `git@github.com:<repo>.git` | 2018/04/19 | [
"https://Stackoverflow.com/questions/49925748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5953635/"
] | Check git global config
-----------------------
Check the global git config for any [insteadOf](https://git-scm.com/docs/git-config#Documentation/git-config.txt-urlltbasegtinsteadOf) settings which automatically replace git urls with https urls.
```
git config -l
...
url.https://github.com/.insteadof=git@github.com:
url.https://.insteadof=git://
...
```
Unset those:
```
git config --global --unset-all url.https://github.com/.insteadof
git config --global --unset-all url.https://.insteadof
```
Alternatively you could use `git config --global --edit` to edit the global config in your editor (nano, vim etc) and delete the relevant sections.
Test again and hopefully it will show the same urls with both `git remote -v` and `git config --get remote.origin.url`.
I had the same problem in a VM environment which I received from a colleague, and since I hadn't realised they had added these global config settings I couldn't figure out what was going on. It seems that some people use this as a workaround in environments which block access to git urls for whatever reason.
Confirm ssh authentication is working
-------------------------------------
Aside from checking git's config settings, it can be helpful to make sure that ssh authentication to git is working properly.
```sh
ssh -Tv git@github.com
```
If it succeeds you should see a message like the following. Any sort of error suggests there's a problem with your ssh keys, ssh settings, or environment related to ssh and you should check that first.
```
Hi userName! You've successfully authenticated, but GitHub does not provide shell access.
``` | Try removing and then adding the `origin` again, if that is ok for you.
To remove origin,
```
$ git remote rm origin
```
Verify if the origin actully removed. The secondnd command should have given you a error.
```
$ git remote -v
$ git pull
```
Now add origin and verify,
```
$ git remote add origin git@github.com:username/repository-name.git
$ git remote -v
``` |
23,726,344 | I'm embedding tweet on a website and I would like to remove the follow button and also the *reply*, *favorite* and *retweet* buttons that are in the footer. A minimal HTML example is the following
```
<blockquote class="twitter-tweet">
<a href="https://twitter.com/StackCareers/statuses/468107750333894656"></a>
</blockquote>
<script src="http://platform.twitter.com/widgets.js" charset="utf-8"></script>
```
By inspecting the code, once the tweet is diplayed, I figured that the button is wrapped as following
```
<a class="follow-button profile" href="https://twitter.com/StackCareers" role="button" data-scribe="component:followbutton" title="Follow StackOverflowCareers on Twitter"><i class="ic-button-bird"></i>Follow</a>
```
So far I tried to remove this class using JQuery
```
$('.follow-button.profile').remove()
```
I also tried to overwrite the css by adding the following line to my stylesheet :
```
.follow-button {visibility:hidden;}
```
And following this [post](https://stackoverflow.com/questions/11635579/twitter-embedded-tweets-remove-reply), I tried adding also this line
```
.twt-actions { display: none; }
```
None of the above worked. Is there a solution to customize these embedded tweets ? | 2014/05/18 | [
"https://Stackoverflow.com/questions/23726344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1852681/"
] | I've managed to do this with the `widget` that returns a `Shadow DOM element`. I read [here](http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/) that you can manipulate `CSS` from `shadow elements`. The `Twitter Widget` defines a `Shadow element` that, in my case where I just have one tweet embedded, has an id: `#twitter-widget-0`.
So, I put the following in my `CSS`:
```
#twitter-widget-0::shadow div.Tweet-brand {
display: none;
}
```
I hope it's useful! | in case you have multiple widgets
```
<style>
[id*="twitter-widget"]::shadow div.Tweet-brand { display: none; }
</style>
``` |
1,745,888 | I see the term "dirty" or "dirty objects" a lot in programming.
What does this mean? | 2009/11/17 | [
"https://Stackoverflow.com/questions/1745888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75500/"
] | A dirty object is an object that has changed in its content, but this content has not been synchronized back into the database/disk. It's a typical situation of desynchronization between a cache and a storage. | *EDIT: original question was phrased as `I find a lot in "programming dirty"`, this answer attempts to address that. The accepted answer is about `dirty objects`, which signifies changed status or content.*
*"Programming dirty"* as you quote it, also means that you use a ["quick and dirty" method for solving a problem](http://www.gamasutra.com/view/feature/132500/dirty_coding_tricks.php), usually to stay within time constraints, and hoping to fix it later.
Programming dirty is often used with prototyping (i.e., a mini=-program that shows the principles of a later-to-be-built larger program), where it is needed to show something quickly, but your code is not meant to last. |
11,686,361 | I need to let the user open a specific album from their gallery, and let them to do something with images.
In order to retrieve an image from an album, I'm using:
`Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri).`
Everything works fine, except the fact that if the album contains many pictures, it ends up trowing an `OutOfMemoryException.`
Now, I know how to mitigate this issue based on [Android guidelines](http://developer.android.com/training/displaying-bitmaps/index.html), but the problem is that I'm already retrieving the original Bitmap with `getBitmap()`
So, is there a possibility to retrieve the image in the byte array format, or an input stream format, and scale it down before assigning it in memory to avoid memory leaks? (in the same way the Android guidelines advice) | 2012/07/27 | [
"https://Stackoverflow.com/questions/11686361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271435/"
] | As others have mentioned, you loop over a function reference and not the result from executing `smalls`.
Yet, as you use jQuery, you can write shorter/simpler code:
```
var smalls = $("#box-table-a").find("small"); // this var really contains the elements
smalls.addClass("form-absolute-right").wrapInner("<span class='bubble' />");
smalls.parent().addClass("relative");
```
This has various advantages:
* the classes are simply added to the list and you don't have to worry about the whitespaces.
* wrapInner does preserve the DOM (with all listeners etc) instead of messing with html strings
* the parent() traversing methods uniques the set, so elements with more than one `table-box` do get only one class
* you don't need a loop at all, jQuery methods are executed on every item in the set. | Try
```
var smalls = function(){
var table = $("#box-table-a");
return table.find("small");
}, smallContent;
for(var i = 0; i<smalls().length; i++){
smallContent = smalls()[i].innerHTML;
smalls()[i].parentElement.className += "relative";
smalls()[i].className += "form-absolute-right";
smalls()[i].innerHTML = "<span class='bubble'>" + smallContent + "<span>";
}
```
Because the return will never has been called without the call of the whole function.
BTW:
```
$('#box-table-a .small')
.toggleClass('form-absolute-right',true)
.wrap('<span class="bouble" />')
.parent()
.toggleClass('relative',tru);
```
may even better. |
22,624,027 | I want to use Js to calculate the running time of my function, but it seems only the first time the time interval is not zero.
```
var i = 0;
//var timeArray = new Array();
//var date1;
//var date2;
var time = 0;
while(i < 5) {
var date1 = new Date();
var date2 = new Date();
var t = decide_class(attr[i]);
time += (date2.getTime() - date1.getTime());
i++;
}
```
The attr is two dimension array and I am sure the decide\_class function execute every loop. | 2014/03/25 | [
"https://Stackoverflow.com/questions/22624027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263729/"
] | You need to use high precision timers. The following is not completely my code.
```
window["performance"] = window.performance || {};
performance.now = (function() {
return performance.now ||
performance.webkitNow ||
performance.msNow ||
performance.oNow ||
performance.mozNow ||
function() { return new Date().getTime(); };
})();
```
instead of using date.getTime() just use performance.now(); | What about calculating all the loop?
```
var i = 0;
//var timeArray = new Array();
//var date1;
//var date2;
var date1 = Date.now();
alert(date1)
while(i < 5) {
var t = decide_class(attr[i]);
i++;
}
var date2 = Date.now();
var time = (date2-date1);
```
This could help to eliminate some imprecision if the method decide\_class is too fast. If even then you are getting a 0 value for time, try to evaluate if your decide\_class function isn't too fast. Try something like this [JavaScript sleep/wait before continuing](https://stackoverflow.com/questions/16873323/javascript-sleep-wait-before-continuing) and evaluate the value returned in time. |
34,489,320 | I've seen a lot of different topics and suggestions on aligning and inputting buttons/text, but the ways I've seen seem kind of risky.
What is the optimal way, for example, to add two buttons, stack them together, and have them be 10% from the bottom of the screen, and centered horizontally on all devices? | 2015/12/28 | [
"https://Stackoverflow.com/questions/34489320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5484801/"
] | Learn Auto Layout if you haven't yet. Use constraints for achieving the following:
>
> 1. For centrally Horizontal on all devices: Use Center X with SuperView.
> 2. For having them 10% from bottom, use multiplier value say **0.10** .
>
>
> | For iOS 9, an even simpler Auto Layout approach would be to use [UIStackView](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/).
As you can see, no constraints are needed for the buttons embedded in the stack view, as the stack view lays out the buttons for you. All you have to constrain is the location of the stack view itself.
Here's an example of two vertically stacked buttons, 10% from the bottom of the screen, and centered horizontally for all devices.
[](https://i.stack.imgur.com/izHwx.png) |
13,000,266 | I've got problem with dynamically background changing in whole HTML document. Here is piece of code:
```
function changeHTMLBackground() {
var html = document.getElementsByTagName('html')[0];
html.style.background = "#ff00ff";
}
```
Problem appears only in IE9. In Chrome, FF, Opera works fine. I know there is one solution to change "body" instead of "html", but it isn't solution for me, I need to change style for HTML tag. | 2012/10/21 | [
"https://Stackoverflow.com/questions/13000266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1643940/"
] | I'm not sure what the problem is but here are a few possible solutions.
1) Maybe the selector isn't working.
try using
```
document.html.style.backgroundColor = "#977689";
```
2) Maybe IE9 has an issue with html bg colors anyway. is the CSS code working?
3) try adding a class and id to the html tag, and selecting the element with that. | Pretty sure that IE does not support applying CSS to the html tag itself, nor am I sure that's expected by the standard. As a trivial test, try:
```
<!doctype html><html style="background: green"><body>Testing</body></html>
``` |
24,708,285 | Let's say a method returns a `CFErrorRef` via a pointer. This returned error may be `NULL`. So would it be safe to perform a `__bridge_transfer` still or should I check for `NULL`.
E.g.
```
CFErrorRef cfError;
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, &cfError);
NSError *error = (__bridge_transfer NSError *)cfError;
```
I don't see any mention of this in the documentation and `CFRelease` documentation specifically states `This value must not be NULL.`
<https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRelease> | 2014/07/12 | [
"https://Stackoverflow.com/questions/24708285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1979235/"
] | You do not need to check for NULL.
ARC is a strictly compile-time mechanism. When you use `__bridge_transfer` you are merely transferring memory management responsibility of a variable to the compiler. Whether `cfError` happens to be NULL or not at runtime is completely irrelevant to the compiler.
In your case, ARC will insert a release for `error`, but if `error` happens to be nil it's a simple no-op. | Unlike NSObjects, sending messages to NULL CF objects is not ok. I don't know about bridging casts specifically, but I would guess that no, casting a CF object to an NSObject using \_\_bridge\_transfer is NOT ok.
Why not try it and see? Cast it to a variable in the local scope of an instance method. That way, as soon as the method goes out of scope the system should try to release the object. |
54,993,836 | I use ajax get a json like this:
```
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
```
How to append "delete\_flag" , "id" , "icon\_img" to 3 different places on html ? | 2019/03/05 | [
"https://Stackoverflow.com/questions/54993836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11070790/"
] | You can use this pure javascript method like below.
The code basically uses [`document.getElementById()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) to get the element, and [`.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) to parse the data into the correct object that our code can read. The `[0]` at the end is to select the object we wanted since it would give us an array (and we want an object).
```js
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
```
```html
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
```
Or you can use [jQuery](https://developer.mozilla.org/en-US/docs/Glossary/jQuery) (which in my opinion, is much simpler). The code below uses [`.html()`](http://api.jquery.com/html/) to change the inside of the divs to the item from the object, and [`.attr()`](http://api.jquery.com/attr/) to set the attribute src to the image source you wanted.
```js
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
``` | you can use jQuery [.html()](http://api.jquery.com/html/) or [.text()](http://api.jquery.com/text/)
For example:
```js
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
```
```html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
``` |
36,025,580 | I start a new project from File -> New -> project
I add a button to ViewController.
I open UITest folder which created by xcode by default. Run the test code.
It fails:
```
2016-03-16 12:57:09.191 XCTRunner[3511:150419] Continuing to run tests in the background with task ID 1
t = 10.18s Assertion Failure: UI Testing Failure - Failed to background test runner.
/Users/Bernard/Desktop/ExampleTestApplication/ExampleTestApplicationUITests/test2.m:27: error: -[test2 testExample] : UI Testing Failure - Failed to background test runner.
2016-03-16 12:57:12.789 XCTRunner[3511:150419] *** Terminating app due to uncaught exception '_XCTestCaseInterruptionException', reason: 'Interrupting test'
```
Now I add a break point as follow:
[](https://i.stack.imgur.com/mIMVb.png)
Now test is successful! Anyone can explain the reason? | 2016/03/16 | [
"https://Stackoverflow.com/questions/36025580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679519/"
] | I was also facing same issues and none of the available solutions worked for me. Issue was not letting app to attach to the simulator itself.
I checked the log and saw that i did a mistake in code while locating the element. for Predicate instead of BEGINSWITH i wrote STARTSWITH and this was stopping the app to get attached.
So check your logs in the test report to get the issue. | I was getting this error happening when the iOS simulator was already launched (which may not necessarily mean you can see it in the OS X dock). You can check the state of the various simulators using the `simctl` command.
I.e.
```
xcrun simctl list devices
```
Then, ensure that any devices listed as "Booted" are shutdown:
```
xcrun simctl shutdown <device-udid-here>
```
Then, try running your UI tests again. |
7,846,591 | i want to acess the web config value in javascript
config entry:
```
<add key ="RootPath" value ="C:\Test" />
```
javascript code:
```
var v1 = '<%=ConfigurationManager.AppSettings["RootPath"].ToString() %>'
```
The output that i am getting is
```
C:Test
```
but what i want is C:\Test
Any idea how to acheive this ? | 2011/10/21 | [
"https://Stackoverflow.com/questions/7846591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Try this
```
ConfigurationManager.AppSettings["RootPath"].ToString().Replace(@"\", @"\\")
``` | **if you adding this**
```
<add key ="RootPath" value ="C:\\Test" />
```
then you will retrive like `"C:\Test"`.
**Its behavior of .net.** |
116,735 | I propose a new Gold level Sportsmanship badge. I earned the silver badge June 4th, and I continue to vote for competing answers. I would like to feel that I am working toward something, not because I would otherwise cease to vote for these answers, which clearly I have not, but because it adds to the fun of the site, just like the other badges.
Following the ratios of some other badges, since the silver is at 100, perhaps 400 votes for competing answers is a good level?
---
When I asked this question I was unaware that all votes for competing answers were counted, believing it was limited to the number of questions. Since in fact all votes are counted I think the threshold needs to be higher, perhaps 1000 votes as suggested by **user unknown**.
---
This feature request is fairly popular but has failed to reach critical mass. If anyone has new ideas about how this request might be changed to make it more likely to succeed please share them.
---
### May 2016
There is renewed interest in this topic due to a similar request on Meta Stack Overflow (as well as a generous bounty just started by [Josh Crozier](https://meta.stackexchange.com/users/232567/josh-crozier)):
* [Needs More Sportsmanship](https://meta.stackoverflow.com/q/323487/618728)
The community should at least be aware of this parallel development. Perhaps that question should be migrated here and combined with this one as I believe badges are network-wide? Any missing or controversial aspects of this question could be edited appropriately. | 2011/12/21 | [
"https://meta.stackexchange.com/questions/116735",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/158428/"
] | I really do like the incentive to vote for competing answers,
but maybe this badge is a little bit more easy to grind at than a gold badge ought to be.
---
There's also the room people to avoid the incentive by up-voting on questions that are weeks or months old(thus not putting their own answer in jeopardy). You might want to put some sort of time-limit on this, or only count votes that occur before the OP has accepted an answer. | I am not going to discus the name nor the number of votes necesary for such badge, just going to quote the Tour:
>
> Good answers are voted up and rise to the top.
>
>
>
If this is really what we want, such badge will be useful, as it would motivate even people with upvoted answers vote for other good answers. |
59,849,484 | I am a little confused on the idea of using props in the context I am using for my React app. In my component, I need to check if the value of a certain prop (`props.companyCode`) matches a certain string, and only then will it print out a `<p>` of what I need. Below is what I have for calling the prop in the component:
`Components/CompanyContact.jsx`
```
class CompanyContact extends React.Component {
help() {
if (this.props.companyInfoList.companyCode === '1234') {
return <p>something</p>;
}
return <p>somethingelse</p>;
}
render() {
const help = this.help();
return (
<div>
{help};
</div>
)}}
export default CompanyContact;
```
And this is what I have for the container:
`Container/InfoContainer.jsx`
```
class InfoContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
companyInfoList: null,
};
}
async componentWillMount() {
const companyInfoCachedData = CachingService.getData('companyInfoList');
if (companyInfoCachedData) {
this.setState({ companyInfoList: companyInfoCachedData });
return;
}
}
async getCompanyInfo(accessToken) {
try {
const companyProfileResponse = await requestAWSGet('api/company-profile', undefined, accessToken);
CachingService.setData('companyInfoList', companyProfileResponse);
this.setState({ companyInfoList: companyProfileResponse });
} catch (err) {
throw err;
}
}
render() {
return (
<CompanyContact companyInfoList={this.state.companyInfoList} />
);
}
}
export default InfoContainer;
```
Nothing is returned when I run the application and I believe it's because I'm not calling the prop correctly in my component but I am unsure as to how to go about fixing it. I'm fairly new to working with props so still trying to get my bearings. | 2020/01/21 | [
"https://Stackoverflow.com/questions/59849484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6122293/"
] | I'm assuming you are getting an error somewhere because of `this` not having `props` and `this.props.companyInfoList.companyCode` trying to access a property on a non object. `this.props.companyInfoList` is initially set to `null` so accessing a property on it will break.
A few strategies to fix the problem:
1. Default it to an empty object
```js
this.state = {
companyInfoList: {},
}
```
2. Block the rendering of the component until it has a value:
```js
if (this.state.companyInfoList) {
return (
<CompanyContact companyInfoList={this.state.companyInfoList} />
);
} else {
return null;
}
```
3. Check that the prop is an object and has the key `companyCode` on it:
```js
if (this.props.companyInfoList &&
this.props.companyInfoList.companyCode &&
this.props.companyInfoList.companyCode === '1234') {
```
In addition, `this` will be in the wrong context and the changes above will most likely no be enough. Try changing to an arrow function like this:
```js
help = () => {
// your code here
}
``` | I would personally refactor that component logic and directly use the prop value inside the render method like:
```
class CompanyContact extends React.Component {
render() {
const { companyInfoList } = this.props;
return companyInfoList && companyInfoList.companyCode === '1234' ? (
<p>something</p>
) : (
<p>somethingelse</p>
)
}
}
export default CompanyContact;
``` |
11,362 | The product I work on has a communication network of 192.168.0 (four systems 100, 101, 102, and 103). From time to time there is a desire to patch in a set of these systems (using their 192 addresses) to the site network to communicate using various instrumentation tools that have tight licensing that is bound to a site machine.
Apparently this poses a non-trivial route issue as 192 addresses could pop up here, there or anywhere (However only one set of 192's on the site at any one time obviously).
Thank you kindly for your help. | 2009/05/22 | [
"https://serverfault.com/questions/11362",
"https://serverfault.com",
"https://serverfault.com/users/3376/"
] | A router of some sort (i.e. router or firewall) is the obvious answer to connect the two networks. If IP address conflicts are a concern, then using NAT will prevent problems.
Always be careful when connecting development to production. You could accidentally bind to the production database and delete a table or something... not that this ever happens of course. | If you need an exception for a system to jump subnets look into the [windows route](http://www.cisco.com/en/US/products/sw/custcosw/ps1001/products_tech_note09186a0080150baf.shtml) command. It is often the solution to these kinds of things (assuming your on a windows machine). This works especially well in a temporary situation where adding new hardware might be more cumbersome. |
27,897,157 | Below mentioned is html details of Accept/Reject button.
```html
<div id="ContentPlaceHolder1_EmployeeProfile_divAction" class="btn-row btn-accept-recet" style="display:block;">
<button onclick="__doPostBack('ctl00$ContentPlaceHolder1$EmployeeProfile$btnAccept','')" id="ContentPlaceHolder1_EmployeeProfile_btnAccept" class="btn pull-left btn-primary" type="button">
<i class="fa fa-angle-right"></i>Accept
</button>
<button onclick="__doPostBack('ctl00$ContentPlaceHolder1$EmployeeProfile$btnReject','')" id="ContentPlaceHolder1_EmployeeProfile_btnReject" class="btn pull-left btn-primary" type="button">
<i class="fa fa-angle-right"></i>Reject
</button>
</div>
```
I wanted to click on accept or reject button in update-panel. I tried using actions:
```html
WebElement element = driver.findElement(By.id("ContentPlaceHolder1_EmployeeProfile_btnAccept"));
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();
``` | 2015/01/12 | [
"https://Stackoverflow.com/questions/27897157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444272/"
] | You can try the below approach
```
driver.findElement(By.xpath("//button[contains(.,'Accept')]".submit();
driver.findElement(By.xpath("//button[contains(.,'Reject')]".submit();
``` | ```
driver.manage().window().maximize();
WebElement scroll = driver.findElement(By.id("ContentPlaceHolder1_EmployeeProfile_btnAccept"));
scroll.sendKeys(Keys.PAGE_DOWN);
driver.findElement(By.id("ContentPlaceHolder1_EmployeeProfile_btnAccept")).click();
``` |
18,868 | I found some papers that use fuzzy logic to solve robotics algorithmic problems. But I have recently been told by a few roboticists that fuzzy logic should not be used in robotics because it has recently been proven by some theoreticians to be a mathematically dubious field. And so any results that you generate using fuzzy logic in robotics will not get published. Is that true?
I find it hard to believe. Is fuzzy logic dubious with respect to applications on real-world problems, say robotics? I have talked to mathematicians and they surely believe that fuzzy logic is a robust and clever field. But then mathematicians do a lot of abstract stuff that is completely irrelevant to the real world and must not be touched. Is fuzzy logic one of those things? | 2019/05/30 | [
"https://robotics.stackexchange.com/questions/18868",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/14868/"
] | Short answer: Fuzzy logic (FL) isn't applicable for robotics research, The long answer is, that in the 1980s as part of the fifth computer generation fuzzy logic was researched in Japan with the attempt to build intelligent advanced parallel computers, but the Japanese researchers have failed. Fuzzy logic isn't a technical idea but a philosophical description of the world and a marketing term used for selling rice cookers and washing machines.
After a short time, the consumers have noticed, that Fuzzy stabilized camcorders doesn't have any improvements over a normal camcorder and multi-value logic was repressed into obscurity. If a robot contains of a so called fuzzy controller, it's a clear sign, that's a non-academic project which can't be proven if it's working or not.[1] The term fuzzy has it's origin in a clumsy cowboy character in western film produced in black/white recording decades ago. It's a synonym for a failed project which doesn't fulfill the minimum standards in academia.
[1] Elkan, Charles, et al. "The paradoxical success of fuzzy logic." IEEE expert 9.4 (1994): 3-49. | I have not seen any industry-grade application of fuzzy logic in space, flight, automotive control systems. Fuzzy logic came during mid-60s and it gradually faded away due to several reasons:
1. It did not solve any control problem that cannot already be solved by the existing methods at that time. Bad news, no major advantage in terms of extending the application domain!
2. It lacked theorems for proving stability, performance of closed-loop system. Bad news, not being so rigorous!
The second item is of utmost importance for safety-critical systems such as space, aviation, self-driving cars, surgical robotics, etc. You are not allowed to deploy an aircraft flying over cities before certifying its flight control system. When you put a fuzzy logic controller in the loop, how can you prove that the closed-loop system is stable? I mean, in the rigorous sense. FAA won't accept the ad-hoc hand-tuning, working experiment results as a certificate. You have to provide the operating conditions that fuzzy logic controller will not work.
Back to your question, nowadays, there are so many publishers in academia. Even if you do fuzzy logic research in robotics, of course, you can find a journal that will eventually accept your work. The real question is if someone will read your paper or adopt your methods for their own application.
A friendly advice, as a researcher, I would not invest my time to do research in fuzzy logic area. Control theory is already a mature field; and fuzzy logic is arguably NOT one of the fruitful sub-areas. I spent one year working on fuzzy logic during my undergraduate years. Then, I came to USA for my PhD and realized that most of control researchers in USA were not working on fuzzy logic anymore. Nonetheless, never say never! Maybe, you can contribute to the field and make it more widely-used in the future. |
248,711 | I am working with engineering equations in a vacuum system and want to emphasize that a certain set of parameters will not work. Usually, this is due to real world effects (friction, pump efficiency factors, wear and tear of bearings, etc), but I want to emphasize that a particular setup **wouldn't work even under perfect textbook conditions**.
I would like to say it is "theoretically impossible", but that has a ring of just the opposite of what I would like to say! It sounds like:
>
> a safety rating better than 100% is theoretically impossible, but the
> Tesla Model S did it!
>
>
>
What is a word or phrase to say something is absolutely forbidden by fundamental, physical laws, even under ideal conditions? | 2015/05/26 | [
"https://english.stackexchange.com/questions/248711",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/123046/"
] | Just from reading the question's title, I would've suggested *taboo*... but, obviously, that doesn't fit in the physics world.
So instead, I'd recommend something like **infeasible**, i.e. the antonym of *feasible*, defined as "capable of being done, effected, or accomplished". (Note that you could [also use](https://english.stackexchange.com/q/207115/17645) *unfeasible*.)
Alternatively, borrowing from a more biological background, another option would be **nonviable**: "not practicable or workable". | "Inherently unrealizeable" works for me. |
12,778,209 | Is a PostgreSQL function such as the following automatically transactional?
```
CREATE OR REPLACE FUNCTION refresh_materialized_view(name)
RETURNS integer AS
$BODY$
DECLARE
_table_name ALIAS FOR $1;
_entry materialized_views%ROWTYPE;
_result INT;
BEGIN
EXECUTE 'TRUNCATE TABLE ' || _table_name;
UPDATE materialized_views
SET last_refresh = CURRENT_TIMESTAMP
WHERE table_name = _table_name;
RETURN 1;
END
$BODY$
LANGUAGE plpgsql VOLATILE SECURITY DEFINER;
```
In other words, if an error occurs during the execution of the function, will any changes be *rolled back*? If this isn't the default behavior, how can I make the function *transactional*? | 2012/10/08 | [
"https://Stackoverflow.com/questions/12778209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] | **PostgreSQL 12 update**: [there is limited support for top-level `PROCEDURE`s that can do transaction control](https://www.postgresql.org/docs/12/plpgsql-transactions.html). You still cannot manage transactions in regular SQL-callable functions, so the below remains true except when using the new top-level procedures.
---
Functions are part of the transaction they're called from. Their effects are rolled back if the transaction rolls back. Their work commits if the transaction commits. Any `BEGIN ... EXCEPT` blocks within the function operate like (and under the hood use) savepoints like the `SAVEPOINT` and `ROLLBACK TO SAVEPOINT` SQL statements.
The function either succeeds in its entirety or fails in its entirety, barring `BEGIN ... EXCEPT` error handling. If an error is raised within the function and not handled, the transaction calling the function is aborted. Aborted transactions cannot commit, and if they try to commit the `COMMIT` is treated as `ROLLBACK`, same as for any other transaction in error. Observe:
```
regress=# BEGIN;
BEGIN
regress=# SELECT 1/0;
ERROR: division by zero
regress=# COMMIT;
ROLLBACK
```
See how the transaction, which is in the error state due to the zero division, rolls back on `COMMIT`?
If you call a function without an explicit surounding transaction the rules are exactly the same as for any other Pg statement:
```
BEGIN;
SELECT refresh_materialized_view(name);
COMMIT;
```
(where `COMMIT` will fail if the `SELECT` raised an error).
PostgreSQL does not (yet) support autonomous transactions in functions, where the procedure/function could commit/rollback independently of the calling transaction. This can be simulated using a new session via [dblink](https://stackoverflow.com/a/22353286/32453).
**BUT**, things that aren't transactional or are imperfectly transactional exist in PostgreSQL. If it has non-transactional behaviour in a normal `BEGIN; do stuff; COMMIT;` block, it has non-transactional behaviour in a function too. For example, `nextval` and `setval`, `TRUNCATE`, etc. | Postgres 14 update: All statements written in between the `BEGIN` and `END` block of a Procedure/Function is executed in a single transaction. Thus, any errors arising while execution of this block will cause automatic roll back of the transaction. |
73,553,464 | I just looking for a widget type where it provides a simple default solution to draw shared border lines between children widgets, instead of touching two different borders or turning a widget into a border. Basically it's just a table thing with the children as it's cell widgets.
There's `Table` in Flutter. But sadly seems like the cells is unspannable. No "colspan" thing for it's `TableCell`. If I put `TableRow`s with different numbers of `TableCells`, I get error
>
> Table contains irregular row lengths. Every TableRow in a Table must
> have the same number of children, so that every cell is filled.
> Otherwise, the table will contain holes.
>
>
>
I used to do it with Java.
```
<TableLayout ...>
<TableRow ...>
<... android:layout_span .../>
</TableRow>
</TableLayout>
```
I just want to do it again with Flutter. That's all. | 2022/08/31 | [
"https://Stackoverflow.com/questions/73553464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297048/"
] | [`random.choices` returns a list of random elements from an iterable, with replacement](https://docs.python.org/3/library/random.html#random.choices)
Either use `+=` ([to add two lists together](https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python)):
```py
players_card += random.choices(cards, k=1)
```
Or, use [`random.choice`](https://docs.python.org/3/library/random.html#random.choice) to only get one element:
```py
players_card.append(random.choice(cards))
``` | `random.choices(cards, k=1)` returns a list having only one value.
You can concatenate the two lists like this
```
players_card = players_card+random.choices(cards, k=1)
```
OR you could also do
```
players_card.append(random.choices(cards, k=1)[0])
``` |
60,892,474 | I have a chart with lines in it, and when I mouseover a line I want to display a text in the svg. Here is the code :
```
let lines = svg.append("g").attr("class", "lines");
lines
.selectAll(".line-group")
.data(data)
.enter()
.append("g")
.attr("class", "line-group")
.on("mouseover", function (d, i) {
console.log(d.name)
svg
.append("text").attr("class", "title-text")
.style("fill", color(i))
.text(d.name + "efzeiufzihefizeifiu")
.attr("text-anchor", "middle")
.attr("x", 200)
.attr("y", 30);
})
.on("mouseout", function (d) {
svg.select(".title-text").remove();
})
```
I have no error, and the mouseover is working fine as I can see in the console the value of d.name, however there is no text attribute adding in the svg. I inspired myself from : <https://codesandbox.io/s/multi-line-chart-example-wrxvs>, which is doing basically the same thing, but it adds the text when hovering. Any idea ? | 2020/03/27 | [
"https://Stackoverflow.com/questions/60892474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7695244/"
] | The `mouseover` event will not trigger if the group `<g>` does not contain any element for the mouse to be on. You must append something to the groups so that the event will be triggered once the mouse enters. | you have to use .text(function(d){return d.name})
instead of .text(d.name) |
25,321 | I recently upgraded to Lion and since then I haven't been able to use Keychain to look at my stored passwords. When I click on the checkbox to show them it prompts me for my master password, then pops up a dialog that says "Access to this item is restricted".
Based on reading questions here and on other support sites, I've tried using the Keychain Access program's "Keychain First Aid" feature. It reports that there are no errors. I also used Disk Utility to Repair Disk Permissions, and this didn't fix the problem either.
I looked in ~/Library/Keychains/ and it looks like I do have owner permission to read and write the keychain file, and my main account is the owner.
Is there anything else I can try to fix this? I'd hate to lose my keychain passwords.
Update:
I also tried dragging my login.keychain file from Finder into Keychain Access, and had no luck. I tried some digging around in the security command line app as well, but have made no progress...
Update 2:
After trying all the suggestions I commented on here I was still getting this error, but then I did a software update, and rebooted, and now my keychain is working again. So, I have no idea what went wrong, but it is now fixed! I'll just pick an answer as accepted. | 2011/09/18 | [
"https://apple.stackexchange.com/questions/25321",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/11122/"
] | There are several reasons Keychain does this. Often it's because a new account that you might have switched to does not have the same/correct paths to Keychain that it used to. For starters try changing the main login password of your account; if that doesn't do anything try this in terminal:
```
$ sudo touch login.keychain
$ codesign -vvv /Applications/Utilities/Keychain\ Access.app
```
If you get an error such as:
```
/Applications/Utilities/Keychain Access.app: code or signature modified
```
then:
```
$ codesign -vvv /Applications/Utilities/Keychain\ Access.app
```
which should give you the response:
```
/Applications/Utilities/Keychain Access.app: valid on disk
/Applications/Utilities/Keychain Access.app: satisfies its Designated Requirement
```
Reboot. | Keychain says “Access to this item is restricted”
As posted by Matt: This worked for me as well.
* open Keychain access, click the lock to lock the keychains, then unlock again! -
Its the simplest least potentially destructive option and I was very sceptical, but it worked. So worth a shot as it takes seconds. I'm running OS X El Capitan V 10.11.6 |
589,997 | As another user asked about firefox:
[Increase limit of bookmark folders in Firefox?](https://superuser.com/questions/38325/increase-limit-of-bookmark-folders-in-firefox)
I would like to increase the number of folders that you are presented with when you press the add bookmark star in Chrome. As it is now, you get a choice from the last five used folders, "bookmark bar", "other bookmarks" or choose another folder. The last five folders are listed in a last in last out progression, so if you happen to bookmark five different pages to five different folders the sixth folder chosen would move the first one out.
It would also be a nice option if along with increasing the number of presented folders, to pin chosen folders to always appear in the pulldown selection, regardless if I have used it recently or not, so if I find that I have bookmarked 10 different pages to their respective folders, that "my" most used folders are always quickly available.
A different solution would be to allow the creation of a(nother) special folder called "pinned favorites" that would be displayed along with "bookmarks bar" and "other bookmarks" that contain the folder selection that you choose to not be a part of the sequential deletion of the five "most recently used" folders. This folder would display the pinned folder selection once "pinned folders" was selected as a pulldown similar to the choose another folder option. | 2013/05/01 | [
"https://superuser.com/questions/589997",
"https://superuser.com",
"https://superuser.com/users/221208/"
] | The limit of 5 folders is [hardcoded](https://github.com/chromium/chromium/blob/318345ccda37a7f187e6014baff53a2d4eb2bdab/chrome/browser/ui/bookmarks/recently_used_folders_combo_model.cc#L21-L22).
I've been [patching chromium](https://gist.github.com/gg7/8172378) for years because of this. | According to this forum <https://productforums.google.com/forum/#!topic/chrome/yQ3jbWf0DgU> it has never been a feature to create a top level folder in bookmarks. I have noticed that connecting a chrome account on iOS has created a "Mobile Bookmarks" folder, but otherwise seems impossible to create or edit the top level folders. |
7,024,777 | I've got problem with local copy of SVN folder
```
$ svn up
svn: REPORT of '/svn-xxx/!svn/vcc/default': Could not read chunk size: connection was closed by server (http://127.0.0.1)
$ svn cleanup
$ svn up
svn: REPORT of '/svn-xxx/!svn/vcc/default': Could not read chunk size: connection was closed by server (http://127.0.0.1)
$ svn status
! .
! TM
? newTM/backup
```
I do not want to delete and restore whole folder because it contains many additional, ignored stuff
On another exported copy, with the same server, everything works flawlessly.
How can I proceed with svn up ? | 2011/08/11 | [
"https://Stackoverflow.com/questions/7024777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872856/"
] | * Rename the folder
* Checkout the folder (`svn co path/to/folder/`)
* Copy files from the old folder to the new one (but avoid `.svn` directories!)
* When everything works: delete renamed old folder | I would probably go with copying all files as you suggested (voted up)
* Checkout to new folder
* Copy all from old to new without overwriting and without .svn
```
rsync -av --exclude=.svn --ignore-existing old/ new/
``` |
4,837,616 | Hi im having a problem to figure this out, i am literally going nuts. I got a scenario like this. Category , Category-SubCategory, Category-SubCategory-SubSubCategory
I cant for the life of me figure out this route. My last and current is like this
```
routes.MapRoute(
"Navigation",
"Navigation/{nav}/{sub}/{subsub}/{id}",
new { controller = "Navigation", action = "Site", nav = UrlParameter.Optional, sub = UrlParameter.Optional, subsub = UrlParameter.Optional, id = UrlParameter.Optional }
);
```
I figure like this that UrlParameter.Optional would skip the sub or the subsub but instead it puts system.UrlParameter.Optional as a parameter there. Any ideas on how this can be handled?
**EDIT 1:**
so far i limited the site with 2 sub categories and did 3 routes and 3 actionresults. not a pretty solution but works for now | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148601/"
] | Cut it to one route by cheating a bit.
```
routes.MapRoute(
"navigation",
"{nav}/{name}",
new { controller = "Navigation", action = "Page", nav = UrlParameter.Optional, name = UrlParameter.Optional }
);
```
and i write all the categories, subcategories in the nav like
```
<%: Html.ActionLink("HOME", "Page", "Navigation", new { nav = "Category/Sub/", name = "Name" }, null)%>
```
i figure the {nav} dont really got any function here except to show the category path and in case i need to break it out ill use the string spliter. | I agree with @Darin that you might want to think a little more about your architecture, but I believe this series of routes would work for you:
```
routes.MapRoute(
"Navigation",
"Navigation/{nav}/{sub}/{subsub}/{id}",
new { controller = "Navigation", action = "Site", nav = "", sub = "", subsub = "", id = UrlParameter.Optional }
);
routes.MapRoute(
"Navigation",
"Navigation/{nav}/{sub}/{subsub}",
new { controller = "Navigation", action = "Site", nav = "", sub = "", subsub = UrlParameter.Optional, id = "" }
);
routes.MapRoute(
"Navigation",
"Navigation/{nav}/{sub}",
new { controller = "Navigation", action = "Site", nav = "", sub = UrlParameter.Optional, subsub = "", id = "" }
);
routes.MapRoute(
"Navigation",
"Navigation/{nav}",
new { controller = "Navigation", action = "Site", nav = UrlParameter.Optional, sub = "", subsub = "", id = "" }
);
``` |
47,828,275 | From my android app, I am connecting to `MongoDB` through `mLab` and seeking some clarifications.
As per [mlab documentation](http://docs.mlab.com/connecting/) it is mentioned to use `MongoDB Driver` for better security and performance instead of using `mLab Data API`.
But Is it a good practice to connect to MongoDB directly from Android app using drivers. Which is the better way to connect wit the below?
1. Mongo DB Drivers
2. mLab Data API and consume it through Anroid App (this API provides only basic functionality)
3. Create a Web API and consume it through Android App
Also any other suggestions apart from this? | 2017/12/15 | [
"https://Stackoverflow.com/questions/47828275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I definitely strongly recommend to provide your own Web API / restful API. The benefits are huge. I recommend making your android app completely mongodb agnostic. Behind your own API, you do what you like, you might want to be able to consider moving to another data store solution in the future. You make your application easier to test / mock. What if your mongodb is dead? How do you cache, optimise, error handle, ... As a matter of fact, you will want to implement plenty of your logic onto a server, and not necessarily have all your logic sitting on your android app. How else will you build an iPhone app and then later a web app? There are so many reasons / advantages to not go directly to mongodb.
This question and feedback will give you more advice and details on why to consider a rest API rather than accessing mongodb directly: <https://softwareengineering.stackexchange.com/questions/277701/why-do-people-do-rest-apis-instead-of-dbals>
As to considering Rest, Crud, or web, I recommend you read the advice given here: [What is the advantage of using REST instead of non-REST HTTP?](https://stackoverflow.com/questions/2191049/what-is-the-advantage-of-using-rest-instead-of-non-rest-http). This will give you information on possibly starting with a Crud API, Vs Rest. I feel that might become your next question to ask. | try stitch . it's still in beta and currently you can use it only on atlas but in some days you can use it locally also.Please go through the link
<https://www.mongodb.com/cloud/stitch> |
119,420 | shall i wait more or its hanged????
[](https://i.stack.imgur.com/j2w9y.png)
[2016-06-05 16:35:03 CEST] Job "maintenance\_mode {"enable":true}" has been started
[2016-06-05 16:35:03 CEST] Magento maintenance mode is enabled.
[2016-06-05 16:35:03 CEST] Job "maintenance\_mode {"enable":true}" has successfully completed
[2016-06-05 16:35:03 CEST] Job "update {"components":[{"name":"magento/product-community-edition","version":"2.1.0-rc1"}]}" has been started
[2016-06-05 16:35:03 CEST] Starting composer update...
[2016-06-05 16:35:03 CEST] ./composer.json has been updated
[2016-06-05 16:36:02 CEST] Update is already in progress.
[2016-06-05 16:37:03 CEST] Update is already in progress.
[2016-06-05 16:38:05 CEST] Update is already in progress.
[2016-06-05 16:39:03 CEST] Update is already in progress.
[2016-06-05 16:40:03 CEST] Update is already in progress.
[2016-06-05 16:41:03 CEST] Update is already in progress.
[2016-06-05 16:42:03 CEST] Update is already in progress.
[2016-06-05 16:43:03 CEST] Update is already in progress.
[2016-06-05 16:44:02 CEST] Update is already in progress.
[2016-06-05 16:45:03 CEST] Update is already in progress.
[2016-06-05 16:46:02 CEST] Update is already in progress.
[2016-06-05 16:47:03 CEST] Update is already in progress.
[2016-06-05 16:48:03 CEST] Update is already in progress.
[2016-06-05 16:49:02 CEST] Update is already in progress.
[2016-06-05 16:50:03 CEST] Update is already in progress.
[2016-06-05 16:51:02 CEST] Update is already in progress.
[2016-06-05 16:52:02 CEST] Update is already in progress.
[2016-06-05 16:53:03 CEST] Update is already in progress.
[2016-06-05 16:54:03 CEST] Update is already in progress.
[2016-06-05 16:55:03 CEST] Update is already in progress.
[2016-06-05 16:56:03 CEST] Update is already in progress.
[2016-06-05 16:57:02 CEST] Update is already in progress.
[2016-06-05 16:58:04 CEST] Update is already in progress.
[2016-06-05 16:59:03 CEST] Update is already in progress.
[2016-06-05 17:00:03 CEST] Update is already in progress.
[2016-06-05 17:01:02 CEST] Update is already in progress.
[2016-06-05 17:02:03 CEST] Update is already in progress.
[2016-06-05 17:03:04 CEST] Update is already in progress.
[2016-06-05 17:04:02 CEST] Update is already in progress.
[2016-06-05 17:05:03 CEST] Update is already in progress.
[2016-06-05 17:06:03 CEST] Update is already in progress.
[2016-06-05 17:07:03 CEST] Update is already in progress.
[2016-06-05 17:08:03 CEST] Update is already in progress. | 2016/06/05 | [
"https://magento.stackexchange.com/questions/119420",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/40487/"
] | I was having the same problem when trying to upgrade from the web. I ended up trying to do the upgrade from the command line and it worked. Here are the commands I used to upgrade from the command line.
```
composer require magento/product-community-edition 2.1.0 --no-update
composer update
rm -rf var/di var/generation
php bin/magento cache:flush
php bin/magento setup:upgrade
php -d memory_limit=2048M bin/magento setup:di:compile
php bin/magento cache:flush
php bin/magento maintenance:disable
php bin/magento setup:static-content:deploy
``` | Don't wait longer. It doesn't take half an hour to update, unless you have slow internet or a slow computer I'd stop it and try again.
Also: You shouldn't be running Magento on localhost, set up a virtual host.
<https://john-dugan.com/wamp-vhost-setup/> |
40,967,422 | I have a question relating to scheduled jobs in SQL Server. Well, I guess it isn't exactly related to scheduled jobs, but in fact related to SQL queries.
Anyway I have 2 tables Table\_1 and Table\_2 in my database.
I wish to run a scheduled job every 5 minutes that would update Table\_2 with all the missing records from Table\_1.
For instance if Table\_1 has 3 records:
```
1 ABC
2 PQR
3 XYZ
```
and Table\_2 has only 2 records:
```
2 PQR
3 XYZ
```
What the job does is adds the record "1 ABC" to Table\_2:
```
2 PQR
3 XYZ
1 ABC
```
the query I've written in the steps of the scheduled job is as follows:
In my code table names are different so please excuse me:
```
Table_1 = [sfs_test].dbo.[Table_1],
Table_2 = [sfs_test2].dbo.[Table_1]
INSERT INTO [sfs_test2].dbo.[Table_1] (UserID, UserName)
SELECT UserID, UserName
FROM [sfs_test].dbo.[Table_1]
WHERE UserID NOT IN (SELECT DISTINCT UserID
FROM [sfs_test2].dbo.[Table_1])
```
Now, the problem I'm facing is that if I update/change a record in Table\_1 as in if I change the ID of the record "1 ABC" to "4 ABC"
When the job runs I get the following records in Table\_2
```
2 PQR
3 XYZ
1 ABC
4 ABC
```
While I'm looking for the following output:
```
2 PQR
3 XYZ
4 ABC
```
I have tried to explain my situation as well as I could. I am new to this forum, so, my apologies for asking any stupid question or not explaining it well.
Any help is appreciated
EDIT:
Thank you for all the replies guys!
I believe that I have failed to mention that any column of Table\_1 can be updated and the same should reflect in Table\_2.
@Jibin Balachandran 's solution works fine where only UserID is updated, but not where other columns are changed.
I've come up with a solution of my own and would like your opinion:
would it make sense to delete the records from Table\_2 using Right Join and then using Left Join insert the records that exist in Table\_1 into Table\_2?
@Ranjana Gritmire I still haven't tried your solution. Will do if nothing else works out. Thank you :) | 2016/12/05 | [
"https://Stackoverflow.com/questions/40967422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529764/"
] | ```
DECLARE @TAB AS TABLE (Id int, Duplicate varchar(20))
INSERT INTO @TAB
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'
DELETE FROM @TAB WHERE Id IN (
SELECT Id FROM (
SELECT
Id
,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
-- Change the partition columns to include the ones that make the row distinct
FROM
@TAB
) a WHERE ItemNumber > 1 -- Keep only the first unique item
)
``` | First you create trigger on table 1
```
CREATE TRIGGER trgAfterupdate ON [sfs_test].dbo.[Table_1]
FOR update
AS
declare @empid int;
declare @empname varchar(30);
select @empid=i.UserID from inserted i;
select @empname=i.UserName from inserted i;
if update(UserID)
UPDATE [sfs_test2].dbo.[Table_1] SET UserID=@empid WHERE UserName=@empname
if UPDATE(UserName)
UPDATE [sfs_test2].dbo.[Table_1] SET UserName=@empname WHERE UserID=@empid
GO
```
then you can scheduled your query
```
INSERT INTO [sfs_test2].dbo.[Table_1] (UserID, UserName)
SELECT UserID, UserName
FROM [sfs_test].dbo.[Table_1]
WHERE UserID NOT IN (SELECT DISTINCT UserID
FROM [sfs_test2].dbo.[Table_1])
``` |
133,570 | My background is in Electrical and Electronic Engineering.
Last year I paid and attended [android developer nano-degree by google](https://www.udacity.com/course/android-developer-nanodegree-by-google--nd801) course.
At the end of it I uploaded my [capstone](https://play.google.com/store/apps/details?id=theo.easy.news) project on play store.
Now I am watching another course on Udemy called **NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)** which teaches you how to create node.js. applications. I have also attended two other Udemy courses regarding Android Development.
I applied for various android role positions, but didn't hear anything back. I was expected at least to be interviewed on my capstone's project code which is also in [github](https://github.com/theo82/Capstone-Udacity-Android-Nanodegree). The code has been reviewed and works cool. Of course, I need to use at some point patterns like RxJava and MVVM.
But is all this considered as **commercial experience** or I wasted my money watching online courses? | 2019/04/09 | [
"https://workplace.stackexchange.com/questions/133570",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/85518/"
] | There is a bit of a false dichotomy in your final question.
First of all, training courses are not considered professional (or commercial) experience, because it does not meet the definition of professional experience. There may be courses where you may have a placement within a professional environment, working on professional project, and that may be muddying the water a little, but they are very rare.
Professional experience means to be employed in the profession in question. There are a range of implications that step from that. Commercial experience implies that you've worked on a product that has seen some degree of commercialisation (in other words, you sold it to someone.) Note that sticking an app on an App Store is likely to count for very little given how trivial that is to do. Get a large number of downloads, and it may be a different story.
>
> But is all this considered as commercial experience or I wasted my money watching online courses?
>
>
>
If you end goal was to gain commercial experience, then you have (probably) not reached that goal by doing a Udacity course, but that doesn't necessarily mean you wasted your money.
If you learnt valuable skills as part of that course, it makes you more employable. If the course is recognised by the person making the hiring decision, you're even more employable.
Just because some large organisation "accredits" a course doesn't mean that it is held in universal regard.
Also, I just want to point out, that even widely-known certification authorities are considered as useless by some people, for various reasons. Just as degrees are considered the same by some people too. | It's good to have a certain course completed from a widely-known certification authority (online of offline) and have the certificate, but most of the time, that counts towards your proficiency level and theoretical knowledge.
Majority of the cases, they are **not** considered as professional experience.
If you have pet-projects which you can showcase, that adds to the value, sure.
* If you're searching for entry-level positions (fresh out of college), they may look very good on your CV.
* However, if you're having certain experience, and the course is not directly related to your field/ domain of work experience, the online certifications are seldom worthy of *substantial* influence alone. |
30,660,119 | I try to attach a click handler for links with a specific class within an anonymous function definition which is unfortunately not working. Why?
```
(function($) {
var init = function() {
console.log('init...');
mediaPlayer($('.media-toggle'));
};
var mediaPlayer = function(mediaLink) {
console.log('media player init ...');
console.log(mediaLink);
mediaLink.on("click", function(e) {
console.log('media toggle clicked ...');
e.stopPropagation();
e.preventDefault();
alert('clicked');
});
};
init();
})(jQuery);
```
The used HTML markup looks like:
```
<ul>
<li>
<a href="https://www.foo.org/audios/preview1.mp3" class="media-toggle">Preview 1</a>
<audio src="https://www.foo.org/audios/preview1.mp3"></audio>
</li>
<li>
<a href="https://www.foo.org/audios/preview2.mp3" class="media-toggle">Preview 2</a>
<audio src="https://www.foo.org/audios/preview2.mp3"></audio>
</li>
<li>
<a href="https://www.foo.org/audios/preview3.mp3" class="media-toggle">Preview 3</a>
<audio src="https://www.foo.org/audios/preview3.mp3"></audio>
</li>
</ul>
```
I have to admit, that I use the [MediaElement.js](http://mediaelementjs.com/) library to play the audio files, which works fine.
If I would use a "global" function handler definition like the code snippet below, it would work. But I don't understand why and what is the difference.
```
$(function(){
$('.media-toggle').click(function(e) {
e.preventDefault();
alert('Clicked ...');
});
``` | 2015/06/05 | [
"https://Stackoverflow.com/questions/30660119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3703096/"
] | I missed a very important part on my example. A piece of JS code after this function is or was responsible for the not working code. Which removed all the event handlers by moving a parent div element (with all the links inside) to another part within the DOM tree.
Instead of
```js
$(".preview-audio").remove().insertAfter($(".foo"));
```
I should rather have written
```js
$(".preview-audio").insertAfter($(".foo"));
``` | You have defined a function `mediaPlayer` but you have a typo when calling it: `medialPlayer($('.media-toggle'));`
It's likely you would see an error in the console.
Also, make sure you've got this inside an `onload` or `$(document).on('ready')` function to ensure that the DOM node you're interested in (`.media-toggle`) has been loaded. |
72,937,810 | So i made a template struct cause i want to be able to decide what type i give to my `val`. But when creating a function i don't know how to do it.
Here's what i'm doing:
**In my .hpp**
```
template<typename T>
struct Integer
{
T val;
void setUint(const T &input);
};
```
Now i can set what variable i want in the val and what i want in the function.
But now in my **cpp** i don't know how to invoke the function.
```
void Integer<T>::setUint(const T &input)
{
val = input;
}
```
Error: identifier "T" is undefined. | 2022/07/11 | [
"https://Stackoverflow.com/questions/72937810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15469942/"
] | A template function is a way to operate with generic types (you may consider the type as an argument). Your template parameter `T` allows to pass different types to a function when you invoke the function (which means, simply said, you may replace `T` with some other types `int, double`, ...)
Please, have a look at the following simple example.
```cpp
#include <iostream>
#include <typeinfo>
// you may put it all in a hpp and thus include the hpp file in the CPP
template<typename T>
struct Integer
{
T val;
void setUint(const T &input){
val=input;
std::cout <<"the type is " << typeid(T).name() << " value is "<< val << std::endl;
}
};
// or look at Jarod42's implementation details.
/*
template<typename T>
void Integer<T>::setUint(const T &input){
val=input;
std::cout <<"the type is " << typeid(T).name() << " value is "<< val << std::endl;
}*/
// and here you have your cpp calling you template function with different types
int main()
{
Integer<double> value;
value.setUint(1500000);
Integer<int> value2;
value2.setUint(5);
return 0;
}
``` | Also for templates, check if T actually matches your expectations. Your template will not make sense for types that are not Integers. Example on how to add these constraints here : <https://godbolt.org/z/YsneKe7vj> (both C++17 SFINAE, and C++20 concept)
```
#include <type_traits>
#include <string>
//-----------------------------------------------------------------------------------------------------------
// for C++17 setup a constexpr that will evaluate (at compile time, that's the constexpr bit)
// if a given type is an integer type
template<typename type_t>
constexpr bool is_integer_type_v = std::is_integral_v<type_t> && !std::is_same_v<type_t,bool>;
// create a template that can optionally be enabled. This is an example of a technique called SFINAE
template<typename type_t, typename enable = void>
struct Integer;
// for C++ define a specialization that will succesfully be enabled of integer types only
template<typename type_t>
struct Integer<type_t,std::enable_if_t<is_integer_type_v<type_t>>>
{
void Set(const type_t v)
{
value = v;
}
type_t value;
};
//-----------------------------------------------------------------------------------------------------------
// for C++20 use concepts
template<typename type_t>
concept is_integer = std::is_integral_v<type_t> && !std::is_same_v<type_t, bool>;
// note is_integer now replaces typename, and it can only accept types
// that satisfy the concept
template<is_integer integer_t>
struct IntegerCpp20
{
void Set(const integer_t v)
{
value = v;
}
integer_t value;
};
//-----------------------------------------------------------------------------------------------------------
int main()
{
//Integer<std::string> value; // will not compile;
Integer<int> value;
value.Set(2);
//IntegerCpp20<std::string> value; // will not compile;
IntegerCpp20<int> value20;
value20.Set(20);
return 0;
}
``` |
6,932,617 | So I am starting to learn C#, like literally just started learning, and coming from a Java background, it doesn't look too bad. However, I have a question. I am following [THIS](http://msdn.microsoft.com/en-us/library/ee857094%28office.14%29.aspx#SP2010ClientOM_Creating_Populating_List) tutorial on using the client-object model. And just starting from the top, I added the references, but `using Microsoft.SharePoint.Client;` keeps giving me the error that "the namespace 'SharePoint' does not exist in the namespace 'Microsoft', but I clearly see it on the right side panel. So looking at the instructions, the only difference I can think of is that fact that I am using Visual Studio Express and thus do not have the option to choose which framework to use when creating a new project. Other than that, I don't know what the problem might be. Does anyone have any ideas on what else I could be missing or how to correct this problem? | 2011/08/03 | [
"https://Stackoverflow.com/questions/6932617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810860/"
] | 1. Add required references to the solution.
2. Make sure that the **target framework is 4 for SP2013**(3.5 for SP2010). | Thanks to those who mentioned the 4.0 framework.
Mine defaulted to .NET Framework 4 Client Profile (and I have no idea what that means), and the Namespaces looked good in Intellisense, but the build would say they weren't found! Crazy. |
4,841,781 | I am not too familiar with queries but here is the question:
My 'neighbourhood' table has columns:
```
n_id, name, country_id, continent_id, city_id.
```
Where n\_id = PK and country\_id, continent\_id, city\_id are FKs to their own tables.
Sample data is:
```
34, Brooke, 23, 3, 1456
```
This output is good for data relationships but not for user output. On the user side when they see Brooke on the website it should be; **Brooke, New York - USA**. (So in essence: Brooke, 1456 - 23).
The question is: if I store only IDs in the neighborhood table then I have to join 2 tables each time to pull the names of the IDs. So to avoid this it is better to store the names again as a duplicate in the table so the columns will be:
```
n_id, name, country_id, country_name, continent_id, city_id, city_name
```
What is the performance difference with both ways? Or the advantages or disadvantages?
\*\* Site is a social network if it helps. | 2011/01/30 | [
"https://Stackoverflow.com/questions/4841781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570181/"
] | When you add duplicate names in the neighborhood table, you are de-normalizing it. De-normalization will make queries faster, especially if the load on your system is very high. But denormalization comes at a cost, because you must write and maintain additional code to keep your redundant data in sync.
I would keep 2 things in mind:
1. As a general rule, never optimize something until you have demonstrated a need to optimze it (Abrash's rule #1)
2. If you find that your joins need to be faster, the first optimization to try is to tune your indexes. This will allow you to have fast joins without losing the benefit of a normalized design. | The major disadvantage of your proposed denormalized design is that the correct referential integrity constraints and update actions become excessively complicated. If the data associated with City\_ID 1456 changes, you not only have to change the one row in the City table, you also have to change the stored value in each of the NBighbourhood rows that cross-references the City table (contains City\_ID = 1456). These 'update anomalies' are the primary reason for the discipline of normalization.
Performance is tricky to measure; it will depend on the DBMS and the size of the tables, but it is conceivable that joining smaller tables will be quicker than having to scan all of a big table (where the 'big table' is your proposed revised Neighbourhood table swollen up by all the extra data that you want to add). Unless you index both the City\_ID and City\_Name columns in the Neighbourhood table, for example (thus using more space in indexes than you would with the normalized design), your scans for all the people in a single city may take longer (because the whole of the Neighbourhood table has to be read sequentially) than an indexed lookup on the City table to find the City\_ID, and then an index scan for precisely the correct City\_ID in the Neighbourhood table.
So, it is possible that your denormalized, 'efficient' design ends up being less efficient by each of several different measures than your current normalized design.
If you do decide to change from your current normalized design, make sure you **measure** the true costs - in complexity of update operations and disk space used as well as in query speed. It might still be better to denormalize; it is not necessarily a slam-dunk. And your cost equation may change over time, as the size of the data changes, so you may need to do your measurements multiple times. |
3,277,172 | I want to use a pair from STL as a key of a map.
```
#include <iostream>
#include <map>
using namespace std;
int main() {
typedef pair<char*, int> Key;
typedef map< Key , char*> Mapa;
Key p1 ("Apple", 45);
Key p2 ("Berry", 20);
Mapa mapa;
mapa.insert(p1, "Manzana");
mapa.insert(p2, "Arandano");
return 0;
}
```
But the compiler throw a bunch of unreadable information and I'm very new to C and C++.
How can I use a pair as a key in a map? And in general How can I use any kind of structure (objects, structs, etc) as a key in a map?
Thanks! | 2010/07/18 | [
"https://Stackoverflow.com/questions/3277172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91945/"
] | `std::map::insert` takes a single argument: the key-value pair, so you would need to use:
```
mapa.insert(std::make_pair(p1, "Manzana"));
```
You should use `std::string` instead of C strings in your types. As it is now, you will likely not get the results you expect because looking up values in the map will be done by comparing pointers, not by comparing strings.
If you really want to use C strings (which, again, you shouldn't), then you need to use `const char*` instead of `char*` in your types.
>
> And in general How can I use any kind of structure (objects, structs, etc) as a key in a map?
>
>
>
You need to overload `operator<` for the key type or use a custom comparator. | Alternatively to what James McNellis stated:
```
mapa.insert(std::make_pair(p1, "Manzana"));
```
you could use `mapa.insert({p1, "Manzana"});` |
61,671 | When a space craft enters the atmosphere, it gets hot and heat shielding is needed. Do objects with more surface area and less density heat up less then heavier, smaller objects? Could an object with a large enough weight to area ratio be air cooled and not burn? I understand that when entering the atmosphere it is not like hitting water since the air gradually becomes more dense. In theory, would a feather get too hot and burn on reentry or would it make it to the ground intact?
I'm thinking a rotating aerographene sphere. | 2023/01/28 | [
"https://space.stackexchange.com/questions/61671",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/35950/"
] | The heat to be dissipated by an object re-entering from orbit is $64$ megajoules per kilogram. There is no dependence here on density: that is the amount of kinetic energy it starts with and has to lose.
In a hyper-gradual re-entry the object can radiate the heat as it goes. But slow deceleration requires lower drag than we know how to attain.
In a fast re-entry the surface of the object (which is what is heated) will get extremely hot and may burn or vaporise. But now the re-entry time begins to matter. To conduct heat from the surface to the inside takes time, and if the re-entry is fast enough, the heat pulse won’t have time to penetrate before the re-entry is over and no more heat is coming in.
Between slow and fast there is a worst case where radiation cools the outer surface but conduction has time to cook the contents. That is why (for example) high-heat-capacity buffers - of beryllium, for instance - end up doing more harm than good. | >
> Do lighter objects heat less while entering the atmosphere?
>
>
>
They heat more, not less. The square-cube law comes into play. Heating is proportional to an object's surface area and inversely proportional to mass. All other things being equal, that means heating is inversely proportional to the square of an object's size. Small meteors tend to vaporize quite high in the atmosphere where the air is still very thin. Larger ones heat to the point where they explode lower in the atmosphere where the air is much thicker. Even larger ones can survive entry and hit the Earth, and sometimes they're still cold. |
42,598,475 | I would like to display IP cameras streaming in RTSP into a web page.
I've tried many solutions, like using VLC to transcode the stream, but none of them seems to be reliable enough to create a real web service.
I'm thinking on using some media server like flussonic or Red5. But I don't know if it will work.
This is why I would like to know what is the best (and the simple) solution to display RTSP streams on a webpage. | 2017/03/04 | [
"https://Stackoverflow.com/questions/42598475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2654121/"
] | >
> ...to create a real web service.
>
>
>
I've been looking for an answer for the past two or three days (I need support on as many browsers as possible, and latency as low as possible, so WebRTC was the way to go (is there anything better?)) and I've finally found it.
Check out [this](https://github.com/deepch/RTSPtoWebRTC) repo.
From the repo's readme + the additional steps I had to take (on Ubuntu 18.04) to make this work:
1. Install go
`$ sudo snap install go --classic`
2. Get the code on your local device (Could someone enlighten me on what the export is for?).
`$ export GO111MODULE=on`
`$ go get github.com/deepch/RTSPtoWebRTC`
3. This step didn't work for me, so I just downloaded the code in a .zip file and extracted it in the given directory and proceeded. (What did I miss? The src directory was not there before I made it)
`$ cd ~/go/src/github.com/deepch/RTSPtoWebRTC`
4. Run from current directory.
`$ go run .`
5. Then I opened the link below a web browser ( I tested on Chrome, iOS Safari, but it also works on Firefox).
`http://127.0.0.1:8083`
This took me very little time to implement. Big thanks to the guys making this. All the other stuff I've found is either 5-7 years old and not working or non-WebRTC or a marketed paid service asking for unreasonable amounts of money.
I hope I answered your question. | You can integrate VLC library into your website and VLC will take care of everything you need for playing RTSP stream:
<https://wiki.videolan.org/index.php?title=HowTo_Integrate_VLC_plugin_in_your_webpage&action=edit&oldid=19150> |
8,972,758 | We have application that runs 24h per day and 7 days per week. Sometimes CPU go to 100% and then go back to 80%. The same with RAM. Is it smart to manually call `GC.Collect` after few hours or betterto leave it automatically.
We are using C# 2010, SQL 2008 and Fluent Nhiberanet. This is desktop application. | 2012/01/23 | [
"https://Stackoverflow.com/questions/8972758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267679/"
] | normally the framework itself will handle calling the GC when it's needed
you could try to run it without calling it yourself for a day | I would refrain from calling `GC.Collect` - exceptional cases as described [here](http://blogs.msdn.com/b/scottholden/archive/2004/12/28/339733.aspx) and [here](https://stackoverflow.com/a/478177/847363) aside.
IF you have any application running 24/7 then I would recommend the following:
* check real hard for memory leaks and correct any such leak (using multiple memory profilers)
IF you need any links please say so...
* try your very best to reduce resource usage by optimizing/rewriting your code
* configure the application to use GC in "server mode" as that is designed for 24/7 situations (for details see [here](http://msdn.microsoft.com/en-us/library/ms229357.aspx))
This is not a miracle solution but something you should try with your application and compare whether it gives you any benefits. |
3,460,304 | Within a standard code block, should HTML appear exactly as written?
For example, if I put the following:
```
<code>
<script type="text/javascript">Something in javascript</script>
</code>
```
Should it appear exactly as above?
I assume the code button here on stackoverflow is doing something else other than just putting it in ?
Thanks! | 2010/08/11 | [
"https://Stackoverflow.com/questions/3460304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229558/"
] | There are certain characters that must be encoded even in the code block. My preference is converting the less than, greater than and ampersand. This handles most of the code. | No. `<code>` isn't even block-level. It also depends on whether you mean "traditional" HTML or XHTML. |
2,412,450 | I am writing a pre-commit hook. I want to run `php -l` against all files with .php extension. However I am stuck.
I need to obtain a list of new/changed files that are staged. deleted files should be excluded.
I have tried using `git diff` and `git ls-files`, but I think I need a hand here. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2412450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/289985/"
] | `git diff --cached --name-status` will show a summary of what's staged, so you can easily exclude removed files, e.g.:
```
M wt-status.c
D wt-status.h
```
This indicates that wt-status.c was modified and wt-status.h was removed in the staging area (index). So, to check only files that weren't removed:
```
steve@arise:~/src/git <master>$ git diff --cached --name-status | awk '$1 != "D" { print $2 }'
wt-status.c
wt-status.h
```
You will have to jump through extra hoops to deal with filenames with spaces in though (-z option to git diff and some more interesting parsing) | None of the answers here support filenames with spaces. The best way for that is to add the `-z` flag in combination with `xargs -0`
```
git diff --cached --name-only --diff-filter=ACM -z | xargs -0 ...
```
This is what is given by git in built-in samples (see **.git/hooks/pre-commit.sample**) |
1,078,319 | I am trying to get a better feel for both the exterior derivative of a form and the contraction of a form by a vector field $X$.
Basically, when are these inverses? If I have a one-form $\omega$ and I compute $dw$, getting a 2-form. When can I find a vector field $X$ so that $w = i\_Xdw$? Is there a general result describing the relation between forms $w, v$ such that $w=i\_Xdv$?
I am aware of the issue of closed and exact forms, but I am having trouble framing this question in this format.
EDIT: Also, is there a "nice" geometric way of seeing the interior product? We can see the exterior derivative in terms of geometric algebra, by creating "parallelepipeds" or their $n$-dimensional equivalent, as volume elements. Is something similarly geometric going on when we contract by a vector field?
Thanks. | 2014/12/23 | [
"https://math.stackexchange.com/questions/1078319",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/197865/"
] | Here is an example Python code that solves the optimization problem suggested by @DeepSea
```
import casadi as ca
opti = ca.Opti()
# Line segment
t = opti.variable()
line_seg = opti.bounded(0, t, 1)
p0 = (-4.0, 0.5)
p1 = (-2.0, 1.5)
x = (1 - t) * p0 + t * p1
# Circle
y = opti.variable(2)
circ = y[0]**2 + y[1]**2 == 1
# Optimization problem
dist_squared = (x[0] - y[0])**2 + (x[1] - y[1])**2
opti.minimize(dist_squared)
opti.subject_to(line_seg)
opti.subject_to(circ)
# Solve
opti.solver('ipopt')
sol = opti.solve()
# Result
print(f"Distance = {sol.value(ca.sqrt(dist_squared))}")
print(f"Point on line segment: {sol.value(x)}")
print(f"Point on circle: {sol.value(y)}")
``` | Assuming that you are talking about the perpendicular distance of a point on the circle closest to the given line.
equation of line $P\_1P\_2$ is $(y-y\_1)=\dfrac{y\_2-y\_1}{x\_2-x\_1}(x-x\_1)$
The formulae for the distance will be $\perp$ distance from the center of the circle to the line - radius of the circle. because the closest point on any curve from a line lies on the common normal to both of them and common normal in this case is the $\perp$ from center to the line.
So the "simple formula" is, $\dfrac{|(y\_c-y\_1)-\dfrac{y\_2-y\_1}{x\_2-x\_1}(x\_c-x\_1)|}{\sqrt{1+(\dfrac{y\_2-y\_1}{x\_2-x\_1})^2}}-r$ |
11,182,725 | I'm writing a fairly complicated multi-node proxy, and at one point I need to handle an HTTP request, but read from that request outside of the "http.Server" callback (I need to read from the request data and line it up with a different response at a different time). The problem is, the stream is no longer readable. Below is some simple code to reproduce the issue. Is this normal, or a bug?
```
function startServer() {
http.Server(function (req, res) {
req.pause();
checkRequestReadable(req);
setTimeout(function() {
checkRequestReadable(req);
}, 1000);
setTimeout(function() {
res.end();
}, 1100);
}).listen(1337);
console.log('Server running on port 1337');
}
function checkRequestReadable(req) {
//The request is not readable here!
console.log('Request writable? ' + req.readable);
}
startServer();
``` | 2012/06/25 | [
"https://Stackoverflow.com/questions/11182725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23837/"
] | Each bit level has a pattern consisting of `2^power` 0s followed by `2^power` 1s.
So there are three cases:
1. When `M` and `N` are such that `M = 0 mod 2^(power+1)` and `N = 2^(power+1)-1 mod 2^(power+1)`. In this case the answer is simply `(N-M+1) / 2`
2. When `M` and `N` are such that both M and N = the same number when integer divided by `2^(power+1)`. In this case there are a few subcases:
1. Both `M` and `N` are such that both `M` and `N` = the same number when integer divided by `2^(power)`. In this case if `N < 2^(power) mod 2^(power+1)` then the answer is `0`, else the answer is `N-M+1`
2. Else they are different, in this case the answer is `N - (N/2^(power+1))*2^(power+1) + 2**(power)` (integer division) if `N > 2^(power) mod 2^(power+1)`, else the answer is `(M/2^(power+1))*2^(power+1) - 1 - M`
3. Last case is where M and N = different numbers when integer divided by `2^(power+1)`. This this case you can combine the techniques of 1 and 2. Find the number of numbers between `M` and `(M/(2^(power+1)) + 1)*(2^(power+1)) - 1`. Then between `(M/(2^(power+1)) + 1)*(2^(power+1))` and `(N/(2^(power+1)))*2^(power+1)-1`. And finally between `(N/(2^(power+1)))*2^(power+1)` and `N`.
If this answer has logical bugs in it, let me know, it's complicated and I may have messed something up slightly.
UPDATE:
python implementation
```
def case1(M, N):
return (N - M + 1) // 2
def case2(M, N, power):
if (M > N):
return 0
if (M // 2**(power) == N // 2**(power)):
if (N % 2**(power+1) < 2**(power)):
return 0
else:
return N - M + 1
else:
if (N % 2**(power+1) >= 2**(power)):
return N - (getNextLower(N,power+1) + 2**(power)) + 1
else:
return getNextHigher(M, power+1) - M
def case3(M, N, power):
return case2(M, getNextHigher(M, power+1) - 1, power) + case1(getNextHigher(M, power+1), getNextLower(N, power+1)-1) + case2(getNextLower(N, power+1), N, power)
def getNextLower(M, power):
return (M // 2**(power))*2**(power)
def getNextHigher(M, power):
return (M // 2**(power) + 1)*2**(power)
def numSetBits(M, N, power):
if (M % 2**(power+1) == 0 and N % 2**(power+1) == 2**(power+1)-1):
return case1(M,N)
if (M // 2**(power+1) == N // 2**(power+1)):
return case2(M,N,power)
else:
return case3(M,N,power)
if (__name__ == "__main__"):
print numSetBits(0,10,0)
print numSetBits(0,10,1)
print numSetBits(0,10,2)
print numSetBits(0,10,3)
print numSetBits(0,10,4)
print numSetBits(5,18,0)
print numSetBits(5,18,1)
print numSetBits(5,18,2)
print numSetBits(5,18,3)
print numSetBits(5,18,4)
``` | It can be kept as simple as -
Take x1 = 0001(for finding 1's at rightmost column), x2 = 0010, x3 = 0100 and so on..
Now, in a single loop -
```
n1 = n2 = n3 = 0
for i=m to n:
n1 = n1 + (i & x1)
n2 = n2 + (i & x2)
n3 = n3 + (i & x3)
```
where -
ni = number of 1's in i'th column(from right) |
61,357,383 | I would like to label my plot, possibly using the equation method from ggpmisc to give an informative label that links to the colour and equation (then I can remove the legend altogether). For example, in the plot below, I would ideally have the factor levels of 4, 6 and 8 in the equation LHS.
```
library(tidyverse)
library(ggpmisc)
df_mtcars <- mtcars %>% mutate(factor_cyl = as.factor(cyl))
p <- ggplot(df_mtcars, aes(x = wt, y = mpg, group = factor_cyl, colour= factor_cyl))+
geom_smooth(method="lm")+
geom_point()+
stat_poly_eq(formula = my_formula,
label.x = "centre",
#eq.with.lhs = paste0(expression(y), "~`=`~"),
eq.with.lhs = paste0("Group~factor~level~here", "~Cylinders:", "~italic(hat(y))~`=`~"),
aes(label = paste(..eq.label.., sep = "~~~")),
parse = TRUE)
p
```
[](https://i.stack.imgur.com/HhXh1.png)
There is a workaround by modifying the plot afterwards using the technique described [here](https://stackoverflow.com/a/58376249/4927395), but surely there is something simpler?
```
p <- ggplot(df_mtcars, aes(x = wt, y = mpg, group = factor_cyl, colour= factor_cyl))+
geom_smooth(method="lm")+
geom_point()+
stat_poly_eq(formula = my_formula,
label.x = "centre",
eq.with.lhs = paste0(expression(y), "~`=`~"),
#eq.with.lhs = paste0("Group~factor~level~here", "~Cylinders:", "~italic(hat(y))~`=`~"),
aes(label = paste(..eq.label.., sep = "~~~")),
parse = TRUE)
p
# Modification of equation LHS technique from:
# https://stackoverflow.com/questions/56376072/convert-gtable-into-ggplot-in-r-ggplot2
temp <- ggplot_build(p)
temp$data[[3]]$label <- temp$data[[3]]$label %>%
fct_relabel(~ str_replace(.x, "y", paste0(c("8","6","4"),"~cylinder:", "~~italic(hat(y))" )))
class(temp)
#convert back to ggplot object
#https://stackoverflow.com/questions/56376072/convert-gtable-into-ggplot-in-r-ggplot2
#install.packages("ggplotify")
library("ggplotify")
q <- as.ggplot(ggplot_gtable(temp))
class(q)
q
```
[](https://i.stack.imgur.com/LFlt5.png) | 2020/04/22 | [
"https://Stackoverflow.com/questions/61357383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4927395/"
] | What about a manual solution where you can add your equation as `geom_text` ?
Pros: Highly customization / Cons: Need to be manually edited based on your equation
Here, using your example and the linear regression:
```r
library(tidyverse)
df_label <- df_mtcars %>% group_by(factor_cyl) %>%
summarise(Inter = lm(mpg~wt)$coefficients[1],
Coeff = lm(mpg~wt)$coefficients[2]) %>% ungroup() %>%
mutate(ypos = max(df_mtcars$mpg)*(1-0.05*row_number())) %>%
mutate(Label2 = paste(factor_cyl,"~Cylinders:~", "italic(y)==",round(Inter,2),ifelse(Coeff <0,"-","+"),round(abs(Coeff),2),"~italic(x)",sep =""))
# A tibble: 3 x 5
factor_cyl Inter Coeff ypos Label2
<fct> <dbl> <dbl> <dbl> <chr>
1 4 39.6 -5.65 32.2 4~Cylinders:~italic(y)==39.57-5.65~italic(x)
2 6 28.4 -2.78 30.5 6~Cylinders:~italic(y)==28.41-2.78~italic(x)
3 8 23.9 -2.19 28.8 8~Cylinders:~italic(y)==23.87-2.19~italic(x)
```
Now, you can pass it in `ggplot2`:
```r
ggplot(df_mtcars,aes(x = wt, y = mpg, group = factor_cyl, colour= factor_cyl))+
geom_smooth(method="lm")+
geom_point()+
geom_text(data = df_label,
aes(x = 2.5, y = ypos,
label = Label2, color = factor_cyl),
hjust = 0, show.legend = FALSE, parse = TRUE)
```
[](https://i.stack.imgur.com/hDPfl.png) | An alternative to labelling with the equation is to label with the fitted line. Here is an approach adapted from an answer on a related question [here](https://stackoverflow.com/a/61362537/4927395)
```
#example of loess for multiple models
#https://stackoverflow.com/a/55127487/4927395
library(tidyverse)
library(ggpmisc)
df_mtcars <- mtcars %>% mutate(cyl = as.factor(cyl))
models <- df_mtcars %>%
tidyr::nest(-cyl) %>%
dplyr::mutate(
# Perform loess calculation on each CpG group
m = purrr::map(data, lm,
formula = mpg ~ wt),
# Retrieve the fitted values from each model
fitted = purrr::map(m, `[[`, "fitted.values")
)
# Apply fitted y's as a new column
results <- models %>%
dplyr::select(-m) %>%
tidyr::unnest()
#find final x values for each group
my_last_points <- results %>% group_by(cyl) %>% summarise(wt = max(wt, na.rm=TRUE))
#Join dataframe of predictions to group labels
my_last_points$pred_y <- left_join(my_last_points, results)
# Plot with loess line for each group
ggplot(results, aes(x = wt, y = mpg, group = cyl, colour = cyl)) +
geom_point(size=1) +
geom_smooth(method="lm",se=FALSE)+
geom_text(data = my_last_points, aes(x=wt+0.4, y=pred_y$fitted, label = paste0(cyl," Cylinders")))+
theme(legend.position = "none")+
stat_poly_eq(formula = "y~x",
label.x = "centre",
eq.with.lhs = paste0(expression(y), "~`=`~"),
aes(label = paste(..eq.label.., sep = "~~~")),
parse = TRUE)
```
[](https://i.stack.imgur.com/Ldxx5.png) |
4,197,674 | I have the following setup:
```
CREATE TABLE dbo.Licenses
(
Id int IDENTITY(1,1) PRIMARY KEY,
Name varchar(100),
RUser nvarchar(128) DEFAULT USER_NAME()
)
GO
CREATE VIEW dbo.rLicenses
AS
SELECT Name
FROM dbo.Licenses
WHERE RUser = USER_NAME()
GO
```
When I try to insert data using the view...
```
INSERT INTO dbo.rLicenses VALUES ('test')
```
an error arises:
```
Cannot insert the value NULL into column Id, table master.dbo.Licenses; column does not allow nulls. INSERT fails.
```
Why doesn't the auto increment of the identity column work when trying to insert using the view and how can I fix it?
Scenario is:
**The different users of the database should only be able to work with their own rows in that table. Therefore I am trying to use the view as a kind of security by checking the username.** Is there any better solution? | 2010/11/16 | [
"https://Stackoverflow.com/questions/4197674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509905/"
] | You just need to specify which columns you're inserting directly into:
```
INSERT INTO [dbo].[rLicenses] ([Name]) VALUES ('test')
```
Views can be picky like that. | ```
INSERT INTO dbo.rLicenses
SELECT 'test'
```
Based on [sqlhack](https://www.sqlshack.com/create-view-sql-inserting-data-through-views-in-sql-server/) in chapter "Data modifications through views" |
381,772 | I want to submit the values of a flex form to a ColdFusion cfc.
If I have a flex form (see below) is the data in the form an object? Or do I have to create an object based on the id's in the form and then pass that new object to the coldfusion component?
```
<mx:Form x="10" y="10" width="790" id="myFrom" defaultButton="{createReport}">
<mx:FormItem label="Resume Report Type:">
<mx:RadioButtonGroup id="showtype"/>
<mx:HBox>
<mx:RadioButton groupName="showtype" id="NotUpdated" value="notupdated" label="Not Updated" width="100" />
<mx:RadioButton groupName="showtype" id="Updated" value="updated" label="Updated" width="75" />
<mx:RadioButton groupName="showtype" id="All" value="all" label="All" width="75" />
</mx:HBox>
</mx:FormItem>
<mx:FormItem label="User Organzation:">
<mx:ComboBox dataProvider="{qOrganization}" labelField="UserOrganization" /> </mx:FormItem>
<mx:FormItem label="Between the following dates:">
<mx:HBox>
<mx:DateField/>
<mx:DateField left="10"/>
</mx:HBox>
</mx:FormItem>
<mx:FormItem>
<mx:Button label="Create Report" id="createReport"/>
</mx:FormItem>
</mx:Form>
``` | 2008/12/19 | [
"https://Stackoverflow.com/questions/381772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24563/"
] | I think in the late 70s it was called [time-sharing](https://en.wikipedia.org/wiki/Time-sharing) :) | 1) They've been using it for years, so I'm thinking yeah.
2) They have web browsers, so yeah.
3) O yes my brothers.
4) The vogue for the term, where it's used like it has some kind of cosmic significance that "Web 2.0" and "software as a service" didn't, is definitely overdone and will fizzle, and it really can't happen too soon.
5) Assuming what you've been doing is use the best methods you can find to accomplish what you need to get done, nothing. |
20,471,181 | I am using Android 4.3 on VirtualBox, for testing apps. However, I'm running the VM on my computer, which is behind a proxy (without DHCP), so I cannot connect to the Internet from the VM.
What I need to accomplish:
1. Setup the Android machine to use a static IP (192.168.1.213/24, with gateway 192.168.1.1)
2. Setup proxy access (proxy is on another server in the network 192.168.1.2 and has user/pass)
Can you please let me know how I can do this? More details on what I'm using:
* From <http://code.google.com/p/android-x86/downloads/list> , I used android-x86-4.3-20130725.iso
* In VirtualBox, under settings for machine, I've used Bridged Adapter and the default selection "Realtek PCIe GBE Family Controller"
* No other changes
Not very familiar with available commands in adb (I just know that you can access it with Alt-F1, and hide it with Alt-F7), so I would appreciate more in-detail instructions.
Thank you
**Edit:** I ran the following commands to setup static IP:
*- su*
*- ifconfig eth0 192.168.1.213 netmask 255.255.255.0 up*
*- route add default gw 192.168.1.1 dev eth0*
This solved requirement 1 (setting up static IP), and now I can ping other computers from my network, so I only need a way to setup a proxy with user/pass (requirement 2) | 2013/12/09 | [
"https://Stackoverflow.com/questions/20471181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1374462/"
] | This article about [Android x86: setting-up IP Address using command line](http://tutorialtabai.blogspot.com/2013/05/android-x86-setting-up-ip-address.html) may helpful to you.
Proxy setup
```
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
INSERT INTO system VALUES(99, 'http_proxy', '<proxy_server>:<port>');
ex: INSERT INTO system VALUES(99, 'http_proxy', '192.168.179.202:3128');
``` | The above answers only work on Android < 6.
If you are using something newer, the following has worked for me
Alt + F1 to get into the shell
```
settings put global http_proxy <address>:<port>
``` |
50,111,863 | First of all I know that there are many questions already regarding this.After reading all answers and trying it out ..but none of them worked.So I'm uploading a question here.Please don't delete it.
So,I created a html file with a form and then sent the form data using ajax jQuery to PHP file as follows.
```
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata
});
//display the message sent by PHP
/*Use the data sent by PHP to perform
different function*/
```
Now I want PHP to send a message to js or html or anything else.Also, I want PHP to send some Boolean data which I will be using to perform some function. | 2018/05/01 | [
"https://Stackoverflow.com/questions/50111863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8420732/"
] | You can use javascript getelementbyid as following:
```
document.getElementById("login-button").click();
``` | The only way it comes to my mind to do it is using jQuery to select the element (button) and then trigger the click:
```
$( "#login-button" ).trigger( "click" );
```
Try it and let us know if it works, here you are a JSFiddle: [link](https://jsfiddle.net/vhbazan/mesg71ww/) |
345,704 | I was wondering when and how the expression "Whatever floats your boat", meaning "What makes you happy; what stimulates you" ([Wiktionary](https://en.wiktionary.org/wiki/whatever_floats_your_boat)) came to be.
My research hasn't yielded anything which could be described as objective. Thus, I'll leave the urban dictionary and reddit assumptions aside. [The ngram shows a steep rise starting in the early 80s.](https://books.google.com/ngrams/graph?content=whatever+floats+your+boat&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cwhatever%20floats%20your%20boat%3B%2Cc0) However, I was not able to pinpoint a definite source.
Can anyone shed light on this issue? | 2016/08/30 | [
"https://english.stackexchange.com/questions/345704",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/184706/"
] | First off, the question of origin for such a colloquial phrase is a hard one to answer. Oral language is often only documented after it has been in use for some time, and anything before the first documented use is going to involve a lot of guesswork. This answer will give (a) predecessors that used similar "whatever verbs you/your thing" phrasing and (b) documented uses of "whatever floats your boat."
Whatever verbs you(r) noun
--------------------------
Fairly late in my research, I turned to the [Corpus of Historical American English](https://www.english-corpora.org/coha/), since Google and academic search engines weren't giving me much to work with. After a couple of tries, I hit on a collocation search for "whatever \_v" (\_v is "verb") and "you\*" (you, your, young - the asterisk is a wildcard). I found a lot of results.
Most results were questions: "whatever are you looking at?" and "whatever gave you that idea?" were two of many examples. There were also uses that functioned as objects of verbs: "He will pretend he is curing you of whatever ails you."
However, there were a few results that functioned quite like *whatever floats your boat* - uses that defer to someone else's preference. The first is quoted in full as it appears in the database, since the play may give more context for the usage. Then two more entries follow.
John Howard Payne, *Richelieu*, 1826.
>
> Janet (aside to madam Dorival) Don't say a word, madam.
>
>
> Mad. D. Madam Dorival (apart) Just Heaven! What shall I do!
>
>
> Rich. Duke of Richlieu (artfully) Ah, I see! My company would be
> intrusive –
>
>
> Dor. Dorival (to his wife) What ails you, my love? Is this mere
> absence of mind? Sure you'll welcome our friend Lamotte once more to
> our fireside.
>
>
> Mad. D. Madam Dorival (forced to speak, but with her eyes cast down)
> You know -- **whatever gives you pleasure** -- (turns abruptly away, and
> says aside) -- My heart revolts from what I say!
>
>
> Rich. Duke of Richlieu (with pretended frankness) Enough. I thank you
> for your invitation, and will not fail to be at supper.
>
>
> Jan. Janet (aside) If he does, may it choke him!
>
>
> Dor. Dorival That's kind, -- that's friendly now; and, to make the
> party more pleasant, I'll have a friend to meet you
>
>
>
Anna Maynard, *The Award of Justice Or, Told in the Rockies A Pen Picture of the West*, 1897
>
> " All right, Mr. Blaisdell, that will be perfectly satisfactory, **whatever suits you young fellows, suits me**. "
>
>
>
Alice Skelsey, *The Working Mother's Guide*, 1970
>
> Now you have all that time to laze around, catch up on projects, slip in a mini-trip or two without the children? **whatever suits your purpose**, just so it is a satisfying change of pace.
>
>
>
So the pattern of saying "whatever suits your purpose" or "whatever suits you" was already in English by the time the 1973 blues album *[Whatever Turns You On](https://en.wikipedia.org/wiki/Whatever_Turns_You_On_(album))* came out, let alone the other forms of "whatever turns you on" that show up in the 1970s.
Whatever floats your boat
-------------------------
>
> Despite all my effort, the earliest source I can find for the usage is
> in the Oxford English Dictionary under "float, v.":
>
>
> transitive. colloquial (originally U.S.). to float a person's boat: to
> interest or excite a person; to appeal to or suit a person. Esp. in
> whatever floats a person's boat.
>
>
> 1981 Sunday Herald (Chicago) 16
> Aug. v. 7/4 Venus enters your house of travel on the 18th to stay
> until Sept. 12, so make getaway any way you can. Fly, drive, row or
> read. **Whatever floats your boat**.
>
>
> 1989 T. Parker Place called Bird
> xxi. 259 **Whatever floats your boat**, you've been doing it all your
> life.
>
>
> 1991 Blitz Sept. 103 Over the following four pages..is a
> composite of **the men and women who float our boats** and why.
>
>
> 1995
>
> Midwest Living Apr. 51/1 (advt.) There are plenty of opportunities
> for fishing, swimming, hiking, biking or **whatever floats your boat**.
>
>
> 2002 More! 3 Apr. 97/4 Small breasts **don't float my boat**.
>
>
>
In the OED entries, by the early 1990s the phrase has become more flexible: "who floats our boats and why" becomes possible. *Green's Dictionary of Slang* notes the extended usage "float one's boat in" as early as 1984, where it appeared in Connie Eble's chapbook *Campus Slang*:
>
> 1984 Eble Campus Sl. Sept. 3: **float my boat** – stimulate, excite: That don't float my boat.
>
>
>
---
Connecting the Dots
-------------------
Given these instances of usage, there are three parts to this guess of an answer:
1. "Whatever verbs you(r) noun" appeared in a few forms as a statement that defers to someone else's preference through the 19th and 20th centuries.
2. "Whatever floats your boat" appeared as a specific instance of this linguistic meme. At the very least, the resemblance is there.
3. The float / boat rhyme generalized in use far beyond its "whatever" origins. The similar meaning and preservation of the rhyme suggest that much. | The idiom, ***whatever floats your boat***, could refer to the American slang, *floating*, meaning *high* or intoxicated by drugs. The term [“whatever”](https://en.wikipedia.org/wiki/Whatever_(slang)) also hints that the speaker is indifferent to the outcome or choice about to be made.
The following extract is from the website *[businessballs.com](http://www.businessballs.com/clichesorigins.htm)*, run by Alan Chapman.
Although copied *ad verbatim*, I chose to break the following article into several paragraphs to facilitate the reader. Any emphasis in bold are mine.
>
> **whatever floats your boat** - if it makes you happy/it's your decision/it's your choice (although I don't necessarily agree and I don't care anyway) - a relatively modern expression from the late 20th century with strangely little known origins.
>
>
> Interestingly the phrase is used not only in the 2nd person (you/your) sense; "Whatever floats your boat" would also far more commonly be used in referring to the 3rd person (him/his/her/their) than "Whatever floats his boat" or Whatever floats her/their boat", which do not occur in common usage. Importantly the meaning also suggests bemusement or disagreement on the part of whoever makes the comment; rather like saying "it's not something I would do or choose myself, but if that's what you want then go ahead, just so long as you don't want my approval".
>
>
> Unofficial references and opinions about the 'whatever floats your boat' cliche seem to agree the origins are American, but other than that we are left to speculate how the expression might have developed.
>
>
> The 'whatever floats your boat' expression is a metaphor that alludes to the person being the boat, and the person's choice (of activity, option, particularly related to lifestyle) being what the boat sits on and supports it, or in a more mystical sense, whatever enables the boat to defy the downward pull of gravity. In this latter sense the word 'floats' is being applied to the boat rather than what it sits on.
>
>
> Whether the phrase started from a single (but as yet unidentified) quote, or just 'grew' through general adoption, the clues to the root origins of the expression probably lie more than anything else in the sense that the person's choice is considered irresponsible or is not approved of, because this sense connects to other negative meanings of 'float' words used in slang. The word 'float' in this expression possibly draws upon meanings within other earlier slang uses of the word 'float', notably **'float around'** meaning to **to occupy oneself circulating among others without any particular purpose** ('loaf around aimlessly' as Cassell puts it, perhaps derived from the same expression used in the Royal Air Force from the 1930s to describe the act of flying irresponsibly and aimlessly).
>
>
> Also, significantly, **'floating'** has since the 1950s been **slang for being drunk or high on drugs.** 'Floating one' refers to passing a dud cheque or entering into a debt with no means of repaying it (also originally from the armed forces, c.1930s according to Cassells). And a 'floater' has for some decades referred to someone who drifts aimlessly between jobs. While none of these usages provides precise origins for the 'floats your boat' expression, they do perhaps suggest why the word 'float' fits aptly with a central part of the expression's meaning, especially the references to drink and drugs, from which the word boat and the combination of float and boat would naturally have developed or been associated.
>
>
>
From *[The Routledge Dictionary of Modern American Slang](https://books.google.co.uk/books?id=5F-YNZRv-VMC&pg=PA380&lpg=PA380&dq=american%20slang%20floating%20drug&source=bl&ots=mjyYZz9C_r&sig=v14M2gPjR4T7joCOHVkHaerRRsA&hl=en&sa=X&ved=0ahUKEwi_24KY0uvOAhVMAcAKHWymBxMQ6AEILzAD#v=onepage&q=american%20slang%20floating%20drug&f=false)*
>
> 2 **drunk or marijuana-intoxicated** US, **1938** “Man, when I see you floating, that'll be the day I quit. That'll be all. See old preacher Kipper floating!”
>
> — Edwin Gilbert, *The Hot and the Cool*, 1953
>
>
>
**[TIME](http://content.time.com/time/subscriber/article/0,33009,777874-1,00.html)** Monday, July 19, 1943
>
> ... the viper [client] says, “Gimme an ace” (meaning one reefer), “a deuce” (meaning two), or “a deck” (meaning a large number). The viper may then quietly “blast the weed” (smoke). Two or three long puffs usually suffice after a while to produce a light jag. **The smoker is then said to be “high” or “floating.”**
>
>
>
**Further research**
Here is a Google Ngram showing only the trend for ***floats your boat*** between 1920 and 2000
[](https://i.stack.imgur.com/LiDpB.png)
The earliest instance, recorded in 1933, has: *the river rises once again and floats your boat away*.
In the quagmire, I did not find any trace of the Oxford English Dictionary's citation, 1981, which Wordwizard listed. It's unlucky there is no digital version of that copy of the *Sunday Herald* (Chicago). However, the two earliest instances I did find online, with its current meaning, are dated **1985**
* *Further, summary or statistical information is difficult to obtain in either English or Spanish.1' And if that [**floats your boat**](https://books.google.co.uk/books?id=P1jpAAAAMAAJ&q=%22floats%20your%20boat%22&dq=%22floats%20your%20boat%22&hl=en&sa=X&ved=0ahUKEwiBhNKomOzOAhXmAMAKHW6cBBMQ6AEINjAG), you can have it for $30 a year (12 issues) paid to ...*
* *They often seem to advance relativistlc [?] arguments — "[**what ever floats your boat**](https://books.google.co.uk/books?id=ABnuAAAAMAAJ&q=%22floats%20your%20boat%22&dq=%22floats%20your%20boat%22&hl=en&sa=X&ved=0ahUKEwiBhNKomOzOAhXmAMAKHW6cBBMQ6AEIMjAF)" — or are nihilist in the sense of admitting to no knowable moral scheme. Their ethics seem to be more individuated. Of course the forgoing [sic] are exaggerated ...*
Who "they" are, I do not know, but it is revealing that the idiom in its entirety appears in connection with *no moral scheme*, and *ethics*. |
3,985,886 | $(a+c)(b+d)=1$, $a,b,c,d \in R^{+}$. Prove that
$$\frac{a^3}{b+c+d} + \frac{b^3}{a+c+d} + \frac{c^3}{a+b+d} + \frac{d^3}{a+b+c} \geq \frac{1}{3}$$
rather annoying that the powers of denominators and numerators are not the same and can't think of easy way to flatten them.. | 2021/01/15 | [
"https://math.stackexchange.com/questions/3985886",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/219483/"
] | **Hint**: Use holders inequality
>
> $$\left(\sum\_{cyc} \frac{a^3}{b+c+d}\right)(1+1+1+1)\left(\sum\_{cyc} b+c+d\right)\ge {\left(\sum\_{cyc} a\right)}^3$$
>
>
>
>
> Apply AM-GM inequality :$$a+b+c+d\ge 2\sqrt{(a+c)(b+d)}$$ to finish
>
>
> | The naive Titu also works
WTS
$$ \sum\_{cyc} \frac{a^3}{b+c+d} = \sum\_{cyc} \frac{ a^4 } { ab+ac+ad } \geq \frac{ (\sum a^2 )^2 } { 2 ( ab+ac+ad+bc+bd+da) } \geq \frac{1}{3}.$$
This follows because
>
> 1. $ a^2 + b^2 + c^2 + d^2 \geq \frac{ 2}{3} ( ab+ac+ad+bc+bd+da)$, and
>
>
>
>
> 2. $a^2 +b^2 + c^2 + d^2 \geq \frac{1}{2} [ (a+c)^2 + (b+d)^2] \geq (a+c)(b+d) = 1$
>
>
> |
576,417 | I was trying to install Cinnamon from Source code in a CentOS v.6.4.
Unfortunately, I was stumbling upon dependencies that were becoming weird each and every time.
Some of them, I tried to build, but didn't work. They needed things like GTK+ of certain version that wasn't available for CentOS.
Do you know if there is anyway to install Cinnamon in CentOS? | 2013/04/01 | [
"https://superuser.com/questions/576417",
"https://superuser.com",
"https://superuser.com/users/206520/"
] | Cinnamon 2.0 is now available in CentOS 7. You can install it from the epel repository.
You can also install the latest Cinnamon 2.8 from epel-testing:
```
yum install --enablerepo=epel-testing cinnamon*
``` | You can always use an [RPM search engine](http://rpm.pbone.net/) to find a [`cinnamon` RPM](http://rpm.pbone.net/index.php3?stat=26&dist=0&size=1513965&name=cinnamon-1.4-1.src.rpm) and install that way. Just download the RPM and install using
```
rpm -ivh cinnamon-1.4-1.src.rpm
``` |
68,769,380 | I have this recyclerview
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/serviceRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@+id/addNewServiceBtn"
app:layout_constraintBottom_toBottomOf="parent"
android:paddingBottom="10dp"
android:layout_marginTop="20dp"
/>
```
which has inside this
```
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/serviceSelectExpertRegisterContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:background="@drawable/border_edit_text"
android:layout_marginHorizontal="20dp"
android:paddingVertical="5dp"
>
<Spinner
android:id="@+id/serviceSelectExpertRegister"
android:layout_width="match_parent"
android:layout_height="30dp"
app:layout_constraintTop_toTopOf="parent"
android:spinnerMode="dropdown"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
<EditText
android:id="@+id/serviceDescriptionExpertRegister"
app:layout_constraintTop_toBottomOf="@+id/serviceSelectExpertRegisterContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:hint="@string/service_description"
android:background="@drawable/border_edit_text"
android:padding="8dp"
android:layout_marginTop="15dp"
android:gravity="top|start"
android:inputType="textMultiLine"
android:lines="3"
android:textColor="@color/light_grey"
/>
```
adn when I open my keyboard it shrinks as the images demonstrate
[this is the shrinked image](https://i.stack.imgur.com/cz1Al.jpg)
[this is not shrinked one](https://i.stack.imgur.com/TYJ6J.jpg)
I have tried android:windowSoftInputMode="adjustPan" (and all the other windowSoftInputModes) but it still has the same reaction.
Is there any way to just make the layout go up and on affect anything. | 2021/08/13 | [
"https://Stackoverflow.com/questions/68769380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16316184/"
] | I haven't tried with your code but putting your recyclerview inside of scrollview might solve your problem. When keyboard opens screen will scroll and try to fit content to the the screen :
```
<androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="20dp"
android:paddingBottom="10dp"
android:fillViewport="true"
android:scrollbars="none"
app:layout_constraintTop_toBottomOf="@+id/addNewServiceBtn"
app:layout_constraintBottom_toBottomOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/serviceRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.core.widget.NestedScrollView>
``` | Just add
```
android:windowSoftInputMode="adjustResize"
```
or
```
android:windowSoftInputMode="adjustPan|adjustResize"
```
or
you can add this line in your onCreate
```
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
``` |
17,360,847 | Code that requires `break` statements or `continue` statements in other languages can be done with `block` & `return-from` or `catch` & `throw` in Common Lisp and Emacs Lisp. Then there is code that requires `redo` statements, or at least best written with `redo`. And `redo` statements don't have to be about loops. How can I do `redo` in Lisp?
If there was a `redo` equivalent in Lisp, I think it would work like this: special form `with-redo` which takes a symbol and forms, and `redo` which takes a symbol. The form `(with-redo 'foo BODY-FORMS...)` may contain `(redo 'foo)` in its BODY-FORMS, and `(redo 'foo)` transfers control back to the beginning of BODY-FORMS. | 2013/06/28 | [
"https://Stackoverflow.com/questions/17360847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1446335/"
] | In Common Lisp:
```
(tagbody
start
(do-something)
(go start))
(dotimes (i some-list)
redo
(when (some-condition-p)
(go redo))
(some-more))
``` | **Update: Emacs 24.4 (soon to be released) has tagbody. cl-lib that comes with Emacs 24.4 includes cl-tagbody.**
For a dialect of Lisp which doesn't have tagbody, one can still implement redo as long as the dialect has a catch/throw equivalent.
For Emacs Lisp:
```
;; with-redo version 0.1
(defmacro with-redo (tag &rest body)
"Eval BODY allowing jumps using `throw'.
TAG is evalled to get the tag to use; it must not be nil.
Then the BODY is executed.
Within BODY, a call to `throw' with the same TAG and a non-nil VALUE causes a jump to the beginning of BODY.
A call to `throw' with the same TAG and nil as VALUE exits BODY and this `with-redo'.
If no throw happens, `with-redo' returns the value of the last BODY form."
(declare (indent 1))
(let ((ret (make-symbol "retval")))
`(let (,ret)
(while
(catch ,tag
(setq ,ret (progn ,@body))
nil))
,ret)))
(defun redo (symbol)
(throw symbol t))
```
Example of use (all examples are in Emacs Lisp):
```
(with-redo 'question
(let ((name (read-string "What is your name? ")))
(when (equal name "")
(message "Zero length input. Please try again.")
(beep)
(sit-for 1)
(redo 'question))
name))
```
Same example written as a mid-test loop instead:
```
(require 'cl-lib)
(let (name)
(cl-loop do
(setq name (read-string "What is your name? "))
while
(equal name "")
do
(message "Zero length input. Please try again.")
(beep)
(sit-for 1))
name)
```
Same example written as an infinite loop with a throw instead:
```
(let (name)
(catch 'question
(while t
(setq name (read-string "What is your name? "))
(unless (equal name "")
(throw 'question name))
(message "Zero length input. Please try again.")
(beep)
(sit-for 1))))
```
---
Implementing `with-lex-redo-anon` and `lex-redo`, where `(lex-redo)` causes a jump to the beginning of body of the textually/lexically innermost `with-lex-redo-anon` form:
```
;; with-lex-redo-anon version 0.1
(require 'cl-lib)
(defmacro with-lex-redo-anon (&rest body)
"Use with `(lex-redo)'."
(let ((tag (make-symbol "lex-redo-tag"))
(ret (make-symbol "retval")))
`(cl-macrolet ((lex-redo () '(cl-return-from ,tag t)))
(let (,ret)
(while
(cl-block ,tag
(setq ,ret (progn ,@body))
nil))
,ret))))
```
Example test:
```
(let ((i 0) (j 0))
(with-lex-redo-anon
(with-lex-redo-anon
(print (list i j))
(when (< j 2)
(incf j)
(lex-redo)))
(when (< i 2)
(incf i)
(lex-redo))))
```
Same output as in another answer. |
8,642 | If a congregation forgot to say *birkas hachodesh* on the *Shabas* before *rosh chodesh*, should it say it another time? When? (Does it, perhaps, depend on what day(s) of the week *rosh chodesh* is?)
Note: AFAICT, *Shaare Efrayim* and *Mishna B'rura* say nothing about this. | 2011/07/03 | [
"https://judaism.stackexchange.com/questions/8642",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/170/"
] | Nitei Gavriel, in the introduction to the second volume of his Laws of Niddah, quotes the Sefer Imrei Yehudah Al Hatorah. (It starts [here](http://www.hebrewbooks.org/pdfpager.aspx?req=46550&st=&pgnum=40), but the part that's relevant to us is [here](http://www.hebrewbooks.org/pdfpager.aspx?req=46550&st=&pgnum=41)).
The Imrei Yehudah Al Hatorah (Tazria pg. 89) explains that we say:
>
> כי בעמך ישראל בחרת מכל האומות
> וחוקי ראשי חדשים להם קבעת
>
>
> For you have chosen your nation Israel from among all the nations, and established for them the laws of the new months.
>
>
>
This refers to the laws of family purity, which follow a monthly cycle. By G-d establishing the the laws of family purity, He has separated us from the nations. When G-d sees that we put aside our love for our wife because of our love for G-d, who commanded us to separate from our wives while they are in a state of impurity, He loves us.
So, we are saying in the Musaf Prayer that it is because of the laws of family purity that G-d chose us over all the other nations.
The Nitei Gavriel also says that the Darchei Moshe (417:1) says something similar, but I didn't check it out. | The laws of Kiddush HaChodesh, when to make 2 days or 1 day Rosh Chodesh, and when to make a leap year. |
45,557,161 | I'm trying to make a program that counts the number of vowels in a sentence, but for some reason my for-loop keeps iterating by 2 (figured this out by printing out the value of i during each iteration). What's wrong with it?
```
//input
Scanner input = new Scanner(System.in);
String sentence;
//prompt
System.out.print("Type a sentence. \nThe number of vowels will be counted.");
sentence = input.nextLine();
//vowel check
int charcount = 0;
String temp;
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i++);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
System.out.print("There are " + charcount + " vowels in your sentence.");
}
}
``` | 2017/08/07 | [
"https://Stackoverflow.com/questions/45557161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8431324/"
] | There are two times when you're incrementing `i` , once in your for loop definition, and once in your `sentence.substring`
Any time you put `i++` the variable `i` will be increased by 1, regardless of it being in the for loop's definition or in another part of the loop.
```
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i+1);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
```
Should work.
Also, and someone who is more familiar with java than I am can correct me on this if I'm mistaken, but `temp.equalsIgnoreCase()` returns a boolean, so you don't need to do `== True`, you can just write `else if (temp.equalsIgnoreCase("u"))`
Addition: As per `Scary Wombat`'s comment, you could simplify this even more so, as so:
```
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i+1);
if (temp.equalsIgnoreCase("a") || temp.equalsIgnoreCase("e") ||
temp.equalsIgnoreCase("i") || temp.equalsIgnoreCase("o") ||
temp.equalsIgnoreCase("u"))
charcount ++;
}
``` | I suggest you don't use the `substring` method as it creates a new string from the original string.
**From the documentation:**
```
String substring(int beginIndex)
Returns a new string that is a substring of this string.
```
Instead, use the `charAt` method which returns the character value at the specified index.
You can also cleanup the implementation by using a `string` with the vowels and invoking the `indexOf` method on it to test if the character in question is a vowel or not. Below is an example:
```
String vowels = "aeiou";
sentence = sentence.toLowerCase();
for (int i = 0; i < sentence.length(); i++) {
char letter = sentence.charAt(i);
if (vowels.indexOf(letter) > -1) {
charCount++;
}
}
``` |
18,780,043 | I have some content in div, basically div will be hide, now i want when i press button the div content will be show with fadeIn function, now my problem i want show the div content one by one means one alphabet fadeIn then other but in my case it will be done word by word.
HTML
```
<div>
<span> THIS IS EXAMPLE OF FADE IN WORLD ONE BY ONE IN ALPHABETIC ORDER</span>
</div>
<input type='button' value='click me'/>
```
JS
```
$("input[type=button]").click(function(){
$("div").show();
$("span").each(function(index) {
$(this).delay(400*index).fadeIn(300);
});
});
```
CSS
```
div { display:none }
```
Fiddle [`Here`](http://jsfiddle.net/subhash9/4GmSF/) | 2013/09/13 | [
"https://Stackoverflow.com/questions/18780043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2331073/"
] | The trick is to split your span into smaller spans, one for every letter, and to use `setTimeout` to fade those spans one after the other :
```
$("input[type=button]").click(function(){
var $div = $('div');
$div.html($div.text().split('').map(function(l){
return '<span style="display:none;">'+l+'</span>'
}).join('')).show().find('span').each(function(i, e){
setTimeout(function(){ $(e).fadeIn() }, i*100);
});
});
```
[Demonstration](http://jsbin.com/uNAMimo/1/) | [**DEMO**](http://jsfiddle.net/cse_tushar/jYz6J/)
```
$(function () {
$('#test').click(function () {
var dest = $('div span#char');
var c = 0;
var string = dest.text();
dest.text('').parent().show();
var q = jQuery.map(string.split(''), function (letter) {
return $('<span>' + letter + '</span>');
});
var i = setInterval(function () {
q[c].appendTo(dest).hide().fadeIn(1000);
c += 1;
if (c >= q.length) clearInterval(i);
}, 100);
});
});
``` |
33,224,761 | I've implemented a function that returns a string. It takes an integer as a parameter (`age`), and returns a formatted string.
All is working well, except from the fact that I have some crazy memory leaks. I know strdup() is the cause of this, but I've tried to research some fixes to no avail.
My code is:
```
const char * returnName(int age) {
char string[30];
sprintf( string, "You are %d years old", age);
return strdup(string);
}
```
Valgrind's output is:
```
==15414== LEAK SUMMARY:
==15414== definitely lost: 6,192 bytes in 516 blocks
==15414== indirectly lost: 0 bytes in 0 blocks
==15414== possibly lost: 0 bytes in 0 blocks
==15414== still reachable: 0 bytes in 0 blocks
==15414== suppressed: 0 bytes in 0 blocks
```
Any help in resolving this memory leak issue is greatly appreciated. | 2015/10/19 | [
"https://Stackoverflow.com/questions/33224761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | strdup() is essentially equivalent to
```
char* dup = malloc(strlen(original) + 1);
strcpy(dup, original);
```
So you need to remember to call `free()` after you're finished using the string.
```
const char* name = returnName(20);
/* do stuff with name */
free((void*)name);
```
If you don't call `free()`, then of course valgrind reports a leak. | **strdup** looks something like this:
```
char *strdup(const char *str){
size_t n = strlen(str) + 1;
char *dup = malloc(n);
if(dup){
strcpy(dup, str);
}
return dup;
}
```
As you can see there is `malloc` involved too, which means that at some point after you dynamically allocate that memory using `strdup` you have to `free` it after you don't need it any more. |
15,556,341 | I have a JTable with multiple rows and every row is presented via Point on a scatter plot. What I have to do is when a given point is selected on the scatter plot I have to associate this selection with selecting of the corresponding row in the JTable.
I have an Integer that represents, which row I have to highlight.
What I tried is:
```
JTable table = new JTable();
...
...// a bit of code where I have populated the table
...
table.setRowSelectionInterval(index1,index2);
```
So the problem here is that this method selects all rows in the given range [index1,index2]. I want to select for example rows 1,15,28,188 etc.
How do you do that? | 2013/03/21 | [
"https://Stackoverflow.com/questions/15556341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479895/"
] | It also works without using the ListSelectionModel:
```
table.clearSelection();
table.addRowSelectionInterval(1, 1);
table.addRowSelectionInterval(15, 15);
table.addRowSelectionInterval(28, 28);
...
```
Just don't call the setRowSelectionInterval, as it always clears the current selection before. | There is no way to set a random selection with a one method call, you need more than one to perform this kind of selection
```
table.setRowSelectionInterval(1, 1);
table.addRowSelectionInterval(15, 15);
table.setRowSelectionInterval(28, 28);
table.addRowSelectionInterval(188 , 188 );
```
And So On.... |
33,470,993 | I have a string:
```
1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----
```
In this string there are spaces which are to be replaced by any special character for splitting the string.
Required output is:
```
1 ~ Vectorial position [X Y] ~ X ~ 682.9 ~ 1.0 ~ -1.0 ~ X ~ 682.6 ~ X ~-0.3 ~ ----.-----****
```
For the above I had tried using:
```
$yval_arr[$i] =~s/ /~/g;
$yval_arr[$i] =~ s/(.)\1\1+/$1$1$1/g;
$yval_arr[$i] =~s/(.)\1{1,}/$1$1$1/g;
```
but using this the first character repeats it self 2 times i.e. if it is `11` in the beginning it becomes `111`.
Please help. | 2015/11/02 | [
"https://Stackoverflow.com/questions/33470993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5506017/"
] | I would split the original string on spaces, and then do some creative field extraction: I assume the first word and the last 9 words in the string are separate fields, and what's left over is to become the 2nd field in the output.
```
$str = "1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----";
@words = split ' ', $str;
@fields = splice @words, -9;
$first = shift @words;
unshift @fields, $first, join(" ", @words);
say join(" ~ ", @fields);
```
```
1 ~ Vectorial position [X Y] ~ X ~ 682.9 ~ 1.0 ~ -1.0 ~ X ~ 682.6 ~ X ~ -0.3 ~ ----.-----
``` | I would split your data into a description and data, and then operate on the data. This makes it easier to understand and debug.
```
#!/usr/bin/perl
use warnings;
use strict;
my $str = '1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----';
my ($description, $data) = $str =~ m|^(.*\])(.*)$|; # $1 - everything upto [X Y]
# $2 - everything else
$data =~ s|\s+| ~ |g; # Replace one or more spaces with space-tilda-space everywhere
$description =~ s|^(\d+)(\s+)|$1 ~ |; # Likewise in description, between number and label
my $result = join '', $description, $data;
print "BEFORE '$str'\n";
print "AFTER '$result'\n";
```
Outputs:
```
BEFORE '1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----'
AFTER '1 ~ Vectorial position [X Y] ~ X ~ 682.9 ~ 1.0 ~ -1.0 ~ X ~ 682.6 ~ X ~ -0.3 ~ ----.-----'
```
If we update `$str` to:
```
my $str = '1 Vectorial position [Z] Z 267.0 1.0 -1.0 Z 267.3 Z 0.3 -----.-*---';
```
The output is:
```
BEFORE '1 Vectorial position [Z] Z 267.0 1.0 -1.0 Z 267.3 Z 0.3 -----.-*---'
AFTER '1 ~ Vectorial position [Z] ~ Z ~ 267.0 ~ 1.0 ~ -1.0 ~ Z ~ 267.3 ~ Z ~ 0.3 ~ -----.-*---'
``` |
528,759 | I would like to draw the following images on my paper. I tried to import the image using `graphicx`, but LaTeX could not find it (the image is in the same file as my `tex`), so I decided to draw them out. Please teach me what package to use and what code would display the following images. Thank you!
[](https://i.stack.imgur.com/h4C3q.png) | 2020/02/17 | [
"https://tex.stackexchange.com/questions/528759",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/207127/"
] | This code requires the [experimental library `3dtools`](https://github.com/tallmarmot/pgf/tree/master/experiments/Marmot/3dtools).
```
\documentclass[tikz,border=3mm]{standalone}
\usepackage{tikz-3dplot}
\usetikzlibrary{backgrounds,3dtools,shapes.geometric}
\tikzset{pics/isocahedron/.style={code={
\path foreach \Coord [count=\X] in
{(0.,0.,-0.9510565162951536),
(0.,0.,0.9510565162951536),
(-0.85065080835204,0.,-0.42532540417601994),
(0.85065080835204,0.,0.42532540417601994),
(0.6881909602355868,-0.5,-0.42532540417601994),
(0.6881909602355868,0.5,-0.42532540417601994),
(-0.6881909602355868,-0.5,0.42532540417601994),
(-0.6881909602355868,0.5,0.42532540417601994),
(-0.2628655560595668,-0.8090169943749475,-0.42532540417601994),
(-0.2628655560595668,0.8090169943749475,-0.42532540417601994),
(0.2628655560595668,-0.8090169943749475,0.42532540417601994),
(0.2628655560595668,0.8090169943749475,0.42532540417601994)}
{\Coord coordinate (p\X) \pgfextra{\xdef\NumVertices{\X}}};
%\message{number of vertices is \NumVertices^^J}
% normal of screen
\path[overlay] ({sin(\tdplotmaintheta)*sin(\tdplotmainphi)},
{-1*sin(\tdplotmaintheta)*cos(\tdplotmainphi)},
{cos(\tdplotmaintheta)}) coordinate (n)
({-sqrt(1/6)},{sqrt(3/6)},{sqrt(2/6)}) coordinate (L);
\edef\lstPast{0}
\foreach \poly in
{{2,12,8},{2,8,7},{2,7,11},{2,11,4},{2,4,12},{5,9,1},{6,5,1},
{10,6,1},{3,10,1},{9,3,1},{12,10,8},{8,3,7},{7,9,11},{11,5,4},{4,6,12},
{5,11,9},{6,4,5},{10,12,6},{3,8,10},{9,7,3}}
{
\pgfmathtruncatemacro{\ione}{{\poly}[0]}
\pgfmathtruncatemacro{\itwo}{{\poly}[1]}
\pgfmathtruncatemacro{\ithree}{{\poly}[2]}
\path[overlay,3d coordinate={(dA)=(p\itwo)-(p\ione)},
3d coordinate={(dB)=(p\itwo)-(p\ithree)},
3d coordinate={(nA)=(dA)x(dB)}] ;
\pgfmathtruncatemacro{\jtest}{sign(TD("(nA)o(p\ione)"))}
% make sure that the normal points outwards
\ifnum\jtest<0
\path[overlay,3d coordinate={(nA)=(dB)x(dA)}];
\fi
% compute projection the normal of the polygon on the normal of screen
\pgfmathsetmacro\myproj{TD("(nA)o(n)")}
\pgfmathsetmacro\lproj{TD("(nA)o(L)")}
\pgfmathtruncatemacro{\itest}{sign(\myproj)}
\ifnum\itest>-1
\draw[thick] [fill=white,fill opacity=0.2]
plot[samples at=\poly,variable=\x](p\x) -- cycle;
\else
\begin{scope}[on background layer]
\draw[gray,ultra thin]
plot[samples at=\poly,variable=\x](p\x) -- cycle;
\end{scope}
\fi
}}}}
\begin{document}
\tdplotsetmaincoords{70}{65}
\begin{tikzpicture}[line cap=round,line join=round,
bullet/.style={circle,fill,inner sep=1.5pt}]
\pic[tdplot_main_coords,scale=2,rotate=30]{isocahedron};
%\foreach \X in {1,...,\NumVertices} {\path (p\X) node[above]{\X};}
\path (p12) node[above]{$D$} --
node[bullet,label=above:$N$](N){}
(p2) node[above]{$A$}
(p7) node[left]{$B$} --
node[bullet,label={[xshift=3pt]above:$M$}]{}
(p11) node[below right]{$C$};
\begin{scope}[xshift=5cm]
\path let \p1=($(N)-(0,0)$) in
node[regular polygon,regular polygon sides=6,draw,thick,minimum size=2*\y1]
(6gon){};
\path (6gon.corner 1) node[above] {$D$}
-- node[bullet,label=above:$N$](N'){}
(6gon.corner 2) node[above] {$A$};
\draw[thick] (6gon.corner 3) node[left] {$M$}
-- node[bullet,label=below right:$O$](O){}
(6gon.corner 6)
(O) edge (N');
\draw ([xshift=-1em]O.center) |- ([yshift=1em]O.center);
\end{scope}
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/k4R1Z.png)
The icosahedron is rotatable in 3d.
```
\documentclass[tikz,border=3mm]{standalone}
\usepackage{tikz-3dplot}
\usetikzlibrary{backgrounds,3dtools,shapes.geometric}
\tikzset{pics/isocahedron/.style={code={
\path foreach \Coord [count=\X] in
{(0.,0.,-0.9510565162951536),
(0.,0.,0.9510565162951536),
(-0.85065080835204,0.,-0.42532540417601994),
(0.85065080835204,0.,0.42532540417601994),
(0.6881909602355868,-0.5,-0.42532540417601994),
(0.6881909602355868,0.5,-0.42532540417601994),
(-0.6881909602355868,-0.5,0.42532540417601994),
(-0.6881909602355868,0.5,0.42532540417601994),
(-0.2628655560595668,-0.8090169943749475,-0.42532540417601994),
(-0.2628655560595668,0.8090169943749475,-0.42532540417601994),
(0.2628655560595668,-0.8090169943749475,0.42532540417601994),
(0.2628655560595668,0.8090169943749475,0.42532540417601994)}
{\Coord coordinate (p\X) \pgfextra{\xdef\NumVertices{\X}}};
%\message{number of vertices is \NumVertices^^J}
% normal of screen
\path[overlay] ({sin(\tdplotmaintheta)*sin(\tdplotmainphi)},
{-1*sin(\tdplotmaintheta)*cos(\tdplotmainphi)},
{cos(\tdplotmaintheta)}) coordinate (n)
({-sqrt(1/6)},{sqrt(3/6)},{sqrt(2/6)}) coordinate (L);
\edef\lstPast{0}
\foreach \poly in
{{2,12,8},{2,8,7},{2,7,11},{2,11,4},{2,4,12},{5,9,1},{6,5,1},
{10,6,1},{3,10,1},{9,3,1},{12,10,8},{8,3,7},{7,9,11},{11,5,4},{4,6,12},
{5,11,9},{6,4,5},{10,12,6},{3,8,10},{9,7,3}}
{
\pgfmathtruncatemacro{\ione}{{\poly}[0]}
\pgfmathtruncatemacro{\itwo}{{\poly}[1]}
\pgfmathtruncatemacro{\ithree}{{\poly}[2]}
\path[overlay,3d coordinate={(dA)=(p\itwo)-(p\ione)},
3d coordinate={(dB)=(p\itwo)-(p\ithree)},
3d coordinate={(nA)=(dA)x(dB)}] ;
\pgfmathtruncatemacro{\jtest}{sign(TD("(nA)o(p\ione)"))}
% make sure that the normal points outwards
\ifnum\jtest<0
\path[overlay,3d coordinate={(nA)=(dB)x(dA)}];
\fi
% compute projection the normal of the polygon on the normal of screen
\pgfmathsetmacro\myproj{TD("(nA)o(n)")}
\pgfmathsetmacro\lproj{TD("(nA)o(L)")}
\pgfmathtruncatemacro{\itest}{sign(\myproj)}
\ifnum\itest>-1
\draw[thick] [fill=white,fill opacity=0.2]
plot[samples at=\poly,variable=\x](p\x) -- cycle;
\else
\begin{scope}[on background layer]
\draw[gray,ultra thin]
plot[samples at=\poly,variable=\x](p\x) -- cycle;
\end{scope}
\fi
}}}}
\begin{document}
\foreach \XX in {0,10,...,350}
{\begin{tikzpicture}[line cap=round,line join=round,
bullet/.style={circle,fill,inner sep=1.5pt}]
\path (-3.5,-3.5) rectangle (3.5,3.5);
\tdplotsetmaincoords{60+20*sin(\XX)}{\XX}
\pic[tdplot_main_coords,scale=3]{isocahedron};
\end{tikzpicture}}
\end{document}
```
[](https://i.stack.imgur.com/sW8Ct.gif) | Please see if this meets the requirement
[](https://i.stack.imgur.com/6UNGV.png)
```
\documentclass[a4paper]{amsart}
\usepackage{graphics, tkz-berge}
\begin{document}
\begin{figure}
\begin{tikzpicture}
\begin{scope}[rotate=90]
\SetVertexNoLabel % <--- This avoids that default $a_0$, .. $b_0$ labels show up
\grIcosahedral[form=1,RA=3,RB=1.5]
% Following two lines assign labels to a-like and b-like nodes
% change it as you prefer
\AssignVertexLabel{a}{$v_0$, $v_1$, $v_2$, $v_3$, $v_4$, $v_5$};
\AssignVertexLabel{b}{$v_6$, $v_7$, $v_8$, $v_9$, $v_{10}$, $v_{11}$};
% The remaining code is unchanged
\SetUpEdge[color=white,style={double=black,double distance=2pt}]
\EdgeInGraphLoop{a}{6}
\EdgeFromOneToSel{a}{b}{0}{1,5}
\Edges(a2,b1,b3,b5,a4)
\Edge(a3)(b3)
\Edges(a1,b1,b5,a5)
\Edges(a2,b3,a4)
\end{scope}
\end{tikzpicture}
\end{figure}
\end{document}
```
Thanks to @JLDiaz who has given the solution -- <https://tex.stackexchange.com/a/183075/197451> |
24,270,637 | I was trying out few examples on do's and dont's of typecasting. I could not understand why the following code snippets failed to output the correct result.
```
/* int to float */
#include<stdio.h>
int main(){
int i = 37;
float f = *(float*)&i;
printf("\n %f \n",f);
return 0;
}
```
This prints `0.000000`
```
/* float to short */
#include<stdio.h>
int main(){
float f = 7.0;
short s = *(float*)&f;
printf("\n s: %d \n",s);
return 0;
}
```
This prints `7`
```
/* From double to char */
#include<stdio.h>
int main(){
double d = 3.14;
char ch = *(char*)&d;
printf("\n ch : %c \n",ch);
return 0;
}
```
This prints garbage
```
/* From short to double */
#include<stdio.h>
int main(){
short s = 45;
double d = *(double*)&s;
printf("\n d : %f \n",d);
return 0;
}
```
This prints `0.000000`
Why does the cast from `float` to `int` give the correct result and all the other conversions give wrong results when type is cast explicitly?
I couldn't clearly understand why this typecasting of `(float*)` is needed instead of `float`
```
int i = 10;
float f = (float) i; // gives the correct op as : 10.000
```
But,
```
int i = 10;
float f = *(float*)&i; // gives a 0.0000
```
What is the difference between the above two type casts?
Why cant we use:
```
float f = (float**)&i;
float f = *(float*)&i;
``` | 2014/06/17 | [
"https://Stackoverflow.com/questions/24270637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713179/"
] | Read about the representation of floating point numbers in systems. Its not the way you're expecting it to be. Cast made through `(float *)` in your first snippet read the most significant first 16 bits. And if your system is little endian, there will be always zeros in most significant bits if the value containing in the `int` type variable is lesser than `2^16`. | If you need to convert int to float, the conversion is straight, because the promotion rules of C.
So, it is enough to write:
```
int i = 37;
float f = i;
```
This gives the result `f == 37.0`.
However, int the cast `(float *)(&i)`, the result is an object of type "pointer to float".
In this case, the address of "pointer to integer" &i is the same as of the the "pointer to float" (float \*)(&i). However, the object pointed by this last object is a `float` whose bits are the same as of the object `i`, which is an integer.
Now, the main point in this discussion is that the bit-representation of objects in memory is very different for integers and for floats.
A positive integer is represented in explicit form, as its binary mathematical expression dictates.
However, the floating point numbers have other representation, consisting of mantissa and exponent.
So, the bits of an object, when interpreted as an integer, have one meaning, but the same bits, interpreted as a float, have another very different meaning. |
24,263,648 | Can't understand, why buttons are not identical in their sizes. Earlier, I used LinearLayout instead of RelativeLayout as a root, but after some googling I understand, there is no chance to make footer with LL, so I make it RL and adjusted by coping previous LL with buttons to RL, but.. [Look at this. I found it with ruler. It really cut my eyes](http://i.stack.imgur.com/qysF5.png)
Also I can't understand, why margin in RL doesn't work anyway (I deleted in from below code), and how I can margin elements inside RL?!
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/linearLayout_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<Button
android:id="@+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/all_mentions_Add" />
<Button
android:id="@+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/all_mentions_Delete" />
</LinearLayout>
<ListView
android:id="@+id/listView_mentions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/linearLayout_buttons" >
</ListView>
</RelativeLayout>
``` | 2014/06/17 | [
"https://Stackoverflow.com/questions/24263648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653714/"
] | As noted in the comments, `isPrime` only needs to evaluate the result of `factorsOf` deeply enough to determine if it is an empty list or not. You could write `isPrime` more idiomatically like this:
```
isPrime = null . factorsOf
```
where null is simply
```
null (_:_) = False
null _ = True
```
Note that as soon as `null` can pattern match on a `(:)` constructor, it returns a result without evaluating the rest of the list.
This means only the `factorsOf` only needs to compute the first factor for `isPrime` to return, whereas `factorsOf` by itself will compute the entire list. | The basic principle of laziness is that nothing is evaluated unless it is really really needed. Really needed in your case means that the first function must return so that the other function gets its input. You can read more about Haskell's Laziness [here](http://en.wikibooks.org/wiki/Haskell/Laziness) |
30,587,459 | ```
#include "stdafx.h"
int main() {
char name;
printf("What is your name:"); // I enter my name..
scanf_s("%c", &name); // Should grab my name in this case (Brian)
printf("Hello, %c\n", name); //Should print "Hello, Brian."
return 0;
}
```
What's wrong? Why is it not storing the whole name and just the first letter? | 2015/06/02 | [
"https://Stackoverflow.com/questions/30587459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682427/"
] | @BeforeMethod - executes before every test method e.g. The Method which uses @Test annotation
@BeforeTest - executes only before tag given in testng.xml file.
In a nutshell, @BeforeMethod works on test defined in Java classes.
And @BeforeTest works on test defined in testng.xml i.e XML files. | ```
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@BeforeMethod: The annotated method will be run before each test method.
The annotations above will also be honored (inherited) when placed on a superclass of a TestNG class. This is useful for example to centralize test setup for multiple test classes in a common superclass.
In that case, TestNG guarantees that the "@Before" methods are executed in inheritance order (highest superclass first, then going down the inheritance chain), and the "@After" methods in reverse order (going up the inheritance chain).
```
To know more about TestNG annotations: <https://testng.org/doc/documentation-main.html#annotations> |
32,453,461 | CORS is enabled and working.
We have a Cordova App which is syncing fine the first time it connects to the CouchDB. After that the db.sync() is not working. Only if we go offline and online with the Fly-mode it syncs again for a short time.
We have a angular.factory which creates the local pouch db and sets up the sync with our remote couchDB
```
(function () {
angular
.module('IkasApp')
.factory('pouch', ['$http', ThisFunction]);
function ThisFunction($http) {
PouchDB.debug.enable('*');
var db = new PouchDB('test_suite_db');
var remoteCouch = 'http://estouch.iriscouch.com/_utils/database.html?test_suite_db';
if (remoteCouch) {
var opts = {
live: true
};
db.sync(remoteCouch, opts);
}
return db;
}
}());
```
We are able to create and update documents in our pouchDB (test\_suite\_db) but it is not live syncing continuously.
As you can see for yourself a lot of inspiration came from this [github](https://github.com/orbitbot/pouch-todo). We are running Pouch 4.0.1. | 2015/09/08 | [
"https://Stackoverflow.com/questions/32453461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862292/"
] | Ok, I just figured out what the error means... :-) I have to create the new directory in advance and now I can copy everything...
```
dir.create('new_folder')
file.copy("my_folder", "new_folder", recursive=TRUE)
```
This works as expected. | I'd rather write an R function that copies the directory using the Terminal. Here's what I use, but note that I wrote it only for Linux and OSX thus far.
```
dir.copy <- function(from, to) {
os <- Sys.info()['sysname']
if (os == "Darwin" || os == "Linux") {
command <- sprintf("cp -R '%s' '%s'", from, to)
system(command, intern = TRUE)
}
}
```
Quick, easy, and works like a charm. |
57,882,874 | I was using SQL statement to bring an aggregate (MAX) for a column and rest of the columns should come from that row. I was using group by clause but for other columns I must also use either max or min, etc. This was budget oriented project so I could not have time to do it using LINQ. (Where I could have used first or default). Anyways I believe this is strong inability of SQL language.
Again this could have done by many ways but not using simple SQL group by.
any ideas? | 2019/09/11 | [
"https://Stackoverflow.com/questions/57882874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11205838/"
] | Your question is a bit light on details but it sounds like you want to know, for some set of items, which item has the maximum of something and then what it’s other properties are.
You cannot group by all the non max columns because this breaks the group down into too small chunks to make the max work
You cannot max all the other columns because this mixes row data up
Here is a simple example:
```
Name, JobRole, StartDate
John, JuniorProgrammer, 2000-01-01
John, SeniorProgrammer, 2010-01-01
```
John was promoted to senior programmer in 2010. We want johns most recent promotion and what he does now. If we do this:
```
SELECT name, jobrole, max(startdate)
FROM emp
GROUP BY name
```
The database will complain that jobrole is not in the group by. If we add it to the group by, John will appear twice, not what we want. If instead we max(jobrole), it DOES accidentally work out ok because alphabetically, SeniorProgrmamer is higher than JuniorProgrammer
If however, John then gets a promotion again in 2019:
```
Name, JobRole, StartDate
John, JuniorProgrammer, 2000-01-01
John, SeniorProgrammer, 2010-01-01
John, ExecutiveDirector, 2019-01-01
```
This time our query is wrong:
```
SELECT name, max(jobrole), max(startdate)
FROM emp
GROUP BY name
```
Hi he row data will be mixed up: the date will be 2019 but the job will still be seniorprogrammer because it’s alphabetically the maximum value
Instead we have to find the max for the person and then join it back to find the rest of the data:
```
SELECT name, jobrole, startdate
FROM
emp
INNER JOIN
(
SELECT name, max(startdate) d
FROM emp
GROUP BY name
)findmax
ON findmax.d = emp.startdate and findmax.name = emp.name
```
There are other ways of achieving the same thing without a join- this method would have issues if an employee was promoted twice on the same day, two records would result. In a dB that supports analytical functions we an do:
```
SELECT name, jobrole, row_number() over (partition by name order by startdate desc)
FROM emp
```
This establishes an incrementing counter in order of descending start date. The counter restarts from 1 for every different employee. There is no group by so no complaints that the extra data isn’t grouped or on aggregate function. All we need to do to choose the most recent promotion date is wrap the whole thing in a select that demands the row number be 1:
```
SELECT * FROM
(
SELECT name, jobrole, row_number() over (partition by name order by startdate desc) r
FROM emp
) emp_with_rownum
WHERE r = 1
``` | You don't want a `group by`. You seem to want a window function:
```
select t.*, max(col) over () as overall_max
from t;
``` |
12,781,830 | I want Radio Group implementation on GridView, so that only single item can be selected among the elements of grid.
Please help. | 2012/10/08 | [
"https://Stackoverflow.com/questions/12781830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1383964/"
] | The purpose to restrict the select of element from the grid can be accomplished as follows:
1.Creation of Grid element.
```
<LinearLayout
android:id="@+id/item_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<RadioButton
android:id="@+id/radiobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image" />
</LinearLayout>
```
2.Inflating this xml in the getView() method of customize adapter.
```
public class MyAdapter extends BaseAdapter {
Context mCtx;
int[] mImg;
LayoutInflater layoutInflater;
RadioGroup rgp;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;
public MyAdapter(Context context, int[] img) {
this.mCtx = context;
this.mImg = img;
rgp = new RadioGroup(context);
layoutInflater = (LayoutInflater) mCtx
.getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mImg.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
Holder holder;
if (view == null) {
view = layoutInflater.inflate(R.layout.element, null);
holder = new Holder();
holder.image = (ImageView) view.findViewById(R.id.imageView);
holder.radioButton = (RadioButton) view
.findViewById(R.id.radiobtn);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((position != mSelectedPosition && mSelectedRB != null)) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton) v;
}
});
if (mSelectedPosition != position) {
holder.radioButton.setChecked(false);
} else {
holder.radioButton.setChecked(true);
if (mSelectedRB != null && holder.radioButton != mSelectedRB) {
mSelectedRB = holder.radioButton;
}
}
return view;
}
}
private class Holder {
ImageView image;
RadioButton radioButton;
}
``` | An alternative approach to this is to create your own subclass of `RadioButton` which has an extra XML attribute (such as `group`). This specifies (as a string) to which group the button belongs. In the subclass, you then ensure that within any particular group, only one radio button is selected.
You can do this as follows:
First create the file `res/values/attrs.xml` which contains something like the following:
```
<resources>
<declare-styleable name="GroupedRadioButton">
<attr name="group" format="string"/>
</declare-styleable>
</resources>
```
Then create your subclass, `GroupedRadioButton`:
```
public class GroupedRadioButton extends RadioButton {
public GroupedRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
processAttributes(context, attrs);
setOnClickListener(internalListener, true);
}
...
}
```
Once fleshed out (see below), you can then use this new class as follows in your layout files:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.app"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.app.GroupedRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 1"
custom:group="group1" />
<com.example.app.GroupedRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 2"
custom:group="group1" />
<com.example.app.GroupedRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 3"
custom:group="group1" />
<com.example.app.GroupedRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option A"
custom:group="group2" />
<com.example.app.GroupedRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option B"
custom:group="group2" />
...
```
The radio buttons can be anywhere in your layout (e.g. in a `GridView`). Note the `xmlns:custom` tag is required since we are using a custom attribute.
The layout above will make options 1, 2 and 3 mutually exclusive and options A and B mutually exclusive.
This is achieved by keeping track (statically) of which `GroupedRadioButton` is currently selected within each group:
```
public class GroupedRadioButton extends RadioButton {
private static Map<String, WeakReference<GroupedRadioButton>> buttonMap;
static {
buttonMap = new HashMap<String, WeakReference<GroupedRadioButton>>();
}
...
}
```
Note that we have to be careful here to ensure that we don't keep strong references to the buttons otherwise they will never be garbage collected.
The `processAttributes()` method specified in the constructor above digs out the `group` attribute from the XML we specified and sets this as instance data:
```
private void processAttributes(Context context, AttributeSet attrs) {
TypedArray attributes = context.obtainStyledAttributes(attrs,
R.styleable.GroupedRadioButton);
int attributeCount = attributes.getIndexCount();
for (int i = 0; i < attributeCount; ++i) {
int attr = attributes.getIndex(i);
switch (attr) {
case R.styleable.GroupedRadioButton_group:
this.groupName = attributes.getString(attr);
break;
}
}
attributes.recycle();
}
```
We define the main `OnClickListener` for this class.
```
private OnClickListener internalListener = new OnClickListener() {
@Override
public void onClick(View view) {
processButtonClick(view);
}
};
```
which calls:
```
private void processButtonClick(View view) {
if (!(view instanceof GroupedRadioButton))
return;
GroupedRadioButton clickedButton = (GroupedRadioButton) view;
String groupName = clickedButton.groupName;
WeakReference<GroupedRadioButton> selectedButtonReference = buttonMap.get(groupName);
GroupedRadioButton selectedButton = selectedButtonReference == null ? null : selectedButtonReference.get();
if (selectedButton != clickedButton) {
if (selectedButton != null)
selectedButton.setChecked(false);
clickedButton.setChecked(true);
buttonMap.put(groupName, new WeakReference<GroupedRadioButton>(clickedButton));
}
if (externalListener != null)
externalListener.onClick(view);
}
```
This does two things. It ensures that it deselects the old group button before selecting the new one (assuming the old and new buttons are different). It then calls `onClick()` on an `externalListener` which is provided so that users of the class can add their own 'on-click' functionality.
The `setOnClickListener()` call in the constructor is to our own method as follows:
```
private void setOnClickListener(OnClickListener listener, boolean internal) {
if (internal)
super.setOnClickListener(internalListener);
else
this.externalListener = listener;
}
```
This sets the `internalListener` as the official `OnClickListener` and sets instance data as appropriate for the external listener. The `View.setOnClickListener()` method can then be overridden as follows:
```
@Override
public void setOnClickListener(OnClickListener listener) {
setOnClickListener(listener, false);
}
```
Apologies for the length of this answer but I hope it helps you and others trying to do the same thing. It would of course not be needed at all if a `RadioGroup` applied recursively to its children! |
27,122,426 | ```
$table_name = $wpdb->prefix . 'offline_card';
// function to create the DB / Options / Defaults
function offline_card_install() {
global $wpdb;
global $table_name;
// create the ECPT metabox database table
if($wpdb->get_var("show tables like '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`order_id` int NOT NULL,
`card_number` varchar(55) NOT NULL,
`card_expiry` varchar(55) NOT NULL,
`card_ccv` varchar(22) NOT NULL,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'offline_card_install');
```
I don't understand what is the reason that it is not creating database table on plugin activation. It is not showing any error though. | 2014/11/25 | [
"https://Stackoverflow.com/questions/27122426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2812955/"
] | Please see a working example of how to delete a row here.
<http://plnkr.co/edit/6TiFC6plEMJMD4U6QmyS?p=preview>
The key is to use `indexOf(row.entity)` and not relying on `row.index` as it doesn't dynamically get updated.
```
$scope.deleteRow = function(row) {
var index = $scope.gridOptions.data.indexOf(row.entity);
$scope.gridOptions.data.splice(index, 1);
};
```
---
Generic approach
```
function deleteRow(row,grid) {
var i = grid.options.data.indexOf(row.entity);
grid.options.data.splice(i, 1);
}
``` | Just remove the row you want to delete from ui-grids data source model using splice.
For example
```
$scope.myGridOptions.data.splice(<YOUR ROW INDEX HERE>, 1);
``` |
44,080,870 | I Have to draw Herringbone pattern on canvas and fill with image
----------------------------------------------------------------
some one please help me I am new to canvas 2d drawing.
I need to draw mixed tiles with cross pattern (Herringbone)
```
var canvas = this.__canvas = new fabric.Canvas('canvas');
var canvas_objects = canvas._objects;
// create a rectangle with a fill and a different color stroke
var left = 150;
var top = 150;
var x=20;
var y=40;
var rect = new fabric.Rect({
left: left,
top: top,
width: x,
height: y,
angle:45,
fill: 'rgba(255,127,39,1)',
stroke: 'rgba(34,177,76,1)',
strokeWidth:0,
originX:'right',
originY:'top',
centeredRotation: false
});
canvas.add(rect);
for(var i=0;i<15;i++){
var rectangle = fabric.util.object.clone(getLastobject());
if(i%2==0){
rectangle.left = rectangle.oCoords.tr.x;
rectangle.top = rectangle.oCoords.tr.y;
rectangle.originX='right';
rectangle.originY='top';
rectangle.angle =-45;
}else{
fabric.log('rectangle: ', rectangle.toJSON());
rectangle.left = rectangle.oCoords.tl.x;
rectangle.top = rectangle.oCoords.tl.y;
fabric.log('rectangle: ', rectangle.toJSON());
rectangle.originX='left';
rectangle.originY='top';
rectangle.angle =45;
}
//rectangle.angle -90;
canvas.add(rectangle);
}
fabric.log('rectangle: ', canvas.toJSON());
canvas.renderAll();
function getLastobject(){
var last = null;
if(canvas_objects.length !== 0){
last = canvas_objects[canvas_objects.length -1]; //Get last object
}
return last;
}
```
How to draw this pattern in canvas using svg or 2d,3d method. If any third party library that also Ok for me.
I don't know where to start and how to draw this complex pattern.
some one please help me to draw this pattern with rectangle fill with dynamic color on canvas.
Here is a sample of the output I need: (herringbone pattern)
[](https://i.stack.imgur.com/BChbm.png "Click to view Full Size")
I tried something similar using [fabric.js](http://fabricjs.com/) library here is my [JSFiddle](http://jsfiddle.net/eA3xH/143/) | 2017/05/20 | [
"https://Stackoverflow.com/questions/44080870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7015792/"
] | Trippy disco flooring
---------------------
To get the pattern you need to draw rectangles one horizontal tiled one space left or right for each row down and the same for the vertical rectangle.
The rectangle has an aspect of width 2 time height.
Drawing the pattern is simple.
Rotating is easy as well the harder part is finding where to draw the tiles for the rotation.
To do that I create a inverse matrix of the rotation (it reverses a rotation). I then apply that rotation to the 4 corners of the canvas `0,0`, `width,0` `width,height` and `0,height` this gives me 4 points in the rotated space that are at the edges of the canvas.
As I draw the tiles from left to right top to bottom I find the min corners for the top left, and the max corners for the bottom right, expand it out a little so I dont miss any pixels and draw the tiles with a transformation set the the rotation.
As I could not workout what angle you wanted it at the function will draw it at any angle. On is animated, the other is at 60deg clockwise.
Warning demo contains flashing content.
---------------------------------------
**Update** The flashing was way to out there, so have made a few changes, now colours are a more pleasing blend and have fixed absolute positions, and have tied the tile origin to the mouse position, clicking the mouse button will cycle through some sizes as well.
```js
const ctx = canvas.getContext("2d");
const colours = []
for(let i = 0; i < 1; i += 1/80){
colours.push(`hsl(${Math.floor(i * 360)},${Math.floor((Math.sin(i * Math.PI *4)+1) * 50)}%,${Math.floor(Math.sin(i * Math.PI *8)* 25 + 50)}%)`)
}
const sizes = [0.04,0.08,0.1,0.2];
var currentSize = 0;
const origin = {x : canvas.width / 2, y : canvas.height / 2};
var size = Math.min(canvas.width * 0.2, canvas.height * 0.2);
function drawPattern(size,origin,ang){
const xAx = Math.cos(ang); // define the direction of xAxis
const xAy = Math.sin(ang);
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.setTransform(xAx,xAy,-xAy,xAx,origin.x,origin.y);
function getExtent(xAx,xAy,origin){
const im = [1,0,0,1]; // inverse matrix
const dot = xAx * xAx + xAy * xAy;
im[0] = xAx / dot;
im[1] = -xAy / dot;
im[2] = xAy / dot;
im[3] = xAx / dot;
const toWorld = (x,y) => {
var point = {};
var xx = x - origin.x;
var yy = y - origin.y;
point.x = xx * im[0] + yy * im[2];
point.y = xx * im[1] + yy * im[3];
return point;
}
return [
toWorld(0,0),
toWorld(canvas.width,0),
toWorld(canvas.width,canvas.height),
toWorld(0,canvas.height),
]
}
const corners = getExtent(xAx,xAy,origin);
var startX = Math.min(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var endX = Math.max(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var startY = Math.min(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
var endY = Math.max(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
startX = Math.floor(startX / size) - 2;
endX = Math.floor(endX / size) + 2;
startY = Math.floor(startY / size) - 2;
endY = Math.floor(endY / size) + 2;
// draw the pattern
ctx.lineWidth = size * 0.1;
ctx.lineJoin = "round";
ctx.strokeStyle = "black";
var colourIndex = 0;
for(var y = startY; y <endY; y+=1){
for(var x = startX; x <endX; x+=1){
if((x + y) % 4 === 0){
colourIndex = Math.floor(Math.abs(Math.sin(x)*size + Math.sin(y) * 20));
ctx.fillStyle = colours[(colourIndex++)% colours.length];
ctx.fillRect(x * size,y * size,size * 2,size);
ctx.strokeRect(x * size,y * size,size * 2,size);
x += 2;
ctx.fillStyle = colours[(colourIndex++)% colours.length];
ctx.fillRect(x * size,y * size, size, size * 2);
ctx.strokeRect(x * size,y * size, size, size * 2);
x += 1;
}
}
}
}
// Animate it all
var update = true; // flag to indecate something needs updating
function mainLoop(time){
// if window size has changed update canvas to new size
if(canvas.width !== innerWidth || canvas.height !== innerHeight || update){
canvas.width = innerWidth;
canvas.height = innerHeight
origin.x = canvas.width / 2;
origin.y = canvas.height / 2;
size = Math.min(canvas.width, canvas.height) * sizes[currentSize % sizes.length];
update = false;
}
if(mouse.buttonRaw !== 0){
mouse.buttonRaw = 0;
currentSize += 1;
update = true;
}
// draw the patter
drawPattern(size,mouse,time/2000);
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
mouse = (function () {
function preventDefault(e) { e.preventDefault() }
var m; // alias for mouse
var mouse = {
x : 0, y : 0, // mouse position
buttonRaw : 0,
over : false, // true if mouse over the element
buttonOnMasks : [0b1, 0b10, 0b100], // mouse button on masks
buttonOffMasks : [0b110, 0b101, 0b011], // mouse button off masks
bounds : null,
eventNames : "mousemove,mousedown,mouseup,mouseout,mouseover".split(","),
event(e) {
var t = e.type;
m.bounds = m.element.getBoundingClientRect();
m.x = e.pageX - m.bounds.left - scrollX;
m.y = e.pageY - m.bounds.top - scrollY;
if (t === "mousedown") { m.buttonRaw |= m.buttonOnMasks[e.which - 1] }
else if (t === "mouseup") { m.buttonRaw &= m.buttonOffMasks[e.which - 1] }
else if (t === "mouseout") { m.over = false }
else if (t === "mouseover") { m.over = true }
e.preventDefault();
},
start(element) {
if (m.element !== undefined) { m.remove() }
m.element = element === undefined ? document : element;
m.eventNames.forEach(name => document.addEventListener(name, mouse.event) );
document.addEventListener("contextmenu", preventDefault, false);
},
}
m = mouse;
return mouse;
})();
mouse.start(canvas);
```
```css
canvas {
position : absolute;
top : 0px;
left : 0px;
}
```
```html
<canvas id=canvas></canvas>
```
Un-animated version at 60Deg
----------------------------
```js
const ctx = canvas.getContext("2d");
const colours = ["red","green","yellow","orange","blue","cyan","magenta"]
const origin = {x : canvas.width / 2, y : canvas.height / 2};
var size = Math.min(canvas.width * 0.2, canvas.height * 0.2);
function drawPattern(size,origin,ang){
const xAx = Math.cos(ang); // define the direction of xAxis
const xAy = Math.sin(ang);
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.setTransform(xAx,xAy,-xAy,xAx,origin.x,origin.y);
function getExtent(xAx,xAy,origin){
const im = [1,0,0,1]; // inverse matrix
const dot = xAx * xAx + xAy * xAy;
im[0] = xAx / dot;
im[1] = -xAy / dot;
im[2] = xAy / dot;
im[3] = xAx / dot;
const toWorld = (x,y) => {
var point = {};
var xx = x - origin.x;
var yy = y - origin.y;
point.x = xx * im[0] + yy * im[2];
point.y = xx * im[1] + yy * im[3];
return point;
}
return [
toWorld(0,0),
toWorld(canvas.width,0),
toWorld(canvas.width,canvas.height),
toWorld(0,canvas.height),
]
}
const corners = getExtent(xAx,xAy,origin);
var startX = Math.min(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var endX = Math.max(corners[0].x,corners[1].x,corners[2].x,corners[3].x);
var startY = Math.min(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
var endY = Math.max(corners[0].y,corners[1].y,corners[2].y,corners[3].y);
startX = Math.floor(startX / size) - 4;
endX = Math.floor(endX / size) + 4;
startY = Math.floor(startY / size) - 4;
endY = Math.floor(endY / size) + 4;
// draw the pattern
ctx.lineWidth = 5;
ctx.lineJoin = "round";
ctx.strokeStyle = "black";
for(var y = startY; y <endY; y+=1){
for(var x = startX; x <endX; x+=1){
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
if((x + y) % 4 === 0){
ctx.fillRect(x * size,y * size,size * 2,size);
ctx.strokeRect(x * size,y * size,size * 2,size);
x += 2;
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
ctx.fillRect(x * size,y * size, size, size * 2);
ctx.strokeRect(x * size,y * size, size, size * 2);
x += 1;
}
}
}
}
canvas.width = innerWidth;
canvas.height = innerHeight
origin.x = canvas.width / 2;
origin.y = canvas.height / 2;
size = Math.min(canvas.width * 0.2, canvas.height * 0.2);
drawPattern(size,origin,Math.PI / 3);
```
```css
canvas {
position : absolute;
top : 0px;
left : 0px;
}
```
```html
<canvas id=canvas></canvas>
``` | The best way to approach this is to examine the pattern and analyse its symmetry and how it repeats.
You can look at this several ways. For example, you could rotate the patter 45 degrees so that the tiles are plain orthogonal rectangles. But let's just look at it how it is. I am going to assume you are happy with it with 45deg tiles.
[](https://i.stack.imgur.com/1tNli.png)
Like the tiles themselves, it turns out the pattern has a 2:1 ratio. If we repeat this pattern horizontally and vertically, we can fill the canvas with the completed pattern.
We can see there are five tiles that overlap with our pattern block. However we don't need to draw them all when we draw each pattern block. We can take advantage of the fact that blocks are repeated, and we can leave the drawing of some tiles to later rows and columns.
Let's assume we are drawing the pattern blocks from left to right and top to bottom. Which tiles do we *need* to draw, at a minimum, to ensure this pattern block gets completely drawn (taking into account adjacent pattern blocks)?
Since we will be starting at the top left (and moving right and downwards), we'll need to draw tile 2. That's because that tile won't get drawn by either the block below us, or the block to the right of us. The same applies to tile 3.
It turns out those two are all we'll need to draw for each pattern block. Tile 1 and 4 will be drawn when the pattern block below us draws their tile 2 and 3 respectively. Tile 5 will be drawn when the pattern block to the south-east of us draws their tile 1.
We just need to remember that we may need to draw an extra column on the right-hand side, and at the bottom, to ensure those end-of-row and end-of-column pattern blocks get completely drawn.
The last thing to work out is how big our pattern blocks are.
Let's call the short side of the tile `a` and the long side `b`. We know that `b = 2 * a`. And we can work out, using Pythagoras Theorem, that the height of the pattern block will be:
```
h = sqrt(a^2 + a^2)
= sqrt(2 * a^2)
= sqrt(2) * a
```
The width of the pattern block we can see will be `w = 2 * h`.
Now that we've worked out how to draw the pattern, let's implement our algorithm.
```js
const a = 60;
const b = 120;
const h = 50 * Math.sqrt(2);
const w = h * 2;
const h2 = h / 2; // How far tile 1 sticks out to the left of the pattern block
// Set of colours for the tiles
const colours = ["red","cornsilk","black","limegreen","deepskyblue",
"mediumorchid", "lightgrey", "grey"]
const canvas = document.getElementById("herringbone");
const ctx = canvas.getContext("2d");
// Set a universal stroke colour and width
ctx.strokeStyle = "black";
ctx.lineWidth = 4;
// Loop through the pattern block rows
for (var y=0; y < (canvas.height + h); y+=h)
{
// Loop through the pattern block columns
for (var x=0; x < (canvas.width + w); x+=w)
{
// Draw tile "2"
// I'm just going to draw a path for simplicity, rather than
// worrying about drawing a rectangle with rotation and translates
ctx.beginPath();
ctx.moveTo(x - h2, y - h2);
ctx.lineTo(x, y - h);
ctx.lineTo(x + h, y);
ctx.lineTo(x + h2, y + h2);
ctx.closePath();
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
ctx.fill();
ctx.stroke();
// Draw tile "3"
ctx.beginPath();
ctx.moveTo(x + h2, y + h2);
ctx.lineTo(x + w - h2, y - h2);
ctx.lineTo(x + w, y);
ctx.lineTo(x + h, y + h);
ctx.closePath();
ctx.fillStyle = colours[Math.floor(Math.random() * colours.length)];
ctx.fill();
ctx.stroke();
}
}
```
```html
<canvas id="herringbone" width="500" height="400"></canvas>
``` |
49,347,055 | I have the following code:
```
x = range(100)
M = len(x)
sample=np.zeros((M,41632))
for i in range(M):
lista=np.load('sample'+str(i)+'.npy')
for j in range(41632):
sample[i,j]=np.array(lista[j])
print i
```
to create an array made of sample\_i numpy arrays.
sample0, sample1, sample3, etc. are numpy arrays and my expected output is a Mx41632 array like this:
```
sample = [[sample0],[sample1],[sample2],...]
```
How can I compact and make more quick this operation without loop for? M can reach also 1 million.
Or, how can I append my sample array if the starting point is, for example, 1000 instead of 0?
Thanks in advance | 2018/03/18 | [
"https://Stackoverflow.com/questions/49347055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7702895/"
] | Please configure you JPA Configuration as per your requirement. I've configured as below. You need to add below configuration in application.properties file.
```
# PROFILES
spring.profiles.active=dev
# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=default
spring.jpa.show-sql=true
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.continue-on-error=false
spring.datasource.generate-unique-name=false
``` | The default driver used by derby is `org.apache.derby.jdbc.AutoloadedDriver`, but springboot and other framework choice `org.apache.derby.jdbc.EmbeddedDriver`.
It causes the driver to be unable to find the driver when using the datasource for the first time.
About `Schema 'SA' does not exist`.
I think that you use the other tool connect the derby, such as **ij**. And the jdbc url they use is the same. It looks like the same database connected, but it's not actually.
This is the key to the problem. |
7,715,009 | Im trying to post some information in my api which is programmed using WCF Web Api. In the client, I'm using restsharp which is a rest client for restful services. However, when I try to post adding some parameters to the request, the post method in the service is never called, and my response object in the client gets a 500 status (internal server error), but when I comment the lines where I'm adding parameters the request reaches the post method exposed in the service.
Here's the code from the client:
```
[HttpPost]
public ActionResult Create(Game game)
{
if (ModelState.IsValid)
{
var request = new RestRequest(Method.POST);
var restClient = new RestClient();
restClient.BaseUrl = "http://localhost:4778";
request.Resource = "games";
//request.AddParameter("Name", game.Name,ParameterType.GetOrPost); this is te line when commented everything works fine
RestResponse<Game> g = restClient.Execute<Game>(request);
return RedirectToAction("Details", new {id=g.Data.Id });
}
return View(game);
}
```
Here's the code for the service:
```
[WebInvoke(UriTemplate = "", Method = "POST")]
public HttpResponseMessage<Game> Post(Game game, HttpRequestMessage<Game> request)
{
if (null == game)
{
return new HttpResponseMessage<Game>(HttpStatusCode.BadRequest);
}
var db = new XBoxGames();
game = db.Games.Add(game);
db.SaveChanges();
HttpResponseMessage<Game> response = new HttpResponseMessage<Game>(game);
response.StatusCode = HttpStatusCode.Created;
var uriBuilder = new UriBuilder(request.RequestUri);
uriBuilder.Path = string.Format("games/{0}", game.Id);
response.Headers.Location = uriBuilder.Uri;
return response;
}
```
I need to add parameters to my request so the game object in the service gets populated, but I dont know how to do this, if the service breaks every time I try to add parameters.
I forgot to mention that both client and server are .NET MVC 3 applications.
Any help would be appreciate it. Thanks in advance. | 2011/10/10 | [
"https://Stackoverflow.com/questions/7715009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925714/"
] | Well after going around this problem over and over again, I finally found a solution, however, I can't explain why this is happening.
I replaced the addParameter method for addBody, and everything worked as expected, I could post information on the server.
The problem seems to be that whenever I'm adding parameters through addParameter method, this method will append parameters as application/x-www-form-urlencoded, and apparently WCF web api is not supporting this type of data, and thats why it returns an internal server error to the client.
In contrary, addBody method uses text/xml which the server can understand.
Again, I don't know if this is whats actually happens, but it seems to be that.
This is how my client code looks now:
```
[HttpPost]
public ActionResult Create(Game game)
{
if (ModelState.IsValid)
{
RestClient restClient = new RestClient("http://localhost:4778");
RestRequest request = new RestRequest("games/daniel",Method.POST);
request.AddBody(game);
RestResponse response = restClient.Execute(request);
if (response.StatusCode != System.Net.HttpStatusCode.InternalServerError)
{
return RedirectToAction("Index");
}
}
return View(game);
```
Please if you have any feedback, or know whats going on let me know. | I'm not familiar with the objects you're calling but is game.Name a string? If it's not, that might explain why AddParameter is failing. |
106,267 | I have a hard drive with a virus that I removed from a PC. I can scan the file system of it as an attached USB drive. But how do I scan the registry of that USB drive since it is not booted up like a regular hard drive?
To clarify, the USB drive was a regular hard drive in a PC that got infected. I cannot boot into the OS to run a scan. I removed it to attach it to a working PC so I can scan its file system. But, I cannot scan the registry of that hard drive, because that drive is not booted up. The hard drive was a regular Windows XP hard drive install that I removed to scan as an attached drive (with an adapter to make it a USB drive). | 2010/02/08 | [
"https://superuser.com/questions/106267",
"https://superuser.com",
"https://superuser.com/users/7498/"
] | What you want to do is called 'offline registry editing'. You can load the registry hives from the old hard disk drive into your registry editor. Here's a tutorial:
*[Load registry hive for offline registry editing](http://smallvoid.com/article/winnt-offline-registry-edit.html)*
However, I'd recommend to use BartPE instead of your current Windows installation to do this:
*[How to edit the registry offline using BartPE boot CD?](http://windowsxp.mvps.org/peboot.htm)*
BartPE will recognize your external USB hard disk drive connected. | You might not need to worry about scanning the registry file on the infected drive.
Removing the infected files by the scans you are able to run (antivirus and antimalware/spyware) will most likely kill the infections. The registry entries will now point to missing files and so on... most likely. Put the drive back in its original system. I bet you can now boot to safe mode and run all the scans again locally... this time clearing out the registry of offensive entries, too. :)
My favorite approach has already been mentioned, though. A bartPE disk with some nice, prebuilt plugins for loading offline registries and feeding those to the scanners. This way, you don't remove the HD... you just boot a CD (or USB stick). A hand-held method to making your own disk is at <http://www.ubcd4win.com/> Good luck! |
303,160 | I tried to install **DIA** from the **Software Center** and from the **Terminal** (dia and dia-gnome), but it didn't seem to work. I couldn't find DIA in the **Application Menu** and I also couldn't find it by searching.
Any ideas? | 2013/06/02 | [
"https://askubuntu.com/questions/303160",
"https://askubuntu.com",
"https://askubuntu.com/users/163825/"
] | Dia cannot be found in the application centre. You have to launch by typing the command `dia` from the terminal or from Alt+F2.
I think this is a bug in 13.04.
Hope this helps. | >
> Dia is an editor for diagrams, graphs, charts etc. There is support
> for UML static structure diagrams (class diagrams),
> Entity-Relationship diagrams, network diagrams and much more. Diagrams
> can be exported to postscript and many other formats.
>
>
>
This package contains the GNOME version of Dia.
To install [**Dia-Gnome** ](https://apps.ubuntu.com/cat/applications/raring/dia-gnome/)
Source:[Ubuntu Apps Directory](https://apps.ubuntu.com/cat/applications/raring/dia-gnome/) |
24,098,464 | I am making a bat file which will change the extension then move it to another folder
I have managed to do the replace part like so:
```
ren *.txt *.jpg
```
However I would like to move all .jpg file without moving the .bat file that renamed them.
Thank you. | 2014/06/07 | [
"https://Stackoverflow.com/questions/24098464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just use [move](http://technet.microsoft.com/en-us/library/cc772528%28v=ws.10%29.aspx):
```
ren *.txt *.jpg
move *.jpg \NewDestination
```
Of course, you should replace `\NewDestination` with the actual path to the folder on your system where you want the files to be moved.
I find the [TechNet Command Line Reference](http://technet.microsoft.com/en-us/library/cc754340%28WS.10%29.aspx) a useful place to have bookmarked. | you can use something like:
```
move dir1\*.jpg dir2\...
``` |
71,555,622 | I want to add to the user all possible group memberships in the Azure Active Directory, but there are so many groups so I dont want to do it manually, is there any script or button to do this quickly? | 2022/03/21 | [
"https://Stackoverflow.com/questions/71555622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12398280/"
] | • Yes, you can surely do that through a powershell script wherein you would need to export the details of all the groups present in Azure AD to a CSV file or to the console. And then call every group to add the said user whose object ID is specified in the powershell command to every group. Please find the below prepared and tested powershell script for the specified user in all the groups present in Azure AD.
Powershell script: -
```
Connect-AzureAD
$groups=Get-AzureADGroup | Select-Object ObjectID
foreach($group in $groups) {Add-AzureADGroupMember -ObjectId $group.ObjectId -RefObjectId "f08cdf62-6d20-4b65-bdd8-33f84c61802f"} ’
```
• Results: -
[](https://i.stack.imgur.com/HPrEx.png)
[](https://i.stack.imgur.com/0wXRq.png)
[](https://i.stack.imgur.com/Qx6dt.png)
Please find below Microsoft documentation for your reference: -
<https://learn.microsoft.com/en-us/azure/active-directory/enterprise-users/groups-settings-v2-cmdlets#add-members> | Kartik and Vineesh answers are pretty good, but If you want to get all available groups and you are already a member of some groups you should use this script
```
try
{
Connect-AzureAD
$groups=Get-AzureADGroup -All $true ` | Select-Object ObjectID
foreach($group in $groups) {
$Members = $group | Get-AzureADGroupMember -All $true
$IsUserInGroup = $Members.ObjectID -contains "your objectId"
if ($IsUserInGroup -eq $false)
{
Add-AzureADGroupMember -ObjectId $group.ObjectId -RefObjectId "your
objectId"
}
}
}
catch
{
Write-Error $_.Exception.ToString()
Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
``` |
64,936,541 | I want to make one list of multiple sublists without using the `flatten` predicate in Prolog.
This is my code:
```ml
acclistsFromList([],A,A).
acclistsFromList([H|T],Listwithinlist,A):-
not(is_list(H)),
acclistsFromList(T,Listwithinlist,A).
acclistsFromList([H|T],Listwithinlist,A):-
is_list(H),
append([H],Listwithinlist,Acc2),
acclistsFromList(T,Acc2,A).
```
I get this as output
```ml
?- listsFromList([1,2,[a,b,c],3,4,[d,e]],X).
X = [[d, e], [a, b, c]] ;
```
But I want this:
```ml
?- listsFromList([1,2,[a,b,c],3,4,[d,e]],X).
X = [a, b, c, d, e] .
?- listsFromList([1,[],2,3,4,[a,b]],X).
X = [a, b] .
?- listsFromList([[[[a]]],b,c,d,e,[f]],X).
X = [f, a] .
?- listsFromList([[[[a]],b,[c]],d,e,[f]],X).
X = [f, a, b, c] .
```
What is the best way to reach this result, without using `flatten`? | 2020/11/20 | [
"https://Stackoverflow.com/questions/64936541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14676776/"
] | This is a one-liner,
```ml
foo(X,L) :-
findall(Z, (member(A,X),is_list(A),member(Z,A)), L).
```
(as seen [here](https://stackoverflow.com/a/64919078/849891)).
To deal with multi-layered nested lists, we need to use a recursive predicate,
```ml
nembr(Z,A) :- % member in nested lists
is_list(A), member(B,A), nembr(Z,B)
;
\+ is_list(A), A=Z.
```
then use *it* instead of that final `member` call in `findall`'s goal:
```ml
bar(X,L) :-
findall(Z, (member(A,X),is_list(A),nembr(Z,A)), L).
```
testing:
```ml
10 ?- foo([1,2,[a,b,c],3,4,[d,e]],X).
X = [a, b, c, d, e].
11 ?- bar([1,2,[a,b,c],3,4,[d,e]],X).
X = [a, b, c, d, e].
12 ?- bar([1,2,[a,b,[[[c]]]],3,4,[d,e]],X).
X = [a, b, c, d, e].
``` | A solution that uses an "open list" to append the elements encountered while walking the list-of-lists, which is essentially a tree, in prefix fashion.
The indicated examples indicate that non-list elements at depth 0 shall be discarded, and the other elements sorted by depth. However, no precise spec is given.
Indeed, one would expect the result of flattening
`[[[[a]],b,[c]],d,e,[f]]`
to be
`[b,f,c,a]`
via the "sorted-by-depth" pair list of Depth-Value pairs:
`[3-a,1-b,2-c,1-f]`
But the question poster requests this result instead:
`[f, a, b, c]`
I don't really know whether this is an error or not.
```none
:- debug(flatwalker).
flatwalker(ListIn,ListOut) :-
Tip=Fin, % 2 unbound variables
% % designating the same memory
% % cell. Hold the Tip, grow at Fin.
flatwalker_2(0,ListIn,Fin,TerFin), % Elements are appended at Fin.
% % The final Fin is found in TerFin
% % on success.
TerFin=[], % Unify TerFin with [], closing
% % the list at Tip.
keysort(Tip,Sorted), % Sort the closed list at Tip
% % by pair key, i.e. by depth.
% % keysort/2 is stable and keeps
% % duplicates.
debug(flatwalker,"Got : ~q",[Tip]),
maplist([_-V,V]>>true,Sorted,ListOut). % Remove depth values.
% ---
% flatwalker_2(+Depth,+TreeIn,+Fin,+TerFin)
% Depth: Input integer, indicates current tree depth.
% TreeIn: The list to flatten at this depth (it's a node of the tree,
% which may or may not contain subtrees, i.e. lists)
% Fin: Always an unbound variable denoting the end of an open list to
% which we will append.
% ("points to an empty memory cell at the fin of the open list")
% Works as an accumulator as a new Fin, advanced by 1 cell at each
% append operation is handed to the next flatwalker_2/4
% activation.
% TerFin: When flatwalker_2/ is done, the final Fin is unified with
% TerFin so that it can be passed to flatwalker/2.
% ---
% We make the guards explicit and cut heavily.
% Optimizing the guards (if so desired) is left as an exercise.
flatwalker_2(_,[],Fin,Fin) :- !. % Done as TreeIn is empty.
% Unify Fin with TerFin.
flatwalker_2(0,[X|Xs],Fin,TerFin) :- % Case of X is nonlist at depth 0:
% % discard!
\+is_list(X),!,
flatwalker_2(0,Xs,Fin,TerFin). % Continue with the rest of the
% list at this depth.
flatwalker_2(D,[X|Xs],Fin,TerFin) :- % Case of X is nonlist at
% % depth > 0: keep!
D>0,\+is_list(X),!,
Fin=[D-X|Fin2], % Grow the result list at its
% % Fin by D-X.
flatwalker_2(D,Xs,Fin2,TerFin). % Continue with the rest of the
% list at this depth.
flatwalker_2(D,[X|Xs],Fin,TerFin) :- % Case of X is a list at any
% % depth.
is_list(X),!,
DD is D+1,
flatwalker_2(DD,X,Fin,Fin2), % Collect one level down
flatwalker_2(D,Xs,Fin2,TerFin). % On return, continue with the
% rest of the list at this depth.
```
Some [`plunit`](https://eu.swi-prolog.org/pldoc/doc_for?object=section(%27packages/plunit.html%27)) tests:
```none
:- begin_tests(flatwalker).
test("empty",true(Out == [])) :-
flatwalker([],Out).
test("simple",true(Out == [])) :-
flatwalker([1,2,3],Out).
test("with empties",true(Out == [])) :-
flatwalker([[],1,[],2,[],3,[]],Out).
test("test 1",true(Out == [a, b, c, d, e])) :-
flatwalker([1,2,[a,b,c],3,4,[d,e]],Out).
test("test 2",true(Out == [a, b])) :-
flatwalker([1,[],2,3,4,[a,b]],Out).
test("test 3",true(Out == [f, a])) :-
flatwalker([[[[a]]],b,c,d,e,[f]],Out).
test("test 4",true(Out == [f, a, b, c])) :-
flatwalker([[[[a]],b,[c]],d,e,[f]],Out).
:- end_tests(flatwalker).
```
And so:
```none
?- run_tests.
% PL-Unit: flatwalker
% Got : []
.
% Got : []
.
% Got : []
.
% Got : [1-a,1-b,1-c,1-d,1-e]
.
% Got : [1-a,1-b]
.
% Got : [3-a,1-f]
.
% Got : [3-a,1-b,2-c,1-f]
ERROR: flatwalker.pl:66:
test test 4: wrong answer (compared using ==)
ERROR: Expected: [f,a,b,c]
ERROR: Got: [b,f,c,a]
done
% 1 test failed
% 6 tests passed
false.
``` |
18,782,291 | I have two objects in two separate files:
```
import FooResults = require('fooresults');
class FooViewModel {
Results = ko.observable<FooResults[]>();
}
export = FooViewModel;
```
And:
```
class FooResults {
Id = ko.observable<number>();
Text = ko.observable<string>();
}
export = FooResults;
```
But `FooViewModel` complained about private access, so I switched to an interface.
```
import FooResults = require('fooresults');
class FooViewModel {
Results: KnockoutObservable<IFooResults[]> = ko.observable<FooResults[]>();
}
export = FooViewModel;
```
And:
```
class FooResults implements IFooResults {
Id: KnockoutObservable<number> = ko.observable<number>();
Text: KnockoutObservable<string> = ko.observable<string>();
}
export = FooResults;
```
With:
```
declare interface IFooResults {
Id: KnockoutObservable<number>;
Text: KnockoutObservable<string>;
}
```
However now the complier complains when compiling `FooViewModel`, saying it cannot convert `FooResults` to `IFooResults` (despite `FooResults` compiling fine to `js`).
Whats wrong? Thanks.
Edit: Here is the actual error...
```
/*
Compile Error.
See error list for details
D:/MyWebProject/Scripts/fooviewmodel.ts(18,4): error TS2012: Cannot convert 'KnockoutObservable<FooResults[]>' to 'KnockoutObservable<IFooResults[]>':
Call signatures of types 'KnockoutObservable<FooResults[]>' and 'KnockoutObservable<Symology.Insight.ViewModels.StreetWorks.Works.IFooResults[]>' are incompatible:
Type 'FooResults' is missing property 'Id' from type 'IFooResults'.
Call signature expects 0 or fewer parameters.
*/
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18782291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1369663/"
] | you can try this. `R+` will replace one or more `R`
```
String str = "i want hello RRRRRRRRRRRR My name RRR is RRRRRRRR arvind RR";
System.out.println(str.replaceAll("R+","A"));
``` | ```
String input = "i want hello RRRRRRRRRRRR My name RRR is RRRRRRRR arvind RR";
String output = input.replaceAll("R+" "A")
``` |
58,414,577 | My app running on Swift UI, and my main page is `Home()`, In the home page there is `NavigationView` and `NavigationLink(destination: SaveThePlanet())`, I have hide the Navigation View on the main page "Home", its also hide in `SaveThePlanet()`.
How can I unhide the navigation back button in the `SaveThePlanet()` page?
```
import SwiftUI
struct Home: View {
@State var show = false
@State var showSaveThePlanet = false
var body: some View {
NavigationView {
ZStack {
Color.gray
ContentView()
.blur(radius: show ? 10 : 0)
.scaleEffect(show ? 0.90 : 1)
.blur(radius: showSaveThePlanet ? 10 : 0)
.scaleEffect(showSaveThePlanet ? 0.90 : 1)
.animation(.default)
leftIcon(show: $show)
.offset(x: 0, y: showSaveThePlanet ? 300 : 70)
.scaleEffect(show ? 0.90 : 1)
.blur(radius: show ? 10 : 0)
.animation(.easeInOut)
SaveThePlanet()
.background(Color("Bg"))
.cornerRadius(10)
.shadow(color: Color("Green-Sh"), radius: 10, x: 0, y: 0)
.animation(.spring())
.offset(y: showSaveThePlanet ? 120 : UIScreen.main.bounds.height)
.padding()
rightIcon(show: $showSaveThePlanet)
.offset(x: 0, y: 70)
.animation(.easeInOut)
.scaleEffect(show ? 0.90 : 1)
.blur(radius: show ? 10 : 0)
.opacity(showSaveThePlanet ? 0 : 1)
rightIconClose(show: $showSaveThePlanet)
.offset(x: 0, y: 70)
.animation(.easeInOut)
.scaleEffect(show ? 0.90 : 1)
.blur(radius: show ? 10 : 0)
.opacity(showSaveThePlanet ? 1 : 0)
MenuView(show: $show)
}
.edgesIgnoringSafeArea(.all)
.navigationBarTitle("Home")
.navigationBarHidden(true)
.navigationBarBackButtonHidden(false)
}
}
}
``` | 2019/10/16 | [
"https://Stackoverflow.com/questions/58414577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12226760/"
] | I'm answering because I think the solution nowadays is pretty easier. So for people having the same problem just add a
```
.navigationBarHidden(true)
```
on your Home() component and you should be fine. This solution works for sure in Swift 5.5, there is to do the onAppear and onDisappear trick of the other answers. It will hide only the navigation bar on the view you specified | It's a little hard to tell based on the code you've posted, but it looks like you are trying to present a view that slides up from the bottom when `showSaveThePlanet` is true, and also show the navigation bar only when that view appears.
This can be accomplished by setting `.navigationBarHidden(!showSaveThePlanet)` anywhere in your `body` property. Note that your code does not use `NavigationLink` anywhere to push a new view onto the `NavigationView` stack, so you would not get a back button. You can add your own button to dismiss the sheet using `.navigationBarItems(leading:)`
Here is a simplified example showing what I mean.
```
struct ContentView: View {
@State private var detailShowing = false
var body: some View {
NavigationView {
ZStack(alignment: Alignment(horizontal: .center, vertical: .top)) {
Color.gray.edgesIgnoringSafeArea(.all)
// A card-like view that is initially offscreen,
// and slides on when detailShowing == true
DetailView()
.offset(x: 0, y: detailShowing ? 120 : UIScreen.main.bounds.height)
.animation(.spring())
// Just here to change state
Button("Toggle") {
self.detailShowing.toggle()
}
.padding()
.offset(x: 0, y: detailShowing ? 0 : 44)
.animation(.none)
}
// This is the key modifier
.navigationBarHidden(!detailShowing)
.navigationBarTitle("Detail View", displayMode: .inline)
.navigationBarItems(leading: Button("Close") {
self.detailShowing = false
})
}
}
}
struct DetailView: View {
var body: some View {
ZStack(alignment: Alignment(horizontal: .center, vertical: .top)) {
RoundedRectangle(cornerRadius: 15).fill(Color.secondary).frame(width: 300, height: 500)
Text("Detail Content")
.padding()
}
}
}
``` |
31,263,567 | I'm new in Javascript and i'm good familiar with `Thread.sleep` in Java. As far as i know, Javascript uses `setTimeout` which is similar to `Thread.sleep`.
I'm using `phantomjs` to print my thread:
```
function doThing(i){
setTimeout(function(){
console.log(i);
}, 100);
}
for(var i=1; i<20; i++){
doThing(i);
}
phantom.exit();
```
***It prints nothing!!***
Can you please let me know, what's wrong here? :(
Help would be appreciated!!
***EDITED:***
I'm using Java program for calling `phantomjs script`. | 2015/07/07 | [
"https://Stackoverflow.com/questions/31263567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5088561/"
] | Try this
```
function doThing(i, last){
setTimeout(function(){
console.log(i);
if (last) phantom.exit();
}, 100 * i);
}
for(var i=1; i<20; i++){
doThing(i, i >= 19);
}
```
There are 2 fixes in this code (in comparison to origin):
1. phantom.exit() must be called just after last operation will be finished (in my revision I resolved this by using flag 'last' which will be set to true only for last iteration);
2. it's better to call setTimeout with slightly different timeout values, just to let them fire one by one (not so critical, but still it's better). | Java and javascript are separate languages. So you can't compare features of those languages. setTimeout executes the block of code after a specified interval.
<http://www.w3schools.com/jsref/met_win_settimeout.asp> |
19,824,312 | Given the following JSON
```
$first = array('code'=>'200','message'=>'ok');
{
"code": "200",
"message": "ok"
}
$second = array("user"=>array('fname'=>'Fred','lname'=>'Flintstone','status'=>'1'))
{
"user": [
{
"fname": "Fred",
"lname": "Flintstone",
"status": "1"
}
]
}
```
How do I combine these to get the output as follows.
```
{
"code": "200",
"message": "ok",
"user": [
{
"fname": "Fred",
"lname": "Flintstone",
"status": "1"
}
]
}
``` | 2013/11/06 | [
"https://Stackoverflow.com/questions/19824312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/505055/"
] | Try merging the arrays
```
$json = json_encode(array_merge($first, $second));
``` | using [array\_merge](http://php.net/manual/en/function.array-merge.php) you can combine the arrays then encode it:
```
//arrays
$first = array('code'=>'200','message'=>'ok');
$second = array("user"=>array('fname'=>'Fred','lname'=>'Flintstone','status'=>'1'));
//merging
$merged_arrays = array_merge($first, $second);
print_r($merged_arrays);
//encoding
$json_data = json_encode($merged_arrays);
echo $json_data;
``` |
21,191 | Is this even possible? Can a Tor binary file be compiled to work on Linux, Windows, OSX, iOS, and Android? We would like to package the binary file so we can launch Tor from our application. Could we build Tor from source on a Linux computer for the different CPU architectures? Is the Tor binary all we need? We currently have the application working on a Linux computer by copy-and-pasting the Tor binary to a different folder than the one installed on the computer and launch Tor from there with a custom `torrc`. Is the binary reading other files on our computer to launch, or can just this one binary file be packaged and it will at least work on other Linux computers that match the same CPU architecture?
Is there official documentation about this process anywhere?
Thank you. | 2020/05/09 | [
"https://tor.stackexchange.com/questions/21191",
"https://tor.stackexchange.com",
"https://tor.stackexchange.com/users/-1/"
] | This [defcon 22 talk](https://www.youtube.com/watch?v=tlxmUfnpr8w) covers most of the possible ways to get caught using Tor:
* All tor nodes are known (except bridges). ISP or system administrator can figure out who was using tor at a given time and from what IP. That information can be used to narrow down who is using tor and find out the suspect.
* People can give away a lot of information themselves. One slip up is enough to give away your location.
* People can be found out using an exploit in the web page (for example, in JavaScript).
* Server can have an RCE exploit (Remote Code Execution), which can be used to contact another server over clearnet, and thus, giving away the real IP.
Also in the talk, it was pointed out that the owner gave away himself by advertising his gmail over some shady forum, looking for an "IT pro in the bitcoin community". Oh, and also [posted on stackoverflow](https://stackoverflow.com/questions/15445285/how-can-i-connect-to-a-tor-hidden-service-using-curl-in-php) asking for help with a Tor hidden service under his real name (later changed to frosty). The exact details on how FBI found his servers are unknown, but after they found them, they started taking them down and also took a copy of the server data. | There is many steps he did wrong that got him caught.
Most of them are not related to tor\exit nodes directly.
>
> 1. He boasted about running his international multimillion dollar drugs marketplace on his LinkedIn profile
> 2. He used a real photograph of himself for a fake ID to rent servers to run his international multimillion dollar drugs marketplace
> 3. He asked for advice on coding the secret website for his international multimillion dollar drugs marketplace using his real
> name
> 4. He sought contacts in courier firms, presumably to work out how to best ship things from his international multimillion dollar drugs
> marketplace, on Google+, where his real name, real face and real
> YouTube profile were visible
> 5. He allegedly paid $80,000 to kill a former employee of his international multimillion dollar drugs marketplace to a man who
> turned out to be an undercover cop
>
>
>
<https://www.theguardian.com/technology/2013/oct/03/five-stupid-things-dread-pirate-roberts-did-to-get-arrested>
<https://www.wired.com/2015/01/silk-road-trial-undercover-dhs-fbi-trap-ross-ulbricht/> |
36,245,037 | I would like to be able to find the first occurrence of m² and then numbers in front of it, could be integers or decimal numbers.
*E.g.*
>
> "some text" 38 m² "some text" ,
>
>
> "some text" 48,8 m² "some text",
>
>
> "some text" 48 m² "some text", etc..
>
>
>
What I have so far is:
```
\d\d,\d\s*(\m\u00B2)|\d\d\s*(\m\u00B2)
```
This right now finds all occurrences, although I guess it could be fixed with `findFirst()`. Any ideas how to improve the Regex part? | 2016/03/27 | [
"https://Stackoverflow.com/questions/36245037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757390/"
] | To get the first match, you just need to use `Matcher#find()` inside an `if` block:
```
String rx = "\\d+(?:,\\d+)?\\s*m\\u00B2";
Pattern p = Pattern.compile(rx);
Matcher matcher = p.matcher("E.g. : 4668,68 m² some text, some text 48 m² etc");
if (matcher.find()){
System.out.println(matcher.group());
}
```
See [IDEONE demo](http://ideone.com/1EYR9U)
Note that you can get rid of the alternation group using an optional non-capturing group `(?:..)?`
Pattern breakdown:
* `\d+` - 1+ digits
* `(?:,\d+)?` - 0+ sequences of a comma followed with 1+ digits
* `\s*` - 0+ whitespace symbols
* `m\u00B2` - m2. | This is what I came up with you help :) (work in progress, later it should return BigDecimal value), for now it seems to work:
```
public static String findArea(String description) {
String tempString = "";
Pattern p = Pattern.compile("\\d+(?:,\\d+)?\\s*m\\u00B2");
Matcher m = p.matcher(description);
if(m.find()) {
tempString = m.group();
}
//remove the m and /u00B2 to parse it to BigDecimal later
tempString = tempString.replaceAll("[^0-9|,]","");
System.out.println(tempString);
return tempString;
}
``` |
27,913,009 | Update:
I think the leak is coming from `getActivity().getSupportLoaderManager().restartLoader(getLoaderId(), null, this);`
where i have my object implement LoaderCallback. Is there a way for me to clear the callback i tired setting it to
```
getActivity().getSupportLoaderManager().restartLoader(getLoaderId(), null, null);
```
but this crashes
Orig:
I have a list of objects in one of my fragments(A). When I navigate forward I add fragment A to the backstack. After I have navigated to a new fragment and I dump the heap. I still see my object in the heap. When I get the shortest path in the dump it looks like below. I can see that in FragmentManagerImpl there is a reference to fragment A in mActive fragments which is keeping my lists object alive.

Is my fragment supposed to stay in mActive fragments or is this a leak?
Adding to backstack
```
FragmentTransaction transaction = mFragmentManager.beginTransaction();
updateTransactionWith(info.getReplacement(), transaction, "replace");
transaction.addToBackStack(info.getReplacement().getClass().toString());
transaction.commit();
mFragmentManager.executePendingTransactions();
``` | 2015/01/13 | [
"https://Stackoverflow.com/questions/27913009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634451/"
] | By calling `addToBackStack()`, you're requesting the `FragmentManager` that the `Fragment` being replaced be just **stopped** and not **destroyed** because you're either anticipating that a back button press is very likely or, the `Fragment` is heavy on initialization and you would still like to avoid doing it again even though the user is not very likely to go back.
The [docs](http://developer.android.com/guide/components/fragments.html#Transactions "Fragment Transactions") clearly state that
>
> If you do not call ***addToBackStack()*** when you perform a transaction
> that removes a fragment, then that fragment is **destroyed** when the
> transaction is committed and the user cannot navigate back to it.
>
>
> Whereas, if you do call ***addToBackStack()*** when removing a fragment,
> then the fragment is **stopped** and will be **resumed** if the user navigates
> back.
>
>
>
Hence, it's not a memory leak and your observations are quite in line with the expected behaviour.
However, just like an `Activity`, the system may still choose to **destroy** this `Fragment`, if it's running out of memory. But, that's expected behaviour too. | It's not a memory leak. You need to decide how to deal with your fragment's state.
Ideally you implement `onSaveInstanceState` and `onViewStateRestored` saving your state to the bundle and restoring it from the bundle respectively.
Alternatively, if you're able to re-create your state easily, you may want to save the bother of (re)storing it using the bundle and just null your references in the `onPause` method and create them during the `onResume` method. Be aware that `onResume` gets called even if the fragment has just been created, so be careful not to do that work more than once.
Either way, be sure to null your references to ensure your objects are marked for GC.
The FragmentManager will decide if it needs to discard and recreate the fragment as necessary in order to allow the user to go back to the fragment you added to the stack. In conditions where there's very little else on the stack and/or there's lots of spare memory it will probably just keep a direct reference to the fragment you added to the back stack.
Given all that, you also need to be careful about keeping references to other fragments, activities, etc as that kind of state is difficult to recreate.
The following approach is recommended for providing proper back navigation:
```
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
```
* More info:
+ <http://developer.android.com/guide/components/fragments.html>
+ <http://developer.android.com/training/implementing-navigation/temporal.html>
* API docs: <http://developer.android.com/reference/android/app/Fragment.html> |
6,544,899 | I am Using SOAP WS for getting the Data. I got the four Parameters in Response - Topic\_Name, Topic\_Id, Topic\_ImagePath and Topic\_Details. Now I have All the Images of Topic Locally with the same name as i got from the web service for Particular Topic\_ID.
My question is I want to use Local image instead using the Topic\_ImagePath 's Image but the data Must Come From the Web Service.
I dont want to use if ..else condition because I have more than 1000 Topics, any one can explain how I get the Path of Local Image and Display it with the Data Comes From the Web Service..
Thanx in Advance. | 2011/07/01 | [
"https://Stackoverflow.com/questions/6544899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421003/"
] | I guess this will help:
<http://stevesouders.com/hpws/>
Steve is an employee at google who works on Latency. He is also the mind behind Firefox YSlow. His set of rules are good read to consider for fast apps. | Google created their own tools that you might want to look at: [Closure](http://code.google.com/closure/). You can check out the O'Reilly title: [Closure The Definitive Guide](https://rads.stackoverflow.com/amzn/click/com/1449381871) as well. |
43,199,572 | I'm having some problems with my program and it gives me `java.nio.file.NoSuchFileException` I'm trying to copy folder and files to another but others are working as well. I'm trying to copy folder and files from the `Arraylist` the values from the arraylist was from the `DEL_COPY_DIR` which is properties file. This is my codes below.
```
ArrayList<String> list1 = readConfigFileList(ConstantVariables.DEL_COPY_DIR);
for (String strList1 : list1)
{
if(strList1.contains("<mnbr>")){
String[] saDirectory = strList1.split("<mnbr>");
String strDirectory = saDirectory[0];
String strMnbrContent = saDirectory[1];
File file = new File(strSource + strDirectory);
String[] saMnbrFile = file.list();
for(int i = 0; i < saMnbrFile.length; i++) {
File fileList = new File(strSource + strDirectory + saMnbrFile[i] + strMnbrContent);
String strsrcList = new String(fileList.toString());
File fileList1 = new File(strDestination + strDirectory + saMnbrFile[i] + strMnbrContent);
String strdestList = new String(fileList1.toString());
if(fileList.isDirectory())
// System.out.println(strSource + strDirectory + saMnbrFile[i] + strMnbrContent);
copyFolders(strsrcList, strdestList);
}
}
else {
copyFolders(strSource + strList1 , strDestination + strList1);
}
}
```
**Copy Files**
```
public void copyFiles(String source, String destination) throws IOException{
try {
File fileFrom = new File(source);
File fileTo = new File(destination);
Files.copy( fileFrom.toPath(), fileTo.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error");
}
}
```
**Copy Folder**
```
public void copyFolders(String src, String dest)
throws IOException{
File srcFrom = new File(src);
File destTo = new File(dest);
if(srcFrom.isDirectory()){
if (!destTo.exists())
{
destTo.mkdir();
txtDetails.append("Directory copied : " + dest + "\n");
}
final String files[] = srcFrom.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolders(srcFile.toString(), destFile.toString());
}
}
else{
copyFiles(src, dest);
txtDetails.append("Files Copying: " + srcFrom.getAbsolutePath() + "...Done" + "\n");
}
}
```
**Full Error**
```
java.nio.file.NoSuchFileException: D:\dest\data\25\misc\AlarmCum.obj -> D:\destination\data\25\misc\AlarmCum.obj
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.copy(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.copy(Unknown Source)
at java.nio.file.Files.copy(Unknown Source)
at org.eclipse.wb.swt.FortryApplication.copyFiles(FortryApplication.java:295)
at org.eclipse.wb.swt.FortryApplication.copyFolders(FortryApplication.java:337)
at org.eclipse.wb.swt.FortryApplication.copyFolders(FortryApplication.java:332)
at org.eclipse.wb.swt.FortryApplication$3.widgetSelected(FortryApplication.java:239)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:51)
at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:346)
```
PS: I'm using textbox for the source and destination | 2017/04/04 | [
"https://Stackoverflow.com/questions/43199572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7772560/"
] | You can simply combine an image and a gradient, like this
```css
div {
height: 200px;
width: 500px;
background-image:
linear-gradient(black,
transparent 20%,
transparent 80%,
black),
url(http://lorempixel.com/500/200/nature/1/);
}
```
```html
<div></div>
```
---
Or use a pseudo element, like this
```css
div {
height: 200px;
width: 500px;
background: url(http://lorempixel.com/500/200/nature/1/);
}
div::after {
content: '';
display: block;
height: 200px;
width: 500px;
background: linear-gradient(transparent, black);
}
```
```html
<div></div>
``` | Inset Box-Shadow
----------------
**Advantage:** slim on code, no additional pseudoelement needed
**Disadvantage:** Box shadow **size and offset values** can for current w3 standard be **ONLY absolute** (not percentual), therefore dynamic/various size of the shadowed element cannot be solved without JavaScript calculating elements dimensions.
**There are better answers, so i am just going to throw this as an additional option (worse).**
```css
div {
display: inline-block;
background:url(http://unsplash.it/200/200);
width:200px;
height:200px;
}
.darkened{
box-shadow: inset 0 -200px 200px -100px rgba(0,0,0,.9);
}
```
```html
<div></div>
<div class="darkened"></div>
``` |
40,708,016 | I am newbie to redux and making a todo list in the redux. My action creator code looks like :
```
/**
* This file is called Action Creator (creates actions)
*
* Actions are objects as :
* {
* type : 'ADD_TODO' //the only thing needed is type
* text: 'this is our first to do'
* }
*/
module.exports = {
addTodo: function (text) {
return (dispatch) => {
dispatch({type: 'ADD_TODO', data: text});
};
}
};
//export default actions = {
// addTodo(text) {
// return {
// type: 'ADD_TODO',
// text: text
// }
// }
//};
//
```
Instead of returning object from the action, I am returning a function. So in the store.js file, I've used `thunkMiddleware` from `react-redux`.
My store.js code looks like :
```
import { applyMiddleware, compose, createStore } from 'redux';
import reducer from '../reducers/reducers';
import thunkMiddleware from 'redux-thunk';
//We separated out the store from the client.js file so that if we have to add middleware here and change our state, we can do that here
//Add middlewares on actions here
let finalCreateStore = compose(
applyMiddleware(thunkMiddleware)
)(createStore);
export default function configureStore(initialState = {todos: []}) {
return finalCreateStore(reducer, initialState);
}
```
but while firing an action, it says that **action is not defined**
**[Edit]**
My Reducer looks like this:
```
function getId(state) {
return state.todos.reduce((maxId, todo) => {
return Math.max(todo.id, maxId)
}, -1) + 1;
}
export default function reducer(state, actions) {
switch (actions.type) {
case 'ADD_TODO':
Object.assign({}, state, {
todos: [{
//add new to do
text: action.text,
completed: false,
id: getId(state)
}, ...state.todos]
});
break;
default:
return state;
}
}
```
Also I'm firing actions using `connect` as :
```
function mapStateToProps(state) {
return state;
}
function mapDispatchToProps(dispatch) {
return {
addTodo: (todo) => {
dispatch(addTodo(todo));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
```
I don't have any clue how can I get rid of this error. | 2016/11/20 | [
"https://Stackoverflow.com/questions/40708016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648216/"
] | Your reducer signature is `(state, actions)` but in the function body you have `action`. You probably meant:
```
function reducer (state, action) {
// code
}
``` | There is a typo in your reducer. You define `actions` as second parameter, but on one line (I added a comment there) you try to read from `action`, which is not defined.
```
export default function reducer(state, actions) {
switch (actions.type) {
case 'ADD_TODO':
Object.assign({}, state, {
todos: [{
//add new to do
text: action.text, // <- action is not defined, but actions is
completed: false,
id: getId(state)
}, ...state.todos]
});
break;
default:
return state;
}
}
```
It's probably nice to call it `action` instead of `actions`, because it's just a single action. |
2,480,116 | There is an insightful question about [reading a C/C++ data structure in C# from a byte array](https://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-from-a-byte-array), but I cannot get the code to work for my collection of big-endian (network byte order) bytes. (EDIT: Note that my real struct has more than just one field.) Is there a way to marshal the bytes into a big-endian version of the structure and then pull out the values in the endianness of the framework (that of the host, which is usually little-endian)?
(Note, reversing the array of bytes will **not** work - each value's bytes must be reversed, which does not give you the same collection as reversing all of the bytes.)
This should summarize what I'm looking for (LE=LittleEndian, BE=BigEndian):
```
void Main()
{
var leBytes = new byte[] {1, 0, 2, 0};
var beBytes = new byte[] {0, 1, 0, 2};
Foo fooLe = ByteArrayToStructure<Foo>(leBytes);
Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes);
Assert.AreEqual(fooLe, fooBe);
}
[StructLayout(LayoutKind.Explicit, Size=4)]
public struct Foo {
[FieldOffset(0)]
public ushort firstUshort;
[FieldOffset(2)]
public ushort secondUshort;
}
T ByteArrayToStructure<T>(byte[] bytes) where T: struct
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T));
handle.Free();
return stuff;
}
T ByteArrayToStructureBigEndian<T>(byte[] bytes) where T: struct
{
???
}
```
Other helpful links:
[Byte of a struct and onto endian concerns](http://blogs.msdn.com/jeremykuhne/archive/2005/07/19/440264.aspx)
[A little more on bytes and endianness (byte order)](http://blogs.msdn.com/jeremykuhne/archive/2005/07/21/441247.aspx)
[Read binary files more efficiently using C#](http://www.builderau.com.au/architect/webservices/soa/Read-binary-files-more-efficiently-using-C-/0,339024590,320277904,00.htm)
[Unsafe and reading from files](http://blogs.msdn.com/ericgu/archive/2004/04/13/112297.aspx)
[Mono's contribution to the issue](http://www.mono-project.com/Mono_DataConvert)
[Mastering C# structs](http://www.developerfusion.com/article/84519/mastering-structs-in-c/) | 2010/03/19 | [
"https://Stackoverflow.com/questions/2480116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116891/"
] | I finally figured out a way that didn't involve reflection and is mostly user-friendly. It uses Mono's [DataConverter](http://www.mono-project.com/Mono_DataConvert) class ([source](http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/corlib/Mono/DataConverter.cs?view=log)) which, unfortunately, is fairly buggy at this point. (For example, floats and doubles don't seem to work correctly, string parsing is broken, etc.)
The trick is to Unpack and re-pack the bytes as big-endian, which requires a string describing what types are in the byte array (see the last method).Also, byte alignment is tricky: there are four bytes in the struct instead of one because marshaling seems to rely on having 4-byte alignment (I still don't quite understand that part). (EDIT: I have found that adding `Pack=1` to the [`StructLayout` attribute](http://msdn.microsoft.com/en-us/library/4xzbssc4%28v=VS.100%29.aspx) usually takes care of byte-alignment issues.)
Note, this sample code was used in LINQPad - the Dump extension method just prints info about the object and returns the object (it's fluent).
```
public void Main()
{
var beBytes = new byte[] {
0x80,
0x80,
0x80,
0x80,
0x80,0,
0x80,0,
0x80,0,0,0,
0x80,0,0,0,
0x80,0,0,0,0,0,0,0,
0x80,0,0,0,0,0,0,0,
// 0,0,0x80,0x3F, // float of 1
// 0,0,0,0,0,0,0xF0,0x3F, // double of 1
0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0 // Testing\0\0\0
};
var leBytes = new byte[] {
0x80,
0x80,
0x80,
0x80,
0,0x80,
0,0x80,
0,0,0,0x80,
0,0,0,0x80,
0,0,0,0,0,0,0,0x80,
0,0,0,0,0,0,0,0x80,
// 0,0,0x80,0x3F, // float of 1
// 0,0,0,0,0,0,0xF0,0x3F, // double of 1
0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0 // Testing\0\0\0
};
Foo fooLe = ByteArrayToStructure<Foo>(leBytes).Dump("LE");
Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes,
"bbbbsSiIlL"
// + "fd" // float, then double
+"9bb").Dump("BE");
Assert.AreEqual(fooLe, fooBe);
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Foo {
public byte b1;
public byte b2;
public byte b3;
public byte b4;
public short s;
public ushort S;
public int i;
public uint I;
public long l;
public ulong L;
// public float f;
// public double d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string MyString;
}
T ByteArrayToStructure<T>(byte[] bytes) where T: struct
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T));
handle.Free();
return stuff;
}
T ByteArrayToStructureBigEndian<T>(byte[] bytes, string description) where T: struct
{
byte[] buffer = bytes;
IList unpacked = DataConverter.Unpack("^"+description, buffer, 0).Dump("unpacked");
buffer = DataConverter.PackEnumerable("!"+description, unpacked).Dump("packed");
return ByteArrayToStructure<T>(buffer);
}
``` | From my point of view you just need to add an Array.Reverse() before the conversion of the byte array. |
39,273,936 | I'm pretty new to Java, and I know what packages do. You use them to sort multiple files of a Java application together. However, is it standard to put it in a package if your application only has a single class? What are the pros and cons of doing this?
EDIT: I'm packaging this single class into a `.jar` file after. | 2016/09/01 | [
"https://Stackoverflow.com/questions/39273936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6072571/"
] | It really depends on how you're compiling and running the program, but ultimately it's **your choice**.
Let's have a look at some of the different ways you might build your program.
### 1. Compiling the file with `javac`
If you're compiling the file using `javac` then the package will not matter. It will generate the `.class` file the **same directory** as the source file.
### 2. Compiling to a JAR File
If you're compiling to a JAR File, then the `.class` file will be inside the directories specified in your package name. Although this would **not affect how the program is ran**.
In both of these cases, I'd say that the **package identifier is unnecessary** for a single-file program. However, there is an exception.
The exception...
----------------
If ever you **plan to use the class in a larger program**, then adding a relevant package name would be essential.
This is because it would...
1. Prevent **name collisions** when other classes in the default packages have the same name.
2. Help people know whether or not your class is **the one they want**.
Can you imagine if 20 different developers made a `List` class in the default package, and somehow they all ended up in a project? It would be *chaos*! How would I choose the right `List`?
So in the case of writing a class that others will use in their own projects, you should **definitely** use package names. | It is probably non-production application if it has a single class and doesn't have any dependencies or resource files. So it is completely up to you how you will start your app.
If you want to distribute your app - make it in compliance with the standards, put it in a jar, publish to maven... |
20,956,944 | I have some text:
>
> The great red fox. Which are not blue foxes. But foxes which are red are not any more faster.
>
>
>
Basically I want to match sentences where "red" and "fox" both appear in that order and another regex where it is not in that order.
How would I do that ? | 2014/01/06 | [
"https://Stackoverflow.com/questions/20956944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697795/"
] | Assuming that there is no abbreviations with dots in your sentences:
for any order:
```
(?=[^.!?]*fox)(?=[^.!?]*red)[^.!?]+[.!?]
```
for "red" before "fox":
```
[^.!?]*?red[^.!?]+?fox[^.!?]*[.!?]
``` | For "red" following "fox":
```
\b[^.?!]+red.*?fox[.?!]+
```
for "fox" following "red":
```
\b[^.?!]+fox.*?red[.?!]+
```
to capture all other sentences except ones have "red" following "fox":
```
(?:\b[^.?!]+red.*?fox[.?!]+)(.*?[.?!]+)
```
as you work with Javascript don't forget to put `g` modifier to capture all occurrences:
```
/\b[^.?!]+red.*?fox[.?!]+/g
```
[Online demo](http://regex101.com/r/iB9dS1) |
31,431,002 | I am new to installing new python modules.
I installed tweepy using pip install tweepy. The installation was successful and 2 folders tweepy & tweepy-3.3.0.dist-info are created in the Lib/site-packages, hence I assumed all should be fine.
However, when I went to the IDE and import tweepy. It is unable to detect the module:
```none
>>> import tweepy
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ImportError: No module named tweepy
```
What is wrong?
I am running python 2.7.5.
**[Update 1]** I am using windows 7.
I first installed pip using another forum's suggestion ([How do I install pip on Windows?](https://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows)). basically saving the get-pip.py script and double clicking it (unable to get "python get-pip.py" to work in cmd prompt as suggested). Then, I went to cmd and nagivated to C:/Python27/Scripts and type in pip install tweepy. I remembered seeing the result as a successful installation.
**[Update 2]** Using a file with import tweepy and running it, I have a similar error.
```
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\xxxx\Desktop\Script1.py", line 2, in <module>
from tweepy import Stream
ImportError: No module named tweepy
```
**[Update 3]** Typed "pip freeze" in cmd. It does show tweepy=3.3.0
```
C:\Python27\Scripts>pip freeze
oauthlib==0.7.2
requests==2.7.0
requests-oauthlib==0.5.0
six==1.9.0
tweepy==3.3.0
wheel==0.24.0
```
**[Answer]** Thanks for all the help guys, especially Cleb & omri\_saadon suggestion that there might be something wrong with the file path.
I just realised that my GIS software, ArcGIS by default installed another Python into the Python27 folder, and everything is taken from that folder, C:\Python27\ArcGIS10.2, instead of C:\Python27. After I install tweepy from C:\Python27\ArcGIS10.2\Scripts, everything works well. | 2015/07/15 | [
"https://Stackoverflow.com/questions/31431002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5117769/"
] | I tried this command `py -m pip install tweepy` and worked for me | If you are using Jupyter Notebook, the only thing that worked for me was to first install Jupyter again
```
pip install jupyter
```
and then install tweepy
```
pip install tweepy
``` |
38,601,784 | I am working on an asp.net mvc web application. now i have a value for operating system which equal to :-
[](https://i.stack.imgur.com/FF8ck.png)
and i am using the following code to build a url containing the above value as follow:-
```
var query = HttpUtility.ParseQueryString(string.Empty);
query["osName"] = OperatingSystem;
var url = new UriBuilder(apiurl);
url.Query = query.ToString();
string xml = client.DownloadString(url.ToString());
```
but the generated url will contain the following value for the operating system :-
```
osName=Microsoft%u00ae+Windows+Server%u00ae+2008+Standard
```
so the UriBuilder will encode the registered sign as `%u00ae+` which is wrong since when i try to decode the `%u00ae+` using online site such as <http://meyerweb.com/eric/tools/dencoder/> it will not decode `%u00ae+` as register sign ??? so can anyone adivce on this please, how i can send the registered sign inside my url ? is this a problem within UrilBuilder ?
Thanks
**EDIT**
This will clearly state my problem..
now i pass the asset name valueas £ ££££££
now the query["assetName"] will get the correct value.. but inside the query the value will get encoded wrongly (will not be encoded using UTF8 )!!!
[](https://i.stack.imgur.com/vQNz4.png) | 2016/07/27 | [
"https://Stackoverflow.com/questions/38601784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1146775/"
] | Try this:
```
url.Query = Uri.EscapeUriString(HttpUtility.UrlDecode(query.ToString()));
```
As mentioned here [HttpUtility.ParseQueryString() always encodes special characters to unicode](https://stackoverflow.com/questions/26789168/httputility-parsequerystring-always-encodes-special-characters-to-unicode) | Use `Uri.EscapeDataString()` to escape data (containing any special characters) before adding it in the Query String |
8,919,481 | I want to use oracle syntax to select only 1 row from table `DUAL`. For example, I want to execute this query:
```
SELECT user
FROM DUAL
```
...and it'd have, like, 40 records. But I need only one record. ...AND, I want to make it happen without a `WHERE` clause.
I need something in the table\_name field such as:
```
SELECT FirstRow(user)
FROM DUAL
``` | 2012/01/19 | [
"https://Stackoverflow.com/questions/8919481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037298/"
] | You use ROWNUM.
ie.
```
SELECT user FROM Dual WHERE ROWNUM = 1
```
<http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm> | More flexible than `select max()` is:
```
select distinct first_row(column_x) over (order by column_y,column_z,...) from Table_A
``` |
24,408,002 | Scenario:
I want to execute multiple `Drools` flow one after another.
That is, I've one input, I'll pass it to on my first DRL/XLS file. Output of this first flow will act as input to second DRL.
My question is, does DROOLS have the facility to execute one flow after another in sequence. If so, how?
Till now, I'm guessing to do it via Java code only, which I want to avoid.
Thank You | 2014/06/25 | [
"https://Stackoverflow.com/questions/24408002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433826/"
] | Try using ruleflow diagrams. In which you have the luxury of using sub process. With this feature you can create a master flow that will call sub flows and in those sub flows you can have your rules tagged under particular ruleflow groups. If you could tell the scenario exactly I can provide in depth answer. Thanks. | You could tag both of your DRL files with `agenda-group "SomeGroupName"`. Your first DRL file could have a trigger rule that activates the second agenda-group. |
46,755,568 | Trying to use the new cypress framework with a maven project - the documentation has only an npm module setup example (npm install cypress) and a package.json usage example.
How would this be converted to usage in a maven dependency? | 2017/10/15 | [
"https://Stackoverflow.com/questions/46755568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6900033/"
] | You can also download Cypress directly without `npm`.
There are instructions as well as the direct download [here](https://on.cypress.io/installing-cypress#Direct-Download). | Here's a [great article](https://www.wimdeblauwe.com/blog/2019/2019-06-15-running-cypress-tests-with-testcontainers-for-a-spring-boot-with-thymeleaf-application/) on using maven to run Cypress tests.
You should be able to use a [Docker container](https://hub.docker.com/u/cypress) for Cypress via the maven [Testcontainers](https://www.testcontainers.org/) plugin. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.