text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How can I remove all the duplicate rows including the original one in SQL?
I have a table like this:
id id2
1 435
2 345
3 345
4 567
5 456
6 987
7 987
Here in id2 345 and 987 are repeating twice, so I want to delete both the rows. My new table should look like this:
id id2
1 435
4 567
5 456
A:
You can remove them from a select just by using aggregation:
select min(id), id2
from t
group by id2
having count(*) = 1;
If you want to remove them from the table, use join and group by:
delete t
from t join
(select id2, count(*) as cnt
from t
group by id2
) tt
on t.id2 = tt.id2
where cnt > 1;
| {
"pile_set_name": "StackExchange"
} |
Q:
I got a array contains integers like 737511, how do I convert every integer in that array into date like 2020-03-27
In python, I got an array that contains integers like 737511, it's supposed to mean 2020-03-27 (March 27th, 2020). How do I convert that integer into 2020-03-27? The left column is the array I want, the right column is the array I got.
2020-03-16 737502
2020-03-17 737503
2020-03-18 737504
2020-03-19 737505
2020-03-20 737506
2020-03-23 737507
2020-03-24 737508
2020-03-25 737509
2020-03-26 737510
2020-03-27 737511
When I do
timestamp = datetime.date.fromtimestamp(1585300000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
I got 2020-03-27 which was correct.
But when I do
a = 733860
timestamp = datetime.date.fromtimestamp(a*1585300000/737511)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
I got 2019-12-27 but I want 2010-03-27.
A:
use datetime.date.fromordinal()
| {
"pile_set_name": "StackExchange"
} |
Q:
VB.NET match whole word and replace
I'm trying to replace a string with another but the problem is that the string is matching some other string partially.
For e.g. -
Dim x as String = "I am Soham"
x = x.Replace("am","xx")
After this replace I would only like the word am to replaced with xx but because my name also contains am its also getting replaced.
The value of x is I xx Sohxx. How can I stop this. Please help.
A:
Use Regex.Replace and use the regular expression \bam\b. In a regular expression \b means "word boundary".
| {
"pile_set_name": "StackExchange"
} |
Q:
C# GOF Pattern Examples
Are there any C# GOF design pattern examples? I Keep finding this site which does have examples, but the "C# Optimised" examples are only available when you purchase one of their products.
A:
There is a book called "Design Patterns in C#" by Steven John Metsker that gives examples in C# for the 23 classic GoF patterns.
Edit: On the "freely available online" side, there is a decent series on Code Project by this author.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement LastUpdate in NHibernate Entities?
I'm attempting to implement an automatic LastUpdate attribute to my NHibernate entities. I thought about using database triggers and then thought it better done in NHibernate. I am following this blog post as a guide.
My domain entity is:
public class Instrument : Entity, IAuditableEntity
{
public virtual string Name { get; set; }
public virtual string Symbol {get; set;}
public virtual ISet<BrokerInstrument> BrokerInstruments { get; set; }
public virtual bool IsActive { get; set; }
}
which inherits from
public abstract class Entity
{
public virtual int Id { get; set; }
public virtual int Version {get; private set;}
public virtual DateTime CreateDate { get; private set; }
public virtual DateTime UpdateDate { get; set; }
}
and here's the interface:
public interface IAuditableEntity
{
DateTime UpdateDate { get; set; }
}
My listener class:
public class CustomUpdateEventListener : DefaultSaveEventListener
{
protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
{
var entity = evt.Entity as IAuditableEntity;
if (entity != null)
{
ProcessEntityBeforeUpdate(entity);
}
return base.PerformSaveOrUpdate(evt);
}
internal virtual void ProcessEntityBeforeUpdate(IAuditableEntity entity)
{
entity.UpdateDate = DateTime.Now;
}
}
and my domain entity Instrument mapping file:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MooDB" namespace="MooDB" >
<class name="MooDB.Domain.Instrument,MooDB" table="instruments">
<id name="Id" column="instrumentId" unsaved-value="0">
<generator class="increment"></generator>
</id>
<version name="Version" column="version" type="integer" unsaved-value="0"/>
<property name="Symbol" column="symbol" type="string" length="10" not-null="false"/>
<property name="Name" column="`name`" type="string" length="30" not-null="false"/>
<property name="IsActive" column="isActive" type="bool" not-null="true" />
<set name="BrokerInstruments" table="brokerInstruments" generic="true" inverse="true">
<key column="instrumentId" />
<one-to-many class="MooDB.Domain.BrokerInstrument"/>
</set>
<property name="CreateDate" column="created" not-null="false" />
<property name="UpdateDate" column="lastUpdated" />
</class>
</hibernate-mapping>
My hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
... connection details snipped
<mapping assembly="MooDB"/>
<listener class="MooDB.Data.CustomUpdateEventListener, MooDB.Data" type="update" />
</session-factory>
</hibernate-configuration>
My solution builds fine but I am getting a FileNotFoundException when NHibernate tries to find the listner. My references are set up correctly and I have the right using statements, so I'm not sure why NHibernate can't find it. Here's the error from the log:
2012-01-15 15:26:12,911 [TestRunnerThread] ERROR
NHibernate.Util.ReflectHelper [(null)] - Could not load type
MooDB.Data.CustomUpdateEventListener, MooDB.Data.
System.IO.FileNotFoundException: Could not load file or assembly
'MooDB.Data' or one of its dependencies. The system cannot find the
file specified. File name: 'MooDB.Data'
Do you know what could be wrong?
Edit: I'm now getting the following SqlTypeException:
2012-01-15 17:06:37,302 [TestRunnerThread] ERROR NHibernate.AdoNet.AbstractBatcher [(null)] - Could not execute command: UPDATE instruments SET version = @p0, symbol = @p1, [name] = @p2, isActive = @p3, created = @p4, lastUpdated = @p5 WHERE instrumentId = @p6 AND version = @p7 System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
It seems that the code entity.UpdateDate = DateTime.Now; in ProcessEntityBeforeUpdate is not being run for some reason. Any ideas?
A:
It's looks like your's assembly name is wrong. try this:
<listener class="MooDB.Data.CustomUpdateEventListener, MooDB" type="update" />
| {
"pile_set_name": "StackExchange"
} |
Q:
difference between *b= *b+1 and *b++
I am trying to change the actual value of a and b in the main function. But when I use *b++ to increment the value of b. It is not working.
#include<iostream>
using namespace std;
int F(int *b,int *c ){
*b++;
*c++;
}
int main(){
int a=1 , b=2;
cout<<a<<" "<< b<<" ";
F(&a, &b);
cout<<a<<" "<< b;
}
but in 2nd Case, the code is working fine.
#include<iostream>
using namespace std;
int F(int *b,int *c ){
*b = *b+1;
*c = *c+1;
}
int main(){
int a=1 , b=2;
cout<<a<<" "<< b<<" ";
F(&a, &b);
cout<<a<<" "<< b;
}
Isn't *b++ and *b=*b+1 same?
A:
They are not the same, the first expression is just manipulating your pointer due to operator precedence.
*b++; // acts like *(b++)
This increments the pointer, then dereferences it. You need extra parentheses
(*b)++;
A:
Per https://en.cppreference.com/w/cpp/language/operator_precedence
++ has higher precedence than *b, so *b++ is *(b++)
+ has lower precedence than *b so *b+1 is (*b) + 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Rounding values up or down in C#
I've created a game which gives a score at the end of the game, but the problem is that this score is sometimes a number with a lot of digits after the decimal point (like 87.124563563566). How would I go about rounding up or down the value so that I could have something like 87.12?
Thanks!
A:
Use Math.Ceiling(87.124563563566) or Math.Floor(87.124563563566) for always rounding up or rounding down. I believe this goes to the nearest whole number.
A:
Try using Math.Round. Its various overloads allow you to specify how many digits you want and also which way you want it to round the number.
A:
To always round down to 2 decimal places:
decimal score = 87.126;
Math.Floor(score * 100) / 100; // 87.12
To always round up to 2 decimal places:
decimal score = 87.124;
Math.Ceiling(score * 100) / 100; // 87.13
| {
"pile_set_name": "StackExchange"
} |
Q:
Excluding some rows in Django queryset
When I want to exclude some data row, I used to use:
entry.object.filter(name__startwith='Tom').exclude(name='foo')
I want to give exclude conditions like below. Is it possible?
entry.object.filter(name__startwith='Tom').exclude(name=['bar','foo'])
Could you give me some solutions?
A:
To check if name is included in a list, use __in:
entry.object.filter(name__startwith='Tom').exclude(name__in=['bar','foo'])
Link to the docs.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I encourage remote employees to ask for help?
We've recently acquired a new developer who's working remotely with occasional visits.
The initial period of friction has passed, but they're still very reluctant to ask for help and would spend hours fighting a problem themselves before reaching out.
We're using Slack for quick communications and I've let them know multiple times that I'm available for questions night and day.
A:
Don't.
You're asking a subjective question - we don't have nearly enough information to provide an answer, but the inference I would draw is that the individual is reluctant to ask for help. You don't describe the efforts you've made to communicate that help is a desired & expected transaction, but I'm going to assume that you've done everything in your power to communicate that concept.
I'd infer that this individual is one of the people whose resume includes phrases like "self-starter". Someone who believes that by figuring out the problem on their own, they'll learn and be more valuable to the company. That learning leads to deeper understanding. You probably don't want to undermine these segments of their self-image - those are valuable traits and if they can be merged with the situation, both sides will benefit.
If encouraging the to ask for help were going to be effective, it would have been effective before this. If you keep encouraging them, then you're not learning from reality, you're trying to bend reality to your will.
What are your options? What incentive structures can you build that will lower the friction of asking for help?
You're going to have to reach out past that gap. Schedule a periodic call with the individual and ask probing questions like, "What are some obstacles that I could help clear? When do you expect to finish this task and is there anything we can do to accellerate that?
Listen carefully (I believe the Chinese word is Ti fong, but explaining why that is relevant would be an essay in and of itself). You're going to have to listen past what the individual is saying and inuit what they are feeling/thinking about the costs and benefits of "help". Sometimes it will involve directly asking, "Amy is an expert on that - want me to set up a 20 minute phone call for her to walk through that with you?" - but that probably won't work; there is a significant risk that the individual will hear, "Your performance is sub-par and I have to assign another employee to intervene." - that will cause them to double down on their self-image.
Find a way to introduce "asking for help" in a win-win context. But this has to be based on deep listening.
Re-allocate the time/tasks/work package estimates for this individual to account for this behavior. If you're good, you're going to be able to shift their behavior somewhat. But even if you're excellent it is going to take some time. Do this in communication with the developer - "I'm going to allocate an extra two weeks on each of these task since you need to teach yourself the skill. Please make use of the stack and of your peers who are doing this now. Next time we talk, let's discuss whether an extra two weeks/task is the right timeframe for you to figure it out on your own. If you think that I'm overestimating the time for you to learn it, or if the resources help you to deliver faster, that would look great for both of us. But I'm only going to adjust that delivery date based on actual deliverable - it would be really disastrous for both of us if the estimated delivery date fluctuated - neither of us would have any credibility going forward."
Listen. Reward every movement in the right direction. Listen carefully to every indication that "figure it out" is triumphing over "team player".
| {
"pile_set_name": "StackExchange"
} |
Q:
Uniform convergence of the series $\sum_{n=1}^\infty\frac{x}{(1+x)^n}$
I have to determine whether or not the series
$$\sum_{n=1}^\infty\frac{x}{(1+x)^n}$$
converges uniformly on $[0,1]$.
I attempted to use Weierstrass' M-Test, by finding the maxima of each $a_n$ which must exist by the maximum value theorem. The maxima turned out to be at $\dfrac{1}{n-1}$, and to be equal to $\dfrac{(n-1)^{n-1}}{n^n}$. The sum of these terms diverges, and hence I can't use Weierstrass' M-Test.
Now, I'm thinking of using Dini's Theorem since $[0,1]$ is compact, and seting $f_n(x)$ to be the $n$-th partial sum gives us a monotonic increasing sequence. So if I can find the pointiwse limit of this sequence, and verify it is continuous, I will be done.
Is this the right track? If it is, how would I compute the series?
A:
Note that as $N\to \infty$
$$\sum_{n=1}^{N}\dfrac{x}{(1+x)^n}=1-\frac{1}{(1+x)^{N}}\to
\begin{cases}0&\text{if $x=0$,}\\
1&\text{if $x>0$.}\end{cases}$$
So the pointwise limit function is not a continuous in $[0,a)$ with $a>0$. What may we conclude about the uniform convergence over such interval?
What happens over $[a,b]$ with $0<a<b$?
| {
"pile_set_name": "StackExchange"
} |
Q:
Write a RGBA8 image as a R32UI
I have an image with the format R8G8B8A8 (Unorm).
I want to write uint data on it (to be able to use atomic function).
So, when I want to "write" it, I am using in the glsl :
layout(set = 0, binding = 2, r32ui) restrict writeonly uniform uimage3D dst;
However, when I am performing something like
imageStore(dst, coords, uvec4(0xffffffff));
RenderDoc (and my app as well) tells me that all my values are 0 (instead of 1.0 (255 unorm)).
If I replace the r32ui by rgba8 everything works fine but I can not use atomic values. So I wonder if it is possible to do such thing. (However, if I use a r32f instead of rgba8, it works fine as well).
Do you have any solution?
A:
Vulkan specification guarantees that atomic operations must be supported for storage images (VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT) with only R32_UINT and R32_SINT formats. Implementations may add such support for other formats as well but it's not obligatory. So it's nothing strange that atomic operations don't work with rgba8 format.
Next. You can create an image view with a different format than the format of the image. In such case the image view's format must be compatible with the image's format. In case of the R8G8B8A8 format, both SINT and UINT R32 formats are compatible (have the same number of bits). But to be able to create an image view with a different format, image itself must be created with a VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT flag.
One last thing - there is a note in the specification about format compatibility/mutable images:
Values intended to be used with one view format may not be exactly
preserved when written or read through a different format. For
example, an integer value that happens to have the bit pattern of a
floating point denorm or NaN may be flushed or canonicalized when
written or read through a view with a floating point format.
Similarly, a value written through a signed normalized format that has
a bit pattern exactly equal to -2^b may be changed to -2^b + 1 as
described in Conversion from Normalized Fixed-Point to Floating-Point.
Maybe this is the problem? Though it seems that there should be no conversion between rgba8 (unorm) and r32 (uint). Did validation layers report any warnings or errors? What layout is Your image in when You try to store data in it? Don't forget that:
Load and store operations on storage images can only be done on images
in the VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR or VK_IMAGE_LAYOUT_GENERAL
layout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Gradle Compilation Errors when adding 'com.amazonaws:aws-android-sdk-core:2.2.+'
I am running Android Studio, and my app has been running perfectly until I added the following dependencies to my gradle file:
compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-cognito:2.2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.+
These caused the following warnings when rebuilding the project:
Note: Some input files use or override a deprecated API.
Note: com.google.android.gms.internal.zzlh accesses a declared method 'getInstance()' dynamically
Maybe this is program method 'android.support.design.widget.SnackbarManager { android.support.design.widget.SnackbarManager getInstance(); }'
Maybe this is program method 'android.support.v4.content.SharedPreferencesCompat$EditorCompat { android.support.v4.content.SharedPreferencesCompat$EditorCompat getInstance(); }'
Maybe this is program method 'android.support.v4.text.BidiFormatter { android.support.v4.text.BidiFormatter getInstance(); }'
Maybe this is program method 'android.support.v7.app.TwilightCalculator { android.support.v7.app.TwilightCalculator getInstance(); }'
Maybe this is program method 'com.amazonaws.metrics.MetricCollector$Factory { com.amazonaws.metrics.MetricCollector getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitoidentity.model.transform.CredentialsJsonUnmarshaller { com.amazonaws.services.cognitoidentity.model.transform.CredentialsJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitoidentity.model.transform.GetCredentialsForIdentityResultJsonUnmarshaller { com.amazonaws.services.cognitoidentity.model.transform.GetCredentialsForIdentityResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitoidentity.model.transform.GetIdResultJsonUnmarshaller { com.amazonaws.services.cognitoidentity.model.transform.GetIdResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitoidentity.model.transform.GetOpenIdTokenResultJsonUnmarshaller { com.amazonaws.services.cognitoidentity.model.transform.GetOpenIdTokenResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.DatasetJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.DatasetJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.DeleteDatasetResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.DeleteDatasetResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.DescribeDatasetResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.DescribeDatasetResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.ListDatasetsResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.ListDatasetsResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.ListRecordsResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.ListRecordsResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.RecordJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.RecordJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.RegisterDeviceResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.RegisterDeviceResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.SubscribeToDatasetResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.SubscribeToDatasetResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.UnsubscribeFromDatasetResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.UnsubscribeFromDatasetResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.cognitosync.model.transform.UpdateRecordsResultJsonUnmarshaller { com.amazonaws.services.cognitosync.model.transform.UpdateRecordsResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.AttributeDefinitionJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.AttributeDefinitionJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.AttributeValueJsonMarshaller { com.amazonaws.services.dynamodbv2.model.transform.AttributeValueJsonMarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.AttributeValueJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.AttributeValueJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.BatchGetItemResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.BatchGetItemResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.BatchWriteItemResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.BatchWriteItemResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.CapacityJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.CapacityJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.ConsumedCapacityJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.ConsumedCapacityJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.CreateTableResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.CreateTableResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.DeleteItemResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.DeleteItemResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.DeleteRequestJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.DeleteRequestJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.DeleteTableResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.DeleteTableResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.DescribeTableResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.DescribeTableResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.GetItemResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.GetItemResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.GlobalSecondaryIndexDescriptionJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.GlobalSecondaryIndexDescriptionJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.ItemCollectionMetricsJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.ItemCollectionMetricsJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.KeySchemaElementJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.KeySchemaElementJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.KeysAndAttributesJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.KeysAndAttributesJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.ListTablesResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.ListTablesResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.LocalSecondaryIndexDescriptionJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.LocalSecondaryIndexDescriptionJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.ProjectionJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.ProjectionJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.ProvisionedThroughputDescriptionJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.ProvisionedThroughputDescriptionJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.PutItemResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.PutItemResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.PutRequestJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.PutRequestJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.QueryResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.QueryResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.ScanResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.ScanResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.StreamSpecificationJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.StreamSpecificationJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.TableDescriptionJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.TableDescriptionJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.UpdateItemResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.UpdateItemResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.UpdateTableResultJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.UpdateTableResultJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.dynamodbv2.model.transform.WriteRequestJsonUnmarshaller { com.amazonaws.services.dynamodbv2.model.transform.WriteRequestJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.s3.util.Mimetypes { com.amazonaws.services.s3.util.Mimetypes getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.AssumeRoleResultStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.AssumeRoleResultStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.AssumeRoleWithWebIdentityResultStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.AssumeRoleWithWebIdentityResultStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.AssumedRoleUserStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.AssumedRoleUserStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.CredentialsStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.CredentialsStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.FederatedUserStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.FederatedUserStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.GetFederationTokenResultStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.GetFederationTokenResultStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.services.securitytoken.model.transform.GetSessionTokenResultStaxUnmarshaller { com.amazonaws.services.securitytoken.model.transform.GetSessionTokenResultStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$BigDecimalJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$BigDecimalJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$BigIntegerJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$BigIntegerJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$BooleanJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$BooleanJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$ByteBufferJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$ByteBufferJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$ByteJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$ByteJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$DateJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$DateJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$DoubleJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$DoubleJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$FloatJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$FloatJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$IntegerJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$IntegerJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$LongJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$LongJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeJsonUnmarshallers$StringJsonUnmarshaller { com.amazonaws.transform.SimpleTypeJsonUnmarshallers$StringJsonUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$BigDecimalStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$BigDecimalStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$BigIntegerStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$BigIntegerStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$BooleanStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$BooleanStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$ByteBufferStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$ByteBufferStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$ByteStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$ByteStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$DateStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$DateStaxUnmarshaller getInstance(); }'
Maybe this is program method 'com.amazonaws.transform.SimpleTypeStaxUnmarshallers$DoubleStaxUnmarshaller { com.amazonaws.transform.SimpleTypeStaxUnmarshallers$DoubleStaxUnmarshaller getInstance(); }'
Preparing output jar [F:\IcyGo-v2.6\app\build\intermediates\multi-dex\debug\componentClasses.jar]
Copying resources from program jar [F:\IcyGo-v2.6\app\build\intermediates\transforms\jarMerging\debug\jars\1\1f\combined.jar]
:app:transformClassesWithDexForDebug
UNEXPECTED TOP-LEVEL ERROR:
java.lang.OutOfMemoryError: GC overhead limit exceeded
at com.android.dx.cf.cst.ConstantPoolParser.parseUtf8(ConstantPoolParser.java:371)
at com.android.dx.cf.cst.ConstantPoolParser.parse0(ConstantPoolParser.java:262)
at com.android.dx.cf.cst.ConstantPoolParser.parse0(ConstantPoolParser.java:323)
at com.android.dx.cf.cst.ConstantPoolParser.parse0(ConstantPoolParser.java:309)
at com.android.dx.cf.cst.ConstantPoolParser.parse(ConstantPoolParser.java:150)
at com.android.dx.cf.cst.ConstantPoolParser.parseIfNecessary(ConstantPoolParser.java:124)
at com.android.dx.cf.cst.ConstantPoolParser.getPool(ConstantPoolParser.java:115)
at com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:482)
at com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)
at com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)
at com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)
at com.android.dx.command.dexer.Main.parseClass(Main.java:764)
at com.android.dx.command.dexer.Main.access$1500(Main.java:85)
at com.android.dx.command.dexer.Main$ClassParserTask.call(Main.java:1684)
at com.android.dx.command.dexer.Main.processClass(Main.java:749)
at com.android.dx.command.dexer.Main.processFileBytes(Main.java:718)
at com.android.dx.command.dexer.Main.access$1200(Main.java:85)
at com.android.dx.command.dexer.Main$FileBytesConsumer.processFileBytes(Main.java:1645)
at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
at com.android.dx.command.dexer.Main.processOne(Main.java:672)
at com.android.dx.command.dexer.Main.processAllFiles(Main.java:569)
at com.android.dx.command.dexer.Main.runMultiDex(Main.java:366)
at com.android.dx.command.dexer.Main.run(Main.java:275)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 3
And here is my complete gradle.build file (app level):
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.myapp.myapp"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "31.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile project(':swipelistview')
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.google.android.gms:play-services-base:6.5.87'
compile 'com.github.nkzawa:socket.io-client:0.3.0'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.google.android.gms:play-services-location:7.5.0'
compile 'com.github.amlcurran.showcaseview:library:5.0.0'
compile 'com.baoyz.swipemenulistview:library:1.3.0'
compile 'com.github.orangegangsters:swipy:1.2.0@aar'
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.google.android.gms:play-services-cast:7.5.0'
compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-cognito:2.2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.+'
}
I think the issue is due to using 'com.google.android.gms:play-services:8.4.0', as in the demo project they used 'com.google.android.gms:play-services:6.1.+', and that demo project is running perfectly.
Thing is, I cannot downgrade my app to use 'com.google.android.gms:play-services:6.1.+'.
Any suggestions or help is highly appreciated in this matter.
A:
Thanks to god, I ultimately found the solution. The cause behind the error was GC overhead limit exceeded Amazon AWS library contains a huge number of methods, that causes java.lang.OutOfMemoryError while compiling.
The solution is to add
dexOptions {
javaMaxHeapSize "4g"
}
and
defaultConfig {
applicationId "com.example.app"
minSdkVersion 15//use any version as needed by you
targetSdkVersion 23//use any version as needed by you
versionCode 1//your own version code
versionName "1.0"//your own versionName
multiDexEnabled true//required
}
this to your app level build.gradle file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Win7 : plink.exe: No such file or directory
I can
git add.
git commit -m "first commit"
but cannot push
git push -u origin master
error:
cannot spawn C:\Users\SEB\Downloads\plink.exe: No such file or
directory fatal: unable to fork
A:
First ensure that you have an installed plink.exe. I recommend to install it to Program Files because your folder C:\Users\SEB\Downloads\ is a bad place.
Then check your environment variable GIT_SSH. It should be something like:
GIT_SSH=%ProgramFiles(x86)%\PuTTY\plink.exe
or
GIT_SSH=%ProgramFiles%\PuTTY\plink.exe
This error also happened when there is a space in the GIT_SSH environment variable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Database does not exist error
When I take a database backup I get an error that the database does not exist, but I can attach the database fine and other processes like data insert and update work fine. But when I take a database backup it gives the error below.
I show the error screen shot and the backup button code
string cnstr="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\fees_data.mdf;Integrated Security=True;User Instance=True;"
SqlConnection connect;
connect = new SqlConnection(cnstr);
connect.Open();
if (txtdname.Text == "")
{ dname = "Default.bak"; }
else
{ dname = txtdname.Text + ".bak"; }
SqlCommand command;
command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
command.ExecuteNonQuery();
connect.Close();
When I click the backup button I get the error:
"Database 'fees_data' does not exist. Make sure that the name is entered correctly.
BACKUP DATABASE is terminating abnormally."
A:
The database name might not be the same as the .mdf file name.
What results do you get when running this query ?
select name from sys.databases;
Use the correct name from there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Chrome does not open
When I click on the Google Chrome icon from the launcher it does not open. I tried searching in the dash and clicking on its icon but it does not open at all.
I tried the terminal as well, like this:
$ google-chrome
and this is the output:
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_long_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_long_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_long_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_long_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_string_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_get_for_screen: assertion `GDK_IS_SCREEN (screen)'
failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_get_for_screen: assertion `GDK_IS_SCREEN (screen)'
failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_prepend_search_path: assertion `GTK_IS_ICON_THEME
(icon_theme)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_get_for_screen: assertion `GDK_IS_SCREEN (screen)'
failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_prepend_search_path: assertion `GTK_IS_ICON_THEME
(icon_theme)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_get_for_screen: assertion `GDK_IS_SCREEN (screen)'
failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_icon_theme_prepend_search_path: assertion `GTK_IS_ICON_THEME
(icon_theme)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_string_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_string_property: assertion `GTK_SETTINGS
(settings)' failed
(google-chrome:19866): Gtk-CRITICAL **:
IA__gtk_settings_set_string_property: assertion `GTK_SETTINGS
(settings)' failed
[19866:19866:0426/060718:ERROR:process_singleton_linux.cc(239)]
readlink(/home/omar/.config/google-chrome/SingletonLock) failed:
Invalid argument
[19866:19866:0426/060718:ERROR:process_singleton_linux.cc(239)]
readlink(/home/omar/.config/google-chrome/SingletonLock) failed:
Invalid argument
[19866:19866:0426/060718:ERROR:process_singleton_linux.cc(263)] Failed
to create /home/omar/.config/google-chrome/SingletonLock: File exists
[19866:19866:0426/060718:ERROR:process_singleton_linux.cc(239)]
readlink(/home/omar/.config/google-chrome/SingletonLock) failed:
Invalid argument
[19866:19866:0426/060718:ERROR:chrome_browser_main.cc(1157)] Failed to
create a ProcessSingleton for your profile directory. This means that
running multiple instances would start multiple browser processes
rather than opening a new window in the existing process. Aborting now
to avoid profile corruption.
A:
OVERVIEW
When google-chrome starts a session it creates some files under ~/.config/google-chrome and delete them when they are not in use anymore.
It is possible that some of these files remain there (because of some crash or upgrade or... whatever...). Then, when you try to run google-chrome it "thinks" that there is another active instance running and doesn't run the program (I'm assuming that you had verified in the list of processes that are no running instances of google-chrome).
SOLUTION
In this case, the basic solution is rename or delete these files, "SingletonLock", "SingletonCookie" and "SingletonSocket", and run google-chrome again. It will create these three files again and will run normally.
A:
If you don't find the Singleton* files discussed in other answers, another source of this error is exhaustion of disk space.
Try df -h to see how much space you have left on your partitions; if any are full, free up some space and try again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift - Duplicate UIView
I'm currently trying to achieve a Shimmer effect in Swift. To do that I create a gray UIView, and another on top of it with an effect.
The problem is that I'm writing the same code twice...
let profileShimmerView = UIView()
profileShimmerView.backgroundColor = whiteClear
profileShimmerView.layer.cornerRadius = 20
profileShimmerView.clipsToBounds = true
let profileView = UIView()
profileView.backgroundColor = grayClear
profileView.layer.cornerRadius = 20
profileView.clipsToBounds = true
self.addSubview(profileView)
self.addSubview(profileShimmerView)
profileShimmerView.translatesAutoresizingMaskIntoConstraints = false
profileShimmerView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 45).isActive = true
profileShimmerView.topAnchor.constraint(equalTo: self.topAnchor, constant: 15).isActive = true
profileShimmerView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileShimmerView.heightAnchor.constraint(equalToConstant: 40).isActive = true
profileView.translatesAutoresizingMaskIntoConstraints = false
profileView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 45).isActive = true
profileView.topAnchor.constraint(equalTo: self.topAnchor, constant: 15).isActive = true
profileView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileView.heightAnchor.constraint(equalToConstant: 40).isActive = true
Is there a more simple way to achieve that?
A:
You can create a function
func shared(color : UIColor)->UIView {
let v = UIView()
v.backgroundColor = color
v.layer.cornerRadius = 20
v.clipsToBounds = true
self.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
v.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 45),
v.topAnchor.constraint(equalTo: self.topAnchor, constant: 15),
v.widthAnchor.constraint(equalToConstant: 40),
v.heightAnchor.constraint(equalToConstant: 40)
])
return v
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Least Squares: Derivation of Normal Equations with Chain Rule
I'm new to Stackexchange so please bear with me. I'm struggling
with the least squares formula. Now Wikipedia does show ways
to derive the "normal equations".
But I'd like to get the same result using the Chain Rule.
Which would be something like this (I don't know if it's possible for matrices,
since I haven't seen this approach anywhere yet):
$$(y - Xb)^2$$
and differentiating it with respect to $b$, which would be something like:
$$2(y - Xb) * (-X)$$
It seems though, that a transpose sign is missing somewhere, since
the formula should look as follows:
$$ \mathbf{-X}^{\rm T} \mathbf y+ (\mathbf X^{\rm T} \mathbf X ){\boldsymbol{b}}$$
Please help me to correct this or point out if I'm totally wrong.
A:
Instead of $m\!\times\!1$ and $n\!\times\!1$ vectors for $y$ and $b$, it might be easier to consider $m\!\times\!p$ and $n\!\times\!p$ matrices.
Then the quantity to minimize is $f = \|Y-X\!\cdot\!B\|^2_F = \|M\|^2_F$
Rewriting this to use the Frobenius product, $f = M:M$, makes taking the derivative easier. Here it is step by step.
$$ \eqalign {
df &= 2M:dM \cr
&= 2M:d(Y-X\!\cdot\!B) \cr
&= 2M:(-X\!\cdot\!dB) \cr
&= 2(Y-X\!\cdot\!B):(-X\!\cdot\!dB) \cr
&= 2(X\!\cdot\!B-Y):X\!\cdot\!dB \cr
&= 2X^T\!\cdot(X\!\cdot\!B-Y):dB \cr
}$$
So the derivative with respect to $B$ is
$$ \eqalign {
\frac {\partial f} {\partial B} &= 2X^T\!\cdot(X\!\cdot\!B-Y) \cr
}$$
Equating it to zero yields the normal equations.
The step you are questioning is how $X$ gets transposed. In the last step of the derivation, we used
$$ \eqalign {
A:X\cdot\!B &= X^T\!\cdot\!A:B \cr
}$$
to move $X$ to the other size of the Frobenius product. Since the Frobenius product is really just a trace operation, it's easy to prove that
$$ \eqalign {
A:X\cdot\!B &= \text{tr}(A\!\cdot(X\cdot\!B)^T) \cr
&= \text{tr}(A\!\cdot\!B^T\!\cdot\!X^T) \cr
&= \text{tr}(X^T\!\cdot\!A\!\cdot\!B^T) \cr
&= X^T\!\cdot\!A:B \cr
}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Proper handling of foreign characters / emoji
Having trouble getting foreign characters and Emoji to display.
Edited to clarify
A user types an Emoji character into a text field which is then sent to the server (php) and saved into the database (mysql). When displaying the text we grab a JSON encoded string from the server, which is parsed and displayed on the client side.
QUESTION: the character for a "trophy" emoji saved in the DB reads as
%uD83C%uDFC6
When that is sent back to the client we don't see the emoji picture, we actually see the raw encoded text.
How would we get the client side to read that text as an emoji character and display the image?
(all on an iphone / mobile safari)
Thanks!
A:
the character for a "trophy" emoji saved in the DB reads as %uD83C%uDFC6
Then your data are already mangled. %u escapes are specific to the JavaScript escape() function, which should generally never be used. Make sure your textarea->PHP handling uses standards-compliant encoding, eg encodeURIComponent if you need to get a JS variable into a URL query.
Then, having proper raw UTF-8 strings in your PHP layer, you can worry about getting MySQL to store characters like the emoji that are outside of the Basic Multilingual Plane. Best way is columns with a utf8mb4 collation; if that is not available try binary columns which will allow you to store any byte sequence (treating it as UTF-8 when it comes back out). That way, however, you won't get case-insensitive comparisons.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to cut off helping an old job, colleague, friend?
So I just recently resigned from my position as an IT manager. I will be starting my new position tomorrow. I believe I left on good terms with the president of the company. And I do not want to burn any bridges, as I would like to use them as a reference in the future.
When I resigned I offered to help out the next IT manager on evenings or weekends, as there is a lot to learn and he/she would not be hired before I left.
Unfortunately, the president hired my assistant to replace me. I was not consulted and I believe it was a bad idea. He is a smart guy, but he does not have the knowledge or experience to do the position. I believe she hired him because he can be paid a cheap salary. They are a very cheap company. But that's irrelevant.
The day after I resigned, a pipe burst in the server room and destroyed several important servers. Fortunately, I have the data backed up remotely, but they are down for now. He has been calling my asking for advice for the last two days and I know its going to happen some more until they get this resolved. I'm so glad I was out of there before this happened.
I want to help out, since I said I would. But I don't want to do it forever. I want to keep a positive relationship with the old company. I also want to keep a positive relationship with my old assistant, as I consider him a friend.
The problem is, how do I maintain these relationships? I have a bad feeling that they/he will continue to call me asking for help and advice.
A:
If that is something you would consider, tell them that you will be glad to help for a fee and name your price. One should never ever work for free.
A:
If they're just asking your advice and it's not taking up a lot of your time, then continue to respond - after at least 24 hours have elapsed.
Since they're not paying you, they can't really complain if you don't respond on the same day. A next-business-day response is still more than generous on your part.
(Set your phone so that their calls automatically go to voicemail without ringing).
Giving them a day to think about it will likely mean that they've started to solve the problem before they hear back from you, so it'll wean them off contacting you every time they have a problem.
If they actually ask you to go in to the office (or log in remotely) and do the work, as opposed to merely offering advice, then it's time to tell them you'll do it, but at your hourly/daily consulting rate (this should be at least double what they were paying you before).
| {
"pile_set_name": "StackExchange"
} |
Q:
Filtering the good homework from the bad
You all know the problem, trying to eliminate the bad homework stuff and keep the good.
I code off and on and my personal website has a filter on every input box to eliminate the stuff I don't want to see on the comments, the usual limitations...language, abuse, etc.
My suggestion is as follows (I can't find a duplicate of it. I am only here 10 days so please be nice in your comments and replies. Thanks.):
Kids come onto the sites from any page so target the question boxes.
Install a filter that spots obvious phrases like "My teacher says I have to have this...", etc.
When these phrases are spotted, produce a popup that stresses the homework policy again and scares them (a little) with it. Make it more kid-oriented and suggest a list of kid-based sites that they could go to.
Stop the "Can you do this straight away part" by telling them that the question will be reviewed for quality and there will be a one week delay period before an answer.
Then, after the question is written, analyse the wording of the question for the common bad homework phrases using the filter and if they occur then shunt those questions into a review area, so that it's NOT immediately added to the list of questions, and it really does have to wait a week.
So for example, if the phrase "in your opinion" came up in a physics question, then it would be flagged straightaway.
If it is a bad question, then send out the standard line about "it will not be answered" and then delete it.
This above part seems easy (to me) to do with a few bits of whatever code integrates with the underlying Stack Exchange code). Is it that easy, you tell me, I don't know the Stack Exchange code foundations.
Now you want to keep the good questions. The more advanced kids will know to stick to their guns and stay here and they are the ones you WANT to stay here. Maths.SE must have the same (if not worse) problem and between the population of physics and maths users there must be enough talent to produce all sorts of correlation code between phrases used in good questions. The data exists and the system can be tweaked as more homework stuff comes in.
Funnel the good homework stuff for manual review and then release them to the users.
It can't cater for all kids, but what's the current rate of unanswered kids' questions now anyway?
That's it. My question is (because I havn't enough experience of the site yet), is it doable?
A:
Firstly, thanks for your time in sending me the above. Believe it or not, we are at one on this, despite the way I composed my question. I edited my post based on some of the comments I got and some more reading on the subject. The first draft was much more student friendly, I think.
Just hear me out for a minute.
I'm a complete self study person in quantum physics (no university contact at all) who has learned more about how real science works (and some science people really behave towards each other!) in the last 10 days from this site than I ever imagined.
Think Robinson Crusoe teleported to NYC, and you will get the idea
I do 100% agree with your last paragraph. I have given lots of tutorials, and I deal with the online student exactly the same way as at my home, trying to get them to keep asking me questions and then think it through themselves as far as they could until the next hint.
The reason I posted the question was because I was absolutely furious at the way one particular student was treated by a "teacher" who either could not care less about the student or was too tired or, I don't know basically had a bad day and should have ignored the post if they could not handle it. I know, I should have flagged it, but I didn't.
That student is now going to stay off physics, for a while anyway, because he/she was shouted at, basically. It made me mad, because I could see he/she had potential.
Then I saw lots of posts about "too many bad homework questions", "should we ban homework", etc., and I thought: if the students are getting bad answers partially because of too many bad questions stressing the "teachers" out, could I think of a way of removing that stress by shunting the bad questions away from them in the way described in my post and then see what people with more experience than me had to say.
OK, it's not doable (the Stack Exchange site is way too complex and way too big, but I didn't realise that until this post), and it's time to move on...there is no easy way to avoid bad questions preventing the "teachers" from occasionally dealing badly with the students (or from some students behaving badly). It's just that I never in my tutorials treated the students in any way, but the best way I could. You really would go a long way to help a student that shows academic promise; it could change their whole life. I'm telling you what you know already here, sorry!
To wind up, the existing scheme on Stack Exchange is the best we have. Most students get treated with patience, some students just want the easiest way out and don't get the long term picture of understanding being the goal, not just rote, and unfortunately some just get unlucky with their "teacher".
And, worst of all IMO, some students submitting homework in a badly presented way because of real pressure from their parents that they will be a failure if they don't win the Nobel prize. Pretty sure you have come across this in some way yourself.
Sorry about the "kids" rather than students reference, but I have done enough tutorials by now (I'm 54) that it's just a habit that I carried from my real life tutorials, answering the OP, especially if it's a basic question, as well, a kid!
That's basically it, question answered and closed, and I will delete it as well.
BTW, I'm Irish (as you might already have guessed!) so I'm constitutionally obliged to wish you a happy St. Patrick’s Day.
Best regards and thanks again for your post.
A:
I understand your passion to resolve a problem, or even alleviate it a bit, and this is of course always welcomed.
But sometimes a problem cannot be captured as it is happening, or it is not worth the resources to do so.
Often, problems simply require a post fix - in this case community moderation - and as we have a strong community moderation system already setup, it's probably much more efficient to utilise that.
(Note, in this answer I state "frequency of problem" not "frequency of homework questions" - some are ok)
Not worthwhile
Install a filter that spots obvious phrases like "My teacher says I have to have this...." etc.
Given:
W% of users won't post any phrase at all
X% of users will ignore any/all warnings
Y% potential false positives catered for (to avoid wrongly
moderating users)
Z% frequency of the problem this attempts to resolve
I just don't see this being worthwhile as we'd have a complex set of algorithms to try to catch the "odd" question here and there.
Warn them, tell them, tell them again, plead with them...
When these phrases are spotted, produce a popup that stresses the HW
policy again
How many levels deep does one go before we give up and say "this user is never going to adhere to the rules, read the rules, or care"?
They are warned, the rules are clear and readily available.
If they got that far, and post what you consider a "bad homework question", then they will be told in comments.
If they do not edit/fix their question from warnings in comments, then this user is unable to be cleansed of their demons.
You could show them 10 warnings, ranging from "Please change this question" to "pretty please" to "We know where you live...".
You just can't tell, persuade, or educate some people. They simply cannot be bothered/don't care.
You give them the info, once, and if they choose to ignore it, then they lose a potential fantastic answer from a professional.
We're here to advise, help where help will be taken, but we're not here to hold everyone's hand who is not willing to put in some pre effort or have a little humility and resolve an issue they are post made aware of.
Either way, I think the current path and entire process is adequate.
We already have community moderation, and while these problems are annoying, and a solution would be great, it's only closing a few bad homework questions and this proposal is too "meaty".
One week answer delay
Stop the "Can you do this straight away part" by telling them that the
question will be reviewed for quality and there will be a one week
delay period before an answer.
No idea what this aims to resolve or help with.
Maybe I've misunderstood it. (?)
As I understand it:
With a "one week answer delay", where does the question "wait"? In that time it'll be pushed so far down the list, page X depending on the tags - i.e. PHP tag probs > 1000 pages. So they'll never get an answer anyway.
Also, this is not how Stack works. It's (almost) as simple as:
If the question is not acceptable, close it
If the question is acceptable, answer it
Use of resources
This will be a lot of time spent discussing, implementing, testing, maintaining and most certainly tweaking given the likely false positives that will arise.
It won't be easy to roll out a perfect system, and also given the plethora of potential word combinations where some are from the bad list and some not, not every scenario can be pre established, and not every false positive can initially be accounted for.
It really is a potential minefield.
If we were getting 10 "bad" homework questions "per hour" then perhaps this might be looked at.
But even then it would likely be something much more simple than this proposal, just a quick and dirty way to "slow them down a bit".
Alternative use of resources
I'd much rather we had some new systems and time spent on making some of the "general" bad questions go away.
The homework questions can come through thick and fast after term holidays end etc, but they are not exactly a serious issue.
And I'd rather forgive a teenager for being, well, a teenager*, and help them if they say "sorry I'll edit my question" than the lazy bone idle people who post poor, lazy, no code, questions, and ignoring the comments of people telling them as such, as they know someone will answer them anyway.
* I mean no insult - I have an 18 YO step son doing Engineering degree/A levels, and know how hard it is, often a lot of info, and sometimes they are desperate for some help they don't think about pleasantries.
This does not excuse it, but I give "kids" as you put it a little more leeway than "adults" who should be more mature.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error with dynamic json array in php
I have an application that retrieves data from a mysql database and generates a json output with php to send to a plugin.
I'm generating the following json output from php:
{
"mapwidth":"1300",
"mapheight":"1000",
"categories":"[]",
"levels":{
"id":"lots",
"title":"Lots",
"map":"maps\/lot-map.svg",
"minimap":"",
"locations":[
{
"id":"lot1",
"title":"Lot 1",
"pin":"hidden",
"description":"<p>Status: <b style=\\\"color: #8eba5e;\\\">Available<\/b><br>Size:\u00a0<b>850 sqm<\/b><br>Please get in touch for an Offer.<\/p>",
"link":null,
"x":"0.4849",
"y":"0.4629",
"fill":null,
"category":"false",
"action":"tooltip"
}
]
},
"maxscale":"1.8"
}
But the format is incorrect. Should be like the following tested json file:
{
"mapwidth": "1300",
"mapheight": "1000",
"categories": [],
"levels": [
{
"id": "lots",
"title": "Lots",
"map": "maps/lot-map.svg",
"minimap": "",
"locations": [
{
"id": "lot12",
"title": "Lot 12",
"pin": "hidden",
"description": "<p>Status: <b style=\"color: #8eba5e;\">Available</b><br>Size: <b>850 sqm</b><br>Please get in touch for an Offer.</p>",
"link": "#more",
"x": "0.3726",
"y": "0.4565"
}
]
}
],
"maxscale": 1.8
}
The difference is in the "levels" key.
This is my php code:
$results = array(
'mapwidth' => '1300',
'mapheight' => '1000',
'categories' => '[]'
);
$results['levels'] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
if ($lotes)
{
// build usable array
foreach($lotes['results'] as $lote)
{
$results['levels']['locations'][] = array(
'id' => $lote['slug'],
'title' => $lote['title'],
'pin' => $lote['pin'],
'description' => $lote['description'],
'link' => $lote['link'],
'x' => $lote['position_x'],
'y' => $lote['position_y'],
'fill' => $lote['fill'],
'category' => $lote['category'],
'action' => $lote['action']
);
}
}
else
$results['error'] = lang('core error no_results');
$results['maxscale'] = '1.8';
// display results using the JSON formatter helper
display_json($results);
Any suggestions? Thanks
A:
You need to make the levels a multidimensional array.
$results['levels'] = array();
$results['levels'][0] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
Then when you append to do, do it as follows:
$results['levels'][0]['locations'][] = array(
| {
"pile_set_name": "StackExchange"
} |
Q:
Do you send automatic weekly reports about status of your server?
I am working on redoing a weekly report, I send, to anyone on our development team.
The previous version just sent sql server based scheduled jobs status, backup status, and database size.
But for this new version, will have more information from every part of our server.
Coldfusion:
Verify Main Datasource
List Scheduled Tasks
Server Version
Undelivered Mail
IIS:
Current Connection Count
SQL Server:
Database Size
Drive Space % LEft
Last Backup Date
So what I am asking about is two things.
(1) What other essential must have information, would be useful to have/see on a weekly basis via email?
(2) How to best present or display that information, that looks professional, albeit inside an html email, without looking like eye candy? Because right now i just have a simple bullet list of server aspect and statuses. I want to make it look really professional.
Any suggestions, ideas, links to inspirations...etc...
My goal is to automate keeping my team informed about any key issues about the server, in a way anyone can understand.
Thank You for your time.
A:
Is the goal to have the developers be aware of a problem? Then fail loudly and succeed silently. Otherwise the failures/problems will soon be ignored.
Send a report when the drive space is critical with a subject line "DRIVE SPACE CRITICAL!"
Send a report when the backup didn't occur saying "BACKUP FAILED!"
From control room design: every alarm should have a unique response, and no alarm should be generated for events that have no corrective action - the event should be journaled to a log that the developers can go inspect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Передвижение объекта в массиве
Как передвинуть любой объект из этого массива?
self.images = [NSMutableArray array];
NSFileManager* manager = [NSFileManager new];
NSBundle* bundle = [NSBundle mainBundle];
NSDirectoryEnumerator* enumerator = [manager enumeratorAtPath:[bundle bundlePath]];
for (NSString* name in enumerator) {
if ([name hasSuffix:@"PawnWhite.png"]) {
for (int i = 0; i <= 7; i++) {
UIImage* image = [UIImage imageNamed:name];
[self.images addObject:image];
}
}
}
for (int i = 0; i < self.images.count; i++) {
CGPoint myPoint = CGPointMake(75.f, 0);
self.view = [[UIView alloc] initWithFrame:CGRectMake(84.f + myPoint.x * i, 870.f, 75.f, 75.f)];
self.imagesView = [[UIImageView alloc] initWithFrame:self.view.bounds];
self.imagesView.image = [self.images objectAtIndex:i];
[self.view addSubview:self.imagesView];
[valueView addSubview:self.view];
Выделить отдельное view и изменить его местоположение?
A:
можно каждому imageView назначить тэг
self.imagesView.tag = i+1; //не использовать тэг=0
и искать их по тэгу и изменять фрейм
[[self.view viewWithTag:SOMETAG] setFrame:CGRectMake(0,0,1,1)];
либо создать еще один массив и в него сложить все imagesView и когда надо изменить фрейм какого то imageView у него будет тот же индекс, что и у image
[[self.imageViews objectAtIndex:[self.images objectAtIndex:SOMEINDEX]] setFrame:CGRectMake(0,0,1,1)];
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional string representation based on variable type
I would like to create a string representation of a datetime object that could contain a None value. So far, I came up with a solution, but I was looking at a better/cleaner way of doing it.
Let's say I have the following two variables:
import datetime as dt
a = None
b = dt.datetime(2017, 11, 30)
def str_format(str):
return '{:%Y-%m-%d}'.format(str)
The following would return a formatted string:
str_format(b)
'2017-11-30'
But the following would return an error:
str_format(a)
TypeError: unsupported format string passed to NoneType.__format__
So far I can up with the following solution:
def str_format(str):
if isinstance(str, type(None)) is False:
return '{:%Y-%m-%d}'.format(str)
else:
return '{}'.format(str)
str_format(a)
'None'
str_format(b)
'2017-11-30'
However, I was looking at a more efficient/cleaner way of writing the function.
A:
your function is overcomplex. None is a singleton, so the pythonic way of testing against it is just is None.
Just do it in one line with a ternary expression:
def str_format(s):
return str(s) if s is None else '{:%Y-%m-%d}'.format(s)
or to return a default date (ex: 1/1/2010) if None is passed:
def str_format(s):
return '{:%Y-%m-%d}'.format(s or dt.datetime(2010, 1, 1))
as a side note don't use str as a variable name as it is the python string type.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML 5 Canvas Whiteboard for iOS
I have been working with the code here: http://code.google.com/p/html-5-canvas-whiteboard/
Everything works great in the browser, but not on iOS devices.
Can anyone point me in the right direction to make this iOS compatible? More specifically, I would like it to work in Safari for my iPad.
Here is a test version of my code: http://www.coderedsupport.com/whiteboard
Any advice would be great.
A:
You have mousedown, mouseup, and mousemove events, you need to add touchstart, touchend and touchmove events to match them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues with Parse error: syntax error, unexpected $end On internet explorer
Internet Explorer is showing the following classic error:
Parse error: syntax error, unexpected $end in C:\xampplite\htdocs\obg001\tpl\chooseStart.tpl.php on line 133 which is most of times a missing bracer, however there are two things i do not understand completely:
1.- php_error_log is not reporting any error
2.- the error only appears on IE
i do not find any missing bracer myself. The code without almost anything else more than the brackets is:
<?php
if ($_SESSION['game']['status']=='OPEN'){
?>
<?php
foreach($gamers as $gamer){
}
?>
<?php
}else{
?>
<?php
foreach($gamers as $gamer){
}
}
?>
<?php
if($_SESSION['game']['status']=='CHOOSING'){
?>
<?php
}
else if ($_SESSION['game']['status']=='DONECHOOSING'){
?>
<?php
}
else if ($_SESSION['game']['status']=='ROLLING'){
?>
<?php
if ($canRoll['result']==true){
?>
<?php
}else{
?>
<?php ?>
<?php
}
?>
<?php
}else if ($_SESSION['game']['status']=='DONEROLLING'){
if($_SESSION['game']['userId'] == $_SESSION['user']['userId']){
?>
<?php
}
}else {
if($_SESSION['game']['userId'] == $_SESSION['user']['userId']){
?>
<?php
}
}
?>
If you want to see the code without the cutoff go here
Thank you very much.
Server configuration:
Operative Syste: windows 7 x64
ApacheFriends XAMPP version 1.7.7:
Apache 2.2.21
MySQL 5.5.16 (Community Server)
PHP 5.3.8 (VC9 X86 32bit thread safe) + PEAR
php.ini
Update:
If i get it correctly my php.ini should log everything:
error_reporting = E_ALL | E_STRICT
display_errors = On
log_errors = On
error_log = "\xampplite\php\logs\php_error_log"
Also, the project was and is created and coded by myself only, so i'm sure there is not one directive to not log errors in any of the includes.
Update 2
If i add intentionally a closing bracer to the last line of that code i get in php_error_log the following line:
[12-Jul-2012 22:23:30] PHP Parse error: syntax error, unexpected '}' in C:\xampplite\htdocs\obg001\tpl\chooseStart.tpl.php on line 139
So PHP is login parsing errors after all, which should happen when IE loads the page and again it does not.
I can finally add that the page loads perfect even on a iPad so this just does not make much sense to me.
A:
The problem depends on IE, which keeps a cached version of the old page, without calling the application.
under development is recommended to send this header
Cache-Control: no-cache
| {
"pile_set_name": "StackExchange"
} |
Q:
Is a single batch request equivalent to a single tsql request?
I'm looking into some performance metrics and every recommendation includes monitoring Batch Requests/sec. But, maybe a silly question, does a singe batch request correspond to exactly one tsql statement? Say it contains exactly one select or one update, etc. So, for example, a stored procedure with 3 selects and 2 inserts triggers 5 batch requests. Or, as I think, a batch request can include for example a full stored procedure, a function, several select/update/insert statements, etc.
All I can find is similar to these descriptions:
TechNet Number of Transact-SQL command batches received per second. This statistic is affected by all constraints (such as I/O, number of users, cache size, complexity of requests, and so on). High batch requests mean good throughput.
Understanding how SQL Server executes a query Batch Request This request type contains just T-SQL text for a batch to be executed. This type of requests do not have parameters, but obviously the T-SQL batch itself can contain local variables declarations. This is the type of request SqlClient sends if you invoke any of the SqlCommand.ExecuteReader(), ExecuteNonQuery(), ExecuteScalar(), ExecuteXmlReader() (or they respective asyncronous equivalents) on a SqlCommand object with an empty Parameters list. If you monitor with SQL Profiler you will see an SQL:BatchStarting Event Class
A:
As per the comment, then no - it's not a single statement.
A batch can cover multiple individual T-SQL statements in a single batch.
| {
"pile_set_name": "StackExchange"
} |
Q:
sudo not working alongwith su
I am using a Ubuntu system. Today, I accidentally changed the sudoers file in /etc due to which my normal user prathmesh is not able to perform sudo operation. I don't know how to go to the root mode. I am trying "su" but it is giving me authentication failure error. Plus I don't remember setting root user's password ever.
What is the best way to solve this situation ?? Use a live CD to change the sudoers file or something else ??
A:
You have two easy ways:
use the Ubuntu installation CD, choose the "rescue a system" option and then drop into the shell (of the target system) to change the password of the user(s) or modify the /etc/sudoers to your liking.
boot into single user mode and modify the passwords or /etc/sudoers.
The second method may be hard on more recent Ubuntu versions where GRUB doesn't wait for you to choose the single user mode.
| {
"pile_set_name": "StackExchange"
} |
Q:
whereIn being ignored when filtering a laravel query
I am attempting to filter a DB query, I am wondering is it possible to use whereIn to do this? Currently it is being ignored.
First query is working fine:
$cosmeticTestAllData = DB::table('table')
->whereIn('part_number', ['P1', 'P2', 'P3', 'P4', 'P5', 'P6'])
->get();
Sample Results:
Array (
[0] => stdClass Object
(
[part_number] => P1
[status] => FAIL
[shipment_channel] => DP
[created_at] => 2017-01-24 10:25:21
)
[1] => stdClass Object
(
[part_number] => P2
[status] => PASS
[shipment_channel] => DP
[created_at] => 2018-01-24 10:25:21
)
[2] => stdClass Object
(
[part_number] => P2
[status] => FAIL
[shipment_channel] => DP
[created_at] => 2018-01-24 10:25:21
)
)
This query correctly filters the where clause but ignores whereIn
$fullCount = $cosmeticTestAllData;
$fullCount->where('created_at', '>', '2018-01-01 00:00:00');
$fullCount->whereIn('shipment_channel', ['ANYTHING']);
$fullCount->whereIn('status', ['ANYTHING')];
echo '<pre>';
print_r($fullCount->all());die;
Results:
Array (
[0] => stdClass Object
(
[part_number] => P2
[status] => PASS
[shipment_channel] => DP
[created_at] => 2018-01-24 10:25:21
)
[1] => stdClass Object
(
[part_number] => P2
[status] => FAIL
[shipment_channel] => DP
[created_at] => 2018-01-24 10:25:21
)
)
A:
You seem to by trying to treat a collection like a query builder. However most collection operations don't change the collection. Change your code to :
$fullCount = $cosmeticTestAllData
->where('created_at', '>', '2018-01-01 00:00:00');
->whereIn('shipment_channel', ['ANYTHING'])
->whereIn('status', ['ANYTHING' ]);
echo '<pre>';
print_r($fullCount->all());die;
This way you are chaining the result of each operation to the next operation.
Alternatively you can do those operations on the query builder before you execute the query
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I kill Vincon Traut and the other conspirators?
When I approach Vincon Traut in Chapter 2 in an attempt to obtain his enchanted armor, he warns me that it was a mistake to go there by myself. Spot on, Vincon -- I thought I was fairly comfortable with the combat system but your blade and your conspirators are making me look like a complete fool. I can't even kill a single one of you, since there are six men and I'm stuck in a small room with no space to roll around. You take advantage of me at the beginning of the battle by swinging your blade while I draw my sword, wiping away 20% of my health and making me bleed, too. It's not like Quen is of much use, either, since two men make such short work of it.
How am I supposed to survive this encounter? Should I rely on extreme luck with Aard? Or is there some tactic that will make this encounter much easier for me?
A:
You can get Backup... as soon as you know Traut's location you can talk to Dethmold. He will give you 4 of his soldiers as backup. So, when you then go to fight Traut, you just have to open the middle door in the room, there the 4 soldiers are waiting to help you in the fight.
| {
"pile_set_name": "StackExchange"
} |
Q:
If a column has string to execute syntax
I wanted to know if there was a way to do an IF ELSE statement within SQL syntax or if someone could help me with CASE. Basically if a file name (string) is found in the file_url column then change where I want to use secondary information. I hope my example can help further explain what I am trying to do.
$sql = "SELECT vm.file_url FROM #__virtuemart_medias AS vm
INNER JOIN #__virtuemart_product_medias AS pm ON vm.virtuemart_media_id = pm.virtuemart_media_id
WHERE pm.virtuemart_product_id = {$product_id} ";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$FILEURL = $row["vm.file_url"];
if ($FILEURL == "thumb_phone01.jpg"){
$sql .= "AND pm.ordering = 2";
}
else {
$sql .= "AND pm.ordering = 1";
}
$this->_db->setQuery($sql);
$img = $this->_db->LoadResult();
return $img;
}
Thank you.
A:
One option would be to use CASE and REGEXP:
SELECT vm.file_url FROM #__virtuemart_medias AS vm
INNER JOIN #__virtuemart_product_medias AS pm
ON vm.virtuemart_media_id = pm.virtuemart_media_id
WHERE pm.virtuemart_product_id = {$product_id}
AND pm.ordering = CASE
WHEN vm.file_url REGEXP 'thumb_phone01.jpg'
THEN 2
ELSE 1
END
Here is the SQL Fiddle.
Good luck.
| {
"pile_set_name": "StackExchange"
} |
Q:
Copy several folders and files from a git repository to another while preserving history
I have a repo on github/bitbucket called X, here's the directory structure
├── folder1
├── folder2
├── folder3
├── folder4
│ ├── a.cpp
│ └── b.cpp
├── c.cpp
└── d.cpp
I want to make a new repo called Y, which should have
├── folder1
├── folder4
│ └── a.cpp
└── c.cpp
The commit history of all the files should be preserved, and also the directory structure of X to be intact, how can I do this?
Also if the above is possible, I don't want to move these files out of X because they are required by other files in X but want to work on them in repo Y and then push those changes to X somehow. I don't want change the directory structure of X or make the copied folders as submodules either. How can I make changes in the copied files and folders in Y and push those changes to a desired branch in X?
A:
hmm... What you are suggesting is to have two separate repos working on some of the same files, but in the same directory. As far as I am aware you can't have that exact setup. But I also think it's not a very good setup - you are breaking "encapsulation" rules.
What would be better is to have:
repo X:
├── folder1
├── folder2
├── folder3
├── folder4
│ └── b.cpp
├── common (submodule called "common")
| ├── c.cpp
│ └── a.cpp
└── d.cpp
Repo Y:
├── folder1
├── common (submodule called "common")
| ├── c.cpp
│ └── a.cpp
└── e.cpp (repo Y only files)
repo common
├── c.cpp
└── a.cpp
So here you have three git repos: X, Y and Common.
Common is a submodule in X and Y. This is a better way to structure you project.
Then your common submodule keeps a shared history (well, its own history) and your specific X and specific Y files have their own separate history.
To get to there from where you are you need to create the two new repos (Y and common):
Move in the common files into common.
Move the Y files into Y.
Include the common submodule into X and Y: git submodule add <url to common>
Commit and push the changes to each repo.
Well, that's the rough outline of it. If you want further clarification just ask...
Note: If you want the directory structure exactly intact you could name "common" to "folder4" but it would still need to be a submodule.. but I think a slight re-work of your folders is better to move all the common stuff into one place.
update 1
From @J.Doe's request here is how you can create Y from X, but without submodules you this will have copies of files from Y...
mkdir Y - create new folder (outside of any git repo)
cd Y - move into that folder
git init - turn this into a git repository
cp -r <path-to-X\folder1> . - copy folder1 into repo
mkdir folder4 - create a folder 4.
cp <path-to-X\folder4\a.cpp> folder4 - copy a.cpp
cp <path-to-X\c.cpp> . - copy c.cpp
git add -A - add all files into the repo (stage them)
git commit -m "initial version of Y" - commit the files to the repo
git remote add origin <url to remote Y> - add the remote Y repo (you will have to create this in github first).
git push origin master - assuming you are on the master branch (the default) push your initial commit to the remote.
As I said this will create repo Y with copies from X as a separate repo with a new history. If you want to have the history from X you can do that as well, but the method is slightly different.
update 2
To create Y with the history of X preserved:
cp -r X Y - make a copy of X but call it Y
cd Y - cd into Y (note this is still just a copy of X)
rm -r folder2 folder3 folder4/b.cpp d.cpp - remove the files you don't want in Y
git add -A - add all changes (in this case git will detect the delete files)
git commit -m "Y Created from X - initial version"
git remote rm origin - remove the remote pointing to X on github.
git remote add origin <url to Y on github> - add remote to Y on github
git push origin master - push the new repo to Y.
Note: here you will have the entire history of X in repo Y. Y will now move on separately from X (i.e. diverge).
NOTE: one problem with your requirement is that git does not work on individual files.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find the number of elements in least common multiple problem?
The problem is as follows:
Over a table there is a certain number of muffins, if we count them by
multiples of four the remainder is three. If we count them by
multiples of six the remainder is five but if we count them by
multiples of ten the remainder is nine. What is the least number of
muffins over the table?
What I tried to do is to build up the equations to get the supposed number as follows:
$\textrm{n is defined as the number of muffins}$
$4k+3=n$
$6k+5=n$
$10k+9=n$
Then i equated those to get the value of $k$.
$4k+3=6k+5$
$2k=-2$
$k=-1$
$10k+9=6k+5$
$4k=-4$
$k=-1$
$4k+3=10k+9$
$6k=-6$
$k=-1$
However in all cases I reach to $-1$ and it does not seem to be reasonable to use it in any of those equations. I'm lost in this one can somebody help me to address this situation the easiest way possible?.
A:
The reason you are getting a nonsensical answer is because there is no reason why the values of $k$ in your three equations should be the same. All you really know is that there are integers $a,b,c$ such that
$$\begin{align}
n &= 3 + 4a, \\
n &= 5 + 6b, \\
n &= 9 + 10c.
\end{align}$$
To solve this, you can iteratively substitute. From the first equation $n = 3 + 4a$, we see that
$$ 3 + 4a = 5 + 6b,$$
or rather that $2a = 1 + 3b = 4 + 3(b-1) = 4 + 3b'$ for some integer $b'$. Note that $b'$ must be even so that the right hand side is even (which must occur as the left hand side is even). So we can write $b' = 2b''$ for some integer $b''$.
Then from $2a = 4 + 6b''$, we have that $a = 2 + 3b''$. Substituting into $n = 3 + 4a$, we find that $n = 3 + 4(2 + 3b'') = 11 + 12b''$ for some integer $b''$. It's annoying to write $b''$, so I'll write $d$ instead of $b''$.
The point is that the information that
$$\begin{align}
n &= 3 + 4a \\
n &= 5 + 6b
\end{align}$$
is contained within the single equation $n = 11 + 12d$. Indeed, if $n = 11 + 12d$ for some integer $d$, then its remainder upon dividing by $4$ is $3$, and its remainder upon dividing by $6$ is $5$. We showed the converse above. Thus from two equations, we have one.
Now we repeat, this time with
$$\begin{align}
n &= 11 + 12 d \\
n &= 9 + 10 c.
\end{align}$$
Equating, we see that $9 + 10c = 11 + 12d$, or rather that $5c = 1 + 6d$. As above, we massage the right hand side a bit and write $5c = 25 + 6(d - 4) = 25 + 6d'$. In this form, we see that $d'$ must be divisible by $5$ to make the right hand side divisible by $5$ (as the left hand side is divisible by $5$). So we can write $d' = 5 d''$ for some integer $d''$. Thus $5c = 25 + 30d''$, or rather $c = 5 + 6d''$. Writing $d''$ is annoying, so I use $e$ instead.
Then we have that $c = 5 + 6e$. Substituting into $n = 9 + 10c$, we have that
$$ n = 9 + 10(5 + 6e) = 59 + 60e.$$
Notice that if $n = 59 + 60e$, then dividing by $4$ leaves remainder $3$, dividing by $6$ leaves remainder $5$, and dividing by $10$ leaves remainder $9$. And to get $n = 59 + 60e$, we just massaged the equations above.
Thus the set of integers that leave the three necessary remainders are exactly those integers of the form $59 + 60e$. The smallest (positive) integer of this form is $59$. (Note that $-1$ is also of this form, and you found $-1$ by essentially guessing a value for $e$ at the start).
So the answer is $59$.
Addendum: the computations I performed were elementary, but they can seem a bit uninspired. But I knew to do this because I was modifying a proof of the Chinese Remainder Theorem, which would apply naively if $\gcd(4,6,10) = 1$ (which it's not). The computations feel more natural when considered in congruences. To see this, let's redo the first pair reduction using congruences.
So $n = 3 + 4a$ is the same as $n \equiv 3 \mod 4$, and $n = 5 + 6b$ is the same as $n \equiv 5 \mod 6$. So we are trying to solve the simultaneous congruence
$$\begin{align}
n &\equiv 3 \mod 4, \\
n &\equiv 5 \mod 6.
\end{align}$$
To do this we write $n = 3 + 4a$ and substitute into the second congruence, getting
$$ 3 + 4a \equiv 5 \pmod 6 \implies 2a \equiv 1 \pmod 3 \implies a \equiv 2 \pmod 3.$$
And thus $a = 2 + 3b$ for some $b$, so that $n = 3 + 4(2 + 3b) = 11 + 12 b$ for some $b$. Or rather $a \equiv 11 \pmod {12}$.
This is exactly as above, except without the various variable shenanigans I employed previously. The rest of the argument works the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof Check: $x \leq y+ \epsilon$ for all $\epsilon >0$ iff $x \leq y$.
Synopsis
I want to be sure I'm utilizing proof by contradiction correctly, so please check my proof of the exercise below. It's relatively simple, so it shouldn't take you too much time.
Exercise
Let $x$ and $y$ be real numbers. Show that $x \leq y + \epsilon$ for all real numbers $\epsilon > 0$ if and only if $x \leq y$.
Proof
Suppose $x \leq y + \epsilon$ for all $\epsilon > 0$ and $x > y$. Then $x - y > 0$ and $x - y + \epsilon > \epsilon$ for all $\epsilon > 0$. But if $x \leq y + \epsilon$, then $y - x + \epsilon \geq 0$. So $0 \leq y-x+\epsilon < y-x+(x-y+\epsilon) = \epsilon$, a contradiction. For the converse, suppose $ x \leq y$. Then it is obvious that $x \leq y+\epsilon$. This concludes our proof.
Update
This proof is obviously wrong. It is not a contradiction that $\epsilon >0$. For some reason, I deluded myself that my conclusion stated that $\epsilon < 0$, but that's just due to my occasional stupidity and habitual lack of double checking. Instead, consider some $\epsilon$ such that $0 < \epsilon < x-y$. Then $x \leq y + \epsilon < y+x-y < x$, a contradiction. Thank you to the various people who commented on the issues with my proof. This was a very stupid mistake, and I don't even know how I overlooked what I did.
A:
0≤y−x+ϵ<y−x+(x−y+ϵ)=ϵ, a contradiction.
Why is that a contradiction? $0$ is $< \epsilon$.
....
Instead Note $\epsilon$ is not fixed. If $x-y >0$ then we can let $\epsilon$ be some value $0 < \epsilon < x-y$ and .... then what happens?
$x \le y + \epsilon < y+(x-y) = x$ so $x < x$. Which certainly is a contradiction!
| {
"pile_set_name": "StackExchange"
} |
Q:
Component Link data is null in DXA
My data from component link in schema is not getting filled in Model DXA
In my class "Feed". Schema is with same name.
I am able to read the text fields and getting updated in Model automatically.
But component link data is null.
[SemanticEntity(Vocab = SchemaOrgVocabulary, EntityName = "Feed", Prefix = "s", Public = true)]
public class Feed : EntityModel
{
public string Headline { get; set; }
public string Url { get; set; }
public int Limit { get; set; }
public int Year { get; set; }
public string testFeedText { get; set; }
[SemanticProperty("s:externalcareer")]
public List<ExternalCareer> ExternalCareer { get; set; }
}
Data is getting updated in above model automatically but not updating in "ExternalCareer"
"ExternalCareer" is the component link. And multiple component link can be added.
When I see source of component where data is filled against Feed schema. Below is the XML
<Feed xmlns="uuid:65b54eb0-92de-47cd-9c65-8ef54be672e1">
<limit>10</limit>
<year>2018</year>
<readMoreText>Read more</readMoreText>
<externalcareer xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="tcm:20-66542" xlink:title="Australia Career"></externalcareer>
<externalcareer xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="tcm:20-66543" xlink:title="HG Career"></externalcareer>
<testFeedText>Test Content</testFeedText>
</Feed>
And on preview the Json page data is as follows. Please advise.
"externalcareer": {
"Name": "externalcareer",
"Values": [],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [
{
"LastPublishedDate": "0001-01-01T00:00:00",
"RevisionDate": "2019-05-14T13:42:58",
"Schema": {
"RootElementName": "ExternalCareer",
"Id": "tcm:21-66534-8",
"Title": "ExternalCareer"
},
"Fields": {
"selectcountry": {
"Name": "selectcountry",
"Values": [],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 3,
"CategoryName": "Test Career Countries",
"CategoryId": "tcm:21-24802-512",
"XPath": "tcm:Content/custom:ExternalCareer/custom:selectcountry",
"KeywordValues": [
{
"Description": "Australia",
"Key": "australia",
"TaxonomyId": "tcm:21-24802-512",
"Path": "\\Test Career Countries\\Australia",
"ParentKeywords": [],
"MetadataFields": {},
"Id": "tcm:21-66520-1024",
"Title": "Australia"
}
]
},
"externalcareersdetailsbycountry": {
"Name": "externalcareersdetailsbycountry",
"Values": [],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"EmbeddedValues": [
{
"division": {
"Name": "division",
"Values": [ "GH/Cargo" ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry[1]/custom:division",
"KeywordValues": []
},
"url": {
"Name": "url",
"Values": [ "https://www.ssfdsffdijTest.nl/ " ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry[1]/custom:url",
"KeywordValues": []
}
}
],
"EmbeddedSchema": {
"RootElementName": "Content",
"Id": "tcm:21-66541-8",
"Title": "ExternalCareersDetailsByCountry"
},
"FieldType": 4,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry",
"KeywordValues": []
}
},
"MetadataFields": {},
"ComponentType": 1,
"Categories": [],
"Version": 2,
"Id": "tcm:21-66542",
"Title": "Australia Test Career"
},
{
"LastPublishedDate": "0001-01-01T00:00:00",
"RevisionDate": "2019-05-14T13:43:30",
"Schema": {
"RootElementName": "ExternalCareer",
"Id": "tcm:21-66534-8",
"Title": "ExternalCareer"
},
"Fields": {
"selectcountry": {
"Name": "selectcountry",
"Values": [],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 3,
"CategoryName": "Test Career Countries",
"CategoryId": "tcm:21-24802-512",
"XPath": "tcm:Content/custom:ExternalCareer/custom:selectcountry",
"KeywordValues": [
{
"Description": "UK",
"Key": "uk",
"TaxonomyId": "tcm:21-24802-512",
"Path": "\\Test Career Countries\\UK",
"ParentKeywords": [],
"MetadataFields": {},
"Id": "tcm:21-66536-1024",
"Title": "UK"
}
]
},
"externalcareersdetailsbycountry": {
"Name": "externalcareersdetailsbycountry",
"Values": [],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"EmbeddedValues": [
{
"division": {
"Name": "division",
"Values": [ "GH/Cargo" ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry[1]/custom:division",
"KeywordValues": []
},
"url": {
"Name": "url",
"Values": [ "http://Test.co.uk/recruitment" ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry[1]/custom:url",
"KeywordValues": []
}
},
{
"division": {
"Name": "division",
"Values": [ "Travel" ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry[2]/custom:division",
"KeywordValues": []
},
"url": {
"Name": "url",
"Values": [ "https://Testtravelcareers.com/" ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry[2]/custom:url",
"KeywordValues": []
}
}
],
"EmbeddedSchema": {
"RootElementName": "Content",
"Id": "tcm:21-66541-8",
"Title": "ExternalCareersDetailsByCountry"
},
"FieldType": 4,
"XPath": "tcm:Content/custom:ExternalCareer/custom:externalcareersdetailsbycountry",
"KeywordValues": []
}
},
"MetadataFields": {},
"ComponentType": 1,
"Categories": [],
"Version": 2,
"Id": "tcm:21-66543",
"Title": "UK Career"
}
],
"FieldType": 6,
"XPath": "tcm:Content/custom:Feed/custom:externalcareer",
"KeywordValues": []
}, "TestFeedText": {
"Name": "TestFeedText",
"Values": [ "Test Content" ],
"NumericValues": [],
"DateTimeValues": [],
"LinkedComponentValues": [],
"FieldType": 0,
"XPath": "tcm:Content/custom:Feed/custom:TestFeedText",
"KeywordValues": []
}
Regards,
A:
I think the problem lies in the SemanticProperty annotation/attribute for the ExternalCareer property.
The default semantic mapping maps that (Pascal case) property to a CM field named externalCareer (camel case), but it seems your CM field is called externalcareer (lowercase).
You do have a SemanticProperty annotation mapping it to “externalcareer”, but that is in the “schema.org” vocabulary, instead of in the “Core Vocabulary”. The latter is normally used for mapping to CM fields.
See, for example: https://github.com/sdl/dxa-modules/blob/master/webapp-net/Core/Models/Entity/Teaser.cs
(That’s a rather extreme example of CM mapping, but it shows the use of the “Core Vocabulary” for that purpose)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to send emails from my app using a Gmail account?
I'm trying to send emails from an app.
The problem is Gmail doesn't let me authenticate due to unusual locations - of course, each app installed in other location.
My code (using Javax):
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", SMTP_SERVER);
props.put("mail.smtp.port", PORT);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, new StringBuilder(PASSWORD).toString());
}
});
That code works fine on my testing device, but crash on others using my app.
The error I get:
javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via 534-5.7.14 your web browser and then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 l9-v6sm11531942wrf.4 - gsmtp
I gave a try to all found solutions found, but no avail.
The solution with "Allow less secure apps" and "Unlock display catcha" - didn't help
As well I tried to turn-on 2FA and authenticating with AppPassword generated from google - didn't help.
Any clue?
A:
For anyone interested, no solution worked. Gmail just refused to allow different locations to login, because of extra-security (without option to disable this).
I moved to use other email provider. No problems anymore with the same code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compost pile in vegetable garden area
I am putting in a new garden and thinking about putting our compost pile in one corner. Will this attract harmful bugs to any degree that may interfere with the health of the plants growing nearby? Are there any other drawbacks to siting the compost heap in a vegetable garden that I should consider?
A:
I have had compost bins in the past. I had 3 bins side-by-side just off my lawn, and filled up one, then moved to the next, and so on. Once I had all 3 bins full, the 1st was generally ready to use as compost. I also had one just off my garden, which is very useful to have it near by, much more practical for putting plant material in it from your garden. I never noticed it attracting unwanted pests. I also understand, ground up tree leaves and coffee grounds are the best for making compost.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create relationship based on common Epochtime property
I am trying to do a model for state changes of a batch. I capture the various changes and I have an Epoch time column to track these. I managed to get this done with the below code :
MATCH(n:Batch), (n2:Batch)
WHERE n.BatchId = n2.Batch
WITH n, n2 ORDER BY n2.Name
WITH n, COLLECT(n2) as others
WITH n, others, COALESCE(
HEAD(FILTER(x IN others where x.EpochTime > n.EpochTime)),
HEAD(others)
) as next
CREATE (n)-[:NEXT]->(next)
RETURN n, next;
It makes my graph circular because of the HEAD(others) and doesn't stop at the Node with the maximum Epoch time. If I remove the HEAD(others) then I am unable to figure out how to stop the creation of relationship for the last node. Not sure how to put conditions around the creation of relationship so I can stop creating relationships when the next node is null
A:
This might do what you want:
MATCH(n:Batch)
WITH n ORDER BY n.EpochTime
WITH n.BatchId AS id, COLLECT(n) AS ns
CALL apoc.nodes.link(ns, 'NEXT')
RETURN id, ns;
It orders all the Batch nodes by EpochTime, and then collects all the Batch nodes with the same BatchId value. For each collection, it calls the apoc procedure apoc.nodes.link to link all its nodes together (in chronological order) with NEXT relationships. Finally, it returns each distinct BatchId and its ordered collection of Batch nodes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove Stack Snippets on Meta Stackexchange
Stack snippets are available on this meta.stackexchange.com site, but as mentioned in the initial meta post about them there was no discussion as to whether they should be here or not.
I would suggest they be disabled / removed from this site.
We get many off-topic programming / code questions here, and the fact that the snippets buttons render within the questions gives those questions a sense of legitimacy, potentially indicating to the poster that their question is actually valid here, when that is likely not the case.
I'm sure there are some valid use-cases for having them around - sandbox testing for instance - but that could be mitigated by referring people to the a sandbox post on MSO instead.
Do we need stack snippets on a site dedicated to questions about Stack Exchange? We would still be able to discuss them, but I don't think there's a need to actually implement them here.
A:
I believe the reason is that the team plan to enable the Snippets on other sites, at some point, so the proper meta for bugs related to the Stack Snippets is/will be MSE.
This is why it is enabled here, in my opinion, and I really don't think that someone who failed to notice it's the wrong place to begin with will notice this missing icon and suddenly realize "Hey, it's not Stack Overflow!".
So I don't think we should remove this from MSE. Let it live, and as usual deal with the off topic questions as they arrive.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing title of an application when launching from command prompt
I am a business user of an application that has two separate environments: test and production. It is important that I know which environment I'm using at all times, but the application gives no indication. Window title, layout, and all features are identical, and there is no function in the program to identify the environment, so it's my responsibility to remember which .exe I'm currently using.
I had the thought that I could modify the shortcut or use a command prompt to open the window such that the title clearly says "TEST" or "PRODUCTION".
I attempted the below, but, while it launches the application as expected, there is no change to the window title. (I suspect this only works when launching command prompts)
start "different title" fake.exe
Is there a way to accomplish this? Any ideas would be very much appreciated.
A:
You need to make a program to do this.
You need to call the Windows' API. This is how to make a title bar changing program.
Create a file using notepad and call it SetText.bas. Store it on your desktop.
Paste this into it.
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Public Module MyApplication
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Sub Main()
On Error Resume Next
Dim CmdLine As String
Dim Ret as Long
Dim A() as String
Dim hwindows as long
CmdLine = Command()
If Left(CmdLine, 2) = "/?" Then
MsgBox("Usage:" & vbCrLf & vbCrLf & "ChangeTitleBar Oldname NewName")
Else
A = Split(CmdLine, Chr(34), -1, vbBinaryCompare)
hwindows = FindWindow(vbNullString, A(1))
Ret = SetWindowText(hwindows, A(3))
End If
End Sub
End Module
Then type in a command prompt window.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:winexe /out:"%userprofile%\desktop\SetText.exe" "%userprofile%\desktop\settext.bas" /verbose
A program has been created on your desktop called settext.exe. To use
"%userprofile%\desktop\settext" "Untitled - Notepad" "A Renamed Notepad"
| {
"pile_set_name": "StackExchange"
} |
Q:
Change Checkbox Color in Javascript
<!DOCTYPE html>
<html>
<body>
<form action="form_action.asp" method="get">
<span style='background-color: red;'>
<input style="FILTER: progid:DXImageTransform.Microsoft.Alpha( style=0,opacity=50);" type="checkbox" name="vehicle" value="Bike" /></span>I have a bike<br />
<span style='background-color: red;'>
<input style="-moz-opacity:0.5" type="checkbox" name="vehicle" value="Car" /></span> I have a car <br />
<input type="submit" value="Submit" />
</form>
<p>Click on the submit button, and the input will be sent to a page on the server called "form_action.asp".</p>
</body>
</html>
I found pieces of examples online and pieced this together the top input checkbox should work for ie and the bottom for FF and chrome. Neither on works well. IE looks sloppy and FF and chrome doesn't seem to work at all. I am trying to figure this out for a list of checkboxes, some of which are disabled based on previous choices. I have it working for most browsers but some of the browsers don't grey the boxes out.
So, I need to figure out how to grey out the boxes using javascript. This doesn't seem to work and document.getelementbyid(elementID).style.background = "#dbdbdb"; just outlines the box.
Any help is greatly appreciated
A:
Your checklist does not need to be clickable?
Disable it as the simple solution in some browsers, and then increase the opacity for the other browsers:
document.getElementById(elementID).disabled="disabled";
document.getElementById(elementID).style.opacity="0.5";
That's assuming your background is black... likely not.
Otherwise get the x,y position of the checkbox:
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left;
Then create a black div with opacity with a higher z-index and absolute positioning in front of the checkbox.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the parallel package slower than just using apply?
I am trying to determine when to use the parallel package to speed up the time necessary to run some analysis. One of the things I need to do is create matrices comparing variables in two data frames with differing number of rows. I asked a question as to an efficient way of doing on StackOverflow and wrote about tests on my blog. Since I am comfortable with the best approach I wanted to speed up the process by running it in parallel. The results below are based upon a 2ghz i7 Mac with 8gb of RAM. I am surprised that the parallel package, the parSapply funciton in particular, is worse than just using the apply function. The code to replicate this is below. Note that I am currently only using one of the two columns I create but eventually want to use both.
(source: bryer.org)
require(parallel)
require(ggplot2)
require(reshape2)
set.seed(2112)
results <- list()
sizes <- seq(1000, 30000, by=5000)
pb <- txtProgressBar(min=0, max=length(sizes), style=3)
for(cnt in 1:length(sizes)) {
i <- sizes[cnt]
df1 <- data.frame(row.names=1:i,
var1=sample(c(TRUE,FALSE), i, replace=TRUE),
var2=sample(1:10, i, replace=TRUE) )
df2 <- data.frame(row.names=(i + 1):(i + i),
var1=sample(c(TRUE,FALSE), i, replace=TRUE),
var2=sample(1:10, i, replace=TRUE))
tm1 <- system.time({
df6 <- sapply(df2$var1, FUN=function(x) { x == df1$var1 })
dimnames(df6) <- list(row.names(df1), row.names(df2))
})
rm(df6)
tm2 <- system.time({
cl <- makeCluster(getOption('cl.cores', detectCores()))
tm3 <- system.time({
df7 <- parSapply(cl, df1$var1, FUN=function(x, df2) { x == df2$var1 }, df2=df2)
dimnames(df7) <- list(row.names(df1), row.names(df2))
})
stopCluster(cl)
})
rm(df7)
results[[cnt]] <- c(apply=tm1, parallel.total=tm2, parallel.exec=tm3)
setTxtProgressBar(pb, cnt)
}
toplot <- as.data.frame(results)[,c('apply.user.self','parallel.total.user.self',
'parallel.exec.user.self')]
toplot$size <- sizes
toplot <- melt(toplot, id='size')
ggplot(toplot, aes(x=size, y=value, colour=variable)) + geom_line() +
xlab('Vector Size') + ylab('Time (seconds)')
A:
Running jobs in parallel incurs overhead. Only if the jobs you fire at the worker nodes take a significant amount of time does parallelization improve overall performance. When the individual jobs take only milliseconds, the overhead of constantly firing off jobs will deteriorate overall performance. The trick is to divide the work over the nodes in such a way that the jobs are sufficiently long, say at least a few seconds. I used this to great effect running six Fortran models simultaneously, but these individual model runs took hours, almost negating the effect of overhead.
Note that I haven't run your example, but the situation I describe above is often the issue when parallization takes longer than running sequentially.
A:
These differences can be attributed to 1) communication overhead (especially if you run across nodes) and 2) performance overhead (if your job is not that intensive compared to initiating a parallelisation, for example). Usually, if the task you are parallelising is not that time-consuming, then you will mostly find that parallelisation does NOT have much of an effect (which is much highly visible on huge datasets.
Even though this may not directly answer your benchmarking, I hope this should be rather straightforward and can be related to. As an example, here, I construct a data.frame with 1e6 rows with 1e4 unique column group entries and some values in column val. And then I run using plyr in parallel using doMC and without parallelisation.
df <- data.frame(group = as.factor(sample(1:1e4, 1e6, replace = T)),
val = sample(1:10, 1e6, replace = T))
> head(df)
group val
# 1 8498 8
# 2 5253 6
# 3 1495 1
# 4 7362 9
# 5 2344 6
# 6 5602 9
> dim(df)
# [1] 1000000 2
require(plyr)
require(doMC)
registerDoMC(20) # 20 processors
# parallelisation using doMC + plyr
P.PLYR <- function() {
o1 <- ddply(df, .(group), function(x) sum(x$val), .parallel = TRUE)
}
# no parallelisation
PLYR <- function() {
o2 <- ddply(df, .(group), function(x) sum(x$val), .parallel = FALSE)
}
require(rbenchmark)
benchmark(P.PLYR(), PLYR(), replications = 2, order = "elapsed")
test replications elapsed relative user.self sys.self user.child sys.child
2 PLYR() 2 8.925 1.000 8.865 0.068 0.000 0.000
1 P.PLYR() 2 30.637 3.433 15.841 13.945 8.944 38.858
As you can see, the parallel version of plyr runs 3.5 times slower
Now, let me use the same data.frame, but instead of computing sum, let me construct a bit more demanding function, say, median(.) * median(rnorm(1e4) ((meaningless, yes):
You'll see that the tides are beginning to shift:
# parallelisation using doMC + plyr
P.PLYR <- function() {
o1 <- ddply(df, .(group), function(x)
median(x$val) * median(rnorm(1e4)), .parallel = TRUE)
}
# no parallelisation
PLYR <- function() {
o2 <- ddply(df, .(group), function(x)
median(x$val) * median(rnorm(1e4)), .parallel = FALSE)
}
> benchmark(P.PLYR(), PLYR(), replications = 2, order = "elapsed")
test replications elapsed relative user.self sys.self user.child sys.child
1 P.PLYR() 2 41.911 1.000 15.265 15.369 141.585 34.254
2 PLYR() 2 73.417 1.752 73.372 0.052 0.000 0.000
Here, the parallel version is 1.752 times faster than the non-parallel version.
Edit: Following @Paul's comment, I just implemented a small delay using Sys.sleep(). Of course the results are obvious. But just for the sake of completeness, here's the result on a 20*2 data.frame:
df <- data.frame(group=sample(letters[1:5], 20, replace=T), val=sample(20))
# parallelisation using doMC + plyr
P.PLYR <- function() {
o1 <- ddply(df, .(group), function(x) {
Sys.sleep(2)
median(x$val)
}, .parallel = TRUE)
}
# no parallelisation
PLYR <- function() {
o2 <- ddply(df, .(group), function(x) {
Sys.sleep(2)
median(x$val)
}, .parallel = FALSE)
}
> benchmark(P.PLYR(), PLYR(), replications = 2, order = "elapsed")
# test replications elapsed relative user.self sys.self user.child sys.child
# 1 P.PLYR() 2 4.116 1.000 0.056 0.056 0.024 0.04
# 2 PLYR() 2 20.050 4.871 0.028 0.000 0.000 0.00
The difference here is not surprising.
A:
Completely agree with @Arun and @PaulHiemestra arguments concerning Why...? part of your question.
However, it seems that you can take some benefits from parallel package in your situation (at least if you are not stuck with Windows). Possible solution is using mclapply instead of parSapply, which relies on fast forking and shared memory.
tm2 <- system.time({
tm3 <- system.time({
df7 <- matrix(unlist(mclapply(df2$var1, FUN=function(x) {x==df1$var1}, mc.cores=8)), nrow=i)
dimnames(df7) <- list(row.names(df1), row.names(df2))
})
})
Of course, nested system.time is not needed here. With my 2 cores I got:
| {
"pile_set_name": "StackExchange"
} |
Q:
Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml
I am using Eclipse Luna and working on a maven project. When I add the entry for ojdbc jar in pom.xml , it is giving error in the xml. I can't find any reason for the issue as groupId, artifactId and version are correct.
How can I fix the problem?
A:
Due to Oracle license restriction, there are no public repositories that provide ojdbc jar.
You need to download it and install in your local repository.
Get jar from Oracle and install it in your local maven repository using
mvn install:install-file -Dfile={path/to/your/ojdbc.jar} -DgroupId=com.oracle
-DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
If you are using ojdbc7, here is the link
A:
This is the quickest way to solve the problem but it's not recommended because its applicable only for your local system.
Download the jar, comment your previous entry for ojdbc6, and give a new local entry like so:
Previous Entry:
<!-- OJDBC6 Dependency -->
<!-- <dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>runtime</scope>
</dependency> -->
New Entry:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/ojdbc6/ojdbc6.jar</systemPath>
</dependency>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prevent browsers downloading Google AdSense ADS on Mobile with responsive site?
With media query, I set the Div to display:none which contains AdSense code. However, I wanted to show another AdSense Ad which is in another DiV with display:block.
Need your help in understanding the below:
Does display:none will prevent sending the Ad request to Google or prevent it from downloading the AD from Google?
My challenge, the last I wanted to show will be fourth AdSense Ad and I cannot show 4 ads as per AdSense policy.
A:
display:none on parent div does not prevent ad request from that ad unit:
<div style="display:none">
<ins class="adsbygoogle adslot_1" ... ></ins>
</div>
That is a violation of AdSense policy about hiding ads: "Hiding ad units at anytime (e.g., display:none), unless you're implementing a responsive ad unit."
To prevent ad request, we need to apply display:none on AdSense ins tag:
<style type="text/css">
.adslot_1 { display: inline-block; width: 320px; height: 50px; }
@media (max-width: 400px) { .adslot_1 { display: none; } }
@media (min-width: 500px) { .adslot_1 { width: 468px; height: 60px; } }
@media (min-width: 800px) { .adslot_1 { width: 728px; height: 90px; } }
</style>
<ins class="adsbygoogle adslot_1"
data-ad-client="ca-pub-1234"
data-ad-slot="5678"></ins>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
That is "Hiding an ad unit" advanced feature. For the viewport less than 401px, above example will inject <!--No ad requested because of display:none on the adsbygoogle tag--> comment inside ins tag (instead of the advertisement).
I think my "How to 'move' AdSense ads" JSFiddle example is probably what you want - "I wanted to show another AdSense Ad which is in another DiV with display:block". (Move vertical border to see ads "moving".)
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a UNIQUE constraint from a JSON object
Lets take some example table peoples , that got only 2 fields: id and data(json).
SELECT data FROM peoples ;
{"name": "Adam","pos":"DBA","age":22 }
{"name": "Alice","pos":"Security","age":33 }
{"name": "Bob","pos":"Manager","age":42 }
I want to create constraint for "pos" field, that must be unique.
I've searched over the internet about JSON constraints but no results.
How can I handle this problem ?
A:
First and foremost: I agree with both the comments of @a_horse_with_no_name and @dezso: you should normalize your data. JSON is not for that.
However, if some reason I cannot fathom really makes this an advantage, it is possible:
Create an expression based UNIQUE INDEX:
CREATE UNIQUE INDEX people_data_pos_idx ON peoples( (data->>'pos') ) ;
If, at this point, you try to insert the following piece of data into your table (with an already existing ->>pos):
INSERT INTO peoples(data)
VALUES
('{"name": "Eve", "pos":"DBA", "age":34}') ;
You get this as a response:
ERROR: duplicate key value violates unique constraint "people_data_pos_idx"
SQL state: 23505
Detail: Key ((data ->> 'pos'::text))=(DBA) already exists.
NOTE: I've assumed that data.pos will always be a string. If you want to generalize, you can use ( (data->'pos') ) instead. You would index then a JSON(B) expression instead of a text. Check JSON Functions and Operators.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to configure apache tomcat to use a different java home when it's installed as a windows service?
I want to redistribute tomcat as part of my application. I'll be distributing a bundled jre as well, and I need to have my app's installer a) install the tomcat service in windows and b) not have it use JAVA_HOME if it's already set on the machine. That is, I need tomcat to point to my bundled jre.
I read here that you can pass a command line parameter to tomcat6w.exe to change the jre that tomcat uses. Will this change persist even after stopping the tomcat service?
I also noticed that the tomcat service manager program stores its settings in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters. Is it enough to change the Java\Jvm key to the jvm.dll of my bundled jre?
A:
The tomcat6.exe file that comes with the distribution has command line switches for doing all of this. It also comes with service.bat which does some of the work for you. I ended up modifying service.bat, passing in the --Jvm switch with the location of the jvm I wanted it to use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Responsive width with em unit in CSS
I am trying to make a custom slider for which I have found a sample code. I have customized it a bit as per my needs but unable to set the width of the slider range element appropriately.
The size and transformation calculations are defined in em units in using SCSS. I can set the width for $track-w in SCSS the slider is wide enough for my screen size but it comes differently for other screens. Below is the code.
$track-w: 55em; //this width is not responsive
$track-h: .25em;
$thumb-d: 1.5em;
$dist: $track-w - $thumb-d;
@mixin track() {
box-sizing: border-box;
border: none;
width: $track-w;
height: $track-h;
}
.wrap {
display: flex;
align-items: center;
position: relative;
width: $track-w;
height: 3.5*$thumb-d;
font: 1em/1 arial, sans-serif
}
[type='range'] {
&, &::-webkit-slider-thumb {
-webkit-appearance: none
}
flex: 1;
margin: 0;
padding: 0;
min-height: $thumb-d;
background: transparent;
font: inherit;
&::-webkit-slider-runnable-track {
@include track()
}
&::-moz-range-track { @include track }
&::-ms-track { @include track }
&::-webkit-slider-thumb {
margin-top: .3*($track-h - $thumb-d);
}
&::-ms-thumb {
margin-top: 0;
}
&::-ms-tooltip { display: none }
~ output {
display: none;
.js & {
display: block;
position: absolute;
left: .5*$thumb-d; top: 0;
padding: .25em .5em;
border-radius: 3px;
transform: translate(calc((var(--val) - var(--min))/(var(--max) - var(--min))*#{$dist} - 50%));
background: #4285f4;
color: #eee;
}
}
}
Here is the codepen link-https://codepen.io/thebabydino/pen/WdeYMd for the sample output and more details. How can I make the slider responsive? Please let me know if I can provide more details.
A:
The unit Em is merely responsive to the size of the font (of the element, Rem is of the root). To scale this you have to scale the font size.
Instead you can use other responsive units such as vw for view-width or vh for view-height (and vmin and vmax) or % (which comes with a bit of knowing how parents, position and display impact that)
Here's more info about units in css
Since a slider is more wide than high I suppose you could change the em for vw and play around with the values a bit.
See:
https://codepen.io/anon/pen/RYzpdx
This will be responsive as in always 50% of the page wide (I did add a 25vw margin to the left to center it, to show it off a bit beter)
$track-w: 50vw;
$track-h: .25vw;
$thumb-d: 1.5vw;
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows 2008 R2 not all folders showing in user home folder after migration
During our migration process from SBS2003 to Windows Server 2008 R2, I copied the user home directories across to their new location on the Windows 2008 R2 server.
I have a specific problem with one of the users.
She can access her files and folders "\old_server\users\HerUserName" and she can access her files in her My Documents on "\new_server\users\HerUserName\My Documents".
However when I copy her other folders in her user home directory across to the new server, i.e. "\old_server\users\HerUserName\Directory1" to "\new_server\users\HerUserName\Directory1" (using XCopy or RoboCopy), the folder and its content is copied across to the new server, and I can see the folder on the new server, but when browsing to the share from her desktop, she can only see her "My Documents" folder.
I have verified that she is the Owner of the folder that was copied to her home directory, and all the permissions also look ok.
Any assistance would be appreciated.
A:
Try using this on the server: attrib -s -h c:\users\HerUserName
Do this for each folder she can't see.
I guess robocopy set the hidden and/or system attribute on the copied folders. Already noticed this behaviour myself when copying from one server to another where they didn't know each others user accounts.
| {
"pile_set_name": "StackExchange"
} |
Q:
Doquier, dondequiera, adondequiera?
Es normal escuchar esta palabras, pero ¿verlas escritas? Es molesto, por lo menos para mi ver esas palabras así. ¿Están realmente bien escritas? Parece ser que doquier es una abreviatura de dondequiera. ¿No significarían lo mismo donde quiera y a donde quiera que sus formas en bloque?
Referencia: http://www.wordreference.com/definicion/doquier
A:
A diferencia de "dondequiera" y "adondequiera", que van seguidos de una relativa con "que", la palabra "doquier" se usa sola. Una de las combinaciones más habituales (en realidad, la única que me viene a la mente) es "por doquier" (que significa "por todas partes").
"Dondequiera" y "adondequiera" son respectivamente equiparables a "en cualquier lugar" y "a cualquier lugar", y siempre sirven de antecedente a una relativa. El "quiera" que las conforma es impersonal y no debe confundirse con el "quiera" personal correspondiente a la primera o tercera persona del singular, en cuyo caso se debe escribir por separado:
Irás a donde (yo) quiera que vayas.
Dejaré el presente donde (él/ella) quiera que lo deje.
En estos casos, "que" introduce una proposición nominal: Yo/Él/Ella quiero/e que ...
Para comprobar que "dondequiera" y "adondequiera" son impersonales y deben escribirse como una sola palabra, debemos poder reemplazar esas palabras por las frases, también impersonales, "(a) donde sea/fuera que".
| {
"pile_set_name": "StackExchange"
} |
Q:
Python3.5.2, selenium 3.0.0b2, Firefox 48.0: inconsistent use of tabs and spaces in indentation
Traceback (most recent call last):
File "C:/Users/****/PycharmProjects/********/load_all_params.py", line 2, in <module>
from selenium import webdriver
File "C:\Users\*****\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium-3.0.0b2-py3.5.egg\selenium\webdriver\__init__.py", line 25, in <module>
from .safari.webdriver import WebDriver as Safari # noqa
File "C:\Users\*****\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium-3.0.0b2-py3.5.egg\selenium\webdriver\safari\webdriver.py", line 49
executable_path = os.environ.get("SELENIUM_SERVER_JAR")
^
TabError: inconsistent use of tabs and spaces in indentation
Process finished with exit code 1
My question is this an error with my code or is this error caused by update to selenium-3.0.0b2? The weird thing is that I am using Firefox(48.0) and here the Safari is listed. What is going on?!
The script I wrote has no spaces or tabs - its just a list of commands.
My code sample:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://192.168.99.100:8080/***/***")
driver.implicitly_wait(10)
element = driver.find_element_by_id("lv-username")
and so on...
A:
I had the same error and what worked for me was going to the path of the init.py in your case it would be
"C:\Users*****\AppData\Local\Programs\Python\Python35-32\lib\site- packages\selenium-3.0.0b2-py3.5.egg\selenium\webdriver__init__.py"
Then just comment out the line
from .safari.webdriver import WebDriver as Safari # noqa
That is the one for the safari browser. Since that is not the one you want to use anyways.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cant place a div with width=100% next to a div with width=200px?
I have a Problem with two divs. The first one (DetailWrapper) should be on the left side with a width=100%. But next th this div there should be the second div (RightLinkBar) with a width=200px.
How can i get the two divs next to each other? at the Moment the RightLinkBar div is below the first one.
The Content of the div with the 100% width will be filled dynamically so i dont know how much content it will have. Because of the Background Color it should always have the whole place except the 200px which should be saved for the second div...
the HTML:
<div class="MainWrapper">
<div class="HeaderWrapper">
<!--BEGIN Header Bar -->
<div class="HeaderBar">
HeaderLine
</div>
<!--End Header Bar -->
</div>
<div class="DetailWrapper">
<!--BEGIN Detail Bar -->
<div class="DetailSection">
DetailSection
<div class="HeaderLeft">
HeaderLeft<br />Overflow so it can have every Size<br />test<br />test<br />test<br />test
</div>
<div class="NaviGraph">
NaviGraph<br />and<br />much<br />more<br />stuff<br />so<br />that<br />it<br />needs<br />some<br />space<br />whatever<br />
</div>
<div class="Detail">
Detail <br />one <br />with <br />any <br />height
</div>
<div class="Detail">
Detail <br />two <br />with <br />any <br />height<br />see?<br />its<br />bigger<br />than<br />one
</div>
<div class="Detail">
Detail <br />three <br />with <br />any <br />height<br />see?<br />between 2 and one
</div>
</div>
<!--END Detail Bar -->
<!--BEGIN Right Link Bar -->
<div class="RightLinkBar">
RightLinkBar
<div class="LinkItem">
Search Div
</div>
<div class="LinkItem">
Link Div One
</div>
<div class="LinkItem">
Link Div Two
</div>
</div>
<!--END Right Link Bar -->
</div>
and the CSS:
.MainWrapper
{
background-color: #FFFFFF;
border: 1px solid #000000;
height: 1200px;
width: 1000px;
background-color: Gray;
top: 100px;
left: 6%;
position: absolute;
}
.HeaderWrapper
{
background-color: #FFFFFF;
}
.HeaderBar
{
background-color: #E1E1F0;
width: 100%;
height: 50px;
}
.DetailWrapper
{
background-color: #FFFFFF;
height:100%;
width:100%;
}
.DetailSection
{
width: 100%;
height: 100%;
float: left;
background-color: #FFFFFF;
}
.HeaderLeft
{
background-color: #E1E1F0;
width: 100%;
overflow: auto;
}
.NaviGraph
{
background-color: #E1E1F0;
width: 100%;
height:300px;
}
.Detail
{
background-color: #E1E1F0;
width: 100%;
overflow: auto;
}
.RightLinkBar
{
background-color: #FFFFFF;
width: 200px;
height: 100%;
float: right;
}
.LinkItem
{
background-color: #E1E1F0;
width: 100%;
height: 100px;
}
I hope someone can help me out here!
Beste Regards
Khaine
A:
Width:100% is relative to the parent element, so there is no 200px left for the other div. You could for example use width:80% for the left div and width:20% for the right div.
.DetailWrapper
{
background-color: #FFFFFF;
width:80%;
}
.RightLinkBar
{
background-color: #FFFFFF;
width: 20%;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to connect a input box to an external database?
Hi I was wondering if anyone could tell me how to connect an email box to an external database for something like an email subscription. I don't really have any code to show but example..
<input type="email" placeholder="Your Email" maxlength="50">
How would I send what is input and submitted in that box to an external database?
A:
You may do it this way: bind an js event on your input, prevent default actions on this element. execute javascript ajax call to server with your external database, catch the request with php installed there, and then execute functions which will write to external(now local) database. The point is, you must work through 2 servers and 2 databases. this is not very effective. I recommend to move database form external resource to server, on which your php runs.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find most frequent values in numpy ndarray?
I have a numpy ndarray with shape of (30,480,640), the 1th and 2th axis representing locations(latitude and longitute), the 0th axis contains actual data points.I want to use the most frequent value along the 0th axis at each location, which is to construct a new array with shape of (1,480,640).ie:
>>> data
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[40, 40, 42, 43, 44],
[45, 46, 47, 48, 49],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
(perform calculation)
>>> new_data
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]]])
The data points will contain negtive and positive floating numbers. How can I perform such calculations? Thanks a lot!
I tried with numpy.unique,but I got "TypeError: unique() got an unexpected keyword argument 'return_inverse'".I'm using numpy version 1.2.1 installed on Unix and it doesn't support return_inverse..I also tried mode,but it takes forever to process such large amount of data...so is there an alternative way to get the most frequent values? Thanks again.
A:
To find the most frequent value of a flat array, use unique, bincount and argmax:
arr = np.array([5, 4, -2, 1, -2, 0, 4, 4, -6, -1])
u, indices = np.unique(arr, return_inverse=True)
u[np.argmax(np.bincount(indices))]
To work with a multidimensional array, we don't need to worry about unique, but we do need to use apply_along_axis on bincount:
arr = np.array([[5, 4, -2, 1, -2, 0, 4, 4, -6, -1],
[0, 1, 2, 2, 3, 4, 5, 6, 7, 8]])
axis = 1
u, indices = np.unique(arr, return_inverse=True)
u[np.argmax(np.apply_along_axis(np.bincount, axis, indices.reshape(arr.shape),
None, np.max(indices) + 1), axis=axis)]
With your data:
data = np.array([
[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[40, 40, 42, 43, 44],
[45, 46, 47, 48, 49],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
axis = 0
u, indices = np.unique(arr, return_inverse=True)
u[np.argmax(np.apply_along_axis(np.bincount, axis, indices.reshape(arr.shape),
None, np.max(indices) + 1), axis=axis)]
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
NumPy 1.2, really? You can approximate np.unique(return_inverse=True) reasonably efficiently using np.searchsorted (it's an additional O(n log n), so shouldn't change the performance significantly):
u = np.unique(arr)
indices = np.searchsorted(u, arr.flat)
A:
Use SciPy's mode function:
import numpy as np
from scipy.stats import mode
data = np.array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[40, 40, 42, 43, 44],
[45, 46, 47, 48, 49],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
print data
# find mode along the zero-th axis; the return value is a tuple of the
# modes and their counts.
print mode(data, axis=0)
| {
"pile_set_name": "StackExchange"
} |
Q:
Get locale in freemarker template
How can I get the current locale used in a freemarker template? I have seen implementation of <spring.message code />
I need this to do a conditional
<#if locale = DE >
.....
<#else>
....
</#if>
A:
As stated by the Freemarker documentation:
Special variables are variables defined by the FreeMarker engine itself. To access them, you use the .variable_name syntax
.locale: Returns the current value of the locale setting. This is a string, for example en_US. For more information about locale strings see the setting directive.
So to access the current local within a Freemarker template you would use
The current locale is: ${.locale}
To use it in a conditional statement as per your requirements, you would do:
<#if .locale == "DE">
...
<#else>
...
</#if>
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle: Select two different rows from one table and select value from another table if any of the entry does not exist
These are the two tables. I want to select created time of TABLE1 for type = 'PENDINGTIMESTAMP' and type = 'DISTRIBUTEDTIMESTAMP' for TABLE2ID.
TABLE1
+------+--------+--------------------+-------------------+
|ID |TABLE2ID|TYPE |CREATED |
+------+--------+--------------------+-------------------+
|156174|849118 |PENDINGTIMESTAMP |2016-09-09 03:33:11|
|156175|849118 |DISTRIBUTEDTIMESTAMP|2016-09-09 03:33:11|
|156176|849118 |PROCESSTIME |2016-09-09 03:33:11|
|156177|849119 |DISTRIBUTEDTIMESTAMP|2016-09-09 03:33:11|
|156178|849119 |PROCESSTIME |2016-09-09 03:33:11|
+------+--------+--------------------+-------------------+
TABLE2
+------+-------------------+
|ID |CREATED |
+------+-------------------+
|849118|2016-09-09 05:00:00|
|849119|2016-09-09 06:00:00|
+------+-------------------+
If any of the entry not exist in TABLE1 for TABLE2ID then i want select created time of TABLE2.CREATED where TABLE2.ID
Final Result would be
+--------+-------------------+-------------------+
|TABLE2ID|TIME1 |TIME2 |
+--------+-------------------+-------------------+
|849118 |2016-09-09 03:33:11|2016-09-09 03:33:01|
|849119 |2016-09-09 06:00:00|2016-09-09 03:33:01|
+--------+-------------------+-------------------+
For Highlighted entry -> Entry not exist in TABLE1 and created timestamp taken from TABLE2
TIME1 in the second row should be taken from TABLE2
I tried somethink like below. It is doing cartesian product and return two many rows
select
table2.id table2id,
case when t2.logtype = 'PENDINGTIMESTAMP' then t2.created else table2.created end as time1,
case when t1.logtype = 'NEWTIMESTAMP' then t1.created else table2.created end as time2
from
table2,
table1 t1,
table1 t2
where
table2.id(+) = t1.table2id
and table2.id(+) = t2.table2id
A:
i assume now, that table2 contains every possible table2id.
so I would create 2 outer joins from table2 to table1, one for pending and one for distributed timestamps.
finally, on selecting we can use the NVL function to use the created timestamp as fallback value.
SELECT m.id AS table2id,
NVL(p.created, m.created) AS time1,
NVL(d.created, m.created) AS time2
FROM table2 m
LEFT OUTER JOIN table1 p ON (p.table2id = m.id AND p.type = 'PENDINGTIMESTAMP')
LEFT OUTER JOIN table1 d ON (d.table2id = m.id AND d.type = 'DISTRIBUTEDTIMESTAMP')
or with Oracle outer join syntax (I'm not sure if the IS NULL is really necessary to compensate missing rows):
SELECT m.id AS table2id,
NVL(p.created, m.created) AS time1,
NVL(d.created, m.created) AS time2
FROM table2 m,
table1 p,
table1 d
WHERE m.id = p.table2id(+)
AND p.type(+) = 'PENDINGTIMESTAMP'
AND m.id = d.table2id(+)
AND d.type(+) = 'DISTRIBUTEDTIMESTAMP'
please note: I do not have a Oracle System to test the statement at hand, and I haven't used Oracle SQL syntax for about 3 years now. So please excuse, if there are syntactical errors.
But I hope, you get the idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
Even Perfect numbers $n$ with $n+1$ prime
The set $S$ of even perfect numbers $n$ such that $n+1$ is a prime number contains
$$
6,28,33550336,137438691328
$$
Latter number found by Joerg Arndt, corresponds to $M_{19}$ (mersenne)
Question: Is $S$ reduced to these $4$ numbers.
New: Joerg Arndt checked up to exponent $110503$ that the corresponding number $n+1$
is composite. (Improved $19$ to $110503$).
Which function of $x$ migh describe well the size of the set of elements in $S$ less than $x$
divided
by the size of the set of all even perfect numbers less than $x$; mainly with big $x.$
So, I am asking for relative size not absolute size. E.g., if I were asking
for relative density of the prime numbers congruent to $3$ modulo $4$: I do not want to use
the big machinery of the prime number theorem, or Dirichlet's Theorem to deduce how many should be there. I just want (in these case) to know how to describe in terms of $x$
number of primes congruent to $3$ modulo $4$ and less than $x$
divided by
number of primes less than $x$
How many such numbers $n$ we may
expect inside the known 47 perfect numbers ?
A:
There's a conjecture (for which I can't find a source now) that the number of Mersenne primes $2^n-1$ with $n < x$ is $c \log x$ for some constant $c$. Differentiating this, the "probability" that $2^n-1$ is prime is about $c/n$. (This is unconditional; that is, I'm not assuming $n$ is prime.)
The even perfect numbers are exactly of the form $2^{n-1}(2^n-1)$ with $2^n-1$ prime.
So the "probability" that $2^n-1$ and $2^{n-1} (2^n-1) + 1$ is prime, assuming independence, is $c/n$ times the probability that $2^{n-1} (2^n-1) + 1$ is prime. $2^{n-1} (2^n-1) + 1$ is roughly $2^{2n}$, so by the prime number theorem its "probability" of being prime is about $1/log(2^{2n})$, or again a constant divided by $n$. That is, the "probability" that $2^n-1$ is prime and the corresponding number is one less than a prime is $c/n^2$; since $\sum_{n \ge 1} cn^{-2}$ is finite this leads us to suspect that there are finitely many solutions.
Of course none of this is anywhere near being a proof...
A:
For dealing with large potential primes a good choice is openpfgw
Using openpfgw I finished the list to $1 3466 917$ in about 20 minutes without finding new primes.
[added] The only prime perfect + 1 candidate from the known Mersenne primes is for $M_{20996011}$ - I am running ECM factoring on it.
[later] François Brunault found that $M_{20996011}$ is divisible by $1552147$ which settles the question for the known perfect numbers.
Here is the log:
./pfgw64 -f10 -lmer1log.txt /tmp/mer.txt
2^0*(2^1-1)+1 is trivially prime!: 2
2^1*(2^2-1)+1 is trivially prime!: 7
2^2*(2^3-1)+1 is trivially prime!: 29
2^4*(2^5-1)+1 trivially factors as: 7*71
2^6*(2^7-1)+1 trivially factors as: 11*739
2^12*(2^13-1)+1 is trivially prime!: 33550337
2^16*(2^17-1)+1 has factors: 7
2^18*(2^19-1)+1 is 3-PRP! (0.0000s+0.0009s)
2^30*(2^31-1)+1 has factors: 29
2^60*(2^61-1)+1 is composite: RES64: [36E090A8C361AD6C] (0.0000s+0.0003s)
2^88*(2^89-1)+1 has factors: 7
2^106*(2^107-1)+1 has factors: 7
2^126*(2^127-1)+1 has factors: 11
2^520*(2^521-1)+1 has factors: 7
2^606*(2^607-1)+1 has factors: 11
2^1278*(2^1279-1)+1 is composite: RES64: [570A6B3FD91E6339] (0.8700s+0.0011s)
2^2202*(2^2203-1)+1 is composite: RES64: [ECB4FE924C674723] (4.6906s+0.0010s)
2^2280*(2^2281-1)+1 has factors: 197
2^3216*(2^3217-1)+1 has factors: 11
2^4252*(2^4253-1)+1 has factors: 7
2^4422*(2^4423-1)+1 is composite: RES64: [F3603EEF4BD4F197] (17.0237s+0.0031s)
2^9688*(2^9689-1)+1 has factors: 7
2^9940*(2^9941-1)+1 has factors: 7
2^11212*(2^11213-1)+1 has factors: 7
2^19936*(2^19937-1)+1 has factors: 7
2^21700*(2^21701-1)+1 has factors: 7
2^23208*(2^23209-1)+1 has factors: 35603
2^44496*(2^44497-1)+1 has factors: 11
2^86242*(2^86243-1)+1 has factors: 7
2^110502*(2^110503-1)+1 has factors: 491
2^132048*(2^132049-1)+1 is composite: RES64: [1B3B60AEC3578817] (744.2790s+111.7145s)
2^216090*(2^216091-1)+1 has factors: 4673
2^756838*(2^756839-1)+1 has factors: 7
2^859432*(2^859433-1)+1 has factors: 7
2^1257786*(2^1257787-1)+1 has factors: 11
2^1398268*(2^1398269-1)+1 has factors: 7
2^2976220*(2^2976221-1)+1 has factors: 7
2^3021376*(2^3021377-1)+1 has factors: 7
2^6972592*(2^6972593-1)+1 has factors: 7
2^13466916*(2^13466917-1)+1 has factors: 11
The rest Mersenne primes lead to small factors:
Format ($p$,factor) (24036583,149),(25964951,7),( 30402457,11),( 32582657,7),( 37156667,7),( 42643801,3593),( 43112609,7)
A:
The numbers involved are pretty huge - have you tried all the Mersenne primes' perfect numbers yet?
The other answer might be referring to Wagstaff's conjecture about the number of these primes being less than $e^{\gamma}/\log(2) *\log(\log(x))$; see e.g. here, here, or here for some references (some better than others).
I would imagine that this would be helpful in solving this, but gives a sense of just how hard it would be to prove anything.
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory deallocation of pointer variable in c++
If I take a block of memory by the following line .
int* a = new int[10];
Then for freeing the memory , the code would be
delete [] a;
But if I take a pointer of single memory segment like the following
int* a = new int;
And then insert a array of data like following .
for(int i=0;i<10;i++)
{
a[i]= i ;
}
So to free the first memory segment that pointer "a" is pointing, the code would be like following
delete a;
But Here I inserted 9 more data from the memory that pointer "a" is pointing .So I am using actually 10 memory segment here . how can I free all this 10 memory ? Please help me to get the answer .
A:
how can I free all this 10 memory ?
You can't and you shouldn't because the moment you tried to "insert a array of data like following" you have entered Undefined Behavior land for writing to a location that you didn't allocate with new in the first place. You asked for a single int, you got a single int. Don't write past it.
| {
"pile_set_name": "StackExchange"
} |
Q:
changing the titlebar results in not showing (fonts issue) the listview items
I want to change the title bar color .Following the instructions here
, or eliminating the title bar with Notitle bar in AndroidManifest esults in not showing the text fonts in the list view (I use "simple_list_item_checked" listview).
Here is the xml for this activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#FFFAFA"
>
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/green_button"
android:text="@string/show_items_kfc"
android:onClick="onClick"/>
<ListView
android:id="@+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
(the rest of xml code is the same as the link above)
Any solutions to this?
Thanks!
A:
If I got the problem:
Instead of parent="android:Theme":
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="customTheme" parent="android:Theme">
<item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
</style>
</resources>
Use parent="android:Theme.Light":
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="customTheme" parent="android:Theme.Light">
<item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
</style>
</resources>
The problem is that you are overriding the native Black theme which has black background and white letters. By switching to Light theme you achieve the black letter also have your own white background!
Note: After that you may have to fix custom theme colors (eg. title text color force to white) to white/black if they do not fit the UI you need.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flycheck and syntax tables: erroneous behavior I'm unsure how to fix
In the course of writing a Flycheck checker for ten-hundred-mode's new (and as yet inchoate) permissive mode, I noticed that the checker's overlay behavior was influenced by the currently active syntax table in a way that didn't work out well for my purposes.
Consider the following text:
Now they've done it.
"They've" is not one of the thousand most commonly used words, and my checker will report it as an error at line 1, column 5.
In text-mode, or a major mode which uses a syntax table derived from text-mode-syntax-table, Flycheck will overlay as follows:
Now they've done it.
This is, of course, the correct behavior.
In a mode whose syntax table doesn't derive from text-mode's, though -- notably, any programming mode -- Flycheck instead does this:
Now they've done it.
This appears to occur because ' is a word-constituent character in text-mode-syntax-table and its derivatives, but not in the syntax tables of programming modes. I'm not certain why this affects overlay positioning, but my surmise is that Flycheck's method of inferring where a given overlay should end makes use of syntax classes. In any case, it's trivial to produce both correct and incorrect behavior by switching the syntax table or major mode.
(Since "they" is a permissible word, it's reasonable to suspect that the problem here lies with the checker's matching behavior, and not with Flycheck's overlaying behavior. Indeed, that was my initial suspicion, and I spent a couple of hours looking for a bug in my own code and not finding it, before being reluctantly forced to the conclusion that the problem lay elsewhere.)
Since my checker code only controls what problems are reported to Flycheck, and not how Flycheck chooses to overlay them, I'm somewhat at a loss for how to proceed here. In private code I could advise flycheck-error-region-for-mode to conditionally wrap it in with-syntax-table, or something like that, but this is a publicly distributed module, so advice is off the table. Unfortunately, I'm not seeing any other way to get the behavior I need.
Can someone with more knowledge of Flycheck's internals suggest a way in which I can produce correct overlay behavior regardless of the currently active syntax table?
A:
You cannot easily fix this issue. It's a consequence of how we highlight errors in Flycheck.
Currently Flycheck can only receive a single position from a syntax checker, as a pair of line and column. A single character highlight is all too easy to overlook, however, so Flycheck tries to be smart and expand the highlighting region reasonably.
The exact behaviour is controlled by flycheck-highlighting-mode whose default symbols—which you see here—expands the highlighting to symbol boundaries around the column position.
Symbol boundaries are defined by the syntax table, but there's only one for the entire buffer. If the syntax table turns ' into punctuation this behaviour spills into comments even though these are typically free text.
Hence the behaviour you see here: The symbol around the column reported by your syntax checker simply ends at '.
At some point we will support error ranges in Flycheck which let syntax checkers explicitly specify the whole region for the highlight, but that's still far off. At this point we'll also provide a more flexible API to add Flycheck highlights to the current buffer which will let you programmatically add errors to the current buffer without the additional indirection of a syntax checker.
But meanwhile you simply have to accept this behaviour. Other than advising as you suggested there's nothing that you can do.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is this code producing an exponential loop? .Net, Lehvenstein Distance
So recently I embarked on a coding project to try create some code to mathematically create a way to depict how similar two strings are. On my research I found plenty of examples online to help me create the code I desired.
I have an error with one I found which in my running of it is creating, what I am calling, exponential loops. It's not an infinite loop, it runs and it solves problems, but the longer the strings I pass into the method the exponentially longer the method runs for. The code is here below
public static int LevenshteinDistance(this string source, string target)
{
Console.WriteLine("Start of method");
if (source.Length == 0) { return target.Length; }
if (target.Length == 0) { return source.Length; }
int distance = 0;
Console.WriteLine("Distance creation");
if (source[source.Length - 1] == target[target.Length - 1]) { distance = 0; }
else { distance = 1; }
Console.WriteLine("Recursive MethodCall");
return Math.Min(Math.Min(LevenshteinDistance(source.Substring(0, source.Length - 1), target) + 1,
LevenshteinDistance(source, target.Substring(0, target.Length - 1))) + 1,
LevenshteinDistance(source.Substring(0, source.Length - 1), target.Substring(0, target.Length - 1)) + distance);
}
So, for smaller strings this method runs just fine however, when I start to pass in things like addresses or long names it takes a long time. So long in fact I disbanded this method entirely and wrote another one (i'll provide this if anybody wants it but it's not important for the question) which serves my purpose but in the interest of solving problems and learning, I tried to figure out exactly why this one was taking so long when coded recursively. I stepped through my code with pen and paper, in debug mode and when I get to the recursive call here
return Math.Min(Math.Min(LevenshteinDistance(source.Substring(0, source.Length - 1), target) + 1,
LevenshteinDistance(source, target.Substring(0, target.Length - 1))) + 1,
LevenshteinDistance(source.Substring(0, source.Length - 1), target.Substring(0, target.Length - 1)) + distance);
}
And I can work out what is happening solidly for these parts
return Math.Min(***Math.Min(LevenshteinDistance(source.Substring(0, source.Length - 1), target) + 1,
LevenshteinDistance(source, target.Substring(0, target.Length - 1))) + 1,***
LevenshteinDistance(source.Substring(0, source.Length - 1), target.Substring(0, target.Length - 1)) + distance);
}
I tried to bolden and italicize the part I mean, it's the part with '***' around it. Getting to that part I understand but then the next part, the third LevenshteinDistance Call and it's first iteration I start to lose focus on recursion and how it works and where my confusion starts. This part
LevenshteinDistance(source.Substring(0, source.Length - 1), target.Substring(0, target.Length - 1)) + distance);
}
The code from what I gather once it reaches this call then starts to do the first LevenshteinDistance call all over again and reiterating over the calls it just performed. This is what I'm being confused on. Why does it call the first part of the recursive call again and then the second and what is causing the time to complete the code to lengthen exponentially?
Note: The time may not be exponentially in the literal sense, the times for running a short string comparison were sub-second and once the strings got a little longer it jumper from sub-second -> ~15 seconds -> 2:30 mins -> 35 minutes
2nd Note: Tagged as infinite loop as exponential loop doesn't exist and this somewhat is close to it.
A:
Because it's recursive, not just single recursion (like you would use for a treeview), this puppy passes the return result of itself 3 recursive calls!
That's why your seeing exponential timing increases with longer strings.
| {
"pile_set_name": "StackExchange"
} |
Q:
NodeJS MongoDB cursor toArray callback function doesn't make changes on parent scope variable
MongoClient.connect(dburl, function (err, db) {
var collections = [];
db.listCollections().toArray(function (err, collInfos) {
for (var i = 0; i < collInfos.length; i++) {
collections[i] = collInfos[i].name;
}
console.log(collections);
});
console.log(collections);
});
So I want to get all my database collections into an array of strings and this is a piece of my code.
The problem is that the console.log outside of the toArray callback gets executed first and outputs [], whereas the console.log inside the toArray callback outputs the array properly.
It seems to me there is some kind of scope problem but I am not familiar with how NodeJS and MongoDB exactly.
A:
This portion of the code is asynchronous:
db.listCollections().toArray(function (err, collInfos) {
for (var i = 0; i < collInfos.length; i++) {
collections[i] = collInfos[i].name;
}
console.log(collections);
});
So it will execute after your second call to console.log(collections), which is why you see an empty array [] first and then a populated list of collections. It's not a scope problem but a confusion about synchronous vs asynchronous function call order.
If I were you, I would ditch the callback pattern and instead use promises. Then you can do something like this:
var Promise = require('bluebird');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var Collection = mongodb.Collection;
Promise.promisifyAll(Collection.prototype);
Promise.promisifyAll(MongoClient);
var client = MongoClient.connectAsync('mongodb://localhost:27017/test')
.then(function(db) {
return db.collection("myCollection").findOneAsync({ id: 'someId' })
})
.then(function(item) {
// Use `item`
})
.catch(function(err) {
// An error occurred
});
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift 4: Save and retrieve an array of custom objects (with nested custom objects) to UserDefaults
I am trying to save an array of custom objects to UserDefaults. I believe I should, at this point, be saving correctly, but I continue to get the "unrecognized selector" error. I think this may be because two parts of my custom object are arrays of other custom objects. What am I doing wrong here?
The Object:
class SaleObject: NSObject, NSCoding {
//MARK: Properties
var ranges: [RangeObject]
var timberSaleName: String
var lbOperatorName: String
var lbOperatorID: String
var timberSaleID: Int
var ID: Int
var contracts: [ContractObject]
//MARK: Initialization
init(ranges: [RangeObject], timberSaleName: String, lbOperatorName: String, lbOperatorID: String, timberSaleID: Int, ID: Int ,contracts: [ContractObject]) {
//Initialize stored properties
self.ranges = ranges
self.timberSaleName = timberSaleName
self.lbOperatorName = lbOperatorName
self.lbOperatorID = lbOperatorID
self.timberSaleID = timberSaleID
self.ID = ID
self.contracts = contracts
}
required init?(coder aDecoder: NSCoder) {
self.ranges = (aDecoder.decodeObject(forKey: "ranges") as? [RangeObject])!
self.timberSaleName = (aDecoder.decodeObject(forKey: "timber_sale_name") as? String)!
self.lbOperatorName = (aDecoder.decodeObject(forKey: "lb_operator_name") as? String)!
self.lbOperatorID = (aDecoder.decodeObject(forKey: "lb_operator_id") as? String)!
self.timberSaleID = (aDecoder.decodeObject(forKey: "timber_sale_id") as? Int)!
self.ID = (aDecoder.decodeObject(forKey: "id") as? Int)!
self.contracts = (aDecoder.decodeObject(forKey: "contracts") as? [ContractObject])!
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.ranges, forKey: "ranges")
aCoder.encode(self.timberSaleName, forKey: "timber_sale_name")
aCoder.encode(self.lbOperatorName, forKey: "lb_operator_name")
aCoder.encode(self.lbOperatorID, forKey: "lb_operator_id")
aCoder.encode(self.timberSaleID, forKey: "timber_sale_id")
aCoder.encode(self.ID, forKey: "id")
aCoder.encode(self.contracts, forKey: "contracts")
}
}
The save attempt:
let userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: self.saleArray)
userDefaults.set(encodedData, forKey: "sales")
The error:
2018-11-28 14:28:30.024768-0600 Load BOSS[14991:282335]
libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not
supported on this platform.
2018-11-28 14:28:30.362954-0600 Load BOSS[14991:282335] [MC] System
group container for systemgroup.com.apple.configurationprofiles path
is /Users/beauburchfield/Library/Developer/
CoreSimulator/Devices/4ED03814-DD8C-43F3-ABA7-
B5D0751161A0/data/Containers/Shared/SystemGroup/
systemgroup.com.apple.configurationprofiles
2018-11-28 14:28:30.364591-0600 Load BOSS[14991:282335] [MC] Reading
from private effective user settings.
2018-11-28 14:28:31.034136-0600 Load BOSS[14991:282394] -
[Load_BOSS.RangeObject encodeWithCoder:]: unrecognized selector sent
to
instance 0x600001bcc680
2018-11-28 14:28:31.037429-0600 Load BOSS[14991:282394] ***
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[Load_BOSS.RangeObject
encodeWithCoder:]: unrecognized selector sent to instance
0x600001bcc680'
*** First throw call stack:
(
0 CoreFoundation 0x000000010cbc51bb _ .
_exceptionPreprocess + 331
1 libobjc.A.dylib 0x000000010b73b735
objc_exception_throw + 48
2 CoreFoundation 0x000000010cbe3f44 -
[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010cbc9ed6 ___forwarding___ + 1446
4 CoreFoundation 0x000000010cbcbda8 _CF_forwarding_prep_0 + 120
5 Foundation 0x000000010b182175 _encodeObject + 1230
6 Foundation 0x000000010b182aee -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 439
7 Foundation 0x000000010b182175 _encodeObject + 1230
8 Load BOSS 0x000000010add0e2f $S9Load_BOSS10SaleObjectC6encode4withySo7NSCoderC_tF + 207
9 Load BOSS 0x000000010add128c $S9Load_BOSS10SaleObjectC6encode4withySo7NSCoderC_tFTo + 60
10 Foundation 0x000000010b182175 _encodeObject + 1230
11 Foundation 0x000000010b182aee -[NSKeyedArchiver _encodeArrayOfObjects:forKey:] + 439
12 Foundation 0x000000010b182175 _encodeObject + 1230
13 Foundation 0x000000010b18122e +[NSKeyedArchiver archivedDataWithRootObject:] + 156
14 Load BOSS 0x000000010adbf15a $S9Load_BOSS18MainViewControllerC14getJsonFromUrlyyFy10Foundation4DataVSg_So13NSURLResponseCSgs5Error_pSgtcfU_ + 15706
15 Load BOSS 0x000000010adbf43d $S9Load_BOSS18MainViewControllerC14getJsonFromUrlyyFy10Foundation4DataVSg_So13NSURLResponseCSgs5Error_pSgtcfU_TA + 13
16 Load BOSS 0x000000010adbf590 $S10Foundation4DataVSgSo13NSURLResponseCSgs5Error_pSgIegggg_So6NSDataCSgAGSo7NSErrorCSgIeyByyy_TR + 336
17 CFNetwork 0x000000010e0d9940 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke + 19
18 CFNetwork 0x000000010e0efb0c __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 172
19 Foundation 0x000000010b1a8f9e __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7
20 Foundation 0x000000010b1a8ea5 -[NSBlockOperation main] + 68
21 Foundation 0x000000010b1a5c14 -[__NSOperationInternal _start:] + 689
22 Foundation 0x000000010b1abc4b __NSOQSchedule_f + 227
23 libdispatch.dylib 0x000000010f0ae595 _dispatch_call_block_and_release + 12
24 libdispatch.dylib 0x000000010f0af602 _dispatch_client_callout + 8
25 libdispatch.dylib 0x000000010f0b254d _dispatch_continuation_pop + 565
26 libdispatch.dylib 0x000000010f0b1927 _dispatch_async_redirect_invoke + 859
27 libdispatch.dylib 0x000000010f0c000a _dispatch_root_queue_drain + 351
28 libdispatch.dylib 0x000000010f0c09af _dispatch_worker_thread2 + 130
29 libsystem_pthread.dylib 0x000000010f49e70e _pthread_wqthread + 619
30 libsystem_pthread.dylib 0x000000010f49e435 start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
A:
Go ahead and implement NSCoding for the other two custom objects. Also, change your decodeObject to decodeInteger on all Integers of your custom objects, and remove the "as! Int" from them. Then, do this:
let userDefaults = UserDefaults.standard
let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.saleArray)
userDefaults.set(encodedData, forKey: "sales")
To retrieve the data, do this:
let newArray = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as! [SaleObject]
After you have it working, go back and research Codable. Enjoy!
| {
"pile_set_name": "StackExchange"
} |
Q:
Unslider dots function not showing
I'm building a website where there is a slider on top, I wanted to use the unslider because it seems very easy.
According to the site you should just use the function- dots: true
I have that, but my slider doesn't have any slides.
The site where I'm trying to set things up.
(its a school project)
A:
Try adding some CSS.
.dots {
position: absolute;
left: 0;
right: 0;
bottom: 20px;
text-align: center;
}
.dots li {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 4px;
text-indent: -999em;
border: 2px solid #fff;
border-radius: 6px;
cursor: pointer;
opacity: .4;
-webkit-transition: background .5s, opacity .5s;
-moz-transition: background .5s, opacity .5s;
transition: background .5s, opacity .5s;
}
.dots li.active {
background: #fff;
opacity: 1;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Building coded ui test project fails when "Perform runtime contract checking" is set to "full"
I have a simple Test project where a CodedUITestMethod is created. The test method simply clicks the Windows Start button in the taskbar. The method is generated by the Coded UI Test Builder tool from Visual Studio 2010 Ultimate.
Then, I go to project's Properties page, Code Contracts tab.
Check the Perform Runtime Contract Checking check box.
Change the value of Contract Reference Assembly combo box to "Build".
Now I hit F6 to build the project and receive the 2 errors:
Reading assembly 'Microsoft.VisualStudio.TestTools.UITesting' resulted in errors.
C:\Program Files (x86)\Microsoft\Contracts\MsBuild\v4.0\Microsoft.CodeContracts.targets (240,5): error MSB3073: The command ""C:\Program Files (x86)\Microsoft\Contracts\Bin\ ccrewrite" "@CodedUITest_Contract2ccrewrite.rsp"" exited with code -1.
I have uploaded my project zip file to my codeplex project
Could someone download the project and see if they can reproduce the compile error? Thanks.
A:
The problem is solved. It appears that Microsoft.VisualStudio.TestTools.UITesting.dll references another dll that is not added into the project.
Add Microsoft.VisualStudio.TestTools.UITest.Playback.dll in the folder C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\ solves the issue.
Thanks to David K Allen who answered the question on the msdn forum.
| {
"pile_set_name": "StackExchange"
} |
Q:
'currentApple' is already defined showing in jslint
I have have a js code...
in that i ran the js lint...
i have this error 'currentApple' is already defined....
do i need to remove var currentApple from else will it work...
providing my code below...
if(appleTab == Lifeline){
var currentApple = appleWorklist.getcurrentAppleTime("currentAppointmentcurrentAppleTime");
fo.allApples = currentApple;
}
else
{
var currentApple = appleWorklist.getcurrentAppleTime("CalendarcurrentAppointmentcurrentAppleTime");
fo.allApples = currentApple;
}
A:
var currentApple;
if (appleTab == Lifeline) {
currentApple = /* etc. */
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting elements in a big vector in R
I'm working with vectors in R, storing bigz objects (GMP package). It works fine when the vector is not too big (up to 200 elems), but when the vector grows, the performance decrease dramatically.
Trying to get where the bottleneck is, I execute my programm with the profvis library, and I get that the problem is the next piece of code:
res <- as.bigz(rep(0, length(resT))) #resT is a list of bigz of length 600
res[[1]] <- sum.bigz(a_bigz_elem, another_bigz_elem)
i <- 1
while (i <= length(resT) - 1) {
res[[i + 1]] <- sum.bigz(resT[[i + 1]], resE[[i + 1]])
i <- i + 1
}
and more specifically, in the 5th line (the elem assignment in the list).
I know this solution is better than a growing vector, i.e. res <- c(res, sum.bigz(resT[[i + 1]], resE[[i + 1]])), but I'm pretty sure there is a more efficient way to do the assignment.
I've read related post in SO and the Advanced R reference documentation, but nothing improves my performance. Any idea how can it be improved?
A:
With
res <- as.bigz(rep(0, length(resT))) #resT is a list of bigz of length 600
you are not creating a list. When you change it to:
res <- as.list(as.bigz(rep(0, length(resT))))
you create a list and the execution time should be reduced.
A reproducible example would look like:
library(gmp)
resT <- as.list(urand.bigz(600, seed=0))
resE <- as.list(urand.bigz(600, seed=1))
a_bigz_elem <- resT[[1]]
another_bigz_elem <- resE[[1]]
res <- as.list(as.bigz(rep(0, length(resT))))
res[[1]] <- sum.bigz(a_bigz_elem, another_bigz_elem)
i <- 1
while (i <= length(resT) - 1) {
res[[i + 1]] <- sum.bigz(resT[[i + 1]], resE[[i + 1]])
i <- i + 1
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Android: in RecyclerView Adapter how do I test if an entry from SQLite database isNull?
I have a RecyclerView list of CardViews. The CardViews show user entered data that is stored in a SQLite database. One of the data fields from the database is a DueDate thtat stores a date from a DatePicker. If the user does not enter a DueDate then the SQLite database entry for the DueDate column is "NULL".
I would like to test in onBindViewHolder() whether the DueDate entry is "NULL" or not. What am I missing here?
Model file is Contact.java:
private String duedate;
...
public String getDuedate() {
return duedate;
}
RecyclerView Adapter.java:
...
private List<Contact> contactList;
public ContactListAdapter(Context context) {
this.context = context;
this.contactList = new ArrayList<>();
}
...
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {
final Contact contact = contactList.get(viewHolder.getAdapterPosition());
final ContactHolder holder = (ContactHolder) viewHolder;
*** here is where I'm lost ***
if (contact.getDuedate() = isNull) { // If no DueDate, setText below.
holder.cardBlankText10.setText("DueDate not entered");
} else {
...
A:
*** here is where I'm lost ***
if (contact.getDuedate() == null) { // If no DueDate, setText below.
holder.cardBlankText10.setText("DueDate not entered");
} else {
| {
"pile_set_name": "StackExchange"
} |
Q:
inserting table through directive
I am trying to insert a table through a directive in Angular1.3 -
controller
var studentControllerModule = angular.module('studentDetailApp.controllers', []);
/*StudentController: controller for students*/
studentControllerModule.controller('StudentController', function ($scope) {
$scope.studentList = [ ....];
});
directive
angular.module('studentDetailApp.directives',[]).directive('studentDirective', function () {
return {
template: '<table><thead><tr> <th>NAME</th><th>COUNTRY</th></tr></thead><tbody> <tr ng-repeat="aStudent in studentList"><td>{{aStudent.name }}</td><td>{{aStudent.country }}</td></tr></tbody></table>'};
});
index.html
<html lang="en" ng-app="studentDetailApp">
<head>
<title>AngularJS Partial example</title>
<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>
</head>
<body>
<div ng-controller="StudentController">
<div studentDirective></div>
</div>
</body>
</html>
I get no exception - but I do not see the table either.
What am I doing wrong?
A:
You were missing your ng-app, directives need to be normalized in the html:
https://docs.angularjs.org/guide/directive
Modified HTML:
<body ng-app="studentDetailApp">
<div ng-controller="StudentController">
<div class='a' student-directive></div>
</div>
</body>
Modified JS:
var app = angular.module('studentDetailApp', []);
app.controller('StudentController', function ($scope) {
$scope.studentList = ['nate', 'john', 'seth'];
});
app.directive('studentDirective', function () {
return {
template: '<table><thead><tr> <th>NAME</th><th>COUNTRY</th></tr></thead><tbody> <tr ng-repeat="aStudent in studentList"><td>{{aStudent.name }}</td><td>{{aStudent.country }}</td></tr></tbody></table>'
};
});
https://jsfiddle.net/cn3otfa6/3/
| {
"pile_set_name": "StackExchange"
} |
Q:
Deploying Sinatra app on Dreamhost/Passenger with custom gems
I've got a Sinatra app that I'm trying to run on Dreamhost that makes use of pony to send email. In order to get the application up and running at the very beginning (before adding pony), I had to gem unpack rack and gem unpack sinatra into the vendor/ directory, so this was my config.ru:
require 'vendor/rack/lib/rack'
require 'vendor/sinatra/lib/sinatra'
set :run, false
set :environment, :production
set :views, "views"
require 'public/myapp.rb'
run Sinatra::Application
I have already done gem install pony and gem unpack pony (into vendor/). Afterwards, I tried adding require 'vendor/sinatra/lib/pony' to config.ru only to have Passenger complain about pony's dependencies (mime-types, tmail) not being found either!
There has to be a better way to use other gems and tone down those long, ugly, redundant requires. Any thoughts?
A:
I'd recommend creating your own gem path "somewhere" then adding it in your config.ru
like:
ENV['GEM_PATH'] = xxx
Gem.clear_paths
then install your gems into that
A:
Install Ruby gems on dreamhost
http://c.kat.pe/post/installing-ruby-gems-on-dreamhost/
Change config.ru (works for Sinatra 1.0)
require 'rubygems'
require 'vendor/sinatra/lib/sinatra.rb'
ENV['GEM_HOME'] = '/home/username/.gems'
ENV['GEM_PATH'] = '$GEM_HOME:/usr/lib/ruby/gems/1.8'
require 'rubygems'
Gem.clear_paths
disable :run, :reload
set :environment, :production
require 'yourapp'
run Sinatra::Application
Hope it helps someone.
I am using pony and a lot of other gems for my Sinatra. It should work well for you too. It's just those two lines (GEM_HOME and GEM_PATH) you have to add on your config.
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking if object is an object literal
Going on from this question here: Checking for undefined
I wanted to know if an object was an Array, now I need to test to see if an Object is specifically an Object and not just a subclass of an Object
Because at the moment an Array would return true if checked to see if it is an instance of an Object. Are there any other types that would evaluate to true?
EXTRA INFO
I have found that if you call toString on an Array that has one string element it resolves to that string element and not "[object Array]" so you need to be careful of that. For example:
["str1", "str2"].toString() === "[object Array]"
but
["str1"].toString() === "str1"
A:
Test like this:
if ({}.toString.call(obj) == '[object Object]') {
// is object
}
if ({}.toString.call(obj) == '[object Array]') {
// is array
}
obj is any object. Same with objects such as RegExp, Date, etc... In old IE you may need to do ({}) for it to work properly.
Demo: http://jsbin.com/exofup/2/edit
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to have a Shiny ConditionalPanel whose condition is a global variable?
My goal is to have a tabsetPanel wrapped in a conditionalPanel whose condition is a global variable being false.
ui.R
mainPanel(
conditionalPanel("searchPage == \"false\"",
tabsetPanel(
tabPanel("Summary",htmlOutput("summary")),
tabPanel("Description", htmlOutput("description"))
))),
global.R
searchPage <- "true"
then in server.R I assign new values to it a few different times, but all like this:
observeEvent(input$openButton,
output$results <- renderUI({
textOutput("")
searchPage <- "false"
}))
No matter what I do, I always get "Uncaught ReferenceError: searchPage is not defined". I've tried changing the global.R to multiple different combinations of using quotes, not using quotes, using <- or <<-, making it this.searchPage, my.searchPage and numerous other things (of course always making server.R and ui.R match too), but haven't had much luck at all.
A:
As mentioned in a comment on the question's post, this is a perfect usecase for the shinyjs toggle()/show()/hide() functions. Whenever you need to conditionally show something where the condition is not a simple javascript expression of an input, it's easy to use these functions instead of a conditionalPanel().
In order to use these functions, you need to have some way to specify the element you want to hide/show (in this case, the mainPanel()). The easist way to do this is to just wrap the entire panel in a div with an id. So define the panel like mainPanel(div(id = "mainpanel", ...)) and voila, there's an id to your panel, and now you can call shinyjs::show("mainpanel") or hide() whenever you want in the server code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unity3D Collision on Demand
I'm working on a title where a player can drop a bomb on his current position. The problem is that I whish, that the player cannot walk through any placed bomb (except he took up an specific item).
But a non-trigger collider causes, that placing the bomb pushes the player away (maybe into a wall, where he finally stuck), which seems not to be the way.
So is there any easy way to enable the collision with the bomb, which stops player movement script-based or do I have to check on each step the player takes, if he would collide with a bomb and stop the movement?
Update (Answer to Comment from Programmer)
If the bomb collider is not meant as a trigger, which would cause the auto collision behaviour, the player who drops the bomb as his current position, is pushed away in any direction, which is event not the wished behaviour, because the player can also pushed into a wall, where he cannot get out.
Update (after Answer from Jeroen De Clercq)
The bomb collider is initially set to trigger and the attached script looks like this:
public class Bomb : MonoBehaviour
{
private SphereCollider collider;
// Use this for initialization
void Start()
{
collider = GetComponent<SphereCollider>();
}
// Update is called once per frame
void Update()
{
Collider[] collidings = Physics.OverlapSphere(gameObject.transform.position, 1);
if (!collidings.Any(s => s.tag.Equals("Player")))
collider.isTrigger = false;
}
}
And if the player collected an item which allows him to walk through the bomb, his own layer will be changed to a specified player layer, which does not collide with the bomb!
A:
As Soon as u Spawn the bomb; spawn a invisible gameobject with a script and inactive collider on it that. Make the script check if anyone is in the collider, as soon as he is out activate the collider. make sure it is a child of the bomb that way they die together. As for your special item, just add method to same script that been called to deactivate the collider and that overides the checking for player aswell.
| {
"pile_set_name": "StackExchange"
} |
Q:
Redirect the page according to the user role after validating user
I have been trying to redirect the user that has logged into the system to their respective page after checking their email and password. But i am not sure about the logic behind that coding and when i try it it just response with the else statement. I have tried the validation of the email and password and that works fine and redirects to the correct page, but when i add the user type condition it doesnt work
I have tried including nested if statements, but i am not sure about its logic,it always executes the else statement.
loginControllerServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email=request.getParameter("email");
String password=request.getParameter("pwrd");
User theUser=loginDbUtil.gettype(email);
if(loginDbUtil.check(email, password))
{
String p="pharmacist";
if(theUser.getType()==p)
{
// HttpSession session=request.getSession();
// session.setAttribute("email", email);
response.sendRedirect("medicine.jsp");
}
else
{
response.sendRedirect("index.jsp");
}
}else
{
response.sendRedirect("index.jsp");
}
}
}
loginDbUtil.java
public boolean check(String email,String password)
{
Connection myConn=null;
PreparedStatement myStmt=null;
ResultSet rs=null;
try
{
//get db connection
myConn=dataSource.getConnection();
//sql statemtn
String sql="select email,pass from usertab where email=? and pass=? ";
myStmt=myConn.prepareStatement(sql);
//set the param values for user
myStmt.setString(1, email);
myStmt.setString(2, password);
rs=myStmt.executeQuery();
if(rs.next())
{
return true;
}
}catch(Exception e)
{
e.printStackTrace();
}
return false;
}
public User gettype(String email) {
User type=null;
Connection myConn=null;
PreparedStatement myStmt=null;
ResultSet rs=null;
try
{
//get db connection
myConn=dataSource.getConnection();
//sql statemtn
String sql="select type from usertab where email=? ";
myStmt=myConn.prepareStatement(sql);
//set the param values for user
myStmt.setString(1, email);
rs=myStmt.executeQuery();
if(rs.next())
{
String t=rs.getString("type");
type =new User(t);
}
}catch(Exception e)
{
e.printStackTrace();
}
return type;
}
}
What i want is after the email and password is checked then next check for the users data type and redirect them to the correct page
A:
In your loginControllerServlet.java change this to
if(theUser.getType()==p)
to this
if(theUser.getType().equals(p))
| {
"pile_set_name": "StackExchange"
} |
Q:
How does EF4 determines if a property has really changed?
I need a way to track modified properties and audit them.
I am hooking into SaveChanges where I get the modified properties
//Get only Modified Customer entries
var modifiedCustomerOses = context.ObjectStateManager
.GetObjectStateEntries<Customer>(EntityState.Modified)
.ToList();
What I have noticed and I am using EF4 with codeGeneration that it reports when a property is not really modified as modified.
If a property EG "CustomerName" is set to "John" and when I do an update I dont change the name but I do
EntityCustomer.Name=customerDto.Name and the name are exactly the same it still reports as changed.
I have looked at the generated code and cannot see if EF property does a check like
if(name==value)//propertyNotchanged dont raiseevent.
Any suggestions? Do you know how EF4 determines if a property has really changed?
thanks
A:
The tracking is performed on entity level, not on property level.
The more appropriate way to trace if the property was changed is to use the OnPropertyChanged partial method.
Just create a custom code that will hold the changed properties.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show Dialog while clicking a specific tab in tabView of PrimeFaces
I'm new to jsf and I'm using Primefaces 4.0 to write a tabView.
I want to do something in my Backing Bean when specific tab is clicked, so I tried this:
page:
<p:tabView effect="fade" effectDuration="normal">
<p:ajax event="tabChange" listener="#{myConsoleBean.onTabChange}" update=":rightForm"/>
<p:tab title="My">
</p:tab>
<p:tab id="statTab" title="Stat">
</p:tab>
</p:tabView>
Backing Bean:
public void onTabChange(final TabChangeEvent event) {
TabView tv = (TabView) event.getComponent();
int activeTabIndex = tv.getActiveIndex();
System.out.println(activeTabIndex);
if(activeTabIndex==1)//Stat tab clicked
{
//do something here...
}
}
Everything works till now,but the Backing Bean is slow for some reason,I want to show a Dialog which contains a progress bar while the Backing Bean is progressing:
Dialog like this:
<p:dialog id="pBarDialog" header="Progressing..." widgetVar="dlg" modal="true" height="70" resizable="false" closable="false">
<h:outputText value="Please wait, we're generating your info..." />
<p:progressBar widgetVar="pbAjax" ajax="true" value="100" styleClass="animated"> </p:progressBar>
</p:dialog>
So, how can I show the dialog when I click the "Stat" tab?
A:
I think I resolved this problem.
I used p:remoteCommand after I saw this thread.
And here's my final codes:
Page:
<p:tabView effect="fade" effectDuration="normal">
<p:ajax event="tabChange" listener="#{myConsoleBean.onTabChange}" oncomplete="dlg.hide()" update=":rightForm"/>
<p:tab title="My">
</p:tab>
<p:tab id="statTab" title="Stat">
<p:remoteCommand actionListener="#{myConsoleBean.goToUrl('myStat.xhtml')}" update=":rightForm" name="showStat" global="true" onstart="dlg.show()" oncomplete="dlg.hide()"></p:remoteCommand>
</p:tab>
</p:tabView>
<p:dialog id="pBarDialog" header="Progressing..." widgetVar="dlg" modal="true" height="70" resizable="false" closable="false">
<h:outputText value="Please wait, we are generating your info..." />
<p:progressBar widgetVar="pbAjax" ajax="true" value="100" styleClass="animated">
</p:progressBar>
</p:dialog>
Bean:
public void onTabChange(TabChangeEvent event) {
TabView tv = (TabView) event.getComponent();
int activeTabIndex = tv.getActiveIndex();
if(activeTabIndex==1)
{
RequestContext.getCurrentInstance().execute("showStat()");
}
}
No matter how, thank you both,Lamq and Emil Kaminski.
I will never find that thread without your help because I type key words from your answers.
| {
"pile_set_name": "StackExchange"
} |
Q:
reading value from a file in batch script
We can set the value of a variable (say, "upper_bound") in a batch file in the following way:
SET upper_bound=3
But is there any way to read this value '3' from a input.txt file which will just contain value 3?
A:
Like this:
SET/P upper_bound=<input.txt
| {
"pile_set_name": "StackExchange"
} |
Q:
skip same dates in foreach loop
this is a text file content which will be chatting database
you:2016-05-02 11:41:53 Hi
Muhammad:2016-05-02 11:42:41 Hi
you:2016-05-02 11:43:33 How are you ?
Muhammad:2016-05-02 14:44:56 I'm fine!
this is the code to loop to get content
<?php
$chat = file("members/cdn/1/chats/9188.txt");
foreach($chat as $line){
$name = strchr($line,":",true);
$message = explode(' ', substr(strchr($line,":"),1), 3);
if(some thing){
?>
<div>
<!-- here i want to skip the same dates -->
<?=$message[0];?>
</div>
<?php
}
?>
<div class="container">
<div class="arrow">
<div class="outer"></div>
<div class="inner"></div>
</div>
<div class="message-body">
<p><?=$message[2];?></p>
<p class="message_time"><?=date("g:i a", strtotime($message[1]));?></p>
</div>
</div>
<div class="spacer"></div>
<?php
}
?>
I want the date of the message appear one time above of messages in the same date
A:
Simply remember that date you last used and then compare it to the one in $message[0]
<?php
$lastDate = NULL;
$chat = file("members/cdn/1/chats/9188.txt");
foreach($chat as $line) :
$name = strchr($line,":",true);
$message = explode(' ', substr(strchr($line,":"),1), 3);
if($lastDate != $message[0]) :
$lastDate = $message[0];
?>
<div><?=$message[0];?></div>
<?php
endif;
?>
<div class="container">
<div class="arrow">
<div class="outer"></div>
<div class="inner"></div>
</div>
<div class="message-body">
<p><?=$message[2];?></p>
<p class="message_time"><?=date("g:i a", strtotime($message[1]));?></p>
</div>
</div>
<div class="spacer"></div>
<?php
endforeach;
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference Between Empty Return Type for Method
Can anyone suggest me what is the difference between
- (void)tabtwoAction:(id)sender;
and
- ()tabtwoAction:(id)sender;
with no return type
A:
Method return types default to id, so all of
- (id)foo;
- ()foo;
- foo;
are equivalent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why was Thomas sent to the Glade?
In The Maze Runner, Thomas is part of the organization that created maze, then why was he sent to the Glade? Once sent he had no previous memory like the others. Then how is he able to witness flashbacks of his past?
Was the purpose of the whole research to analyse the potential of all the boys or just Thomas?
A:
"Thomas is part of the organization that created maze, then why was he sent to the Glade?"
According to this conversation, It is not stated in the movie why Thomas and Teresa is sent to the maze even though they worked as the part of organization.
-Why would they send us
up if we were with them?
-It doesn't matter.
-He's right.
-It doesn't matter. Any of it.
But as per my understanding, sporadically you keep hearing that Thomas was one of the creators favorites and for years others were failed to complete the maze. So, they wanted to test whether Thomas can do it or not and he does that.
And also in the end, Ava Paige says,
Thomas continues to
surprise and impress.
So, it sounds like it's part of Ava's plan to send Thomas to the maze and manipulate others to complete Phase One.
"Once sent he had no previous memory like others then how is he to able witness flash backs of his past?"
It's not only Thomas had flashbacks but whoever is infected with the poison injected by the Griever.
"The purpose of whole research was to analyze potential of all boys or just Thomas?"
By the words of Ava Paige in the end, it should be to analyze potential of all boys including Thomas.
| {
"pile_set_name": "StackExchange"
} |
Q:
CentOS, ZPanel and Cloudflare DNS error
I am stuck in a problem. I have a VPS which gave me a dedicated IPv6 address and a shared IPv4 address. I have tunneled it and installed ZPanel on my centOS server. Now I can access ZPanel from 31.220.48.155:22277 and I have also added a new domain in zpanel. I am adding 31.220.48.155:22277 in Cloudflare A record but it wont allow saying "You entered '31.220.48.155:22277' which is not a valid IP address." I am stuck. Please Help...
A:
You can't put the port number in there. The IP address is 31.220.48.155.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I move my cart into my navigation instead of the header?
No one seems to have the answer to this. I literally just want to move my cart from the default header position in the RWD theme into my navigation instead. How can this be done? thank you
A:
You will need to do a bit of restyling with CSS and possibly make HTML changes to the cart template but here is how you can move the cart to the end of the navigation in Magento RWD theme.
In your theme's layout file add the following:
<default>
<reference name="header">
<action method="unsetChild">
<name>minicart_head</name>
</action>
</reference>
<reference name="catalog.topnav">
<action method="insert">
<name>minicart_head</name>
</action>
</reference>
</default>
This will move the block from the header block into the navigation block. You then need to copy the template "page/html/topmenu.phtml" into your theme and output the "minicart_head" child block within an li.
<?php $_menu = $this->getHtml('level-top') ?>
<?php if($_menu): ?>
<nav id="nav">
<ol class="nav-primary">
<?php echo $_menu ?>
<li class="header-minicart">
<?php echo $this->getChildHtml('minicart_head'); ?>
</li>
</ol>
</nav>
<?php endif ?>
See below screenshot of it working in RWD. As mentioned you will need to make some CSS changes.
| {
"pile_set_name": "StackExchange"
} |
Q:
SessionScope variable in for loop
I am trying to apply for loop in the xpages application.
In the computed field, I put the following code and it shows the result as expected.
var msg = "";
for(var j = 1; j <5;j++)
{
msg += "* This message is from " +j +" " ;
}
return msg;
//Result will show something like this
//"* This message is from 1 * This message is from 2 * This message is from 3 * This message is from 4 * This message is from 5 "
Assume in page A there is a multiline edit box, it uses sessionScope variable (ssvTopic). In pages B there is a computed field, I can show the values from the multiline edit box by use this code
sessionScope.ssvTopic
This works fine. Now I try to apply the sessionScope variable in the for loop.
var msg ="";
var value = sessionScope.ssvTopic
for(var i =0; i< value.length; i++)
{
msg += "* This message is from " + value+" " ;
}
return msg;
When I run the application, I notice the value.length means the number of characters in value. I mean if the sessionScope.ssvTopic values are life style, news, sports, the characters are 24, so the in the for loop, the message will display 24 times.
So I change the code value.length to @Count(value). When I run the application, the message only display one time.
var msg ="";
var value = sessionScope.ssvTopic
for(var i =0; i< @Count(value); i++)
{
msg += "* This message is from " + value+" " ;
}
return msg;
//The result display like this, it only display one time
//* This message is from life style, news, sports
I think @Count(value) is close to the result (compare with value.length), but I don't understand why it shows the message one time only.
I also try to put the sessionScope value in a array, but the result is the same, it just shows one message.
var msg ="";
var value = sessionScope.ssvTopic
var valueArray = new Array();
viewScope.put("valueArray", @Implode(valueArray, ",")) ;
valueArray.push(value);
//no matter if I use @Count(valueArray) or valueArray.length, the result does not have difference
for(var i =0; i< @Count(valueArray); i++)
{
msg += "* This message is from " + valueArray+" " ; //no matter if I use valueArray or valueArray[i], the result does not have difference too
}
return msg;
I am not sure which part I make mistake. What I intend to do is to show the number of messages depends on the number of the sessionScope variable values. In my case if the sessionScope variable contains life style, news, sports, the result will be someting like this
* This message is from life style * This message is from news * This messages is from sports
If I run this code again, it works fine.
var msg = "";
for(var j = 1; j <5;j++)
{
msg += "* This message is from " +j +" " ;
}
return msg;
So I just change the "5" to sessionScope variable, it will not show the number of messages depends on the number of the sessionScope variable values.
Would someone let me know how to solve this issue. Thanks a lot.
(A quick update)
I try the following the code but it does not return anything.
for(var i =0; i< sessionScope.ssvTopic; i++)
{
msg += "* This message is from " + ssvTopic[i]+" " ; // with [i] or without [i], the result is the same, it does not return anything
}
return msg;
Instead of return the message, I try to return other things such @Count(value), @Count(valuArray), valueArray.length.
@Count(value) //this returns 1.0
@Count(valueArray) //this returns 1.0
valueArray.length //this returns 1.0
value.length //this return 24.0 as mentioned above, this returns the number of characters of the value
Therefore I notice this a mistake in the code, but I don't understand the The mistake only return 1.0 for the result.
A:
You missed only a little thing to get it to work:
var msg = "";
var value = sessionScope.ssvTopic.split('\n');
for(var i = 0; i < value.length; i++) {
msg += "* This message is from " + value[i] + " " ;
}
return msg;
Multiline edit box returns a multi-line string, not an array of strings. So, you need to split the string by newline first. Then you can work with the resulting array.
(@Count always returned 1 as multiline edit box's value was only one string)
| {
"pile_set_name": "StackExchange"
} |
Q:
Defacing a downclosed post
I'm curious what the right response is to the situation where a post gets downclosed, and then the OP defaces it. For example,
Complexity of finding a hamiltonian circuit in a Great Rhombicuboctahedral graph (the post is now deleted.)
For the <10K users, the post linked to above went from this:
to this:
A:
I think the comment by robjohn applies to malicious defacement, but this case falls into another group: OP wants to delete their unanswered question but does not know how. In such a case, I would
Rollback, to maintain professional appearance of the site's front page.
...
(okay, you can stop laughing now)
Inform the OP that there is a delete button just under the post, to the left.
Note that unregistered users can't delete own posts. If the user is unregistered, fall back on flagging for mod's attention.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make two axios requests and save both responses in a hook?
I'm using Axios to make API calls to my backend. The problem is that I want to make a call, save the response in a hook, than make another call and save the response in the same hook. I must make the second call after receiving the response from the first one, since in my backend the second call listen to an EventEmmiter:
const [invoice, setInvoice] = useState({
loading: false,
error: false,
content: null,
paid: false
});
function createInvoice() {
setInvoice({ ...invoice, loading: true });
api
.post("/lightning/createinvoice", {
amount: values.amount
})
.then(response => {
setInvoice({
loading: false,
error: false,
content: response.data,
paid: false
});
return api.get("/lightning/invoicestatus", {
params: { id: response.data.id }
});
})
.then(response => {
if (response.data.status === "Confirmed")
setInvoice({ ...invoice, paid: true });
})
.catch(() => {
setInvoice({ loading: false, error: true, content: null });
});
}
This code works, however I get invoices.content: null. I suspect that setInvoice({ ...invoice, paid: true }); fails, as the invoice state doesn't have its most updated state.
How should I fix it?
Thanks in advance
A:
I have made a cleaner, much readable approach rather than just promise callbacks. Let me know if you find any issue, as I am not sure about your actual API calls which I can test. But the code below should work irrespectively.
const [invoice, setInvoice] = useState({
loading: false,
error: false,
content: null,
paid: false
});
const createInvoice = async (api, values) => {
try {
setInvoice({ ...invoice, loading: true });
const firstResponse = await api.post("/lightning/createinvoice", {
amount: values.amount
});
setInvoice({
...invoice,
content: firstResponse.data
});
const secondResponse = await api.get("/lightning/invoicestatus", {
params: { id: firstResponse.data.id }
});
if (secondResponse.data.status === "Confirmed") {
setInvoice({ ...invoice, paid: true });
}
} catch (err) {
setInvoice({ loading: false, error: true, content: null });
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
crontab -e does not open the crontab for this user
I had set up a few jobs using crontab a few months back and they had been working well up until a few days ago, I noticed one had not run. I just tried to check the crontab file using the user that created the jobs, using crontab -e, and no file opens. Terminal quickly flitts tosome screen and then back to the screen where I had entered the command. It goes and comes back too quickly for me to see what is there.
I have (as sudo) checked under /var/spool/cron/crontab/ and see there is a file for the mentioned user, which contains the basic:
> DO NOT EDIT THIS FILE - edit the master and reinstall.
> (- installed on Wed Mar 21 00:12:22 2018)
> (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
I notice that the isntall date is pretty much exactly where my cron jobs stopped! Maybe the system needed a restart for some reason...
I restarted the machine and again tried: crontab -e, this time I got the following error coming from Emacs (the default editor, I believe):
emacsclient: can't find socket; have you started the server?
To start the server in Emacs, type "M-x server-start".
Warning: due to a long standing Gtk+ bug
http://bugzilla.gnome.org/show_bug.cgi?id=85715
.... [truncated]
So I changed the default editor to nano:
user@user:~$ select-editor
Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/code
4. /usr/bin/emacs24
5. /usr/bin/vim.tiny
Choose 1-5 [2]: 2
... and tried again:
user@user:~$ crontab -e
This just gave the same problem as initially described - it shortly seemed to open a file then close it again.
Is there another way to debug and (hopefully) get back the original crontab file? The jobs were quit complex to set up (see note #2 below) :-/
I tried to find running crontab tasks using this answer, so cron is running, but what about my crontab tasks?
user@user:~$ ps -o pid,sess,cmd afx | egrep "( |/)cron( -f)?$"
1077 1077 /usr/sbin/cron -f
Other notes:
anacron is installed
the cron jobs themselves are defined in the crontab file, not via external scripts
one cronjob used a virtual env, which does still exist and works and I can execute the job manually
Updates:
The output from some further checks (mostly requested by @steeldriver)
user@user:~$ ls -l $(which crontab)
-rwxr-sr-x 1 root crontab 36080 Apr 5 2016 /usr/bin/crontab
Is that the setuid s in there? I compared it to ping, because I read that should have some kind of elevated permissions:
user@user:~$ ls -l $(which ping)
-rwsr-xr-x 1 root root 44168 Mai 7 2014 /bin/ping
Running crontab as sudo:
user@user:~$ sudo crontab -e
[sudo] password for user:
no crontab for root - using an empty one
No modification made
Trying the desired command as sudo, using the user's setup:
user@user:~$ sudo -H -u user bash -c 'crontab -e'
No modification made
Checking if permissions for the entire spool are as expected:
user@user:~$ ls -ld /tmp
drwxrwxrwt 16 root root 36864 Apr 1 14:22 /tmp
user@user:~$ sudo namei -l /var/spool/cron/crontabs/$USER
f: /var/spool/cron/crontabs/user
drwxr-xr-x root root /
drwxr-xr-x root root var
drwxr-xr-x root root spool
drwxr-xr-x root root cron
drwx-wx--T root crontab crontabs
-rw------- user crontab user
A:
Just to post the outcome and perhaps help someone who sees the same thing - this is a summary of the comments below my original question
Using crontab -e was the start of the problem - it didn't do anything.
It turns out the Emacs setup was the cause (but I assume any other editor could somehow cause this problem).
Following @steeldriver 's advice of trying EDITOR=/bin/nano crontab -e (trying to force crontab to use nano did not help.
I recorded a screen-cast and stopped on the frame where a file quickly opens - it was Emacs' splash screen.
There were settings in ~/.profile, which caused the Emacs daemon to hijack calls to an editor. After removing those setting and restarting, crontab -e as the user worked.
The settings seemed to be an incorrectly copy-pasted version of this (found on the Emacs wiki):
export ALTERNATE_EDITOR=""
export EDITOR="emacsclient -t" # $EDITOR should open in terminal
export VISUAL="emacsclient -c -a emacs" # $VISUAL opens in GUI with non-daemon as alternate
[I don't remember where the actual mistake was]
The original crontab file was lost. I still don't understand how that happened
| {
"pile_set_name": "StackExchange"
} |
Q:
GRPC. Testing Context
Currently we able to test positive cases following way:
class AuthServer(auth_grpc.AuthServicer):
def __init__(self, *args, **kwargs):
print("Initializing auth server..")
super(AuthServer, self).__init__(*args, **kwargs)
def register(self, request, context):
return auth_messages.registerResponse(uuid="Test")
With pytest fixtures looking following way:
@pytest.fixture(scope="session")
def server():
return AuthServer()
@pytest.fixture(scope="session")
def context():
return DummyGRPCTestContext()
In test case environment accessed following way:
def test_user_registration(server, context, user):
request = auth_messages.registerRequest(**user)
result = server.register(request, context)
print("RESULT %s " % result)
However, if we want test negative case and changing grpc servicer method to following:
def register(self, request, context):
context.set_code(grpc.StatusCode.ALREADY_EXISTS)
context.set_details("User already exists")
return auth_messages.registerResponse()
We're failing in errors, related to dummy context.
Where we can get grpc context, that can be easily plugged into test environment?
Contexts like this one look complex and not ready for plug and test.
A:
grpc.ServicerContext is just an interface; within your test code you should be able to write your own implementation of it and pass that to your servicer under test.
It's true that at this time we don't provide in grpc_testing a grpc.ServicerContext implementation ready to be used by tests and passed to systems under test, but it's also not entirely clear that we could provide one that would be simply implemented and also valuable to a large number of tests. There's a large behavioral space of how servicers under test use grpc.ServicerContext objects and there's another large behavioral space of how authors write tests of servicers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generate and set random colors on text view background within Recycler View in Android
I am Trying to Generate Random Colors and set the Random color as background of Text View Just Like in GMail app. The Text view is Having a circular background initially set in xml which i have done using shape. I have done some research and used some code available on internet but the changes are not reflecting in my app.
Below is my Recycler View Adapter Class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.Items> {
ArrayList<GmailDataHolder> data;
Context context;
public RecyclerViewAdapter(ArrayList<GmailDataHolder> data, Context context) {
this.data = data;
this.context = context;
}
@Override
public RecyclerViewAdapter.Items onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.gmail_layout_row, parent, false);
Items i = new Items(v);
return i;
}
@Override
public void onBindViewHolder(final RecyclerViewAdapter.Items holder, int position) {
//Generating Random Color
int randomAndroidColor = holder.androidColors[new Random().nextInt(holder.androidColors.length)];
Drawable background = holder.circleTv.getBackground();
if (background instanceof ShapeDrawable) {
((ShapeDrawable)background).getPaint().setColor(randomAndroidColor);
} else if (background instanceof GradientDrawable) {
((GradientDrawable)background).setColor(randomAndroidColor);
} else if (background instanceof ColorDrawable) {
((ColorDrawable)background).setColor(randomAndroidColor);
}
holder.line1.setText(data.get(position).getLine1());
holder.line2.setText(data.get(position).getLine2() + "...");
holder.line3.setText(data.get(position).getLine3() + "...");
holder.time.setText(data.get(position).getTime());
//get Star Image State from MySql DB
MyFunctions.getStarState(data, holder, position);
holder.circleTv.setText(String.valueOf(data.get(position).getLine1().charAt(0)).toUpperCase());
//Changing Star Image on Click
MyFunctions.starClickListener(holder);
}
@Override
public int getItemCount() {
return data.size();
}
public class Items extends RecyclerView.ViewHolder {
TextView circleTv, line1, line2, line3, time;
int[] androidColors;
public ImageView star;
public Items(View itemView) {
super(itemView);
//Loading Color from resources
androidColors = itemView.getResources().getIntArray(R.array.androidcolors);
circleTv = (TextView) itemView.findViewById(R.id.tv_circle);
line1 = (TextView) itemView.findViewById(R.id.tv_line1);
line2 = (TextView) itemView.findViewById(R.id.tv_line2);
line3 = (TextView) itemView.findViewById(R.id.tv_line3);
time = (TextView) itemView.findViewById(R.id.tv_time);
star = (ImageView) itemView.findViewById(R.id.img_star);
}
}
Colors.xml File:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#dc4538</color>
<color name="colorFacebook">#374dae</color>
<color name="colorCenterFb">#d5617ae6</color>
<color name="colorStartGoogle">#d8dd4c3a</color>
<color name="colorEndGoogle">#dd4c3a</color>
<color name="colorEndLinkedIn">#1887b0</color>
<color name="colorStartLinkedIn">#e31887b0</color>
<color name="colorStrokeLinkedIn">#ec106584</color>
<color name="colorStrokeGoogle">#b73e2e</color>
<color name="colorStrokeFacebook">#e2263a91</color>
<color name="status">#ba3223</color>
<item name="blue" type="color">#FF33B5E5</item>
<item name="purple" type="color">#FFAA66CC</item>
<item name="green" type="color">#FF99CC00</item>
<item name="orange" type="color">#FFFFBB33</item>
<item name="red" type="color">#FFFF4444</item>
<item name="darkblue" type="color">#FF0099CC</item>
<item name="darkpurple" type="color">#FF9933CC</item>
<item name="darkgreen" type="color">#FF669900</item>
<item name="darkorange" type="color">#FFFF8800</item>
<item name="darkred" type="color">#FFCC0000</item>
<integer-array name="androidcolors">
<item>@color/blue</item>
<item>@color/purple</item>
<item>@color/green</item>
<item>@color/orange</item>
<item>@color/red</item>
<item>@color/darkblue</item>
<item>@color/darkpurple</item>
<item>@color/darkgreen</item>
<item>@color/darkorange</item>
<item>@color/darkred</item>
</integer-array>
</resources>
Initially The TextView is having the following Background declared in xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#48b3ff"/>
</shape>
A:
Random r = new Random();
int red=r.nextInt(255 - 0 + 1)+0;
int green=r.nextInt(255 - 0 + 1)+0;
int blue=r.nextInt(255 - 0 + 1)+0;
GradientDrawable draw = new GradientDrawable();
draw.setShape(GradientDrawable.OVAL);
draw.setColor(Color.rgb(red,green,blue));
mTextView.setBackground(draw);
A:
If you needs to use your own/required colors, just use below code
List<String> colors;
colors=new ArrayList<String>();
colors.add("#5E97F6");
colors.add("#9CCC65");
colors.add("#FF8A65");
colors.add("#9E9E9E");
colors.add("#9FA8DA");
colors.add("#90A4AE");
colors.add("#AED581");
colors.add("#F6BF26");
colors.add("#FFA726");
colors.add("#4DD0E1");
colors.add("#BA68C8");
colors.add("#A1887F");
// all colors used by gmail application :) may be,
// genrating random num from 0 to 11 because you can add more or less
Random r = new Random();
int i1 = r.nextInt(11- 0) + 0;
//genrating shape with colors
GradientDrawable draw = new GradientDrawable();
draw.setShape(GradientDrawable.OVAL);
draw.setColor(Color.parseColor(colors.get(i1)))
// assigning to textview
contact_name_circle.setBackground(draw); //textview
| {
"pile_set_name": "StackExchange"
} |
Q:
In Photoshop CC 2017, how do I draw outside the image, in the bordering canvas space?
I'm trying to do guiding lines that continue outside the image space, into the canvas space, to guide my perspective drawing but every time I do a pen tool, use anchor points, or the line tool, it hides the outside lines that fall into the canvas, only leaving the line parts that fall into the image portion
A:
All pixels in Photoshop are restricted to the Canvas Size. You can't draw outside the canvas.
However, there is a way to draw outside a particular area via Artboards within Photoshop.
Set the Canvas size to as large as you want, larger than your needed drawing area.
Then select the Artboard Tool (under the Move Tool)
And then click-drag with the tool to draw an Artboard the size of your desired image area.
You can refine the size or be more specific with the size by changing the numbers in the Control Bar across the top of the screen:
You'll then have, what is essentially a layer group in the Layers Panel titled "Artboard 1" with a layer inside it.
Anything you draw on that internal layer will be restricted to the artboard size (the red in the image below).
Anything you draw on a layer outside that artboard will be restricted to the canvas size (the blue in the image below).
This is really just the same results as if you had a layer mask applied to a layer group. But Artboards can be easier to manage (and export) than simple layer groups with masks.
While this still restricts all painting to the canvas size, this method makes the actual size of the canvas somewhat irrelevant overall. So, you can make the canvas larger if you need and the Artboard size will remain the same, or add additional artboards if needed. Then export/save artboards as individual images.
I would be remiss if I didn't at least mention using Illustrator if the goal is a great deal of vector paths in perspective. Illustrator has specific features for that.
| {
"pile_set_name": "StackExchange"
} |
Q:
compare two files from an arbitrary line in Perl
I know that one can compare two files in Perl using:
use strict;
use warnings;
use File::Compare;
my $file1 = "example1.txt";
my $file2 = "Test_2.txt";
if (compare($file1,$file2) eq 0)
{
print "They're equal\n";
}else{
print "They aren't equal\n";
}
Well, I am interested to know if one can compare files from a desired line. I have huge files and after a fixed line number maybe they are different. It takes very long time to compare the whole files. Then I am looking for a shortest way!
A:
Sure. compare accepts file handles as well as file names, so you can just open the files and read past the lines you want to ignore before you call compare
This example code just ignores the first line from both files. I hope you understand how to skip a given number of lines, or until a regex pattern matches?
use strict;
use warnings;
use File::Compare 'compare';
open my $fh1, '<', 'file1.txt';
open my $fh2, '<', 'file2.txt';
# read past header lines
<$fh1>;
<$fh2>;
if ( compare( $fh1, $fh2 ) eq 0 ) {
print "They're equal\n";
}
else {
print "They aren't equal\n";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using homebrew installed SDL2 with Xcode
I have installed SDL2 using Homebrew but now I don't know how to make sure Xcode can use it! I imported the created library and added it to the build phases tab of my project. But when I try to build I get the error 'SDL2/SDL.h' not found
A:
To be able to use SDL2 on Xcode you must set two things (which are required for SDL in general):
where to find header files (so that Clang can compile with -Iheader/path)
where to find the .dylib to link it to the project (since with brew you don't have a real .framework)
To know the correct paths you should invoke sdl2-config --cflags and sdl2-config --libs. On my system these produce:
:~jack$ /usr/local/bin/sdl2-config --cflags
-I/usr/local/include/SDL2 -I/usr/X11R6/include -D_THREAD_SAFE
:~jack$ /usr/local/bin/sdl2-config --libs
-L/usr/local/lib -lSDL2
Now just paste the first one into other C flags and the other one into other linker flags field of your project and you are ready to go.
You could set them up in the correct fields, which is Header Search Paths for -I and Library Search Path for -l but the result will be the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mechanism for reaction of NOCl (Tilden reagent) with primary amines
According to my textbook, the reaction between $\ce{NOCl}$ and $\ce{CH3CH2-NH2}$ is as follows:
$$\ce{CH3CH2-NH2 + NOCl -> CH3CH2Cl + N2 + H2O}$$
But how exactly does the reaction proceed?
The first step (what I think) could be that $\ce{NOCl}$ dissociates into $\ce{NO+}$ and $\ce{Cl-}$ ions and then the $\ce{Cl-}$ ion attacks the amine group and replaces it by $\mathrm{S_N2}$ mechanism.
But according to this site, a diazonium product is produced. Even though a diazo product is formed, how does it produce an alkyl halide according to my textbook?
A:
Why would the chloride ion attack the electron rich amine? The amine is the best nucleophile is the system and will attack the NO+. This gives a RNH-NO nitroso species which is then protonated on Oxygen, loses water and gives the diazonium cation. This adds loses nitrogen rapidly and adds Chloride to give the primary alkyl chloride.
More can be read about this process here (which I where I sourced the reaction scheme) or by searching the term "nitrosation of primary amine"
| {
"pile_set_name": "StackExchange"
} |
Q:
Telegram Bot Inline Keyboard not displaying PHP
The following code works, it adds custom keyboard keys 'Button1' and 'Button2'
$keyboard = [
'keyboard' => [['Button1'],['Button2']],
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
];
$keyboard = json_encode($keyboard, true);
$sendto = API_URL."sendmessage?chat_id=".$chatID."&text=".$reply."&parse_mode=HTML&reply_markup=$keyboard";
I need to use Inline Keyboard though for my purposes, but I haven't been able to get it to work
$keyboard = [
'inline_keyboard' => [['Button1' => 'test', 'callback_data' => 'test'],
];
or
$keyboard = [
'inline_keyboard' => [['Button1' => 'test'],['callback_data' => 'test']],
];
doesn't work. I would really appreciate if anyone has a working example or can point out what is wrong in my example.
Link to documentation: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating
A:
It looks like you are missing an additional array. The reply_markup should look like this:
$keyboard = array(
"inline_keyboard" => array(array(array("text" => "My Button Text", "callback_data" => "myCallbackData")))
);
| {
"pile_set_name": "StackExchange"
} |
Q:
std::is_default_constructible with private access and friend function
I was surprised to discover that std::is_default_constructible appears to ignore friend access. When declaring a default constructor private in a class and then friending a function, I'd expect that std::is_default_constructible would return true.
Example: I ran the following on Wandbox: https://wandbox.org/ using Clang 5.0.0 and GCC 7.2.0 under C++17.
#include <type_traits>
#include <cassert>
class PrivateConstructor
{
private:
PrivateConstructor() = default;
friend void doIt();
};
void doIt()
{
bool isConstructible = std::is_default_constructible<PrivateConstructor>::value;
PrivateConstructor value;
assert(isConstructible); // FAILS!
}
int main(int,char**)
{
doIt();
return 0;
}
This code compiles but the assertion fails. Is the defined explicitly in the standard or is this a possible compiler bug?
A:
You declared the function doIt() to be friend of the class, but that function does not access the private class members. Instead, the function std::is_deafault_constructible accesses the class members.
template< class T >
struct is_default_constructible : std::is_constructible<T> {};
The proper way is declaring std::is_default_constructible to be a friend class:
friend class is_default_constructible<PrivateConstructor>;
| {
"pile_set_name": "StackExchange"
} |
Q:
Correlated explanatory variables where both are significant
I am running a multiple linear regression using SPSS to test the effect of ethnicity and ethnic/racial attitudes or perceptions on political predispositions.
One model, as an example, looks like this:
DV: 'support for democracy' (1-7 scale)
Controls: age, gender, education etc.
Predictors: Ethnicity, and various attitude/perception vars
My question is what to do with these attitude/perception variables when they are correlated; i.e. whether to leave all of them in the model, or remove one or more. A particular case is the pair of variables 'common national culture' ('Bolivians share many common values that unite us as a nation; 1-7 disagree-agree scale) and 'strength of national identification' ('To what extent do you identify as a Bolivian citizen?'; 1-7 scale).
As you might expect, 'common national culture' and 'strength of national ID' are correlated (Pearson coefficient=.268 and is significant). But they also both have significant coefficients in the multiple regression, and adjusted R-squared for the model decreases substantially when either one is removed. In this case - i.e. when both correlated vars have significant coefficients -, should both be kept in?
Many thanks in advance.
VIF is between 1.2-1.4 for each.
Condition indices have values of around 12, but there are 15 variables in the model, so perhaps this is not so remarkable? Looking through the variance proportions, however, neither have any values >0.2
A:
You should first do a search on the issue of multicollinearity and how to best understand if it is occurring. If you still have further questions then following up might be appropriate.
Edit: You should be okay. A VIF over 2 worries me a bit. According to this reference 2.50 should be cause for alarm. The more important distinction is how you interpret those two variables in the context of theory. I see this a lot in my field, where often it seems like predictors are included without any kind of theoretical meaning.
I hope that helps. If so, feel free to up vote.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to see the structure of a file
I am a very recent user of Visual Studio Ultimate 2013. In most Ides, there is a structural view of the current file. For example in IntelliJ Idea, one can see the data members and functions in a class file. Or one can see the hierarchical structure of an html file. I could not find such a view in Visual Studio upto now. There is a list of functions above the file editor. But this doesn't work in in cshtml files.
Is there such a structural view in VS? If so how to access it?
A:
You can go to "View/Class View" menu item to get the class view window.
The class view window does not auto-sync. However, you can go to the "Tools/Options" menu item, then go to the "Environment/Keyboard" tree item. Under the "Show Commands Containing", search for "View.SynchornizeClassView". You can then assign this to some key combination which you can then use to sync it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Classes: Alternative way of adding len()
I am building a string Class that behaves like a regular string class except that the addition operator returns the sum of the lengths of the two strings instead of concatenating them. And then a multiplication operator returns the products of the length of the two strings. So I was planning on doing
class myStr(string):
def __add__(self):
return len(string) + len (input)
at least that is what I have for the first part but that is apparently not correct. Can someone help me correct it.
A:
You need to derive from str, and you can use len(self) to get the length of the current instance. You also need to give __add__ a parameter for the other operand of the + operator.
class myStr(str):
def __add__(self, other):
return len(self) + len(other)
Demo:
>>> class myStr(str):
... def __add__(self, other):
... return len(self) + len(other)
...
>>> foo = myStr('foo')
>>> foo
'foo'
>>> foo + 'bar'
6
| {
"pile_set_name": "StackExchange"
} |
Q:
How to export library to Jar in Android Studio?
I have downloaded some library sources and would like to export it as a Jar file using
Android Studio. Is there a way to export to jar file using Android studio ?
edit:
The library I want to export as jar is an Android library.
It's called "StandOut" and can be downloaded from GitHub.
https://github.com/pingpongboss/StandOut
A:
It is not possible to export an Android library as a jar file. It is possible, however, to export it as aar file. Aar files being the new binary format for Android libraries. There's info about them in Google I/O, the New Build System video.
First, build the library in Android Studio or from command line issuing gradle build from your library's root directory.
This will result in <yourlibroot>/libs/build/yourlib.aar file.
This aar file is a binary representation of your library and can be added to your project instead of the library as a dependency project.
To add aar file as a dependency you have to publish it to the maven central or to your local maven repository, and then refer the aar file in your project's gradle.build file.
However, this step is a bit convoluted. I've found a good explanation how to do so here:
http://www.flexlabs.org/2013/06/using-local-aar-android-library-packages-in-gradle-builds
A:
I was able to build a library source code to compiled .jar file, using approach from this solution:
https://stackoverflow.com/a/19037807/1002054
Here is the breakdown of what I did:
1. Checkout library repository
In may case it was a Volley library
2. Import library in Android Studio.
I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.
3. Modify your build.gradle file
// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.3'
}
}
apply plugin: 'android-library'
android {
compileSdkVersion 17
buildToolsVersion = 17
sourceSets {
main {
// Here is the path to your source code
java {
srcDir 'src'
}
}
}
}
// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
delete 'build/libs/myCompiledLibrary.jar'
}
task makeJar(type: Copy) {
from('build/bundles/release/')
into('build/libs/')
include('classes.jar')
rename ('classes.jar', 'myCompiledLibrary.jar')
}
makeJar.dependsOn(clearJar, build)
4. Run gradlew makeJar command from your project root.
I my case I had to copy gradlew.bat and gradle files from new android project into my library project root.
You should find your compiled library file myCompiledLibrary.jar in build\libs directory.
I hope someone finds this useful.
Edit:
Caveat
Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar file (eg. modules have own library directory, that is referenced in build.gradle of given module).
In case where you need to use single library in more then one module, I would recommend using this approach:
Android gradle build and the support library
A:
Since Android Studio V1.0 the jar file is available inside the following project link:
debug ver: "your_app"\build\intermediates\bundles\debug\classes.jar
release ver: "your_app"\build\intermediates\bundles\release\classes.jar
The JAR file is created on the build procedure,
In Android Studio GUI it's from Build->Make Project and from CMD line it's "gradlew build".
| {
"pile_set_name": "StackExchange"
} |
Q:
SELECT columns from a variable in Python PYODBC
my first question up here, please be kind.
I am new to both python and SQL so I am finding my way.
I am writing a function in python which should select columns from a table in the database with column names coming from a variable (list). Below is what I want the code to look like, obviously it does not work. Is there a way to do it, or I should not bother and instead of a list type column names directly into c.execute? Thank you! Alex
def data_extract1():
column_list1 = ["column1","column2"]
c.execute ('SELECT column_list1 FROM myBD' )
for row in c.fetchall():
print (row)
A:
You can use format() and join() to replace column_list1 in your query string with the columns you want.
c.execute('SELECT {} FROM myBD'.format(", ".join(column_list1)))
", ".join(column_list1) creates a comma-separated string from your column list.
format() replaces the {} in your query string with that new string
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading external .bundles on iPhone
I would like to add resource files to a .bundle and push them to my application and it seems to work fine in the simulator but fails to build when I change to the device.
/Users/sosborn/Projects/MyPro/build/Debug-iphoneos/FooBar.bundle:
object file format invalid or
unsuitable
I don't want to load any code or anything, just plain text and jpegs and it would be nice to be able to package them as dependencies.
A:
I found a better solution to my problem. It actually doesn't require the use of bundles at all. I just created an aggregate target instead of a bundle target. Then I added a copy step and a script step. The copy step contains all of the resources I had in the bundle target and the script step actually zips up the files. Then when I download the content into my application I can just unzip it and use it just as if it were a bundle since I'm just storing resource dependencies.
Thanks for your help.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't eclipse resolve class in same package?
I hit F5 ~1000 times and restarted eclipse (also with -clean), deleted /bin, but nothing helps. Manually importing DoodleClient does not help. DoodleClient exists and is perfectly fine, everything worked before. Clicking on "Import 'DoodleClient' ..." does nothing.
What I did before this problem occured:
I added *.class to .gitignore
git rm *.class
On the next pull, hunderts of .class files were deleted by git
A:
Alternatively, you can highlight the project :
Choose Clean ... from Project menu and if you have activated the Build Automatically option (in the same menu), the classes will be generated anew.
A:
I could resolve it:
On another project (from the same git repo), I had the same issue on several files in different packages. All I had to do was writing a white-space into the file, remove it again and save, so eclipse would re-compile it (I guess).
Some kind of a strange behaviour... :S
A:
I got the same error in Maven project. Running Maven Clean and closing the project and reopening didn't work for me.
Right click project -> Maven -> Update Project worked for me.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.