qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
20,651,442 | I have an assignment in which I have to accept an input from the user. I can't use a linked list, only an array, so my plan is:
1. Alloc some memory.
2. If we need to realloc, meaning that I reached the number of cells allocated:
1. Try to realloc. If successful, great.
2. If we couldn't realloc, print input, free memory and realloc then.
I can't really decide about the command that tells me how did I reach the end of memory allocated and that's why I need your help. I wrote:
```
if (i==(MAX_CHARS_INPUT-1))
```
But I am not sure about it.
The code:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHARS_INPUT 200
#define D_SIZE 2
void printWithMalloc(){
int charSize=1;
int *ptr=malloc(MAX_CHARS_INPUT*sizeof(charSize));
int i=0, j=0, c;
printf("please enter a string\n");
while ((c=getchar())!=EOF && c!='\n')
{
ptr[i++]=c;
if (i==(MAX_CHARS_INPUT-1)) /*if we need to realloc*/
{
int *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(charSize));
if (temp==NULL) /*realloc failed*/
{
printf("you wrote:\n");
while(j<=i)
putchar(ptr[j++]);
free(ptr);
ptr=(int*)malloc(MAX_CHARS_INPUT*sizeof(charSize));
}
else
ptr=temp;
}
}
}
int main(){
printWithMalloc();
return 0;
}
```
Thank you! | 2013/12/18 | [
"https://Stackoverflow.com/questions/20651442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1941081/"
] | The problem is indeed with your condition:
```
if (i==(MAX_CHARS_INPUT-1))
```
This works, but only for the first time you reach this limit. When you `realloc` your buffer gets bigger, but you don't check if you run out of *that* space. So imagine I input 500 characters. When the 199th character is read the buffer is reallocated to become 400 characters big. However, `i` is *only* checked at the 199th character, so when the 400th one is reached it will run out of the buffer.
The second problem is that when you reallocate the buffer it will only grow to 400 characters (`D_SIZE * MAX_CHARS_INPUT`) and no bigger.
The third problem is when you re-`malloc` (i.e. when `realloc` failed) you don't reset `i` so it will write past the end of the buffer immediately.
As suggested in a now deleted answer. Keep track of your buffer-size:
```
size_t buffSize = MAX_CHARS_INPUT;
```
when you reallocate, update `buffSize` first, then use that as the argument to `realloc`:
```
buffSize *= D_SIZE; // double the buffer-size
temp = realloc(ptr, buffSize * sizeof(*temp)); // using sizeof *temp is less confusing and less error-prone
```
of course: also update your condition:
```
if(i == buffSize - 1)
```
and when you re-`malloc` reset `i` and `buffSize`:
```
buffSize = MAX_CHARS_INPUT;
ptr = malloc(buffSize*sizeof(*ptr));
i = 0;
```
Though re-`malloc`ing is not very wise, since if an allocation fails there are usually bigger problems (unless memory is very restricted). And (especially since you don't check the result of that `malloc`) possibly problematic since that `malloc` may fail as well. Exiting a program after an alloc-fail is not unusual. | There are few things getting wrong in your code, the new code is:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHARS_INPUT 200
#define D_SIZE 2
void printWithMalloc(){
//int charSize=1; you don't need this.
//int *ptr=malloc(MAX_CHARS_INPUT*sizeof(charSize));
char *ptr=malloc(MAX_CHARS_INPUT*sizeof(char));//sizeof(char) will give you the block size, MAX_CHARS_INPUT: gives you the number of blocks to be allocated and pointer type is char, since you want to save char(s), right?
int i=0, j=0, c;
printf("please enter a string\n");
//while ((c=getchar())!=EOF && c!='\n')
while ((c=getchar())!='\r') //'\r' is for enter key... since the user input is coming from console not form a file, right?
{
ptr[i++]=c;
if (i==(MAX_CHARS_INPUT-1)) /*if we need to realloc*/
if (i==MAX_CHARS_INPUT) // i is already incremented in i++
{
//int *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(charSize));
char *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(char));
if (temp==NULL) /*realloc failed*/
{
printf("you wrote:\n");
while(j<=i)
putchar(ptr[j++]);
free(ptr);
ptr=(char*)malloc(MAX_CHARS_INPUT*sizeof(char));
}
else
ptr=temp;
}
}
}
int main(){
printWithMalloc();
return 0;
}
``` |
14,522,539 | I need to write a command line application, like a shell. So it will include commands etc. The thing is I don't know how to pass parameters to the funcions in a module. For example:
User writes: function1 folder1
Program should now pass the 'folder1' parameter to the function1 function, and run it. But also it has to support other functions with different parameters ex:
User input: function2 folder2 --exampleparam
How to make this to work? I mean, I could just write a module, import it in python and just use the python console, but this is not the case. I need a script that takes command input and runs it.
I tried to use eval(), but that doesn't solve the problem with params. Or maybe it does but I don't see it? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14522539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011042/"
] | Take a look at the **optparse** module in python. It's exactly what you would need:
```
http://docs.python.org/2/library/optparse.html
```
Or you can write your own custom opt-parser (minimalistic though)
```
def getopts(argv):
opts = {}
while argv:
if argv[0][0] == '-': # find "-name value" pairs
opts[argv[0]] = argv[1] # dict key is "-name" arg
argv = argv[2:]
else:
argv = argv[1:]
return opts
if __name__ == '__main__':
from sys import argv # example client code
myargs = getopts(argv)
# DO something based on your logic here
```
But in case your script needs to run on python 3 and beyond, you need to consider [argparse](http://docs.python.org/2/library/argparse.html#module-argparse) module.\
Hope that helps. | Take a look at [optparse](http://docs.python.org/2/library/optparse.html) . This can help passing and receiving shell style parameters to python scripts.
Update:
Apparently `optparse` is deprecated now and [argparse](http://docs.python.org/2/library/argparse.html#module-argparse) is now preferred option for parsing command line arguments. |
34,664,382 | Now I recently saw this question (can't exactly remember where) about how few operations were needed to sort a list of numbers by exclusively reversing sublists.
Here is an example:
**Unsorted Input**: `3, 1, 2, 5, 4`
One of the possible answers is:
1. Reverse index 0 through 3, giving `5, 2, 1, 3, 4`
2. Reverse index 0 through 4, giving `4, 3, 1, 2, 5`
3. Reverse index 0 through 3, giving `2, 1, 3, 4, 5`
4. Reverse index 0 through 1, giving `1, 2, 3, 4, 5`
However, after trying my hand at this problem it proved quite difficult for someone not experienced in algorithms to actually create a piece of code that finds the best solution. The answer noted above was simply done by brute-forcing all possible combinations, but this becomes unbearably slow when lists are longer than 10 numbers (10 takes <2s, 14 took more than 10 minutes). Refitting any existing sorting algorithms doesn't work either because they were built to only swap single elements at a time (and swapping 2 numbers by reversing sublists will take 1-2 operations which is not optimal at all). I have also tried sorting networks because the max size is already determined before running the program, but I didn't have much luck with them either (they also rely on swapping, which is inefficient when you have the ability to swap multiple at a time). I also tried to make a function that would "optimize" a list of operations, as an attempt to make existing sorting algorithms viable, but those answers were also far longer than the optimal ones (think of 16 vs 6).
So, after spending quite some time on this, I simply cannot find a better way to find the shortest solution short of brute-forcing it. As I am a student, I do not have much experience in the art of sorting, algorithms and other math "magic", but I was wondering if anyone here might have a try. The best answer of course is simply giving a hint, because I wouldn't mind trying to solve it with some hints of the smarter minds floating around StackOverflow.
Lets say that all numbers are unique and in the range 0 - 100 (both exclusive). The length of the array is something like `3 < N < 15`, because I seem to recall that the original question does not use big arrays either. | 2016/01/07 | [
"https://Stackoverflow.com/questions/34664382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535434/"
] | I've found a solution with a smaller number of swaps for your example:
1. reverse indexes 0 to 2: 2 1 3 5 4
2. reverse indexes 0 and 1: 1 2 3 5 4
3. reverse indexes 3 and 4: 1 2 3 4 5
Seems like what @greybeard suggested is the best approach. Maybe even think of a sort of heuristics based on greedy+optimization functions based on some notion of "cost".
Maybe for example for each element you can calculate "how far" it is from its original index in a sorted list and start by reversing the highest cost list first (as to minimize subsequent swaps, hopefully) until everything is sorted.
Of course, haven't really tested it, but, as a start, it might help you.
Best,
Bruno | My intuitive feeling is that the problem can be reduced to:
1. Regard 2-tuple swaps between array neighbours, based upon their cardinality. This would be an upper bound for the number of subset reverses.
2. Compound these 2-tuple swaps to higher order (3-tuple, 4-tuple etc), reducing the number or reverses further, until no further compounding is possible.
**Regarding 1)**, I have tested this using the following java code and the supplied array [3, 1, 2, 5, 4]:
```
private static int[] reverseSort(int[] array) {
int temp;
int count = 0;
boolean reversed = false;
do {
reversed = false;
for (int i = 0; i < array.length-1; i++) {
if (array[i] > array[i+1]) {
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
count++;
System.out.println(count + ": reverse [" + i + ", " + (i + 1) + "]");
reversed = true;
}
}
} while (reversed);
return array;
}
```
This yields the following (instantaneous) output:
```
1: reverse [0, 1]
2: reverse [1, 2]
3: reverse [3, 4]
```
Already we have a simpler solution, involving only 2-tuples! (Check it).
**Regarding 2)**, I'll leave it to someone else to figure out the compounding in the general case. I'm soo tired, I want to go to bed...
**A hint** (which is what was asked for) regarding compounding: for 3-tuples, run through every consecutive set of 3 2-tuples to see if they compound to 3-tuple. So for example the switches [1,2] [2,3] [1,2] and [2,3] [1,2] [2,3] will both generate [1, 2, 3] from [3, 2, 1], and can be substituted by a compound reverse. Generalise to n-tuple, and stop when n = length of array. |
3,610,933 | Is it possible to iterate a vector from the end to the beginning?
```
for (vector<my_class>::iterator i = my_vector.end();
i != my_vector.begin(); /* ?! */ ) {
}
```
Or is that only possible with something like that:
```
for (int i = my_vector.size() - 1; i >= 0; --i) {
}
``` | 2010/08/31 | [
"https://Stackoverflow.com/questions/3610933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145359/"
] | Use reverse iterators and loop from `rbegin()` to `rend()` | Here's a super simple implementation that allows use of the for each construct and relies only on C++14 std library:
```
namespace Details {
// simple storage of a begin and end iterator
template<class T>
struct iterator_range
{
T beginning, ending;
iterator_range(T beginning, T ending) : beginning(beginning), ending(ending) {}
T begin() const { return beginning; }
T end() const { return ending; }
};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// usage:
// for (auto e : backwards(collection))
template<class T>
auto backwards(T & collection)
{
using namespace std;
return Details::iterator_range(rbegin(collection), rend(collection));
}
```
This works with things that supply an rbegin() and rend(), as well as with static arrays.
```
std::vector<int> collection{ 5, 9, 15, 22 };
for (auto e : backwards(collection))
;
long values[] = { 3, 6, 9, 12 };
for (auto e : backwards(values))
;
``` |
173,189 | For what value of k, $x^{2} + 2(k-1)x + k+5$ has at least one positive root?
**Approach: Case I :** Only $1$ positive root, this implies $0$ lies between the roots, so $$f(0)<0$$ and $$D > 0$$
**Case II:** Both roots positive. It implies $0$ lies behind both the roots. So, $$f(0)>0$$
$$D≥0$$
Also, abscissa of vertex $> 0 $
I did the calculation and found the intersection but its not correct. Please help. Thanks. | 2012/07/20 | [
"https://math.stackexchange.com/questions/173189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/35297/"
] | You only care about the larger of the two roots - the sign of the smaller root is irrelevant. So apply the quadratic formula to get the larger root only, which is
$\frac{-2(k-1)+\sqrt{4(k-1)^2-4(k+5)}}{2} = -k+1+\sqrt{k^2-3k-4}$. You need the part inside the square root to be $\geq 0$, so $k$ must be $\geq 4$ or $\leq -1$. Now, if $k\geq 4$, then to have $-k+1+\sqrt{k^2-3k-4}>0$, you require $k^2-2k-4> (k-1)^2$, which is a contradiction. Alternately, if $k\leq -1$, then $-k+1+\sqrt{k^2-3k-4}$ must be positive, as required.
So you get the required result whenever $k\leq -1$. | Suppose $x\_{1}$ is a real root, then we have that:
$$ (x\_{1}+(k-1))^{2} - (k^2-3k-4) = 0 $$
$$(x\_{1}+(k-1))^{2} = (k^2-3k-4)$$
$$(k^2-3k-4) \ge 0$$
It's obviously seen that the positive roots are got only when $k \le -1$.
Q.E.D. |
28,625,104 | If it is default constructor, who will initialize the member variables to zero then how come this will be possible
```
class A
{
public int i;
public int j;
public A()
{
i=12;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
Console.WriteLine(a.i + "" + a.j);
Console.ReadLine();
}
}
``` | 2015/02/20 | [
"https://Stackoverflow.com/questions/28625104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476719/"
] | A field initialization happens before a constructor call through the `newobj` command. It is easy to check after decompilation of the executable with the following C# code:
```
using System;
namespace ConsoleApplication1
{
public class A { public int j; }
class Program
{
static void Main(string[] args)
{
A g = new A();
Console.WriteLine(g.j);
}
}
}
```
Part of the decompilted MSIL code (method main):
```
//000017: {
IL_0000: nop
//000018: A g = new A();
IL_0001: newobj instance void ConsoleApplication1.A::.ctor()
IL_0006: stloc.0
//000019: Console.WriteLine(g.j);
IL_0007: ldloc.0
IL_0008: ldfld int32 ConsoleApplication1.A::j
IL_000d: call void [mscorlib]System.Console::WriteLine(int32)
IL_0012: nop
//000020: }
```
As we can see the MSIL uses the `newobj` instruction to create an instance of the A class. According to the following [microsoft acticle](https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.newobj%28v=vs.110%29.aspx):
>
> The newobj instruction allocates a new instance of the class associated
> with ctor and initializes **all the fields in the new instance to 0** (of the
> proper type) or null references as appropriate. It then calls the
> constructor ctor with the given arguments along with the newly created
> instance. After the constructor has been called, the now initialized
> object reference (type O) is pushed on the stack.
>
>
>
If it is wrong, please comment, otherwise assign it as a right answer, please. | During the instance creation, its variables are made available too.
And since int is not nullable, it initializes with default(int). Which is 0 |
465,792 | I have a bare uBITX 3-30 MHz transceiver board per <http://www.hfsignals.com/index.php/ubitx/>
Looking at the hookup directions and other pictures on the site, the designer's recommendation is to simply hook a BNC jack to the main board through a (short) two-wire jumper (fractions of hookup schematic and pic below).
What I would like to do is add an additional SMA output in parallel with the BNC adapter to try things with other antennas and gear I already own without re-opening the case and swapping two-wire jumpers. It seems it wouldn't be much different than connecting a BNC tee to the output with a SMA adapter on one end and only using one or the other and leaving an open port.
What issues are there with mounting multiple RF connectors in parallel if you only intend to use one at any one time?
Are there similar issues with leaving an open Tee on a line?
[](https://i.stack.imgur.com/sx7fM.png)
[](https://i.stack.imgur.com/cFL3l.png) | 2019/11/04 | [
"https://electronics.stackexchange.com/questions/465792",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/30711/"
] | Those things detect a voltage difference between ground and the connected wire. Your body makes the connection to ground - that's why you must touch the contact on the end of it.
The neutral wire in your house is connected to ground - the literal ground beneath your feet and the ground (green) wire in your house wiring.
There is (ideally) no voltage difference between neutral and ground. In practice, there's usually a few (maybe a few tens) of volts difference between neutral and ground. Not enough for the detector to notice.
There's 230V between hot and neutral, but zero between neutral and ground.
If you touch a supposed neutral wire with your detector and it lights up, then you should stop working on your wiring - there is something is wrong, and it could kill you. If your detector lights up on a neutral wire, have your wiring checked by an electrician before you do anything else with the wiring.
---
The detectors are simple, and they fail "safe." That is, if they break you will not be electrocuted while using it.
What can happen, though, is that they fail and don't detect a hot wire.
I always check the detector before doing anything on the wiring.
1. Turn on lights
2. Touch the detector to the hot wire. It should light up.
3. Turn off lights.
4. Touch detector to the hot wire. It should not light up.
If you touch the detector to a supposed hot wire and it doesn't light up, then you should check it again on a known good hot wire (like an outlet.) If it still doesn't light up, it is broken. They are cheap, buy a new one. | Just to add to JRE's answer:
>
> I am using a single-pole voltage detector to detect if there is a current-flow / potential on the clamps of my ceiling lamp ...
>
>
>
You can't use a *voltage detector* to monitor current. As the name suggests, it measures voltage. It has no idea whether or not current is flowing in that part of the circuit. It's usefulness is that it indicates that the potential for current flow exists and that, if a load is connected and it still lights, current should flow.
To monitor current you would use a clamp-on current meter. Provided that there are no earth-faults on the circuit then the current reading on the live will be exactly the same as the current reading on the neutral. (What goes in must come out.) |
2,987 | I understand that Stack Overflow is for technical questions only. Is there another version for other aspects of software—such as marketing software—similar to `serverfault.com` for admin questions? If not, what do you think about the idea? | 2009/07/06 | [
"https://meta.stackexchange.com/questions/2987",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/-1/"
] | You may possibly see sites like this pop up on StackExchange as different communities in and around the web want a home for things. Fishing, Football, all kinds of things would be possible in that world. | I think marketing with relation to Software is in fact valid for Stack Overflow? As would other external factors relating to development. |
18,597,043 | How can I to Upload a file with C# ? I need to upload a file from a dialogWindow. | 2013/09/03 | [
"https://Stackoverflow.com/questions/18597043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2476304/"
] | The following code snippet is the simplest form of performing the file uploading.
I have added a few more lines to this code, in order to detect the uploading file type and check the container exeistance.
Note:- you need to add the following NuGet packages first.
1. Microsoft.AspNetCore.StaticFiles
2. Microsoft.Azure.Storage.Blob
3. Microsoft.Extensions.Configuration
```
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string connstring = "DefaultEndpointsProtocol=https;AccountName=storageaccountnewne9d7b;AccountKey=3sUU8J5pQQ+6YYIi+b5jo+BiSb5XPt027Rve6N5QP9iPEhMXZAbzUfsuW7QDWi1gSPecsPFpC6AzmA9jwPYs6g==;EndpointSuffix=core.windows.net";
string containername = "newturorial";
string finlename = "TestUpload.docx";
var fileBytes = System.IO.File.ReadAllBytes(@"C:\Users\Namal Wijekoon\Desktop\HardningSprint2LoadTest\" + finlename);
var cloudstorageAccount = CloudStorageAccount.Parse(connstring);
var cloudblobClient = cloudstorageAccount.CreateCloudBlobClient();
var containerObject = cloudblobClient.GetContainerReference(containername);
//check the container existance
if (containerObject.CreateIfNotExistsAsync().Result)
{
containerObject.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}
var fileobject = containerObject.GetBlockBlobReference(finlename);
//check the file type
string file_type;
var provider = new FileExtensionContentTypeProvider();
if(!provider.TryGetContentType(finlename, out file_type))
{
file_type = "application/octet-stream";
}
fileobject.Properties.ContentType = file_type;
fileobject.UploadFromByteArrayAsync(fileBytes, 0 , fileBytes.Length);
string fileuploadURI = fileobject.Uri.AbsoluteUri;
Console.WriteLine("File has be uploaded successfully.");
Console.WriteLine("The URL of the Uploaded file is : - \n" + fileuploadURI);
}
``` | **Here is the complete method.**
```
[HttpPost]
public ActionResult Index(Doctor doct, HttpPostedFileBase photo)
{
try
{
if (photo != null && photo.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(photo.FileName);
doct.Image = fileName.ToString();
CloudStorageAccount cloudStorageAccount = DoctorController.GetConnectionString();
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
string imageName = Guid.NewGuid().ToString() + "-" +Path.GetExtension(photo.FileName);
CloudBlockBlob BlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
BlockBlob.Properties.ContentType = photo.ContentType;
BlockBlob.UploadFromStreamAsync(photo.InputStream);
string imageFullPath = BlockBlob.Uri.ToString();
var memoryStream = new MemoryStream();
photo.InputStream.CopyTo(memoryStream);
memoryStream.ToArray();
memoryStream.Seek(0, SeekOrigin.Begin);
using (var fs = photo.InputStream)
{
BlockBlob.UploadFromStreamAsync(memoryStream);
}
}
}
catch (Exception ex)
{
}
return View();
}
```
**where the getconnectionstring method is this.**
```
static string accountname = ConfigurationManager.AppSettings["accountName"];
static string key = ConfigurationManager.AppSettings["key"];
public static CloudStorageAccount GetConnectionString()
{
string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountname, key);
return CloudStorageAccount.Parse(connectionString);
}
``` |
86,282 | Chrome will autofill some user/password fields completely. In others, it will wait until you specify a username, at which point it completes the password.
Is it possible to make Chrome complete the username and password by default? | 2009/12/21 | [
"https://superuser.com/questions/86282",
"https://superuser.com",
"https://superuser.com/users/12555/"
] | I think Brendan is right. Chrome seems to look for a field whose name is "username" along with the password field. If the username field is missing, nothing gets filled in. Also, if the username field has some other name, such as "ID", or if the username field is on a separate page from the password field, it probably won't fill in the name.
Firefox does a much better job of recognizing when username and or password fields need to be filled in or at least completed. This is certainly an area where Chrome could be improved. | Looks like chrome is SUPER picky about pulling the username from the form. The field for password reset forms MUST be of `type="text"` and must not have the `disabled` attribute if you want it to also pull the username for the password manager.
[](https://i.stack.imgur.com/TL97e.png)
As a work around you can set the height to 0 and add a disable tab indexing to the input field
```
<input type="text" autocomplete="username email" tabindex="-1" class="hyde">
.hyde {
overflow: hidden;
height: 0;
min-height: 0;
padding: 0;
margin: 0;
}
```
Sources:
<https://www.chromium.org/developers/design-documents/form-styles-that-chromium-understands>
<https://stackoverflow.com/questions/5192859/how-to-ignore-html-element-from-tabindex> |
303,911 | There is a similar question [here](https://stackoverflow.com/questions/203495/testing-rest-webservices) but it only covers some of the issues below.
We have a client who requires web services using REST.
We have tons of experience using SOAP and over time have gathered together a really good set of tools for SOAP development and testing e.g.
* soapUI
* Eclipse plugins
* wsdl2java
* WSStudio
By "tools" I mean a product "out of the box" that we can start using. I'm not talking about cutting code to "roll our own" using Ajax or whatever.
The tool set for REST doesn't seem to be nearly as mature?
* What tools are out there (we use C# and Java mainly) ?
* Do the tools handle GET, POST, PUT, and DELETE?
* Is there a decent Eclipse plugin?
* Is there a decent client testing application like WSStudio where you point the tool to the WSDL and it generates a proxy on the fly with the appropriate methods and inputs and you simple type the data in?
* Are there any good package monitoring tools that allow you to look at the data? (I'm not thinking about sniffers like Wireshark here but rather things like soapUI that allow you to see the request / response) ? | 2008/11/20 | [
"https://Stackoverflow.com/questions/303911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9922/"
] | I googled and found this plugin for chrome.
[POSTman REST Client](https://github.com/a85/POSTMan-Chrome-Extension). | In terms of a client testing application, I had a similar problem. I couldn't find a tool that I could use to quickly test data going in and out of the web services I was creating/using. So I created my own tool using C# .NET. It's essentially a client application that you can use for GET, POST, PUT, and DELETE queries on rest services.
The software is called REST Scratch Pad. It lets you enter the data to send to the REST service and view the results of queries along with their headers and response times. It will handle basic authentication and will remember the URLs you've used in prior sessions (to avoid having to re-type long URLs).
The current version is free. The next version will use a newer version of .NET and cover more authentication methods.
[REST ScratchPad](http://restscratchpad.com/download) |
9,906,591 | I've built a REST webservice with some webmethods.
But I don't get it to work passing parameters to these methods.
I.E.
```
@GET
@Path("hello")
@Produces(MediaType.TEXT_PLAIN)
public String hello(String firstName, String lastName){
return "Hello " + firstname + " " + lastname
}
```
How would I invoke that method and how to pass the parameters firstname and lastname?
I tried something like this:
```
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
ClientResponse response = service.path("hello")
.accept(MediaType.TEXT_PLAIN).put(ClientResponse.class);
```
But where do I add the parameters?
Thank you for your help,
best regards,
Chris | 2012/03/28 | [
"https://Stackoverflow.com/questions/9906591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297996/"
] | If you are using SpringMVC for REST api development you can use
```
@RequestParam("PARAMETER_NAME");
```
In case of jersey you can use
```
@QueryParam("PARAMETER_NAME");
```
Method look like this
```
public String hello(@RequestParam("firstName")String firstName, @RequestParam("lastName")String lastName){
return "Hello " + firstname + " " + lastname
```
} | This will help you
```
ClientResponse response = resource.queryParams(formData).post(ClientResponse.class, formData);
```
where formData is
```
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("Key","Value");
formData.add("Key","Value");
...
...
...
formData.add("Key","Value");
``` |
48,281,774 | how to perform multiple queries in single stored procedure and then use result we get by all queries in our model. I get **Query error: Commands out of sync; you can't run this command now error** when try to use the result of the stored procedure. Here is my code :
\*\*In Model: \*\*
```
/* convert post array data to string */
$pr = "'" .implode("', '", $data) . "'";
$pr2 = "'" .implode("', '", $data2) . "'";
$pr5 = "'" .implode("', '", $data4) . "'";
/* call stored procedure */
$this->db->query('CALL addCustomerSalesData("'.$pr.'", "'.$pr2.'", "'.$pr5.'", @CustSalesID, @CustSalesProID)');
/* get the stored procedure returned output */
$query = $this->db->query('SELECT @CustSalesID AS cust_sales_id, @CustSalesProID AS cust_sales_pro_id');
$row = $query->row_array();
/* this will release memory which is used by stored procedure and make it free for another process */
$query->next_result();
$query->free_result();
/* return inserted id*/
return $row;
``` | 2018/01/16 | [
"https://Stackoverflow.com/questions/48281774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5620456/"
] | I also used sinch service. For Incoming call, i solved this problem .I hope your problem can be solved by trying this:
1.Replace
```
<activity
android:name="IncomingCallScreenActivity"
android:noHistory="true"
android:showOnLockScreen="true"
android:screenOrientation="sensorPortrait">
</activity>
```
By
```
<activity
android:name="IncomingCallScreenActivity">
</activity>
```
2.Code on onCreate() in your activity:
```
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); }
``` | From Android O and above, if your application is in the background, your application is allowed to create and run background services for some minutes, afterwards your application will enter in the idle stage, and all background service will be stopped.
Posible solution is to use [JobScheduler](https://developer.android.com/reference/android/app/job/JobScheduler.html) api introduced in API21 to perform background tasks. |
5,287,329 | ```
vector<string> v;
v.push_back("A");
v.push_back("B");
v.push_back("C");
v.push_back("D");
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
//printout
cout << *it << endl;
}
```
**I like to add a comma after each element as follow:**
A,B,C,D
I tried researching on Google, but I only found CSV to `vector`. | 2011/03/13 | [
"https://Stackoverflow.com/questions/5287329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/657189/"
] | Does really nobody know the `std::experimental::ostream_joiner`?. See [here](https://en.cppreference.com/w/cpp/experimental/ostream_joiner). To be used in algorithms, like `std::copy`
Or, if you do not want to use `std::experimental` alternatively, `std::exchange`? See [here](https://en.cppreference.com/w/cpp/utility/exchange)
Like this:
```
#include <iostream>
#include <vector>
#include <utility>
int main() {
std::vector data{1,2,3,4};
bool showComma{};
for (const int i: data) std::cout << (std::exchange(showComma, true) ? "," : "") << i;
}
```
Maybe, I have a misunderstanding . . . | To avoid the trailing comma, loop until **v.end() - 1**, and output **v.back()** for instance:
```
#include <vector>
#include <iostream>
#include <iterator>
#include <string>
#include <iostream>
template <class Val>
void Out(const std::vector<Val>& v)
{
if (v.size() > 1)
std::copy(v.begin(), v.end() - 1, std::ostream_iterator<Val>(std::cout, ", "));
if (v.size())
std::cout << v.back() << std::endl;
}
int main()
{
const char* strings[] = {"A", "B", "C", "D"};
Out(std::vector<std::string>(strings, strings + sizeof(strings) / sizeof(const char*)));
const int ints[] = {1, 2, 3, 4};
Out(std::vector<int>(ints, ints + sizeof(ints) / sizeof(int)));
}
```
BTW you posted:
```
vector<string> v;
//...
for (vector<int>::iterator it = v.begin(); //...
```
which is unlikely to compile :) |
2,524,963 | Consider two sequences of positive real numbers $(a\_n)\_{n\in\mathbb{N}}$ and $(b\_n)\_{n\in\mathbb{N}}$ such that $\lim\_{n\to\infty}\frac{a\_n}{b\_n}=+\infty$ and $\lim\_{n\to\infty}a\_n=+\infty$. Prove that $\lim\_{n\to\infty}(a\_n-b\_n)=+\infty$.
The book I'm using to study sequences don't have a solution to this problem, so I don't think it is too difficult (since the book provides the solution to the difficult questions). Unfortunately I couldn't resolve this question and I wasn't even able to make any progress. So please help me. | 2017/11/17 | [
"https://math.stackexchange.com/questions/2524963",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | **(Big) Hint:** since $\lim\_{n\to\infty}\frac{a\_n}{b\_n} =\infty$, there exists an $N\geq 0$ such that
$$
\frac{a\_n}{b\_n} \geq 2
$$
for all $n\geq N$. Then $a\_n - b\_n \geq \frac{a\_n}{2}$ for all $n\geq N$. | **Hint:** Prove that $\lim \frac{b\_n}{a\_n}=0$. Then try factoring $a\_n$ out of the expression $a\_n-b\_n$ and consider the limit of the resulting product. |
1,668,192 | What would a developer used to working in **Visual Studio** have to give up if they switched to **Monodevelop**? This hypothetical developer most often develops **ASP.NET web applications** with **C#**.
I'm aware that Monodevelop has the basic Visual Studio features like syntax highlighting and support for Visual Studio solutions. What are the deficiencies that would **most affect the productivity** of a developer giving up Visual Studio?
To keep things consistent, please confine your answers to points about **Visual Studio 2008** and **Monodevelop 2.0**. | 2009/11/03 | [
"https://Stackoverflow.com/questions/1668192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111495/"
] | Can't speak for the previous versions, but I've been using MonoDevelop 3+ on a MacBook for a commercial project and have found it to be a more pleasant experience than Visual Studio.
It loads faster, compiles faster and all the tools are more easily accessible and more logically laid out (like source control).
The UI layout is much better in my opinion, and you can tell it was developed by actual users of the software not "UI Designers" who don't actually use the software.
I have not found a need for 3rd party tools. In Visual Studio, I used Resharper for code-formatting and other minor things but generally find it overbearing. In MonoDevelop, I've found it handles code-formatting BETTER than Resharper and offers more options by default (e.g. it can format fluent-styles properly unlike Resharper).
On a cost-benefit-analysis alone, MonoDevelop trumps Visual Studio. If you need to do WPF development, TFS-based development, SharePoint or other MS-centric development then it isn't the tool for the job. If you need to build ASP.NET MVC apps, desktop apps, mobile apps, backend apps then I would recommend checking it out and saving money on Visual Studio licenses.
Personally, I plan to migrate 100% to MonoDevelop and eventually phase out Visual Studio. I certainly won't be going down the VS2012/RT route for future development. My current customer got rid of their Win8 machines and decided to use Win7. Their customer is requesting we develop desktop client apps on Mac's as they want to phase out Windows altogether. You make your own mind up where this is all going. | I tried Monodevelop and found that it's not a "wow" experience, though this doesn't mean it's not a great accomplishment.
I'm used to docking controls and being able to easily drag controls into/out of containers. However, if I want to do this in GTK, I have to delete all the controls and start again! Therefore, I could not be productive using MonoDevelop.
In general, someone can learn how to deal with it.
Only guys who know how to program in Linux in C and C++ (Linux Development in General) will find it a "wow" experience. For windows developers, it is an unhappy experience. |
74,034,541 | I have a CSV file, around 5k lines, with the following example:
```none
apple,tea,salt,fish
apple,oranges,ketchup
...
salad,oreo,lemon
salad,soda,water
```
I need to extract only first line matching apple or salad and skip other lines where those words occur.
I can do something like this with regex, "apple|salad", but it will extract all the lines where those words are found.
The desired result is:
```none
apple,tea,salt,fish
salad,oreo,lemon
```
I'm able to use REGEX in a text editor and OpenOffice Calc application. | 2022/10/11 | [
"https://Stackoverflow.com/questions/74034541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20217051/"
] | You could use the great [Miller](https://miller.readthedocs.io/en/latest/installing-miller/), and run
```
mlr --nidx --fs "," filter '$1=~"(apple|salad)"' then head -n 1 -g 1 input.csv
```
to have
```
apple,tea,salt,fish
salad,oreo,lemon
```
* `--nidx`, to set the format, a generic index format
* `--fs ","`, to set the separator
* `filter '$1=~"(apple|salad)"'`, to apply the regex filter to the first field
* `then head -n 1 -g 1`, to take the first record, based on the value of the first field | In Notepad++ repeatedly do a regular expression replace of `^(\w+,)(.*)\R\1.*$` with `\1\2`. Have "Wrap around" selected.
Explanation:
```
^ Match beginning of line
(\w+,) Match the leading word plus comma, save to capture group 1
(.*) Match the rest of the line, save to capture group 2
\R Match a line break
\1 Match the same leading word plus comma
.* Match the rest of the line
$ Match the end of the line
```
The replace string just keeps the first line, the second line is discarded.
Demonstration:
Starting with:
```
apple,tea1,salt1,fish1
apple,tea2,salt2,fish2
apple,oranges1,ketchup1
apple,oranges2,ketchup2
apple,oranges3,ketchup3
apple,oranges4,ketchup4
salad,oreo1,lemon1
salad,oreo2,lemon2
salad,soda1,water1
salad,soda2,water2
```
Doing a "Replace all" with the above expressions yields:
```
apple,tea1,salt1,fish1
apple,oranges1,ketchup1
apple,oranges3,ketchup3
salad,oreo1,lemon1
salad,soda1,water1
```
Two more clicks on "Replace all" yield:
```
apple,tea1,salt1,fish1
salad,oreo1,lemon1
```
Each press of "Replace all" removes approximately half of the unwanted lines. |
46,037,161 | I am struggling to get get anywhere with more advanced filters.
Dates,
As far as I can see `Admin-on-Rest` filter can only be `"where":"field":"value"...}`.
It would be great if filter can included a date range. `{"where":"field" between: "value1" and "value2" ...`
like or regexp
Again, `AOR's` filters are exact. Is it possible to use "`like`" or "`regexp`"? | 2017/09/04 | [
"https://Stackoverflow.com/questions/46037161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8239836/"
] | The problem is that you are storing pointers to char, not strings:
```
vector<char *> myvec;
```
instead of
```
vector<string> myvec;
```
So, when you write your input:
```
A bird came down the walk down END
^ ^
```
these two "down" are different words, and they are stored in differents posititions of memory, and because of that their address are different.
A similar code that works, but using strings, is the following:
```
string input;
getline(cin, input);
stringstream str;
str << input;
vector<string> v;
while (str >> input){
if (find(v.begin(), v.end(), input) == v.end())
v.push_back(input);
}
cout << '\n';
for(auto p = v.rbegin(); p != v.rend(); ++p)
cout << *p << ' ';
cout << '\n';
``` | Since `vector<char*>` is a vector of pointers and `token` is a pointer as well, you are comparing pointers. The two different pointers point to different values, then they are not equal.
Insert this in your code, and you will see the difference:
```
std::cout << "Memory address: " << token << " value: " << *token << std::endl;
```
You want to compare the values, not the pointers. As said in the comments, you can try to use `vector<char>` and then use `*token`, or use `vector<string>` directly (so you can also avoid `input.c_str()`).
PS: if you want to still use `char*` in the vector, you can implement a simple function like this:
```
bool check_character(vector<char*> vec, char* token)
{
for (int i = 0; i < vec.size(); i++ )
{
if (*(vec.at(i)) == *token)
return true;
}
return false;
}
```
(ps code not tested) |
583,847 | I want to know the difference of time (hh:mm:ss) between two times.
For example:
Job start at 11:30pm at night but ends at 10:37 the next morning. | 2013/04/17 | [
"https://superuser.com/questions/583847",
"https://superuser.com",
"https://superuser.com/users/217634/"
] | I concur with @ndev that the problem is probably corrupted
program associations of the selected file extension type.
But I do not think that his suggested .reg file completely solves the problem.
The article [Restore Default Windows 7 File Extension Type Associations](http://www.sevenforums.com/tutorials/19449-default-file-type-associations-restore.html)
contains .reg files to correct program associations for dozens of files-types,
so not only for EXE.
Here are the contents of the [.reg file](http://www.sevenforums.com/attachments/tutorials/123734d1312706455-default-file-type-associations-restore-default_exe.reg) to correct the EXE extension:
```
Windows Registry Editor Version 5.00
[-HKEY_CLASSES_ROOT\.exe]
[HKEY_CLASSES_ROOT\.exe]
@="exefile"
"Content Type"="application/x-msdownload"
[HKEY_CLASSES_ROOT\.exe\PersistentHandler]
@="{098f2470-bae0-11cd-b579-08002b30bfeb}"
[HKEY_CLASSES_ROOT\exefile]
@="Application"
"EditFlags"=hex:38,07,00,00
"FriendlyTypeName"=hex(2):40,00,25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,\
00,6f,00,6f,00,74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,\
32,00,5c,00,73,00,68,00,65,00,6c,00,6c,00,33,00,32,00,2e,00,64,00,6c,00,6c,\
00,2c,00,2d,00,31,00,30,00,31,00,35,00,36,00,00,00
[HKEY_CLASSES_ROOT\exefile\DefaultIcon]
@="%1"
[HKEY_CLASSES_ROOT\exefile\shell]
[HKEY_CLASSES_ROOT\exefile\shell\open]
"EditFlags"=hex:00,00,00,00
[HKEY_CLASSES_ROOT\exefile\shell\open\command]
@="\"%1\" %*"
"IsolatedCommand"="\"%1\" %*"
[HKEY_CLASSES_ROOT\exefile\shell\runas]
"HasLUAShield"=""
[HKEY_CLASSES_ROOT\exefile\shell\runas\command]
@="\"%1\" %*"
"IsolatedCommand"="\"%1\" %*"
[HKEY_CLASSES_ROOT\exefile\shell\runasuser]
@="@shell32.dll,-50944"
"Extended"=""
"SuppressionPolicyEx"="{F211AA05-D4DF-4370-A2A0-9F19C09756A7}"
[HKEY_CLASSES_ROOT\exefile\shell\runasuser\command]
"DelegateExecute"="{ea72d00e-4960-42fa-ba92-7792a7944c1d}"
[HKEY_CLASSES_ROOT\exefile\shellex]
[HKEY_CLASSES_ROOT\exefile\shellex\ContextMenuHandlers]
@="Compatibility"
[HKEY_CLASSES_ROOT\exefile\shellex\ContextMenuHandlers\Compatibility]
@="{1d27f844-3a1f-4410-85ac-14651078412d}"
[HKEY_CLASSES_ROOT\exefile\shellex\DropHandler]
@="{86C86720-42A0-1069-A2E8-08002B30309D}"
[-HKEY_CLASSES_ROOT\SystemFileAssociations\.exe]
[HKEY_CLASSES_ROOT\SystemFileAssociations\.exe]
"FullDetails"="prop:System.PropGroup.Description;System.FileDescription;System.ItemTypeText;System.FileVersion;System.Software.ProductName;System.Software.ProductVersion;System.Copyright;*System.Category;*System.Comment;System.Size;System.DateModified;System.Language;*System.Trademarks;*System.OriginalFileName"
"InfoTip"="prop:System.FileDescription;System.Company;System.FileVersion;System.DateCreated;System.Size"
"TileInfo"="prop:System.FileDescription;System.Company;System.FileVersion;System.DateCreated;System.Size"
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.exe]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.exe]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.exe\OpenWithList]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.exe\OpenWithProgids]
"exefile"=hex(0):
[-HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.exe]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.exe]
@="exefile"
"Content Type"="application/x-msdownload"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.exe\PersistentHandler]
@="{098f2470-bae0-11cd-b579-08002b30bfeb}"
``` | It looks like your installation of Perl damaged your Windows file extension type associations.
Create a new .reg file and paste following code:
```
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.EXE]
@="exefile"
"Content Type"="application/x-msdownload"
[HKEY_CLASSES_ROOT\.EXE\PersistentHandler]
@="{098f2470-bae0-11cd-b579-08002b30bfeb}"
[HKEY_CLASSES_ROOT\exefile]
@="Application"
"EditFlags"=hex:38,07,00,00
"FriendlyTypeName"=hex(2):40,00,25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,\
00,6f,00,6f,00,74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,\
32,00,5c,00,73,00,68,00,65,00,6c,00,6c,00,33,00,32,00,2e,00,64,00,6c,00,6c,\
00,2c,00,2d,00,31,00,30,00,31,00,35,00,36,00,00,00
[HKEY_CLASSES_ROOT\exefile\DefaultIcon]
@="%1"
[HKEY_CLASSES_ROOT\exefile\shell\open]
"EditFlags"=hex:00,00,00,00
[HKEY_CLASSES_ROOT\exefile\shell\open\command]
@="\"%1\" %*"
"IsolatedCommand"="\"%1\" %*"
[HKEY_CLASSES_ROOT\exefile\shell\runas]
"HasLUAShield"=""
[HKEY_CLASSES_ROOT\exefile\shell\runas\command]
@="\"%1\" %*"
"IsolatedCommand"="\"%1\" %*"
[HKEY_CLASSES_ROOT\exefile\shell\runasuser]
@="@shell32.dll,-50944"
"Extended"=""
"SuppressionPolicyEx"="{F211AA05-D4DF-4370-A2A0-9F19C09756A7}"
[HKEY_CLASSES_ROOT\exefile\shell\runasuser\command]
"DelegateExecute"="{ea72d00e-4960-42fa-ba92-7792a7944c1d}"
[HKEY_CLASSES_ROOT\exefile\shellex\ContextMenuHandlers]
@="Compatibility"
[HKEY_CLASSES_ROOT\exefile\shellex\ContextMenuHandlers\Compatibility]
@="{1d27f844-3a1f-4410-85ac-14651078412d}"
[HKEY_CLASSES_ROOT\exefile\shellex\DropHandler]
@="{86C86720-42A0-1069-A2E8-08002B30309D}"
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.EXE\UserChoice]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.EXE\OpenWithProgids]
"exefile"=hex(0):
```
Now right-click on the .reg file and press Merge. You should now be able to run .exe files again. (maybe you have to restart)
If that worked Google for “windows 7 file association fixes” and fix all other damaged file associations. |
11,136,689 | Using Qt I know that `private slots` means the slot is private when called directly but a `connect()` can still allow a signal to be connected to a slot whether private, public, or I guess, protected.
So, is there a way to make a slot really private, such that only a connection within a class can be done? What I am thinking here is because of the `QTimer::singleShot` that calls a slot but the function I want to call I don't want to be accessible outside of the class. I am sure there are other reasons but this is the main one at the moment I have found. | 2012/06/21 | [
"https://Stackoverflow.com/questions/11136689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | Just use [timerEvent](http://qt-project.org/doc/qt-4.8/qobject.html#timerEvent) and [startTimer](http://qt-project.org/doc/qt-4.8/qobject.html#startTimer) instead of slot and QTimer::singleShot. | I think it's possible to add one more argument to your slot and corresponding signal like this:
```
...
private slots:
void slot(..., QObject* sender = 0);
...
void YourClass::slot(..., QObject* sender)
{
if (sender != (QObject*)this)
{
/* do nothing or raise an exception or do whatever you want */
}
...
}
```
Of course it won't make your slot 'completely' private, but it won't let your code to be executed after receiving a signal from the outside of your object. |
29,036,008 | I am building an administrative back-end and thus need to hide public user registration. It appears that if you want to use the built-in Illuminate authentication you need to add
`use AuthenticatesAndRegistersUsers` to your controller definition. This trait is defined [here](http://laravel.com/api/5.0/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.html).
It appears as if it is impossible to disable registration if you want to use the built-in auth handlers... can someone show me wrong? | 2015/03/13 | [
"https://Stackoverflow.com/questions/29036008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962674/"
] | [This page](http://slick.pl/kb/laravel/overriding-login-and-registration-functionality-in-laravel-5/) talks about overriding the auth controller. Its worth a read, at a basic level it seems you can add the following lines to app\Http\Controllers\Auth\AuthController.php :
```
public function getRegister() {
return redirect('/');
}
public function postRegister() {
return redirect('/');
}
```
So if a user accesses the registration url it will redirect them away to a place of your choosing. | You can have your own form of registration. The only thing Laravel does is make it easy to authenticate on a users table because they create the model, build the db schema for users and provide helper methods to authenticate on that model/table.
You don't have to have a view hitting the registration page... But if you want to use the built in auth you still need to use (or set) a Model and a driver for database connections.
You can just remove that view and/or controller method from the route that links to the registration view and create your own (or seed the database manually).
But, no, you cannot forgo using Eloquent, and the User model and expect to use built in auth. Built in authentication requires that you specify settings in /config/auth.php. You may specific a different model (other than User) and you may specify a different table, but you cannot forgo the configuration completely.
Laravel is very customizable though, so you can achieve what you are looking to do... plus why not use Eloquent, it's nice. |
21,472,602 | Ok maybe I am being too picky. Apologies in advance if you cannot see it, but in the second pic, the item on the row is pixellated a bit, or as if a word was placed on top of a word. This only happens after I scroll up on the tableview, otherwise, it is similar to the first image.
First pic:

Second pic (you can see the difference in the font here): 
it's a bit more bold and unrefined once I scroll up.
I frankly have no idea why. The tableview is being loaded normally. Any help, hunch, or suggestion would be greatly associated, even if it can point me to the right area.
Here is the code for the second image's tableview.
```
static NSString *CellIdentifier = @"OrderProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
//configure cell, display name and cost of each item
OrderProduct *p = [[order.items allObjects] objectAtIndex:indexPath.row];
UILabel *lableName=[[UILabel alloc]initWithFrame:CGRectMake(10, 16, 300, 20)];
lableName.backgroundColor=[UIColor clearColor];
lableName.font=[UIFont boldSystemFontOfSize:19];
[lableName setFont:[UIFont fontWithName:@"Arial-Bold" size:12.0]];
lableName.text=p.name;
//UILabel *counterNumber=[[UILabel alloc]initWithFrame:CGRectMake(10, 25, 300, 20)];
//counterNumber.backgroundColor=[UIColor clearColor];
//counterNumber.font=[UIFont systemFontOfSize:12];
//counterNumber.text=[NSString stringWithFormat:@"Scan time :%@",p.scannerCounter];
[cell.detailTextLabel setText:[NSString stringWithFormat:@"%@ %.02f",p.currency, p.cost]];
cell.imageView.image = [UIImage imageNamed:p.image];
[cell addSubview:lableName];
//[cell release];
//[cell addSubview:counterNumber];
return cell;
``` | 2014/01/31 | [
"https://Stackoverflow.com/questions/21472602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255500/"
] | This is happening because you are not reusing cells and hence you are basically adding the label again and again instead of using the already existing one.
Just put the following code inside the if(cell == nil):
```
static NSString *CellIdentifier = @"OrderProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *lableName;
if(cell==nil){
// this is where we should initialize and customize the UI elements,
// or in this case your label.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
lableName=[[UILabel alloc]initWithFrame:CGRectMake(10, 16, 300, 20)];
lableName.backgroundColor=[UIColor clearColor];
lableName.font=[UIFont boldSystemFontOfSize:19];
[lableName setFont:[UIFont fontWithName:@"Arial-Bold" size:12.0]];
[cell addSubview:lableName];
}
// this is where we should assign the value.
OrderProduct *p = [[order.items allObjects] objectAtIndex:indexPath.row];
lableName.text = p.name;
/*
assign other values if any
...
*/
return cell;
```
this way the lableName will not be added to the cell again and again and hence this problem will not occur.
The best way of reusing a cell properties is initializing and customizing everything inside the if(cell==nil) and only adding the value of the element outside the if condition. | 1. Don't add subviews to cell directly, add it to contentView of cell
2. While reusing the cell you need to remove the existing label first and add new label or use the existing cell instead of adding new one.
Change your code like:
```
static NSString *CellIdentifier = @"OrderProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *lableName = nil;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
lableName=[[UILabel alloc]initWithFrame:CGRectMake(10, 16, 300, 20)];
lableName.backgroundColor=[UIColor clearColor];
lableName.font=[UIFont boldSystemFontOfSize:19];
[lableName setFont:[UIFont fontWithName:@"Arial-Bold" size:12.0]];
lableName.tag = 7;
[cell.contentView addSubview:lableName];
}
//configure cell, display name and cost of each item
OrderProduct *p = [[order.items allObjects] objectAtIndex:indexPath.row];
lableName = (UILabel *)[cell.contentView viewWithTag:7];
lableName.text=p.name;
[cell.detailTextLabel setText:[NSString stringWithFormat:@"%@ %.02f",p.currency, p.cost]];
cell.imageView.image = [UIImage imageNamed:p.image];
return cell;
``` |
17,734,301 | I was curious about something. Let's say I have two tables, one with sales and promo codes, the other with only promo codes and attributes. Promo codes can be turned on and off, but promo attributes can change. Here is the table structure:
```
tblSales tblPromo
sale promo_cd date promo_cd attribute active_dt inactive_dt
2 AAA 1/1/2013 AAA "fun" 1/1/2013 1/1/3001
3 AAA 6/2/2013 BBB "boo" 1/1/2013 6/1/2013
8 BBB 2/2/2013 BBB "green" 6/2/2013 1/1/3001
9 BBB 2/3/2013
10 BBB 8/1/2013
```
Please note, this is not my table/schema/design. I don't understand why they don't just make new promo\_cd's for each change in attribute, especially when attribute is what we want to measure. Anyway, I'm trying to make a table that looks like this:
```
sale promo_cd attribute
2 AAA fun
3 AAA fun
8 BBB boo
9 BBB boo
10 BBB green
```
The only thing I have done so far is just create an inner join (which causes duplicate records) and then filter by comparing the sale date to the promo active/inactive dates. Is there a better way to do this, though? I was really curious since this is a pretty big set of data and I'd love to keep it efficient. | 2013/07/18 | [
"https://Stackoverflow.com/questions/17734301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565416/"
] | Please see my comments for [this question](https://stackoverflow.com/questions/1652590/smooth-text-animation-marquee-text-effect-using-qt/1662221#1662221).
Basically you have to call `setTransformationMode(Qt::SmoothTransformation)` on the `QGraphicsPixmapItem`s you want anti-aliasing to apply to.
Calling `setRenderHints` on the view did not work for me, either. | The render hints are only applied if it is set bevor the painter is used. Here a snipped:
```
QGraphicsPixmapItem *
drawGraphicsPixmapItem(const QRectF &rect)
{
auto pixmap = new QPixmap(rect.size().toSize());
pixmap->fill("lightGrey");
auto painter = new QPainter(pixmap);
// set render hints bevor drawing with painter
painter->setRenderHints(QPainter::Antialiasing);
QPen pen;
pen.setColor("black");
pen.setWidth(3);
painter->setPen(pen);
QRectF rectT = rect;
rectT.adjust(pen.widthF()/2,pen.widthF()/2,-pen.widthF()/2,-pen.widthF()/2);
QPainterPath circlePath;
circlePath.addEllipse(rectT);
circlePath.closeSubpath();
painter->fillPath(circlePath,QBrush("green"));
painter->drawPath(circlePath);
auto pixmapItem = new QGraphicsPixmapItem(*pixmap);
pixmapItem->setCacheMode(
QGraphicsItem::CacheMode::DeviceCoordinateCache,
pixmap->size() );
return pixmapItem;
}
``` |
187,255 | I'm trying to make a select that calculates affiliate payouts.
my approach is pretty simple.
```
SELECT
month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)
```
The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results.
Before the above I tried what I was assuming would work like "`amount between 24.94 AND 29.94`" this caused an error. so then I tried "`amount >= 24.94 AND <= 29.94`"
So is it possible to have a range comparison using IF in MySql? | 2008/10/09 | [
"https://Stackoverflow.com/questions/187255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | The second part of the expression evaluates when you use `AND` -
```
SELECT
month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95 AND payments.amount<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95 AND payments.amount<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)
```
I'm not entirely sure why the `between` clause didn't work for you, but the above should do the job. | What error did your first attempt give you? It should definitely work. However, note that the second form you have is incorrect syntax. It should be `amount >= 24.94 and amount <= 29.94`. |
399,867 | Please could someone suggest a suitable battery for a specific project.
I need to power a 40 W 12 V car headlight bulb for 10 sessions of 3 or 4 h each time, recharging after each use.
I have tested with a 7Ah battery and only got 1 hr and I am interested in the difference between the projected mathematical time and real world experience.
Also I need to provide a cost effective solution not only for the battery but also the charger as there will be multiple instances of the set up. | 2018/10/07 | [
"https://electronics.stackexchange.com/questions/399867",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/200564/"
] | You need to break down the question into :
How many ampere hours do you need?
To convert 40Watts to 12 volt and ampere = I = P/U = 40W/12V = 3.33A
And to run the lamp for 4 hours you need a battery with 4h x 3.33A = 13.33A/h
So a battery with 12V and a minimum of 13.33A/h is needed. | So you need 3.3A for 4 hours and recharging in between for 10 cycle, this should do:
<https://www.digikey.ie/product-detail/en/b-b-battery/BP17-12-B1/522-1014-ND/653335> |
19,217,130 | I have an array of strings but the values in array is changing continuously.
Is there any other way of managing the array except removing items and changing index locations?
```
public String[] deviceId=null;
deviceId=new String[deviceCount];
```
in my case deviceCount is changes as new device comes.
so i continuously need to change array size and add or remove items | 2013/10/07 | [
"https://Stackoverflow.com/questions/19217130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1572606/"
] | Use ArrayList in place of String[] ..
And you can also easily cast ArrayList to String[] for your final output as
```
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
``` | **-** In Java arrays are `initialized` at the time of its creation whether its `declared` at class level or at local level.
**-** Once the size is defined of an `array in Java it can't be changed`.
**-** Its better to use Collection like List.
**-** It has the flexibility to add and delete the items in it, and one can also at items at desired location in the List.
**-** List is an `Interface` in Java, you can use its `concrete sub classes` like ArrayList, LinkedList..etc. |
72,834,444 | I have a simple variable:
```
float t = 30.2f;
```
How do I add it to a string?
```
char* g = "Temperature is " + h?
```
Any guaranteed way (I don't have Boost for instance, and unsure of what version of c++ I have) I can get this to work on a microcontroller? | 2022/07/01 | [
"https://Stackoverflow.com/questions/72834444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | For simple cases, you can just use the `std::string` class and the `std::to_string` function, which have both been part of C++ for a long time.
```cpp
#include <string>
#include <iostream>
int main()
{
float t = 30.2;
std::string r = "Temperature is " + std::to_string(t);
std::cout << r;
}
```
However, `std::to_string` doesn't give you much control over the formatting, so if you need to specify a field width or a number of digits after the decimal point or something like that, it would be better to see lorro's answer.
If you have an incomplete implementation of the C++ standard library on your microcontroller so you can't use the functions above, or maybe you just want to avoid dynamic memory allocation, try this code (which is valid in C or C++):
```c
float t = 30.2;
char buffer[80];
sprintf(buffer, "Temperature is %f.", t);
```
Note that `buffer` must be large enough to guarantee there will never be a buffer overflow, and failing to make it large enough could cause crashes and security issues. | ```
std::ostringstream oss;
oss << t;
std::string s = "Temperature is " + oss.str();
```
Then you can use either the string or the `c_str()` of it (as *`const`* `char*`).
If, for some reason, you don't have standard library, you can also use `snprintf()` et. al. (printf-variants), but then you need to do the buffer management yourself. |
8,684,045 | I am attempting to store the rank of users based on a score, all it one table, and skipping ranks when there is a tie. For example:
```
ID Score Rank
2 23 1
4 17 2
1 17 2
5 10 4
3 2 5
```
Each time a user's score is updated, The rank for the entire table must also be updated, so after a score update, the following query is run:
```
SET @rank=0;
UPDATE users SET rank= @rank:= (@rank+1) ORDER BY score DESC;
```
But this doesn't support ties, or skipping rank numbers after ties, for that matter.
I want to achieve this re-ranking in as few queries as possible and with no joins (as they seem rather time consuming).
I was able to get the desired result by adding two columns - last\_score and tie\_build\_up - with the following code:
```
SET @rank=0, @last_score = null, @tie_build_up = 0;
UPDATE users SET
rank= @rank:= if(@last_score = score, @rank, @rank+@tie_build_up+1),
tie_build_up= @tie_build_up:= if(@last_score = score, @tie_build_up+1, 0),
last_score= @last_score:= score, ORDER BY score DESC;
```
I don't want those extra columns, but I couldn't get the single query to work without them.
Any ideas?
Thanks. | 2011/12/30 | [
"https://Stackoverflow.com/questions/8684045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123510/"
] | I'm sure you have a good reason for this design choice but I think you should leave the rank out of the database all together. Updating the entire table for every change in one user's score can cause very serious performance issues with almost any size table. I suggest you reconsider that choice. I would advice to simply sort the table by score and assign ranks in the application code. | i calculated rank and position the following way:
to update AND get the values i needs, i first added them, added an additional 1 and subtracted the original value. that way i do not need any help-columns inside the table;
```
SET @rank=0;
SET @position=0;
SET @last_points=null;
UPDATE tip_invitation
set
rank = @rank:=if(@last_points = points, @rank, @rank + 1),
position = ((@last_points := points)-points) + (@position := @position+1)
where
tippgemeinschaft_id = 1 ORDER BY points DESC;
``` |
48,618,756 | I would like to compare two dates, if the dates match then just record but not insert in database and if they are not same data insert in database.
I need it for attendance system to avoid duplicate entry for same time. | 2018/02/05 | [
"https://Stackoverflow.com/questions/48618756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9315647/"
] | What happens here is you reuse the already filled `qb_info player_info`.
First you insert "Aaron\_Rodgers" and print it
>
> Aaron\_Rodgers,
>
>
>
Next you add "GB" to player\_info
>
> Aaron\_Rodgers, GB
>
>
>
Next you keep "GB" and insert "Alex\_Smith"
>
> Alex\_Smith, GB
>
>
>
Next you keep "Alex\_Smith" and add "KC"
>
> Alex\_Smith, KC
>
>
>
Next you keep "KC" and insert "...", and so on.
---
You may take @Someprogrammerdude's advice and read both values at once, which will simplify your program to just
```
std::vector<qb_info> player_data;
qb_info player_info;
while (data_file >> player_info.player >> player_info.team) {
player_data.emplace_back(player_info);
}
```
Printing can then be done in a simple loop over the vector
```
for (auto &i : player_data) {
std::cout << i.player << ", " << i.team << '\n';
}
``` | You want to push a data structure with two members into your vector, you cannot assign player name and their team separately like that, you only should push back your data structure into the vector when you have both values :
```
for(int i = 0; i < players_and_team.size(); i++) {
if(i % 2 == 0) {
player_info.player = players_and_team.at(i);
// here you don’t need to push back
} else {
player_info.team = players_and_team.at(i);
player_data.push_back(player_info); // now you have both values of player_info to push into vector
}
}
```
In this code, after player\_info has both player and team data, it is pushed to the vector once. |
815,687 | New to javascript, but I'm sure this is easy. Unfortunately, most of the google results haven't been helpful.
Anyway, I want to set the value of a hidden form element through javascript when a drop down selection changes.
I can use jQuery, if it makes it simpler to get or set the values. | 2009/05/02 | [
"https://Stackoverflow.com/questions/815687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | If you have HTML like this, for example:
```
<select id='myselect'>
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>
```
All you have to do is [bind a function to the `change` event of the select](http://docs.jquery.com/Events/change#fn), and do what you need there:
```
<script type='text/javascript'>
$(function() {
$('#myselect').change(function() {
// if changed to, for example, the last option, then
// $(this).find('option:selected').text() == D
// $(this).val() == 4
// get whatever value you want into a variable
var x = $(this).val();
// and update the hidden input's value
$('#myhidden').val(x);
});
});
</script>
```
All things considered, if you're going to be doing a lot of jQuery programming, always have the [documentation](http://docs.jquery.com/Main_Page) open. It is very easy to find what you need there if you give it a chance. | Plain old Javascript:
```
<script type="text/javascript">
function changeHiddenInput (objDropDown)
{
var objHidden = document.getElementById("hiddenInput");
objHidden.value = objDropDown.value;
}
</script>
<form>
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>
``` |
26,617,263 | i'm trying to set up a MySQL server with XAMPP, it's not working and i'm getting this error:
```
2014-10-28 14:14:38 3768 [Note] Plugin 'FEDERATED' is disabled.
2014-10-28 14:14:38 588 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This
option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2014-10-28 14:14:38 3768 [Note] InnoDB: Using atomics to ref count buffer pool pages
2014-10-28 14:14:38 3768 [Note] InnoDB: The InnoDB memory heap is disabled
2014-10-28 14:14:38 3768 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2014-10-28 14:14:38 3768 [Note] InnoDB: Memory barrier is not used
2014-10-28 14:14:38 3768 [Note] InnoDB: Compressed tables use zlib 1.2.3
2014-10-28 14:14:38 3768 [Note] InnoDB: Not using CPU crc32 instructions
2014-10-28 14:14:38 3768 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2014-10-28 14:14:38 3768 [Note] InnoDB: Completed initialization of buffer pool
2014-10-28 14:14:38 3768 [ERROR] InnoDB: C:\xampp\mysql\data\ibdata1 can't be opened in read-write mode
2014-10-28 14:14:38 3768 [ERROR] InnoDB: The system tablespace must be writable!
2014-10-28 14:14:38 3768 [ERROR] Plugin 'InnoDB' init function returned error.
2014-10-28 14:14:38 3768 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2014-10-28 14:14:38 3768 [ERROR] Unknown/unsupported storage engine: InnoDB
2014-10-28 14:14:38 3768 [ERROR] Aborting
```
Extracted From mysql.log
I did try reinstalling, using AppleWS, and some fixes that i found here. None of them worked. | 2014/10/28 | [
"https://Stackoverflow.com/questions/26617263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4191444/"
] | These lines:
```
2014-10-28 14:14:38 3768 [ERROR] InnoDB: C:\xampp\mysql\data\ibdata1 can't be opened in read-write mode
2014-10-28 14:14:38 3768 [ERROR] InnoDB: The system tablespace must be writable!
```
.. indicate a problem with permissions.
Check the permissions on C:\xampp\mysql\data\ibdata1 and ensure that whatever user you're running your server under has read/write access to that folder. | I solved the problem following the following steps:
1. I moved all files and directories from `C:\xampp\mysql\data\` to another directory.
2. I started MySQL from XAMPP to generate new files.
3. I moved not generated files and directories to `C:\xampp\mysql\data\`.
This method didn't make me lost my configuration and my databases |
9,086 | **Abstract**: Analyzing the data from [the last replace-the-homework-policy question](https://physics.meta.stackexchange.com/questions/7645/replacing-the-homework-policy-1-what-existing-questions-should-be-on-off-topic) was inconclusive. So back to the drawing board, or really back to [our starting point](https://physics.meta.stackexchange.com/questions/7407/generalizing-the-homework-policy): what kinds of questions do we *really* want to see closed? In particular, what are better ways to characterize our actual reasons for closing questions where we currently use the "homework-like" close reason?
---
>
> **Important note**, because I guess this hasn't been clear in the past: the purpose of this series of posts is to come up with a *brand new* set of guidelines for question closure. We are not reformulating or tweaking or improving our current homework policy. We are *replacing* it entirely - that means we are getting rid of it and developing a new set of policies and close reasons, which will presumably make no mention of "homework" or "homework-like". Once this process is done, there will be no homework policy and no "homework-like" close reason.
>
>
>
---
As some/many/most people are aware, we are in the midst of a [long-term project](https://physics.meta.stackexchange.com/questions/7407/generalizing-the-homework-policy) to replace our [homework policy](https://physics.meta.stackexchange.com/questions/714) with a new set of guidelines that better reflect what people actually consider on topic and off topic. In the [first phase of this project](https://physics.meta.stackexchange.com/questions/7645/replacing-the-homework-policy-1-what-existing-questions-should-be-on-off-topic), we collected some example questions and voted on whether they should be on or off topic, to help clarify the new guidelines we want to come up with. I also collected some opinions on various qualities of these questions in [a separate survey](https://docs.google.com/forms/d/e/1FAIpQLSfm5QLFJVPUiWEQb45fLGtjhZHhxeC560PoE5ia3LrXr6FMiA/viewform). The goal was to try to find some correlation between the topicality of the questions, as represented by the score, and one or a few of the attributes, and that would tell us what are the main factors people consider while voting to close.
As it turns out... that doesn't work very well. I spent a long time [tinkering with the data](https://gist.github.com/diazona/dc434e5121c441e5a31fa0c934ab725d) and basically what I found is that people's opinions vary widely, making it hard to draw meaningful conclusions. The first thing I checked was whether any individual factor from the survey correlated well to people's impression of whether a question was on topic. There were some correlations with physical context and interest, and to a lesser extent level and effort, and an anticorrelation with tediousness (this means that within our data set, people are more likely to consider questions which concern tedious calculations *on topic*), but none of these are very strong.
[](https://i.stack.imgur.com/nLtzX.png)
I also looked at whether a combination of factors could provide a good discriminator between on-topic and off-topic questions, in a couple different ways. First, a partial least squares regression to test whether some linear combination of ratings would be able to accurately predict the scores of the questions, but that didn't work at all.
[](https://i.stack.imgur.com/kGI3m.png)
The other approach, which I think best mirrors how the actual close-voting logic works, is to find a set of factors such that the on-topic questions rate highly on all factors but each off-topic question rates low on one or more of them. This plot shows the mean minus one standard deviation1 of the distribution of ratings for each of the highest-score (most clearly on-topic) sample questions:
[](https://i.stack.imgur.com/cprj9.png)
and this is the equivalent, showing mean plus one standard deviation, for the lowest-score (most clearly off topic) sample questions:
[](https://i.stack.imgur.com/AjzVK.png)
I was looking for a group of one or a few rating factors such that the corresponding columns in the top plot are all red or white, and the columns in the bottom plot between them contain one blue cell for each question. Unfortunately, there is no clear candidate. I even had the computer go through all possible combinations of rating factors to test them out, and all the combinations in which the on-topic questions rank high have large uncertainties in the off-topic questions, and vice-versa. The one factor that does keep popping up is "check-my-work-ness", which *may* be an indicator that people agree that questions just asking us to check work are off topic and that we do okay at identifying which questions those are.
Anyway, the point seems to be that none of the factors in the survey are a particularly good proxy for how we decide whether questions are on or off topic. (And remember, we're mostly talking about questions which we currently close or might consider closing using the homework-like reason.) So before we proceed, I want to throw the question back to the community in a revisit of [the question where I first tried to collect possible close reasons](https://physics.meta.stackexchange.com/q/7407/124). In light of all the discussion and analysis we've done since then, when we choose to vote to close questions as homework-like, what reasons do we *actually* have in mind? Or, how could we do more research to work this out?
---
1The idea is to identify clearly on-topic questions as those for which something approximating the 68% confidence interval of the score is entirely positive, indicating a high score and clear agreement on that score. It's basically the same idea underlying e.g. the [reddit scoring algorithm](https://medium.com/hacking-and-gonzo/how-reddit-ranking-algorithms-work-ef111e33d0d9). | 2016/08/27 | [
"https://physics.meta.stackexchange.com/questions/9086",
"https://physics.meta.stackexchange.com",
"https://physics.meta.stackexchange.com/users/124/"
] | Determining how to redefine this policy is a tricky subject. Not only because of the varying and contradictory opinions about it, but also because we seem to be tackling the issue from the middle. Admittedly, in football, that is a sound strategy, but in politics (and that's just what this is), it's often best to start from the beginning.
Before we get ahead of ourselves, we should step back and officially answer some questions that I'm sure many of you will consider already answered. But until we know everyone agrees on them and knows our stance, we can't properly move forward.
This first question we need to ask ourselves is simply **"What are the goals of this site?"** What is it we want this site to represent? What are the ideals to which we should hold all of the content on this site? Should it be by physicists and for physicists? Should it be a place where people can learn physics concepts? Should it be a homework help site? Again, many of you may think this an unnecessary step, but when there exists so much disagreement concerning a policy, it makes sense to retreat to a position where we can all agree on something and build from there.
The second question we should ask ourselves is **"How much freedom are we willing to grant users in deviating from the goals and ideals of this site?"** If the site's goals are to make it a place for professional physicists to ask/answer about research-level physics, how much leeway should we give for users to ask more basic questions? This answer needs to be weighed with how much any amount of deviation will detract from the ability of our site to live up to the goals we agree on. It also serves to provide necessary background and understanding so that everyone can be on the same logical page moving forward.
Now we get into some of the more contentious questions. Most close reasons are easy to determine; the ones we need to decide on are the off-topic sub-reasons. So the next thing we must ask ourselves is **"What types/topics/formats of questions would be actively harmful towards meeting the goals/ideals of the site?"** This should be applied to questions at all levels. By determining what is actively harmful towards the proposed site goals, we can more easily determine what is off-topic. We should also take this opportunity to realize that the freedoms we established in question 2 may indicate sub-goals of the site and that it may be the case that some questions, which do not directly contribute to the primary goals, may be beneficial or detrimental to the sub-goals.
The last question we should be asking is **"What commonalities in these harmful questions can be isolated as reasons to close a question as off-topic?"** Here is the important step. This is a place to identify the important patterns in the questions we found to harm the site's objectives. We also should use this step to recognize any biases we have. For example, if we find that everyone is more lenient towards interesting questions, then we need to decide if policy should reflect this or not; allowing exceptions based on general interest or requiring that decisions be made with no regard to the popularity of the question. By approaching this from a standpoint of "Why are these questions harmful to the goals of the site?", we can more easily divine the set of rules that would prevent such questions. But, again, in order to do that properly, we need to have the answers to all the previous questions agreed on and made explicit. I would expect that reasons like the non-mainstream one will remain, but we may find that our homework-like policy never enters into it. We may also find that much of the misuse of some close reasons spawn from a general disinterest of users, and not from any rational source. That would, of course, be a worst case scenario; I'm just giving examples. At any rate, this step also needs to keep in mind how enforceable any close-reason can be. As we once discovered, closing a question purely because it is taken from a homework assignment is not very enforceable. All one needs to do is slightly reword it and claim it is a genuine curiosity. Furthermore, something like closing because a question is too tedious is too subjective to be adequate. Obviously, reasons should be clear, defined, and effective.
If I may jump back to the beginning of my post, we've been approaching this starting from the third question (David Z's thorough research). While I definitely see the appeal in this strategy and advocate it being a good first attempt, once this fails (as we noticed it did), we should go back and truly start from the beginning. It's a longer process that *should* help to create a more permanent solution.
Now, some of you may point out that I haven't actually done anything towards saying how we could answer these questions, nor have I suggested any way the home-work policy should be changed or researched. You're right. At the moment, I don't see much point in trying to directly address the homework policy, nor can I imagine a situation where we could conduct research and find a clear solution. And if I had included my own answers to the questions I presented, you'd all have voted on whether or not you agree with my answers to those questions as opposed to agreeing with the issue of whether or not the questions need to be addressed at all. Additionally, as demonstrated, people don't seem to have any one thing in mind when they use the homework reason, so the only way I know to fix that is to establish a basis that gets everyone on the same page.
We seem to be building a house on sand and every time the tide comes in, we question why part of this house gets washed away and every time, we try to rebuild that section newer and better. Instead, I merely suggest we tear it all down and lay a proper foundation before attempting to build it back up. The tide may eventually erode the foundation, but at least it'll last a good while longer. | Here is my take on the matter. First, let's think about what Stack Exchange Q&A sites are good for and what they are not good for:
* A Q&A site needs Questions, which can be answered in a concise fashion. There may be several good answers, but if a question needs books to be answered or many answers covering different topics (and thus many pages of answers), it's not a good fit.
* Questions that are an especially good fit are questions where there can be different angles from which to approach it so that many good answers can emerge. This also gives meaning to question ranking.
* Questions that spark discussions are a bad fit.
* The specific idea of Stack Exchange Q&A sites is that the answers to questions and the questions themselves should be interesting to a broader audience.
* If the questions are not interesting for very many people, they need to be of research quality.
In fact, as I see it, we have some tradeoff: If Q is the quality of the question in terms of how many people could answer it ("research quality") and A is the audience that can get some new understanding from the question, then the product QA should be large for good questions. This leaves room for conceptual questions about basic theories as well as high level and extremely specific questions about research.
---
If we agree on the above, here is my take on what should be closed and what shouldn't:
**Check-my-work:** Questions like "Where is my mistake?" or "Did I do it right?" come in two flavours: The first questions make one of a few very common mistakes. Those mistakes are common, because they are based on a fundamental misunderstanding of the theory. They should be closed but could be reworded to ask a conceptual question about the theory, which is interesting for many people. The other type of questions are just algebraic/mathematical mistakes. There are a myriad ways to make mistakes and thus the answer to the question is mostly only interesting to the asker and it usually also is of bad "research quality".
--> Close as check-my-work. If you think there is actually an interesting conceptual misunderstanding in the question, rewrite it and/or leave a comment. Then the question can be reopened.
**Really low research effort:** Since most of the audience arrives by search engines, those people will actually do a Google search. If this will directly lead them to a Wikipedia article, what do they gain by coming here? So aside from the fact that low effort questions might disparage researchers from staying on the site, they should be closed because they don't actually have an audience: Why should you come here to get a link to the Wikipedia page you could already see in your Google search results?
--> Close as "low effort", if the question could be commented on by "What about this [Wikipedia/other well-known source that pops up if you type the question into a search engine] is unclear".
---
Those are in my opinion the "easy" ones. Now come the "hard" ones:
**(Low effort) problems:** These are questions that essentially ask for the solution to a homework problem while providing or not providing own ideas. The problem with these questions is two-fold: a) if the asking party actually wants to understand the problem, you'd need to discuss with them --> that's not a good fit for Q&A, b) the audience for these questions is often only the asker him/herself (see "check-my-work" questions).
Defining a close reason such as "no sufficient audience" won't work and will only spark more discussion, as will "homework" ('oh, but that's not homework, I thought about this exercise myself'). One of the biggest problems is also that these questions are best answered by working with the person and asking questions and giving rough sketches and approaches - so they are just a bad fit anyway. This is particularly true for many questions where the author posts a lengthy and detailed list of her own failed effort. While those questions do signal that the author of the question doesn't just try to dump his problem on us, they are just generally a bad fit for Q&A sites.
--> One idea could be the following: Introduce a close reason "not conceptual" and apply it to any questions, asking for one solution to a problem where most variables come with numbers attached. This would allow questions asking about how to generally approach inclined plane problems where a set of parameters is given, but it would disallow questions asking about inclined plane problems with a specific set of parameters (for instance and angle of 45°). Having a rule like "A questions where a lot of variables are fixed is closed" would eliminate some of the ambiguity of the word "conceptual". It would also allow questions asking for different ways to approach some problem, which in my opinion is a valid conceptual question.
**Pure calculations:** Calculations are also difficult, because they can come at any level - and any difficulty. Most calculation questions are only interesting for the person asking them, so they should be off-topic.
But often when somebody reads a paper, he/she may stumble over some step in a calculation or some line of an argument that they don't understand. What about such questions? Now, often, we can refer those questions to math.stackexchange and be done with it, but often the questions may involve physical approximations and are better left here. Not understanding some equation in a paper is something extremely common - sometimes the equation is also just wrong.
Having a platform to ask these questions would be a valuable aid to research, because it could save a lot of time (the idea of course being that I invest some time to explain details in a paper that I understood easily, saving the asker hours or days of searching, while some other times, I am the one asking). In principle, they are also a good fit for Q&A and they should have a decent QA product. If we had arXiv-feedback, this could actually help other readers of the paper and enhance overall research.
However, we don't want to explain simple equivalence transformations in middle school textbooks, where the person was just too lazy to think about it for five minutes. And we don't want to do calculations in research papers that were left out, because they are tedious but foundational to the field and can be looked up in text books asking person is just too lazy to do them him/herself.
How to distinguish these two? If we want to have more people here who are doing research, it might be a good idea to allow paper questions and disallow all others (this would at least get rid of ambiguities). This is somewhat in line with the idea ([Generalizing the homework policy](https://physics.meta.stackexchange.com/questions/7407/generalizing-the-homework-policy/7409#7409))
>
> Questions which attempt to outsource tedious calculations to the community, without any broader context, are off-topic.
>
>
>
but tries to be a bit more inclusive for research-level questions and a bit more exclusive to avoid ambiguities.
--> One suggestion (needs work): Close non-paper related questions, which want to do outsource calculations with a specific "tedious calculation" close-reason. |
28,715,545 | We have our hosting in `aws`. Recently after moving our blog from `wordpress` to `aws`, we are experiencing noticeable delay in server response time. Mainly while accessing the blog. Below are the logs from the `error_log` file,
```
[Wed Feb 25 06:10:10 2015] [error] (12)Cannot allocate memory: fork: Unable to fork new process
[Wed Feb 25 06:12:22 2015] [error] (12)Cannot allocate memory: fork: Unable to fork new process
[Wed Feb 25 06:12:36 2015] [error] (12)Cannot allocate memory: fork: Unable to fork new process
[Wed Feb 25 06:12:50 2015] [error] (12)Cannot allocate memory: fork: Unable to fork new process
[Wed Feb 25 06:13:35 2015] [error] (12)Cannot allocate memory: fork: Unable to fork new process
[error] (12)Cannot allocate memory: fork: Unable to fork new process
[Wed Feb 25 06:27:14 2015] [error] (12)Cannot allocate memory: fork: Unable to fork new process
```
We increased the memory size from 256 to 512 mb in `php.ini` file. But, still the issue exist.
We also changed the KeepAlive as On. Still it doesn't resolve. Any suggestions / solutions would be of great help. | 2015/02/25 | [
"https://Stackoverflow.com/questions/28715545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4303687/"
] | I've face that problem either while hosting a java app with jenkins, mysql & tomcat on ubuntu on an vm of AWS.
First steps I used to solve the problem with restarting a vm.
AWS doesn't give swap memory on a harddrive by default, so you'd better to make it with your hands. How to do this you can find [here](http://www.thegeekstuff.com/2010/08/how-to-add-swap-space/). Need to mention: the solution with swap zone (have no idea why) haven't work for me, I had to create a swap file.
Good luck to you! | I had same problem to fix it there is 2 options:
1- move from micro instances to small and this was the change that solved the problem (micro instances on amazon tend to have large cpu steal time)
2- tune the mysql database server configuration and my apache configuration to use a lot less memory.
tuning guide for a low memory situation such as this one: <http://www.narga.net/optimizing-apachephpmysql-low-memory-server/>
(But don't use the suggestion of MyISAM tables - horrible...)
this 2 options will make the problem much much less happening ..
I am still looking for better solution to close the process that are done and kill the ones that hang in there . |
2,363,013 | This produces an anonymous function, as you would expect (f is a function with three arguments):
```
f(_, _, _)
```
What I don't understand is why this doesn't compile, instead giving a "missing parameter type" error:
```
f(_, _, 27)
```
Instead, I need to specify the types of the underscores explicitly. Shouldn't Scala be able to infer them given that it knows what the function f's parameter types are? | 2010/03/02 | [
"https://Stackoverflow.com/questions/2363013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3905/"
] | If you are thinking about partial application, I thought that this was only possible with **multiple parameter lists** (whereas you only have one):
```
def plus(x: Int)(y: Int) = x + y //x and y in different parameter lists
val plus10 = plus(10) _ //_ indicates partial application
println(plus10(2)) //prints 12
```
Your example is interesting though as I was completely unaware of the syntax you describe and it appears you can have partial application with a single parameter list:
```
scala> def plus2(x: Int, y: Int) = x + y
plus2: (x: Int,y: Int)Int
scala> val anon = plus2(_,_)
anon: (Int, Int) => Int = <function2>
scala> anon(3, 4)
res1: Int = 7
```
So the compiler can clearly infer the type `Int`!
```
scala> val anon2 = plus2(20,_)
<console>:5: error: missing parameter type for expanded function ((x$1) => plus2(20, x$1))
val anon2 = plus2(20,_)
^
```
Hmmm, strange! I don't seem to be able to do partial application with a single parameter list. But then if I declare the type of the second parameter, I *can* have partial application!
```
scala> val anon2 = plus2(20,_: Int)
anon2: (Int) => Int = <function1>
scala> anon2(24)
res2: Int = 44
```
**EDIT** - one thing I would observe is that it seems like the following two shortenings are equivalent, in which case it's a bit more obvious that this is not a "partial application" but more like a "function pointer"
```
val anon1 = plus2(_,_)
val anon2 = plus2 _
``` | I feel this is one of those border cases arising from all the code conversion, since this involves the creation of an anonymous function which directs the call to the original method. The type is for the argument of the outer anonymous function. In-fact, you can specify any sub-type i.e
```
val f = foo(_: Nothing, 1)
```
even this would compile |
1,063,234 | Given....
```
Public MasterList as IEnumerable(Of MasterItem)
Public Class MasterItem(Of T)
Public SubItems as IEnumerable(Of T)
End Class
```
I would like a single IEnumerable(Of T) which will iterate through all SubItems of all MasterItems in MasterList
I would like to think that there is a Linq facility to do this, or an extension method I am overlooking. I need a mechanism that works in VB9 (2008) and hence does not use Yield. | 2009/06/30 | [
"https://Stackoverflow.com/questions/1063234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] | Are you looking for SelectMany()?
```
MasterList.SelectMany(master => master.SubItems)
```
Sorry for C#, don't know VB. | You can achieve this by Linq with SelectMany
C# Code
```
masterLists.SelectMany(l => l.SubItems);
```
Best Regards |
60,644,695 | I am allocating memory in the Jetson TX2. It has 8GB of RAM.
I need to specify the maximun GPU memory size available for TensorRT.
>
> max\_workspace\_size\_bytes = (has to be an integer)
>
>
>
I have seen some examples using these "values":
```
1<<20 = 1048576 (decimal)
= 0001 0000 0000 0000 0000
1<<30 = 1073741824
= 0001 0000 0000 0000 0000 0000 0000
```
But if I have 8GB of RAM, how can "1048576" or "1073741824" represent a part of RAM?
I have used this to allocate 3GB:
```
3*(10**9)
```
But I would like to understand the other way of representing a number. | 2020/03/11 | [
"https://Stackoverflow.com/questions/60644695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6106842/"
] | Perhaps you're having a "Gb vs G**i**b" problem. Usually, 3 Gigas of RAM refers to 3,221,225,472 bytes instead of 3,000,000,000.
The first value is 3 \* (2^10)\*(2^10)\*(2^10), a nice 3 (11) followed by 30 zeros in binary representation, while the second is 3 \* (10^3)\*(10^3)\*(10^3), which is a mess in binary.
This convention of using powers of 2 instead of powers of 10 is the reason why you'll see people writing a 3Gb as `3 << 30`:
```
3 << 30 == 3 * (1 << 10) * (1 << 10) * (1 << 10)
== 3 * (2**10 * 2**10 * 2**10)
== 3 * (2**30)
```
There's a [related question](https://stackoverflow.com/questions/2365100/converting-bytes-to-megabytes?noredirect=1&lq=1) and a good [Wikipedia article](https://en.wikipedia.org/wiki/Binary_prefix) about this issue if you want to learn more. | ```
3GB = 3,221,225,472
1100 0000 0000 0000 0000 0000 0000 0000
3<<30 = 3GB
``` |
1,736,348 | I'm trying to use bsdiff (or any binary diff implementation you come up with) to compute and apply diff onto random binary data. I would like to use it on data from a database, so it would be better not to have to write those onto disk and pass them to bsdiff.exe.
Is there any wrapper library or way in python to do that? | 2009/11/15 | [
"https://Stackoverflow.com/questions/1736348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138352/"
] | You can use [difflib](http://docs.python.org/library/difflib.html) that is part of Python standard library. You can send any arbitrary data into a `difflib.SequenceMatcher`. | Also, the `SequenceMatcher` class (from the Python standard library) can be helpful.
Check out the other contents of the `difflib` module as well. |
24,844,553 | In our database we have a number of tables which have corresponding Translation tables, with language and region IDs (mapped to other tables) with language 1 being English and the default region of language 1 being UK. All tables which have a translation table have the following default columns (although no interface has been defined on the entity framework classes):
```
<EntityTableName>
EntityTableNameID INT PK
Reference NVARCHAR NULL
[Any other columns]
<EntityTableNameTranslation>
EntityTableNameID INT NOT NULL
LanguageID INT NOT NULL
RegionID INT NULL
Title NVARCHAR NOT NULL
Description NVARCHAR NULL
```
The naming is consistent throughout the database, so we could add interfaces if required, but for now I've been trying to do it without to save the effort.
The logic for determining which translation title & description to return is:
1) If there is an exact match for both the language and region, return it
2) If there is a match for the language, but not the region, return the "default" for that language (which is where the RegionID is null, and there will always be one for every language)
3) If there is no match for language, just return the system default (LanguageID = 1, RegionID IS NULL).
I know this might all sound weird and everyone has better ways of doing it, but this is the brief I have to work with. So this is the lambda group join function I created, which is using an entity in the database called "OrgGroup":
```
public static IEnumerable<TransViewModel> GetUserAreaOrgGroups(TransTestEntities context, int companyID, int languageID, int? regionID)
{
var transFull = context.OrgGroupTranslations.Where(tr => tr.LanguageID == languageID && tr.RegionID == regionID);
var transLang = context.OrgGroupTranslations.Where(tr => tr.LanguageID == languageID && !tr.RegionID.HasValue);
var transDefault = context.OrgGroupTranslations.Where(tr => tr.LanguageID == 1 && !tr.RegionID.HasValue);
var results = context.OrgGroups.Where(en => en.CompanyID == companyID)
.GroupJoin(transFull, en => en.OrgGroupID, tr => tr.OrgGroupID,
(en, tr) => new TransJoin<OrgGroup, OrgGroupTranslation> { Entity = en, TransFull = tr.DefaultIfEmpty().FirstOrDefault(), TransLang = null, TransDefault = null})
.GroupJoin(transLang, en => en.Entity.OrgGroupID, tr => tr.OrgGroupID,
(en, tr) => new TransJoin<OrgGroup, OrgGroupTranslation> { Entity = en.Entity, TransFull = en.TransFull, TransLang = tr.DefaultIfEmpty().FirstOrDefault(), TransDefault = null })
.GroupJoin(transDefault, en => en.Entity.OrgGroupID, tr => tr.OrgGroupID,
(en, tr) => new TransJoin<OrgGroup, OrgGroupTranslation> { Entity = en.Entity, TransFull = en.TransFull, TransLang = en.TransLang, TransDefault = tr.DefaultIfEmpty().FirstOrDefault() })
.Select(vm => new TransViewModel
{
EntityID = vm.Entity.OrgGroupID,
Title = (vm.TransFull ?? vm.TransLang ?? vm.TransDefault).Title,
Description = (vm.TransFull ?? vm.TransLang ?? vm.TransDefault).Description
});
return results;
}
```
Which seems to work as expected, and now I'm trying to convert this into a function which will accept the two table types and use expression trees to create, execute, and return the equivalent query. I've got as far as:
```
public static IEnumerable<TransViewModel> GetUserAreaTranslations<TEntity, TTrans>(TransTestEntities context, int companyID, int languageID, int? regionID)
{
// Get types
Type entityType = typeof(TEntity);
Type transType = typeof(TTrans);
string entityName = entityType.Name;
string transName = transType.Name;
// Parameters
var entityParam = Expression.Parameter(entityType, "en");
var transParam = Expression.Parameter(transType, "tr");
var combinedParam = new ParameterExpression[] { entityParam, transParam };
// Properties
var CompanyIDProp = Expression.Property(entityParam, "CompanyID");
var entityIDProp = Expression.Property(entityParam, entityName + "ID");
var transIDProp = Expression.Property(transParam, entityName + "ID");
var transLanProp = Expression.Property(transParam, "LanguageID");
var transRegProp = Expression.Property(transParam, "RegionID");
var transTitleProp = Expression.Property(transParam, "Title");
var transDescProp = Expression.Property(transParam, "Description");
// Tables
//TODO: Better way of finding pluralised table names
var entityTable = Expression.PropertyOrField(Expression.Constant(context), entityName + "s");
var transTable = Expression.PropertyOrField(Expression.Constant(context), transName + "s");
// Build translation subqueries
//e.g. context.OrgGroupTranslations.Where(tr => tr.LanguageID == languageID && tr.RegionID == regionID);
MethodCallExpression fullTranWhereLambda = Expression.Call(typeof(Queryable),
"Where",
new Type[] { transType },
new Expression[]
{
transTable,
Expression.Quote
(
Expression.Lambda
(
Expression.AndAlso
(
Expression.Equal(transLanProp, Expression.Constant(languageID)),
Expression.Equal(transRegProp, Expression.Convert(Expression.Constant(languageID), transRegProp.Type))
), transParam
)
)
});
MethodCallExpression lanTranWhereLambda = Expression.Call(typeof(Queryable),
"Where",
new Type[] { transType },
new Expression[]
{
transTable,
Expression.Quote
(
Expression.Lambda
(
Expression.AndAlso
(
Expression.Equal(transLanProp, Expression.Constant(languageID)),
Expression.IsFalse(MemberExpression.Property(transRegProp, "HasValue"))
), transParam
)
)
});
MethodCallExpression defaultTranWhereLambda = Expression.Call(typeof(Queryable),
"Where",
new Type[] { transType },
new Expression[]
{
transTable,
Expression.Quote
(
Expression.Lambda
(
Expression.AndAlso
(
Expression.Equal(transLanProp, Expression.Constant(1)),
Expression.IsFalse(MemberExpression.Property(transRegProp, "HasValue"))
), transParam
)
)
});
MethodCallExpression entityWhereLambda = Expression.Call(typeof(Queryable),
"Where",
new Type[] { entityType },
new Expression[]
{
entityTable,
Expression.Quote(
Expression.Lambda
(
Expression.Equal(CompanyIDProp, Expression.Convert(Expression.Constant(companyID), CompanyIDProp.Type))
, entityParam
)
)
});
// Create the "left join" call:
// tr.DefaultIfEmpty().FirstOrDefault()
var joinType = typeof(TransJoin<TEntity, TTrans>);
var joinParam = Expression.Parameter(joinType, "tr");
var leftJoinMethods =
Expression.Call(
typeof(Enumerable),
"FirstOrDefault",
new Type[] { transType },
Expression.Call(
typeof(Enumerable),
"DefaultIfEmpty",
new Type[] { transType },
Expression.Parameter(typeof(IEnumerable<TTrans>), "tr"))
);
// Create the return bindings
var emptyTrans = Expression.Constant(null, typeof(TTrans));
//var emptyTrans = Expression.Constant(null);
var fullBindings = new List<MemberBinding>();
fullBindings.Add(Expression.Bind(joinType.GetProperty("Entity"), entityParam));
fullBindings.Add(Expression.Bind(joinType.GetProperty("TransFull"), leftJoinMethods));
fullBindings.Add(Expression.Bind(joinType.GetProperty("TransLang"), emptyTrans));
fullBindings.Add(Expression.Bind(joinType.GetProperty("TransDefault"), emptyTrans));
// Create an object initialiser which also sets the properties
Expression fullInitialiser = Expression.MemberInit(Expression.New(joinType), fullBindings);
// Create the lambda expression, which represents the complete delegate
Expression<Func<TEntity, TTrans, TransJoin<TEntity, TTrans>>> fullResultSelector =
Expression.Lambda <Func<TEntity, TTrans, TransJoin<TEntity, TTrans>>>(fullInitialiser, combinedParam);
// Create first group join
var fullJoin = Expression.Call(
typeof(Queryable),
"GroupJoin",
new Type[]
{
typeof (TEntity), // TOuter,
typeof (TTrans), // TInner,
typeof (int), // TKey,
typeof (TransJoin<TEntity, TTrans>) // TResult
},
new Expression[]
{
entityWhereLambda,
fullTranWhereLambda,
Expression.Lambda<Func<TEntity, int>>(entityIDProp, entityParam),
Expression.Lambda<Func<TTrans, int>>(transIDProp, transParam),
fullResultSelector
}
);
```
The problem is that groupjoin is expecting to return an IEnumerable of TTrans, which I don't seem to be able to bind, and I can't change it to a standard join because I won't be able to use the coalesce in the projection as no result will be returned.
I'm sure I'm doing something very dumb, so can someone help me get my group joins working please? | 2014/07/19 | [
"https://Stackoverflow.com/questions/24844553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2979644/"
] | You definitely don't need to use javascript. This works on the latest version of Chrome, use vendor prefixing for transitions.
<http://jsfiddle.net/pKYu2/16/>
HTML
```
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<span id="mouseOver"><img src="http://placekitten.com/120/120">Mouse Over This</span>
</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
```
CSS
```
#mouseOver {
display: inline;
position: relative;
}
#mouseOver img {
position: absolute;
left: 50%;
transform: translate(-50%);
bottom: 1em;
opacity: 0;
pointer-events: none;
transition-duration: 800ms;
}
#mouseOver:hover img {
opacity: 1;
transition-duration: 400ms;
}
``` | You can use the `hover` event:
```
$("div").hover(function() {
$("img").show();
}, function() {
$("img").hide();
});
``` |
67,297,792 | I'm trying to get the Python package OSMnx running on my Windows10 machine. I'm still new to python so struggling with the basics.
I've followed the instructions here <https://osmnx.readthedocs.io/en/stable/> and have successfully created a new conda environment for it to run in. The installation seems to have gone ok.
However, as soon as I try and import it, I get the following error
```
>>> import osmnx as ox
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\User\.conda\envs\ox\lib\site-packages\osmnx\__init__.py", line 3, in <module>
from ._api import *
File "C:\Users\User\.conda\envs\ox\lib\site-packages\osmnx\_api.py", line 4, in <module>
from .distance import get_nearest_edge
File "C:\Users\User\.conda\envs\ox\lib\site-packages\osmnx\distance.py", line 5, in <module>
import networkx as nx
File "C:\Users\User\.conda\envs\ox\lib\site-packages\networkx\__init__.py", line 114, in <module>
import networkx.generators
File "C:\Users\User\.conda\envs\ox\lib\site-packages\networkx\generators\__init__.py", line 14, in <module>
from networkx.generators.intersection import *
File "C:\Users\User\.conda\envs\ox\lib\site-packages\networkx\generators\intersection.py", line 13, in <module>
from networkx.algorithms import bipartite
File "C:\Users\User\.conda\envs\ox\lib\site-packages\networkx\algorithms\__init__.py", line 16, in <module>
from networkx.algorithms.dag import *
File "C:\Users\User\.conda\envs\ox\lib\site-packages\networkx\algorithms\dag.py", line 23, in <module>
from fractions import gcd
ImportError: cannot import name 'gcd' from 'fractions' (C:\Users\User\.conda\envs\ox\lib\fractions.py)
```
I'm running with
```
conda version : 4.8.2
conda-build version : 3.18.11
python version : 3.7.6.final.0
```
Is anyone able to advise me? Sorry if this is obvious, as I said I'm new to all this. Thank you | 2021/04/28 | [
"https://Stackoverflow.com/questions/67297792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15783372/"
] | You'll need to convert the object to an array, then filter on values and get the corresponding keys:
```js
var obj = { 1: NaN,2: NaN,120: NaN,121: NaN,122: NaN,125: NaN,126: NaN,127: NaN,128: NaN,129: NaN,130: NaN,131: NaN,132: NaN,133: NaN,134: NaN,135: NaN,136: NaN,602: NaN,603: true,604: true,605: NaN,607: NaN,608: NaN,609: NaN,610: NaN,612: NaN,613: NaN,614: NaN,615: NaN,616: NaN,617: NaN,765: NaN};
var values = Object.entries(obj) // Convert the object to a key/value array
.filter(([_, value]) => value) // We only want the entries that have a truthy value.
.map(([key]) => key); // And of those entries, we only want the keys.
console.log(values);
``` | This will be done very much easily with [for-in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop
```js
var obj = { 1: NaN,2: NaN,120: NaN,121: NaN,122: NaN,125: NaN,126: NaN,127: NaN,128: NaN,129: NaN,130: NaN,131: NaN,132: NaN,133: NaN,134: NaN,135: NaN,136: NaN,602: NaN,603: true,604: true,605: NaN,607: NaN,608: NaN,609: NaN,610: NaN,612: NaN,613: NaN,614: NaN,615: NaN,616: NaN,617: NaN,765: NaN};
const arr=[]
for(key in obj){
if(obj[key]){
arr.push(key)
}
}
console.log(arr);
``` |
11,128,043 | We need to implement a WCF Webservice using the [ACORD Standard](http://www.acord.org/standards/downloads/Pages/PCSSpecsPublic.aspx).
However, I don't know where to start with this since this standard is HUMONGOUS and very convoluted. A total chaos to my eyes.
I am trying to use WSCF.Blue to extract the classes from the multiple XSD I have but so far all I get is a bunch of crap: A .cs file with 50,000+ lines of code that freezes my VS2010 all the time.
Has anybody walked already thru the Valley of Death (ACORD Standard) and made it? I really would appreciate some help. | 2012/06/20 | [
"https://Stackoverflow.com/questions/11128043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/912875/"
] | I wrote a ACORD to c# class library converter which was then used in several large commercial insurance products. It featured a very nice mapping of all of the ACORD XML into nice concise, extendable C# classes. So I know from whence you come!
Once you dig into it its not so bad, but I maintain the average coder will not 'get it' for about 3-4 months if they work at it full time (assuming anything but inquiry style messages). The real problem comes when trying to do mapping from a backend database and to/from another ACORD WS. All of the carriers, vendors, and agencies have custom rules.
My best suggestion is to find working code examples (I have tons if you need them) and maybe even a vendor or carrier who will let you hook up to a ACORD ws in a test environment. | I would recommend not creating a model for the entire standard. One could just pass XML and not serialize into a model but instead load it into XDocument/XElement and use Linq to query it and update the DOM using Linq to Xml. So, one is not loading the XML to a strongly typed model, but just loading the XML. There is no model, just an XML document.
From there, one can pick the data off of the XML as needed.
Using this approach, the code will be ugly and have little context since XElements will be passed everywhere, and there will be tons of magic strings of XPaths to query and define elements, but it can work. Also, everything is a string so there will be utility conversion methods to convert to numbers, date times, etc.
From my prospective, I have modeled part of the Acord into an object model using the XmlSerializer but it's well over 500 classes. The model was not tooled from XSD or other, but crafted manually and took some time. Tooling will produce monster unusable classes (as you have mentioned) and/or flat out crash. As an example, I tried to load the XSD into Stylus Studio and it crashed several times.
So, your best bet if your strapped for time is loading into an XDocument as opposed to trying to map out everything in a model. I know that sucks but Acord in general is basically a huge data hot mess. |
2,411,315 | I would like to convert my for loop to STL std::for\_each loop.
```
bool CMyclass::SomeMember()
{
int ii;
for(int i=0;i<iR20;i++)
{
ii=indexR[i];
ishell=static_cast<int>(R[ii]/xStep);
theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]);
al2[ishell] += massp*cos(fm*theta);
}
}
```
Actually I was planning to use parallel STL from g++4.4
```
g++ -D_GLIBCXX_PARALLEL -fopenmp
```
which is allow to run code in parallel without changes if the code is written in standard STL library. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2411315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235125/"
] | You need to seperate out the loop body into a seperate function or functor; I've assumed all the undeclared variables are member variables.
```
void CMyclass::LoopFunc(int ii) {
ishell=static_cast<int>(R[ii]/xStep);
theta=atan2(data->pPOS[ii*3+1],
data->pPOS[ii*3]);
al2[ishell] += massp*cos(fm*theta);
}
bool CMyclass::SomeMember() {
std::for_each(&indexR[0],&indexR[iR20],std::tr1::bind(&CMyclass::LoopFunc,std::tr1::ref(*this));
}
``` | ```
class F {
public:
void operator()(int ii) {
ishell=static_cast<int>(R[ii]/xStep);
theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]);
al2[ishell] += massp*cos(fm*theta);
}
F(int[] r): //and other parameters should also be passed into the constructor
r_(r) {}
void:
int[] r_; // refers to R[ii] array
// and other parameters should also be stored
};
F f(R); // pass other parameters too
for_each(&indexR[0], &indexR[iR20], f);
```
However it might not be a good idea to use this "automatic parallelization" since you need to keep in mind the grainsize of each parallel computation -- I am not sure how well the compiler takes the grain size into account. |
3,513,997 | Hi I'm wanting to set a variable date in the format Y-m-d 20:00:00 of the previous day. can someone help? | 2010/08/18 | [
"https://Stackoverflow.com/questions/3513997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299871/"
] | ```
Dim lastNight As DateTime = DateTime.Today.AddHours(-4)
Dim lastNightString As String = lastNight.ToString("y-M-d HH:mm:ss")
``` | There's probably an easier way but this is how I would probably do it in C#:
DateTime myDate = DateTime.Today.AddHours(20 - DateTime.Today.Hour).AddMinutes(0 - DateTime.Today.Minute).AddSeconds(0 - DateTime.Today.Second).AddMilliseconds(0 - DateTime.Today.Millisecond);
Then for formatting find something along the lines of:
<http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx> |
210,794 | The main plan of *Avengers: Endgame* for solving what Thanos did in *Avengers: Infinity War* involves the
>
> Time Heist.
>
>
>
As part of the plan Tony misplaces
>
> the Tesseract
>
>
>
and so he and Cap have to go looking for it elsewhere. They decide to go back to
>
> a SHIELD base in 1970 where both the Tesseract is stored and Hank Pym is based working on the Pym Particle. Whilst there Tony also bumps into his father, Howard Stark, working on the base.
>
>
>
Tony and Cap have a conversation in hushed tones about choosing it and it seems to be that they both know about it. **Is there anything special about this place and time and how did they both know about it?** | 2019/04/25 | [
"https://scifi.stackexchange.com/questions/210794",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/58193/"
] | Tony remembers (just about) that his dad, Howard Stark, told him that he worked there with Hank Pym in this period.
As Tony says in *Civil War*, his dad mentioned knowing Captain America a lot; and as we see a bit in *Iron Man 2*, he probably tried to tell Tony a lot of useful stuff about his work that Tony largely ignored but sometimes vaguely remembered. Finally, as [Nathan K. points out](https://scifi.stackexchange.com/a/218334/440), the date they go back to is shortly before Tony's own birth, so it's not surprising Tony has a good idea of when his dad and Pym were there together.
As Pym is present, they can get both the Tesseract, and the extra Pym Particles they need to get the Tesseract back to the present (as originally they only had enough for one round trip each).
The base is actually [Camp Lehigh](https://marvelcinematicuniverse.fandom.com/wiki/Camp_Lehigh), the army base where Steve Rogers trained before becoming Captain America, so it’s kind of special for him. (A sign is visible outside the base declaring it the birthplace of Captain America.) The SHIELD facility within is the same bunker that Cap visited in *The Winter Soldier*, which at that time housed the digitised Arnim Zola.
But only Tony was aware of the likelihood that both the Tesseract and Pym particles were there at that time. | In the first Avengers movie, Tony hacks into SHIELD's computers while onboard the helicarrier by placing a device of some sort on the command terminals used by Nick Fury on the bridge.
Later when Tony, Bruce, and Steve are in the lab working on a way to locate the Tesseract, Tony tells Steve that Jarvis is currently hacking SHIELD's computers and, "In a few hours, I will know every dirty secret SHIELD has tried to hide."
It is safe to assume that this information would have included data on both the history of the Tesseract and Dr. Pym.
It is reasonable to assume that before starting the mission to travel back in time that Tony, Steve, and the rest of the team would have reviewed all of this information looking for places in time where they could locate the infinity stones.
This piece of information, in particular, might have piqued their interest and drawn their attention as it involved; one of the items they were looking for, a place Steve was very familiar with, a place Tony's dad worked, and the Pym particles they were using to execute the time travel plan.
It might even have been on the list of possible times and places to get the space stone but was ruled out as there was a better opportunity to get three stones at one time during the battle of New York.
The fact that Scott Lang doesn't seem to know about his alternative time and location s while Tony and Steve do, is a brilliant use of the character driving plot. Tony and Steve are both detailed oriented and would have read the briefings in-depth and committed them to memory. Scott on the other hand, well he's been established as a bit of a slacker and probably would not have read all of the briefing data. |
47,268,698 | Neo4j's manual does a very good job at explaining the meaning of the terms Node, Relationship, Label and a few others.
However, the **real** vocabulary of Cypher seems to include quite a few elusive terms, as well.
For instance, clause 3.3.15.1 of the manual says "Lists and paths are key concepts in Cypher". Fine, but what is a List in Cypher? I have all but given up trying to find a definition of that "key concept".
Similarly, the Cypher Reference Card mentions that "Cypher also supports maps and collections". Elsewhere, one can find that Cypher also "works with dictionaries".
Needless to say, I am in the dark as to how to spot and/or use those in Cypher.
Would really appreciate some illustrations.
Thanks. | 2017/11/13 | [
"https://Stackoverflow.com/questions/47268698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7146357/"
] | Alternatively, you can use the fade function provided in Material UI Next.
```
import {fade} from 'material-ui/styles/colorManipulator';
const theme = createMuiTheme({
overrides: {
MuiButton: {
root: {
boxShadow: `0 4px 8px 0 ${fade(defaultTheme.palette.primary[500], 0.18)}`,
}
},
}
});
export default theme;
```
Here's how it's working : <https://github.com/mui-org/material-ui/blob/v1-beta/src/styles/colorManipulator.js#L157-L164>
Another solution could be to use similar color functions from <https://github.com/styled-components/polished> | For what it's worth, an 8 digit hex code works too
```
const styleSheet = theme => ({
root: {
backgroundColor: '#ffffff80',
},
})
``` |
29,930,711 | Given:
```
a = [1, 2, 3]
b = [4,5]
```
How to get:
```
[1, 2]
[4]
```
In the above example, I know this works:
```
a[:-1]
b[:-1]
```
However, when:
```
c = [1]
c[:-1]
```
The result is an empty list. | 2015/04/28 | [
"https://Stackoverflow.com/questions/29930711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160863/"
] | You want the following code fragment:
```
c[:1] + c[1:-1]
```
For example:
```
>>> c = [1]
>>> c[:1] + c[1:-1]
[1]
```
With `c[:1]` you get a list consisting of the first element (if it exists, otherwise the empty list), and with `c[1:-1]` you get from the second until the end except the last. If there isn't a second element `c[1:-1]` will just return the empty list. | Following JuniorCompressor's answer, if the point is just to remove last element (keep first and if exist others also keep them, but remove last == remove last, if first element is also not the last element). Is it?
```
>>> def removelast(l):
... if len(l)>1: del l[len(l)-1]
... return l
>>> a = range(5)
>>> removelast(a)
[0, 1, 2, 3]
>>> b = [1]
>>> removelast(b)
[1]
``` |
48,266,942 | I use Angular 5 with one type : "@types/markerclustererplus": "2.1.28". This type installs @types/google-maps.
I added script part in "index.html" file to load map.
In my component, I can use google namespace.
This works fine.
However, when I run tests... it fails!
I got "ReferenceError: google is not defined"
I tried so many things... If you have any idea, I take it!
Thank you. | 2018/01/15 | [
"https://Stackoverflow.com/questions/48266942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8934461/"
] | Thank you Alexander!
You bring me a real clue!
After your post, I looked deeper into angular google mock.
I finally found this : [GoogleMock](https://github.com/sttts/google-maps-mock/blob/master/google-maps-mock.js).
I then adjusted it and it works.
Thanks ! | ```
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": ["src/app/mock/GoogleMock.js"],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
``` |
937,043 | I am running an Apache instance on Ubuntu and am having this problem: .HTML files with bonafide HTML inside is being served as a text file:
```
> **For eg. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html>
> <body> <h1>Index to Butterthlies
> Catalogs</h1>
```
etc. etc.\*\*
I checked the header in firebug and sure enough the page is `plain\text`. I figured I'm probably missing the `mod_mime` module, so I tried to include it as a module like this:
```
LoadModule mod_mime /usr/lib/apache2/modules/mod_mime.so
TypesConfig conf/mime.types
```
where the `/usr/lib`... path contains the `mod_mime.so`. But this doesn't work and gives the following error:
>
> Syntax error on line 1 of /usr/www/APACHE3/site.first/conf/httpd.conf: Can't locate API module structure `mod\_mime' in file /usr/lib/apache2/modules/mod\_mime.so: /usr/lib/apache2/modules/mod\_mime.so: undefined symbol: mod\_mime
>
>
> | 2009/06/01 | [
"https://Stackoverflow.com/questions/937043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/328915/"
] | You can use an expression in an ORDER BY. Try this:
```
SELECT *
FROM comments
ORDER BY IF(ParentId = 0, Id, ParentId), Id
```
This will first sort by Id, if ParentId = 0, or by ParentId otherwise. The second sort criterion is the Id, to assure that replies are returned in order. | I highly recommend that you restructure your database schema. The main problem is that you are trying to treat comments and replies as the same thing, and they simple aren't the same thing. This is forcing you to make some difficult queries.
Imagine having two tables: [COMMENTS:(id, text)], and replies to comments in another table [REPLIES(id, commentid, text)]. The problem seems much, much easier when thought of in this way. |
26,584,812 | I am creating some elements dynamically with jquery. (say with id `test_element1`, `test_element2` and so on..)
I have the below CSS -
```
div[id^=test_]:before {
content: "";
height: 100%;
width: 100%;
box-shadow: #aaaaaa 0px 0px 10px inset;
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
```
The `::before` element does not show up when I inspect the element. It shows up only if the `test_element1` is already present in my HTML (ie. static content).
How do I make the `::before` appear for my dynamic elements ? | 2014/10/27 | [
"https://Stackoverflow.com/questions/26584812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209879/"
] | There really should be no reason for the pseudo element not showing up. Maybe check your code to see if there is a problem elsewhere. Here is a working example of what you are trying to achieve, maybe you can compare this with your code and find a solution for your specific case. But the ultimate answer is that it should be working, so the problem is not the css/jquery relationship.
```js
$("body").append(
$("<div />", {
"id": "test_element1"
}).html("test"),
$("<div />", {
"id": "test_element2"
}).html("test"),
$("<div />", {
"id": "test_element3"
}).html("test")
);
```
```css
div[id^=test_] {
position: relative;
padding-top: 1em;
}
div[id^=test_]::before {
content: "i am pseudo element";
height: 100%;
width: 100%;
box-shadow: #aaaaaa 0px 0px 10px inset;
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
display: block;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
``` | **When you set pseudo element, selector z-index + position need to added.**
```css
div[id^=test_] {
position:relative;
z-index:1;
}
div[id^=test_]:before {
content: "";
height: 100%;
width: 100%;
box-shadow: #aaaaaa 0px 0px 10px inset;
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
``` |
5,289,336 | Here is my problem:
Inside a jQuery dialog I have the following code:
```
<%:Ajax.ActionLink("Yes", "SendClaim", "Claim", new { id = Model.ExpenseId }, new AjaxOptions { UpdateTargetId = "dialog" }, new { @class = "button" })%>
```
When stuff fails in the controller based on roles I return a partial view that replaces the existing dialog (see `UpdateTargetId = "dialog"`).
When everything works I want to do a redirect to another page (an index of all claims) to stop the user performing additional actions but this entire page is **rendered inside the jQuery dialog** due to it being an ajax request with an update id.
What is the correct way to approach the problem? | 2011/03/13 | [
"https://Stackoverflow.com/questions/5289336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571216/"
] | I'm a bit of a novice, but I find I have more control with the following approach instead of using `Ajax.ActionLink`. Hopefully it helps and I have understood what you want to do correctly.
Claim Controller:
```
[AcceptVerbs(HttpVerbs.Post)]
public Json Send(int expenseId)
{
// Check user stuff
if(valid)
// do stuff
return new Json(true, JsonRequestBehavior.AllowGet);
else
return new Json(false, JsonRequestBehavior.AllowGet);
}
```
jQuery
```
function submitClaim() {
$.ajax({
url: "/Claim/Send",
type: "POST",
dataType: "json",
data: { 'expenseId': <%=Model.ExpenseId> },
success: function (data) {
if(data) { // if successful, redirect
document.location = "Claim/Index";
}
else { //load your partial view into your dialog
$("#idOfYourDialog").load('Claim/Error/');
}
},
error: function (xhr) { }
});
}
```
html
```
<a href="javascript:submitClaim()">Submit</a>
``` | Returned an 'All OK' dialog and had the following javascript when the user clicks the ok button:
```
function redirect() {
document.location = "<%:(String)ViewBag.Redirect %>";
}
$(document).ready(function() {
$(".ui-dialog-titlebar-close").click(function() {
redirect();
});
});
```
Seems unavoidable - you can't seem to do an `RedirectToAction` when the controller action has been called from `Ajax.ActionLink` as the response will be stuck into the updatetargetid. |
60,306,131 | I'm trying to return 2 objects using an IIFE. I cant find whats wrong here.
```
var UIController = (function(){
return{
getMinput: function(){
return {
mstaff1: document.querySelector('#mstaff1').value,
mstaff2: document.querySelector('#mstaff2').value,
mpda: document.querySelector('#mpda').value,
mpos: document.querySelector('#mpos').value,
mcash: document.querySelector('#mcash').value,
mtotal: document.querySelector('#mtotal').value
};
}
getMinput: function(){
return {
mstaff1: document.querySelector('#mstaff1').value,
mstaff2: document.querySelector('#mstaff2').value,
mpda: document.querySelector('#mpda').value,
mpos: document.querySelector('#mpos').value,
mcash: document.querySelector('#mcash').value,
mtotal: document.querySelector('#mtotal').value
};
}
};
})();
``` | 2020/02/19 | [
"https://Stackoverflow.com/questions/60306131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12791759/"
] | You cannot have two returns from a single run of a function. That's physically impossible.
But you can return an *array* of values.
```
var UIController = (function ... return [ /*whatever porcesing*/ , /*second result */ ]; .. })();
``` | Here you have one object. You can't have the same name for methods inside one object. Also, you need to add ',' after each method or prop.
So do it like this:
```
(function(){
return{
getMinput: function(){
return {
mstaff1: document.querySelector('#mstaff1').value,
mstaff2: document.querySelector('#mstaff2').value,
mpda: document.querySelector('#mpda').value,
mpos: document.querySelector('#mpos').value,
mcash: document.querySelector('#mcash').value,
mtotal: document.querySelector('#mtotal').value
};
},
getMinput1: function(){
return {
mstaff1: document.querySelector('#mstaff1').value,
mstaff2: document.querySelector('#mstaff2').value,
mpda: document.querySelector('#mpda').value,
mpos: document.querySelector('#mpos').value,
mcash: document.querySelector('#mcash').value,
mtotal: document.querySelector('#mtotal').value
};
}
};
})());
OR if you really need two objects you can use array:
(function(){
return [
getMinput: function(){
return {
mstaff1: document.querySelector('#mstaff1').value,
mstaff2: document.querySelector('#mstaff2').value,
mpda: document.querySelector('#mpda').value,
mpos: document.querySelector('#mpos').value,
mcash: document.querySelector('#mcash').value,
mtotal: document.querySelector('#mtotal').value
};
},
getMinput1: function(){
return {
mstaff1: document.querySelector('#mstaff1').value,
mstaff2: document.querySelector('#mstaff2').value,
mpda: document.querySelector('#mpda').value,
mpos: document.querySelector('#mpos').value,
mcash: document.querySelector('#mcash').value,
mtotal: document.querySelector('#mtotal').value
};
}
];
})
());
``` |
944,509 | Apple provides the NSArchiver and NSUnachriver for object serialization / deserialization, but this can not handle any custom xml schema. So filling an object structure with the data of any custom xml schema has to be made manually.
Since the iPhone developer community is rapidly growing, a lot of newbie programmer are despairing to deal with the available xml parsing possibilities.
The iPhone SDK only provides NSXmlParser for xml parsing, which is more useful to read certain parts of an xml file, than filling a whole object structure, which really is a pain.
The other possibility is the famous libxml library, which is written in ANSI C - not easy to use for someone who starts programming with objective-c and never learned proper C before. Event there are a lot of wrappers available, dealing with xml can be a pain for newbies.
And here my idea takes place. An XmlSerializer library which fills an object structure automatically could makes it a lot easier and increase the app quality for many programmers.
My Idea should work like this:
**The xml file**
```
<Test name="Michael" uid="28">
<Adress street="AlphaBetaGammastrasse 1" city="Zürich" postCode="8000" />
<Hobbies>
<Hobby describtion="blabla"/>
<Hobby describtion="blupblup"/>
</Hobbies>
</Test>
```
**The classes to fill**
```
@interface Test : NSObject {
NSString *name;
Adress *adress;
NSArray *hobbies;
int uid;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, retain) Adress *adress;
@property (nonatomic, retain) NSArray *hobbies;
@property (nonatomic, readwrite) int uid;
@end
@interface Adress : NSObject {
NSString *street;
NSString *city;
int postCode;
}
@property (nonatomic, copy) NSString *street;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, readwrite) int postCode;
@end
```
**How the xml serializer should work**
```
NSError *error = nil;
XMLSerializer *serializer = [[XMLSerializer alloc] init];
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TestFile" ofType:@"xml"]];
Test *test = [serializer deserializeWithData:data error:&error];
```
To fill the object structure needs only one line of code:
```
Test *test = [serializer deserializeWithData:data error:&error];
```
This would be so easy to use that any newbie programmer could use it. For more advanced usage the serializer could be configurable.
What do you think, would this be a helpful and popular library for iPhone and OSX Applications?
Edit:
You can see the project [here](http://code.google.com/p/orxml/), but it is fare away from release. | 2009/06/03 | [
"https://Stackoverflow.com/questions/944509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90745/"
] | The NSKeyedArchiver works precisely because it doesn't try to map onto an XML schema. Many, many XML schemas are badly designed (i.e. they're translating an in-memory object structure to an external representation format). The key problem is that the documents should be designed to make sense from a document perspective, and that that would then need to map onto whatever memory layout you wanted for your objects. Ever seen XML documents with lots of 'refid' attributes referring to other parts of the doc? Those are usually transliterated from a relational database which is just sticking angled brackets on the resultset.
So starting by assuming a one-to-one mapping between an XML document and its code representation is pretty much doomed in all but the simplest cases. Just consider where we would be today with HTML if it had been designed around the C++ objects that were used to instantiate the document in the first browser ... (well, more like Objective-C, but hey ...)
The point about NSKeyedArchiver is that you can evolve the data structure without breaking the ability to load older versions. It's unbelievably difficult to do that (properly) using some kind of automated instance-var-to-element mapping. | I've been struggling with requirements in this domain and think it would be a great idea. I've had to bully my dot net services to return JSON for easy consumption on an iPhone. A decent serialization library would be superb. |
16,927,526 | Are there any NoSQL DBs that support object inheritance in .NET out of the box? MongoDB has something which is proper for dynamic languages but I'm looking for real inheritance. Actually I think I should work on an ODBMS instead of NoSQL!? Or does MongoDB support strongly-typed inheritance?
I would like to get data using such queries in LINQ:
```
people.Where(p => p is Student)
``` | 2013/06/04 | [
"https://Stackoverflow.com/questions/16927526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441889/"
] | MongoDB C# driver supports `OfType` and `is` in LINQ queries!
<http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/#csharp-driver-linq-tutorial> | RavenDB has something similar to what you want to do.
<http://ravendb.net/docs/client-api/querying/polymorphism> |
37,947,092 | I am using laravel framework in ubunto system and I want to remove port number from my url
write now I can access my web-project with this url
```
http://localhost:8000
```
and I want this url
```
http://localhost/
```
How can I do this? | 2016/06/21 | [
"https://Stackoverflow.com/questions/37947092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3425009/"
] | If nothing else (e.g. Apache oder Nginx) uses port 80 you COULD start the development webserver like this
```
sudo php artisan serve --port 80
```
You can access the app via <http://localhost/> afterwards
Note that this is ONLY for development and some kind of hack. Install a dedicated webserver (Apache, Nginx) for production :-) | Do not use php artisan server in your commandline and use full URL path in browsers address bar as follows
```
http://localhost/projectname/public
``` |
4,488,849 | 
Following error occurs in /// this coding "
***Cannot insert the value NULL into column 'boarding', table 'C:\USERS\VBI SERVER\DOCUMENTS\VISUAL STUDIO 2008\WEBSITES\VOLVO\APP\_DATA\ASPNETDB.MDF.dbo.boardingpt'; column does not allow nulls. INSERT fails. The statement has been terminated.***
```
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO boardingpt (service, travelid, bdpt_name, time) VALUES('" & Trim(TextBox3.Text.ToString) & "', '" & Trim(TextBox4.Text.ToString) & "', '" & Trim(TextBox1.Text.ToString) & "','" & Trim(TextBox2.Text.ToString) & "')"
cmd.ExecuteNonQuery()
con.Close()
End Sub
``` | 2010/12/20 | [
"https://Stackoverflow.com/questions/4488849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522211/"
] | You are not providing a value for the `boarding` field, which is a `NOT NULL` field (`Allow Nulls` is not checked).
Being a `NOT NULL` field means you *have* to provide a value for it.
If the field is supposed to be the ID of the rows in the table, you should make it into an `IDENTITY` field.
See [this](http://msdn.microsoft.com/en-us/library/aa290124.aspx#dvmscchangingcolumnsidentityproperties) on MSDN for how to change the identity properties using the Visual Studio Database designer. | You are trying to insert NULL value for the column which is set to NOT NULL.
Solution
* Make **boarding** column to ALLOW NULL and remove Primary key (because primary key never can be null)
or
* Set IDENTITY to YES in your table design mode for **boarding** column
Hope this helps
Thanks
Vivek |
620,950 | Is there a way to have Notepad++ generate new file names with the current date?
Like this:
YYYY\_MM\_DD\_new1.txt
or similar.
Currently it just names them: new1, new2, etc.
Date in the file name will work great with autosave, there will be no name conflicts after NPP restart.
All I want is a way to store sessions between restarts. I want to autosave even the unnamed files.
Thanks. | 2013/07/17 | [
"https://superuser.com/questions/620950",
"https://superuser.com",
"https://superuser.com/users/181907/"
] | I just did this using the Python Script plugin for NPP...
```
notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED])
def my_callback(args):
if notepad.getBufferFilename(args["bufferID"]) == "new 1":
fmt = '%Y%m%d%H%M%S'
d = datetime.datetime.now()
d_string = d.strftime(fmt)
notepad.saveAs('X:\\Documents\\Notepad++_autosave\\%s.txt' % d_string)
notepad.callback(my_callback, [NOTIFICATION.BUFFERACTIVATED])
```
With the above code, as soon as I type `Ctrl`+`N`, the new file is created and saved instantly with the name formatted as defined in 'fmt' above. The path for the file to be saved is defined above as well; change it to suit your environment. | I tried using mwoliver's answer and still had trouble running it. I made some changes and now, this will work for any "new #" format instead of just "new 1".
```
notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED])
def my_callback(args):
set1 = set(notepad.getBufferFilename(args["bufferID"]).split(' '))
filenew = set1.pop()
filenumber = set1.pop().isdigit()
setempty = len(set1) == 0
if filenew == "new" and filenumber and setempty:
fmtdate = '%Y-%m-%d'
fmttime = '%H%M%S'
d = datetime.datetime.now()
d_string = d.strftime(fmtdate) + ' Notes ' + d.strftime(fmttime)
notepad.saveAs('C:\\Users\\username\\Desktop\\%s.txt' % d_string)
notepad.callback(my_callback, [NOTIFICATION.BUFFERACTIVATED])
```
I also added the following snippet to the end of the startup.py file (after the code above) in order to prevent the "new 1" upon notepad++'s startup.
```
if notepad.getCurrentFilename() == 'new 1':
notepad.new()
notepad.activateIndex(0,0)
if notepad.getCurrentFilename() == 'new 1':
notepad.close()
``` |
45,097 | Trying to figure out the difference between these. I've lost completely as different source/answers interpret it differently. Does anyone have clear understanding about what does undergraduate/graduate/post-graduate student mean in USA?
I've seen this nice timeline in [other question](https://academia.stackexchange.com/questions/7469/undergraduate-graduate-or-post-graduate-student-is-that-bachelor-master-phd-o) however answers are still controversial.
As well, trying to figure out who the hell am I - I have a Bachelor in Computer Science, Master in Computer Science and another Master in Business Information Systems. Is that graduate or post-graduate? Also, I'm not a student anymore. | 2015/05/08 | [
"https://academia.stackexchange.com/questions/45097",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/34264/"
] | Part of the confusion may be that these adjectives are used in (at least) two different contexts: to describe *degrees* and to describe *students*.
* An *undergraduate degree* generally means a bachelor's degree (B.S., B.A., etc): a degree requiring about four years of university-level study beyond high school.
* A *graduate degree* or *post-graduate degree* is any higher degree that has a bachelor's degree as a prerequisite, such as a masters or doctoral degree (M.S., M.A., M.F.A., M.B.A,. Ph.D., etc.) Depending on context, this term may also include professional degrees (J.D. for law, M.D. for medicine, D.D.S. for dentistry, D.V.M. for veterinary medicine, etc).
* An *undergraduate student* (or simply *an undergraduate*, or colloquially, *an undergrad*) is a student who does not yet have an undergraduate degree, but is studying to earn one.
* A *graduate student* or *post-graduate student* (or colloquially, a *grad student*) is a student who already has an undergraduate degree and is studying to earn a graduate degree.
So in general, the adjectives *graduate* and *post-graduate* are synonyms. This may seem contradictory (since you might expect *post-graduate* to refer to something after *graduate*) but that is how it's used. I understand this as coming from the fact that a *post-graduate degree* is something that you work toward following your *graduation* (i.e. the moment when you earn your *undergraduate degree*).
My impression is that people within academia generally prefer the term *graduate* to *post-graduate* in both contexts; the word *post-graduate* is used more often by non-academics, to whom the word *graduate* is more likely to seem ambigiuous.
So you could say you have an undergraduate degree and two graduate degrees. You could also describe your degrees as post-graduate degrees for further clarification, which would normally be needed only when speaking to someone not intimately familiar with academia. | I have to say that there is one difference between *graduate* and *post-graduate* -- while both mean "beyond Bachelor's degree", the first refers to *level* and the second to *time*.
If I were asked for a transcript of my graduate studies, I'd have to list several courses taken before receiving my B.S. because these were graduate classes -- designed for and taught to graduate students -- and I was permitted to add the classes by special permission. But if asked about post-graduate studies, those wouldn't be included, since they did not chronologically follow my graduation. |
50,177,797 | There is an object with this form:
```
anObject = {name_1 : [4],
name_2 : [1],
name_3 : [5, 1, 2],
name_4 : [3, 4],
};
```
on the left side it is the name of the property and on the right side it is an array of numerical values (one or more values).
I want to show them somehow like this:
```
name_1
- 4
name_2
- 1
name_3
- 5
- 1
name_4
- 3
- 4
```
I can print using an `ng-repeat` the `name_`s like this:
```
<div ng-repeat="(key, value) in $ctrl.anObject ">{{key}}</div>
```
I can show also the numerical values like this:
```
<div ng-repeat="(key, value) in $ctrl.editAlertsByType">{{key}} - {{value}}</div>
```
but I want to put them under the keys. Is it possible? | 2018/05/04 | [
"https://Stackoverflow.com/questions/50177797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9099077/"
] | `value` that you pull out is an array, so display it with the second `ng-repeat`. Here is an example:
```js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.anObject = {
name_1: [4],
name_2: [1],
name_3: [5, 1, 2],
name_4: [3, 4],
};
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="(key, value) in anObject">
{{key}}
<div ng-repeat="x in value">
- {{x}}
</div>
</div>
</div>
``` | ```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="(key, value) in records">{{key}}
<div >{{value.toString()}}</div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = {
"key":[1],
"key2":[1,2],
"key3":[1,2,3]
}
});
</script>
``` |
77,487 | I was starting to install casing on my doors and while positioning the board I realized the door latch is going to contact the casing (1x4 craftsman) before the strike plate. The solutions I've found are extended strike plates or chisel/route the trim. Anything else I'm missing? I see 1x4 used a lot in casing but I couldn't find anyone talking about this issue. I wonder if my door latch (Schlage) is extra long.
[](https://i.stack.imgur.com/fjLcc.jpg)
I approxmated the lengths of two sizes of extended strike plates I can order. Any idea on what size would look/function the best? I was thinking the smaller would not flex and I can get a 3/16" reveal. The longer extends beyond the trim but could flex some.
[](https://i.stack.imgur.com/lggsT.jpg)
[](https://i.stack.imgur.com/xj5uG.jpg)
**Update** I wrote more in detail about the problem and solution here <http://newyuma.blogspot.com/2015/11/craftsman-trim-and-extended-strike.html> | 2015/11/07 | [
"https://diy.stackexchange.com/questions/77487",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/5097/"
] | The issue isn't with the latch, it's with the placement of the trim. The fact that the strike plate is routed into the casing is a dead give-away. With craftsman style trim, you need to leave about a 1/4" reveal of the door jamb - it just doesn't work flushed up to it for this exact reason:
You can get away doing this with ranch style casing...
[](https://i.stack.imgur.com/aYytY.png)
...but not 1x. The casing profile should look more like this:
[](https://i.stack.imgur.com/Vm2Ab.png)
Not only is this the more traditional way of installing craftsman style casings, IMHO it also looks a lot better by adding multiple layers of depth to the trim profile.
Since you already have the casing on, the best way to remedy this installation is (as you suggested in the question) is with an [extended strike plate](https://www.google.com/?gws_rd=ssl#q=Schlage%20extended%20strike%20plate). | Your latch is typical; you just need a strike plate with an extended tongue. (Admittedly, "tongue" probably isn't the right technical term, but I imagine you've got the picture.) |
3,047,839 | I just started playing with Django today and so far am finding it rather difficult to do simple things. What I'm struggling with right now is filtering a list of status types. The StatusTypes model is:
```
class StatusTypes(models.Model):
status = models.CharField(max_length=50)
type = models.IntegerField()
def __unicode__(self):
return self.status
class Meta:
db_table = u'status_types'
```
In one admin page I need all the results where type = 0 and in another I'll need all the results where type = 1 so I can't just limit it from within the model. How would I go about doing this?
**EDIT:** I should have been a bit more clear. I have a model "Unit" which has a foreign key to to StatusTypes. The models are as follows:
```
class StatusTypes(models.Model):
status = models.CharField(max_length=50)
type = models.IntegerField()
def __unicode__(self):
return self.status
class Meta:
db_table = u'status_types'
class Unit(models.Model):
name = models.CharField(unique=True, max_length=50)
status = models.ForeignKey(StatusTypes, db_column='status')
note = models.TextField()
date_added = models.DateTimeField()
def __unicode__(self):
return self.name
class Meta:
db_table = u'units'
```
So now in the admin page for the unit model I want to limit the status to only those with type = 1. Based off of lazerscience response below I tried the following code:
```
from inv.inventory.models import Unit
from django.contrib import admin
class UnitAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(UnitAdmin, self).queryset(request)
return qs.filter(type=0)
admin.site.register(Unit, UnitAdmin)
```
But, it didn't change the select box at all. I also tried printing the value of qs and nothing was outputted to my terminal so I'm wondering if I have to some how call queryset?
**EDIT 2:** It might not have been clear that I want to filter this for the status dropdown that is on the create page for the Unit model. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3047839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38/"
] | EDIT:
It turns out that ModelAdmin.formfield\_for\_foreignkey was the right answer in this situation:
<http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey>
PREVIOUS ANSWER:
Take a look at the [list\_filter attribute of ModelAdmin](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter). That sounds more like what you want to me since it will create a nice interface for filtering on different criteria rather than arbitrarily restricting your queryset. | You can override the `queryset` method of your `MyModelAdmin` class:
```
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(MyModelAdmin, self).queryset(request)
return qs.filter(type=0)
admin.site.register(StatusTypes, MyModelAdmin)
```
This admin will only display you objects of your model that have `type=0`! |
476,231 | I'm developing a Desktop Search Engine in Visual Basic 9 (VS2008) using Lucene.NET (v2.0).
I use the following code to initialize the IndexWriter
```
Private writer As IndexWriter
writer = New IndexWriter(indexDirectory, New StandardAnalyzer(), False)
writer.SetUseCompoundFile(True)
```
If I select the same document folder (containing files to be indexed) twice, two different entries for each file in that document folder are created in the index.
I want the IndexWriter to discard any files that are already present in the Index.
What should I do to ensure this? | 2009/01/24 | [
"https://Stackoverflow.com/questions/476231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57175/"
] | To update a lucene index you need to delete the old entry and write in the new entry. So you need to use an IndexReader to find the current item, use writer to delete it and then add your new item. The same will be true for multiple entries which I think is what you are trying to do.Just find all the entries, delete them all and then write in the new entries. | There are options,listed below, which can be used as per requirements.
See below code snap. [Source code in C#, please convert it into vb.net]
```
Lucene.Net.Documents.Document doc = ConvertToLuceneDocument(id, data);
Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.Open(new DirectoryInfo(UpdateConfiguration.IndexTextFiles));
Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
Lucene.Net.Index.IndexWriter indexWriter = new Lucene.Net.Index.IndexWriter(dir, analyzer, false, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
Lucene.Net.Index.Term idTerm = new Lucene.Net.Index.Term("id", id);
foreach (FileInfo file in new DirectoryInfo(UpdateConfiguration.UpdatePath).EnumerateFiles())
{
Scenario 1: Single step update.
indexWriter.UpdateDocument(idTerm, doc, analyzer);
Scenario 2: Delete a document and then Update the document
indexWriter.DeleteDocuments(idTerm);
indexWriter.AddDocument(doc);
Scenario 3: Take necessary steps if a document does not exist.
Lucene.Net.Index.IndexReader iReader = Lucene.Net.Index.IndexReader.Open(indexWriter.GetDirectory(), true);
Lucene.Net.Search.IndexSearcher iSearcher = new Lucene.Net.Search.IndexSearcher(iReader);
int docCount = iSearcher.DocFreq(idTerm);
iSearcher.Close();
iReader.Close();
if (docCount == 0)
{
//TODO: Take necessary steps
//Possible Step 1: add document
//indexWriter.AddDocument(doc);
//Possible Step 2: raise the error for the unknown document
}
}
indexWriter.Optimize();
indexWriter.Close();
``` |
17,747,606 | For testing purpose, I would like to create on disk a directory which exceeds the Windows MAX\_PATH limit.
How can I do that?
(I tried Powershell, cmd, windows explorer => it's blocked.)
**Edited:**
The use of ZlpIOHelper from ZetaLongPaths library allows to do that whereas the standard Directory class throws the dreaded exception:
```
static void Main(string[] args)
{
var path = @"d:\temp\";
var dirName = "LooooooooooooooooooooooooooooooooooooooooooooongSubDirectory";
while (path.Length <= 280)
{
path = Path.Combine(path, dirName);
ZlpIOHelper.CreateDirectory(path); //Directory.CreateDirectory(path);
}
Console.WriteLine(path);
Console.ReadLine();
}
``` | 2013/07/19 | [
"https://Stackoverflow.com/questions/17747606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25781/"
] | The easiest solution is to create a directory `c:\A\averylongnamethatgoesonandonandon...`,
and then rename `C:\A` to something much longer. Windows does not check every child of A to see if the name of that child would exceed `MAX_PATH`. | How about something like this:
```
var path = "C:\\";
while (path.Length <= 260)
{
path = Path.Combine(path, "Another Sub Directory");
}
``` |
3,633 | With a normal spring, you compress it using a linear force to store energy and then it decompresses and releases the energy, again in a form of linear force. Is there a mechanical mechanism that stores energy by rotating force and releases energy by rotating force? It doesn't have to be spring operated, but I think it's the only way to work, with springs.
I want it to work for many many rotations (to store energy) and to produce many many rotations! what's the best mechanism for this? | 2015/07/20 | [
"https://engineering.stackexchange.com/questions/3633",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/2353/"
] | For "many many rotations", a [pneumatic motor](https://en.wikipedia.org/wiki/Pneumatic_motor) can act as both a compressor and motor. Spinning the motor causes air to be forced through a tube, one-way valve, and storage tank. Opening the valve allows the compressed air in the tank (potential energy) to flow back through the tube and motor, spinning it in reverse. As the number of rotations increases, the pressure increases, acting to stop the axle for a given torque. This presents a rotational limit, based on the volume of compressed gas, size of motor, size of tank, etc. For fast rotary motion this could work, but for slow motion, the pneumatic motor may "leak" and store little or no energy.
For "many many many rotations", a [permanent magnet motor](https://en.wikipedia.org/wiki/Brushed_DC_electric_motor)/generator -> DC rectifier -> battery (or supercapacitor) may work to store considerably more energy. Similar to the pneumatic concept, slow motion will not produce much charge. But the density of stored potential energy is much higher in batteries than it is air tanks.
There are significant losses in both of these, so there won't be enough energy stored to return the axle to it's original starting position. | A spring loaded piston actuating a rack, and turning a pinion gear. Smaller the pinion gear, relative to the length of the rack... the more rotations achieved in a given stroke. And also the greater the piston pressure required... |
16,842,118 | I would like to know if there is a way to count the number of TCP retransmissions that occurred in a flow, in LINUX. Either on the client side or the server side. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16842118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999975/"
] | You can see TCP retransmissions for a single TCP flow using Wireshark. The "follow TCP stream" filter will allow you to see a single TCP stream. And the `tcp.analysis.retransmission` one will show retransmissions.
For more details, this serverfault question may be useful: <https://serverfault.com/questions/318909/how-passively-monitor-for-tcp-packet-loss-linux> | The Linux kernel provides an interface through the pseudo-filesystem `proc` for counters to track the `TCPSynRetrans`
For example:
```
awk '$1 ~ "Tcp:" { print $13 }' /proc/net/snmp
```
Per documentation:
```
* TCPSynRetrans
This counter is explained by `kernel commit f19c29e3e391`_, I pasted the
explanation below::
--
TCPSynRetrans: number of SYN and SYN/ACK retransmits to break down
retransmissions into SYN, fast-retransmits, timeout retransmits, etc.
```
You can also adjust these settings also through the pseudo-filesystem `procfs` but under the `sys` directory. There is a handy utility that does this short-hand for you.
```
sysctl -a | grep retrans
net.ipv4.neigh.default.retrans_time_ms = 1000
net.ipv4.neigh.docker0.retrans_time_ms = 1000
net.ipv4.neigh.enp1s0.retrans_time_ms = 1000
net.ipv4.neigh.lo.retrans_time_ms = 1000
net.ipv4.neigh.wlp6s0.retrans_time_ms = 1000
net.ipv4.tcp_early_retrans = 3
net.ipv4.tcp_retrans_collapse = 1
net.ipv6.neigh.default.retrans_time_ms = 1000
net.ipv6.neigh.docker0.retrans_time_ms = 1000
net.ipv6.neigh.enp1s0.retrans_time_ms = 1000
net.ipv6.neigh.lo.retrans_time_ms = 1000
net.ipv6.neigh.wlp6s0.retrans_time_ms = 1000
net.netfilter.nf_conntrack_tcp_max_retrans = 3
net.netfilter.nf_conntrack_tcp_timeout_max_retrans = 300
``` |
53,963,007 | I have implemented a generic class as below which might be causing the problem,
```
import { Logger } from '@nestjs/common';
import { PaginationOptionsInterface, Pagination } from './paginate';
import { Repository } from 'typeorm';
export class EntityService<T> {
private repository: Repository<T>;
constructor(repository) {
this.repository = repository;
}
async getEntityWithPagination(
options: PaginationOptionsInterface,
): Promise<Pagination<T>> {
const [results, total] = await this.repository.findAndCount({
take: options.limit,
skip: (options.page - 1) * options.limit,
});
return new Pagination<T>({ results, total });
}
}
```
and using with other entity services, such as
```
@Injectable()
export class CarService extends EntityService<CarEntity> {
constructor(
@InjectRepository(CarEntity)
private carRepository: Repository<CarEntity>,
) {
super(carRepository);
}
```
the code is working perfectly fine with `npm run start:dev` but throwing below error when trying to run with production `npm run start:prod`
```
internal/modules/cjs/loader.js:582
throw err;
^
Error: Cannot find module 'src/shared/entity.service'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/home/tejas/Code/web/project/dist/car/car.service.js:27:26)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! project@0.0.0 start:prod: `node dist/main.js`
npm ERR! Exit status 1
```
I have tried deleting dist folder, but still no luck. I have tried updating packages also, package.json is as follows. I have no clue how to debug this.
```
dependencies": {
"@nestjs/common": "^5.5.0",
"@nestjs/core": "^5.5.0",
"@nestjs/jwt": "^0.2.1",
"@nestjs/passport": "^5.1.0",
"@nestjs/typeorm": "^5.2.2",
"bcryptjs": "^2.4.3",
"glob": "^7.1.3",
"passport": "^0.4.0",
"passport-http-bearer": "^1.0.1",
"passport-jwt": "^4.0.0",
"pg": "^7.7.1",
"reflect-metadata": "^0.1.12",
"rimraf": "^2.6.2",
"rxjs": "^6.2.2",
"typeorm": "^0.2.9",
"typescript": "^3.2.2"
},
"devDependencies": {
"@nestjs/testing": "^5.5.0",
"@types/express": "^4.16.0",
"@types/jest": "^23.3.1",
"@types/node": "^10.12.18",
"@types/supertest": "^2.0.7",
"jest": "^23.5.0",
"nodemon": "^1.18.9",
"prettier": "^1.14.2",
"supertest": "^3.1.0",
"ts-jest": "^23.1.3",
"ts-loader": "^4.4.2",
"ts-node": "^7.0.1",
"tsconfig-paths": "^3.5.0",
"tslint": "5.11.0",
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2",
"webpack-node-externals": "^1.7.2"
},
``` | 2018/12/28 | [
"https://Stackoverflow.com/questions/53963007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2010052/"
] | I got this resolved by deleting the generated files and recreating it eg: dist folder | Sometimes the error can be caused by existing code outside the SRC folder (eg Typeform migrations, etc) which causes the compilation inside DIST to enter one level of folders (eg dist/migrations, dist/src) which makes the main file not be in the correct location. |
5,580,583 | I am using autotools for my project.
While building Qt there are the generated `moc_*.cpp` and `ui_*.h` files which I want to have them in a gen subdirectory. The directory and the generated files should be created by make and removed my make clean.
Have anyone here done this before? I'll appreciate it really much! | 2011/04/07 | [
"https://Stackoverflow.com/questions/5580583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549746/"
] | The link you posted takes me to a site that says:
>
> Returns a pseudo-random number in the
> range [0,1) — that is, between 0
> (inclusive) and 1 (exclusive). The
> random number generator is seeded from
> the current time, as in Java.
>
>
>
"inclusive" means the value is part of the range, whereas "exclusive" means that the value is *not* part of the range.
So `Math.random()` returns a value from 0 to just-less-than 1. | between 0 (inclusive) and 1 (**exclusive**) - cannot be 1
Your code is all right |
20,509,158 | I am trying to delay the processing of a method (SubmitQuery() in the example) called from an keyboard event in WinRT until there has been no further events for a time period (500ms in this case).
I only want SubmitQuery() to run when I think the user has finished typing.
Using the code below, I keep getting a System.Threading.Tasks.TaskCanceledException when Task.Delay(500, cancellationToken.Token); is called. What am I doing wrong here please?
```
CancellationTokenSource cancellationToken = new CancellationTokenSource();
private async void SearchBox_QueryChanged(SearchBox sender, SearchBoxQueryChangedEventArgs args)
{
cancellationToken.Cancel();
cancellationToken = new CancellationTokenSource();
await Task.Delay(500, cancellationToken.Token);
if (!cancellationToken.IsCancellationRequested)
{
await ViewModel.SubmitQuery();
}
}
``` | 2013/12/11 | [
"https://Stackoverflow.com/questions/20509158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284169/"
] | If you add `ContinueWith()` with an empty action, ~~the exception isn't thrown.~~ The exception is caught and passed to the `tsk.Exception` property in the `ContinueWith()`. But It saves you from writing a try/catch that uglifies your code.
```
await Task.Delay(500, cancellationToken.Token).ContinueWith(tsk => { });
```
---
UPDATE:
Instead of writing code to handle the exception, a boolean would be much cleaner. **This is only preferred when a delay cancel is expected!**. One way is to create a helper class *(Although I don't like helper classes much)*
```
namespace System.Threading.Tasks
{
public static class TaskDelay
{
public static Task<bool> Wait(TimeSpan timeout, CancellationToken token) =>
Task.Delay(timeout, token).ContinueWith(tsk => tsk.Exception == default);
public static Task<bool> Wait(int timeoutMs, CancellationToken token) =>
Task.Delay(timeoutMs, token).ContinueWith(tsk => tsk.Exception == default);
}
}
```
---
For example:
```
var source = new CancellationTokenSource();
if(!await TaskDelay.Wait(2000, source.Token))
{
// The Delay task was canceled.
}
```
*(don't forget to dispose the source)* | I think it deserves to add a comment about why it works that way.
The doc is actually wrong or written unclear about the TaskCancelledException for `Task.Delay` method. The `Delay` method itself never throws that exception. It transfers the task into cancelled state, and what exactly raises the exception is `await`. It didn't matter here that `Task.Delay` method is used. It would work the same way with any other cancelled task, this is how cancellation is expected to work. And this actually explains why adding a continuation mysteriously hides the exception. Because it's caused by `await`. |
12,406,505 | How do I make a uitableview in interface builder compatible with 4 inch iphone5, and the older iPhone 4/4s?
There are three options in Xcode 4.5:
* Freeform
* Retina 3.5 full screen
* Retina 4 full screen
If I chose Retina 4, then in the 3.5 inch phone it crosses/overflows the screen border
Using code, I can set the frame accordingly, but then what is the use of using interface builder?
How should one do it using Interface Builder?
**EDIT**
My question is for iphone 5 retina 4 inch screen.
When inspecting the size of the view which has a status bar and navigation bar, here is the value of self.view.frame.size.height/width, frame 320.000000 x 416.000000 in case I choose freeform/none/retina 3.5
The autoresizing options are set so that the view expands in all directions, that is all struts and springs are enabled.
**EDIT**
For testing in iOS6 simulator, If I set the following in code
```
self.tableView.frame = CGRectMake(0, 0, 320, 546);
self.tableView.bounds = CGRectMake(0, 0, 320, 546);
self.view.frame = CGRectMake(0, 0, 320, 546);
self.view.bounds = CGRectMake(0, 0, 320, 546);
NSLog(@"%2f - %2f", self.view.bounds.size.width, self.view.bounds.size.height);
NSLog(@"%2f - %2f", self.tableView.bounds.size.width, self.tableView.bounds.size.height);
```
I get the following output
```
320.000000 - 546.000000
320.000000 - 546.000000
```
And All the rows below the 480 px from the top are not selectable, as the 'view' still thinks they are out of bounds.
**MY SOLUTION**
Set the size to Retina 4 for all screens, even the main window xib file. It seems to work fine even on the iphone 4 after this. And all rows below 480px are now clickable in iOS 6 simulator | 2012/09/13 | [
"https://Stackoverflow.com/questions/12406505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226223/"
] | Choose your xib file and change the `Size` attribute.
 | From what i have understand u want to create a table view which can be applicable to both iPhone 4 and 5. First thing first i havnt tried the Xcode 4.5, but the code
```
CGRect fullScreenRect = [[UIScreen mainScreen] bounds];
theTableView.frame = CGRectmake = (0,0,fullScreenRect.width,fullScreenRect.height);
```
the `fullScreenRect` will return the bound of the current device whether its 3.5 or 5 inch. and u can set the height and width dynamically.
Let me know if it worked..
Cheers
W |
26,297,935 | Bit of background info - the developer of the system we use has left the company and I've been asked to add a few new features. Needless to say, there's no documentation and to make matters worse I'm an absolute novice so am having to learn as I go along. I'm kind of managing to do most things but have come totally stuck on this problem. For anyone kind enough to help me out, if you could really dumb any answers down that would be great. So, the problem........
HTML page that is dynamically populated with a list of items. For each item in the list there's a checkbox, and for each checkbox that's ticked I need to update a MySQL database. The code that adds the checkboxes to the page is
```
echo("<td class=\"tableRight\" style=\"width: 5%\"><input type=\"checkbox\" name=\"costume[]\" value=\"".$costume['id']."\" id=\"costume_".$costume['id']."\" onclick=\"tickrow(".$costume['id'].");\" /></td>");
```
The JavaScript file is loaded in the page head with
```
<script src=\"costume-list.js\" type=\"text/javascript\"></script>
```
The button's code that should kick off the database update is
```
echo("<div class=\"navContainer\" onClick=\"batch_move() \" class=\"navItem\">");
echo("<img src=\"/resource/img/icon/move.png\" border=\"0\" /><br />Batch Move Costumes");
echo("</a></div>");
```
And finally the JavaScript I've managed to put together is
```
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php? loc="+move_to_id+"&items="+INeedTheArrayHere,"mywindow","menubar=1,resizable=1,width=350,height=250");
}
```
}
So what I want to do is first make sure that at least one checkbox is ticked and if it is then get the values of the ticked boxes into an array to pass to the called PHP form. I can manage the update code in the opened form, it's just getting the array to it.
Sorry for long post, but hope that's enough info. If there's anything else you need to know please ask and I'll supply more details. Many thanks | 2014/10/10 | [
"https://Stackoverflow.com/questions/26297935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4127496/"
] | Well you can use JOIN and add index on country and city in companies table
```
SELECT Name
FROM companies AS c INNER JOIN tagsForCompany AS tc ON c.id = tc.Company
INNER JOIN tags AS t ON t.id = tc.TID
WHERE city = "your_city" AND country = "your_country" AND t.Name REGEXP 'your_tag'
```
Well in this query a table will be generated first using INNER JOIN then filtering on basis of new table generated
But a better and more optimized solution could be to generate a table using subquery by filtering city and country. Also add index on country and city in companies table as it will reduce a lot of time. Now new query would be
```
SELECT c.Name
FROM
(SELECT id, Name
FROM companies
WHERE city = "your_city" AND country = "your_country" ) AS c
INNER JOIN tagsForCompany AS tc ON c.id = tc.Company
INNER JOIN tags AS t ON t.id = tc.TID
WHERE t.Name REGEXP 'your_tag'
```
Syntax to add index `ALTER TABLE tbl_name ADD INDEX index_name (column_list)`, it adds an ordinary index in which any value may appear more than once.
```
ALTER TABLE companies ADD INDEX city (city);
ALTER TABLE companies ADD INDEX country (country);
``` | May this query is help you.
```
select * from companies c
left join tagsForCompany tc on c.company_id = tc.company_id
left join tags t on t.tag_id = tc.tag_id
where c.city = "your value" and c.country = "Your value" and tc.name = "your value"
``` |
36,832,656 | The string is `myAgent(9953593875).Amt:Rs.594` and want to extract `9953593875` from it. Here is what I tried:
```
NSRange range = [feDetails rangeOfString:@"."];
NSString *truncatedFeDetails = [feDetails substringWithRange:NSMakeRange(0, range.location)];
NSLog(@"truncatedString-->%@",truncatedFeDetails);
```
This outputs: `truncatedString-->AmzAgent(9953593875)` | 2016/04/25 | [
"https://Stackoverflow.com/questions/36832656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5126338/"
] | Or you do like this:
```
NSString *string = @"myAgent(9953593875).Amt:Rs.594.";
NSRange rangeOne = [string rangeOfString:@"("];
NSRange rangeTwo = [string rangeOfString:@")"];
if (rangeOne.location != NSNotFound && rangeTwo.location != NSNotFound) {
NSString *truncatedFeDetails = [string substringWithRange:NSMakeRange(rangeOne.location + 1, rangeTwo.location - rangeOne.location - 1)];
NSLog(@"%@",truncatedFeDetails);
}
``` | Try this
```
NSString *str = @"myAgent(9953593875).Amt:Rs.594.";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"(?<=\\()\\d+(?=\\))"
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *result = [str substringWithRange:[regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])].range];
//result = 9953593875
``` |
58,157,041 | This is my code and file data given bellow. I have file with the name of test. In which I’m trying find a num in first column. If that number is found in any line, I want to delete that row.
```
def deleteline():
n=5
outfile=open('test.txt','r+')
line = outfile.readline()
while line !='':
lines= line.rstrip('\n')
listline=lines.split(',')
num=int(listline[0])
if n==num:
print(listline[1])
outfile.write(lines)
else:
print("no")
line= outfile.readline()
outfile.close()
``` | 2019/09/29 | [
"https://Stackoverflow.com/questions/58157041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3502257/"
] | This should solve your problem:
```
def deleteline():
n = 5
outfile = open('test.txt', 'r')
lines = outfile.readlines()
outfile.close()
outfile = open('test.txt', 'w')
for line in lines:
lineStrip = line.rstrip('\n')
listLine = lineStrip.split(',')
num = int(listLine[0])
if(num == n):
outfile.write('')
else:
outfile.write(line)
outfile.close()
``` | As suggested by Simon in above comment, from [this](https://stackoverflow.com/questions/4710067/using-python-for-deleting-a-specific-line-in-a-file) answer, modify the check condition like this:
```
with open("test.txt", "r") as f:
lines = f.readlines()
with open("test.txt", "w") as f:
for line in lines:
tempLine=line.strip("\n")
tempLine=tempLine.split(',')
if int(tempLine[0]) != 4:
f.write(line)
``` |
9,317 | I've just made hollandaise sauce following Alton Brown method. I used only about 4 tablespoons and I have about 1 cup left.
Using google I found that I shouldn't put it on the fridge, doesn't freeze well and shouldn't be more than 4 hours without use. That leaves little margin.
Is there anything I can do? | 2010/11/20 | [
"https://cooking.stackexchange.com/questions/9317",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/1546/"
] | Oh, yes, you can. There is a way, when you fold in beaten egg whites (soft peaks) after you made your hollondase, not only would those bulk out the sauce and make it able to be kept on warm for long without curdling, but also that would make it able to keep the sauce in the fridge for several days (so that you could have it reheated later) and would even make it to have it frozen for much longer storage, if really needed. | Properly made hollandaise sauce can be refrigerated fir 2 days , best way is warm up a portion in a glass ball over hot water , add a touch water and whisk gently until warm ...perfect good as new |
26,197 | I have Arch Linux plus LXDE installed in my laptop. I want to know the status of the battery level. I tried to install `batterymon`, but got too many errors that I couldn't decipher.
Is there any other way to monitor the battery level? | 2011/12/06 | [
"https://unix.stackexchange.com/questions/26197",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/13083/"
] | There aren't so many tools that can operate directly on DjVu files, compared with other more common formats such as PDF or JPEG. With image manipulation programs, there's the added hurdle that most of these operate on a single image at a time, but the DjVu file contains multiple pages.
One possibility is to go via pdf. With `ddjvu` from [DjVuLibre](http://djvu.sourceforge.net/), [a PDF `un2up` filter](https://unix.stackexchange.com/questions/12482/split-pages-in-pdf), and [pdf2djvu](http://pdf2djvu.googlecode.com/):
```
ddjvu -format=pdf 2up.djvu 2up.pdf
un2up <2up.pdf | pdf2djvu /dev/stdin >1up.djvu
```
You might be able to cobble up an un2up for djvu inspired by my [pdf version](https://unix.stackexchange.com/questions/12482/split-pages-in-pdf/12483#12483) using [python-djvulibre](http://pypi.python.org/pypi/python-djvulibre). I haven't checked how hard that API is to get into. | Taking bot2417's script as base, here my own
```
#!/bin/bash
echo "################################################"
echo Usage: djvusplit2 LASTPAGE FILE.DJVU
echo "################################################"
if [ ! -f $2 ];
then
echo "file $2 not exists!\n"
exit
fi
start=1
mkdir ./tmp
for i in $(seq $start +1 $1)
do
j=$(($i*2-1))
k=$(($i*2))
# extract pages to tiff format
ddjvu -format=pbm -page=$i $2 ./tmp/$i.tiff
# split pages
convert -crop 2x1@ ./tmp/$i.tiff ./tmp/$i-%d.tiff
#delete extracted tiff
#rm ./tmp/$i.tiff
# convert tiff to djvu pages
cjb2 ./tmp/$i-0.tiff ./tmp/$j.djvu
cjb2 ./tmp/$i-1.tiff ./tmp/$k.djvu
#delete splitted tiffs
#rm ./tmp/$i-0.tiff
#rm ./tmp/$i-1.tiff
# create djvu file and add pages
if [ $i -eq 1 ];
then
djvm -c "(new) $2" ./tmp/$i.djvu
echo "create new $2 OK"
djvm -i "(new) $2" ./tmp/$(($i+1)).djvu
echo "insert page $(($i+1)) OK"
else
djvm -i "(new) $2" ./tmp/$j.djvu
echo "insert page $j OK"
djvm -i "(new) $2" ./tmp/$k.djvu
echo "insert page $k OK"
fi
#delete djvu pages
#rm ./tmp/$j.djvu
#rm ./tmp/$k.djvu
done
echo "\nfile (new) $2 created!!!"
echo "\n"
# cleanup temp dir
rm -r ./tmp
``` |
77,534 | I've got a virtual machine with an 8 gig hard drive in one file. I want to now split virtual hard drive into 2 gig chunks so I can copy the VM onto a FAT32 drive. Is this possible? | 2009/10/23 | [
"https://serverfault.com/questions/77534",
"https://serverfault.com",
"https://serverfault.com/users/2420/"
] | Probably the only way to do that would be to download the VMware converter and use that to migrate to a new virtual machine which is configured for 2 Gig files.
It would probably be easier to simply convert the destination hard drive to NTFS. | haven't tried splitting virtual disk but I think that won't be complicated. I used to split HDD with partitionguru and I remember this tool supports virtual disks generated by Vmware. Since it's a free tool, you may as well have a try |
1,073,805 | I cant quite get my head around what the ^ is doing in my preg\_match.
```
if (preg_match('~^(\d\d\d\d)(-(\d{1,2})(-(\d{1,2}))?)?$~', trim($date), $dateParts)) {
echo the $dateparts and do some magic with them
} else {
tell me the date is formatted wrong
}
```
As I see it this is looking to see if the $date matches the format which I read as
4 decimals - 1 or 2 decimals - 1 or 2 decimals
if it does match then the IF statement displays the date, if it doesn't then it gives an error of incorrect date formatting.
However just passing it the year
$date = '1977' with nothing else (no day or month) it still goes through as true and displays the dateparts, I would thought it would throw an error?
Can someone point out what I'm missing in the regular expression? I'm guessing it's the ^ or possibly the ?$ at the end may mean only match part of it? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1073805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28241/"
] | There is no need to group *absolutely everything*. This looks nicer and will do the same:
```
preg_match('~^\d{4}(-\d{1,2}(-\d{1,2})?)?$~', trim($date), $dateParts)
```
This also explains why "`1977`" is accepted - the month and day parts are *both* optional (the question mark makes something optional).
To do what you say ("4 decimals - 1 or 2 decimals - 1 or 2 decimals"), you need to remove both the optional groups:
```
preg_match('~^\d{4}-\d{1,2}-\d{1,2}$~', trim($date), $dateParts)
```
The "`^`" and "`$`" have nothing to do with the issue you are seeing. They are just start-of-string and end-of-string anchors, making sure that *nothing else* than what the pattern describes is in the checked string. Leave them off and `"blah 1977-01-01 blah"` will start to match. | `^` and `$` anchor your pattern to the beginning and end respectively of the string passed in. The `?` is a multiplier, matching 0 or 1 of the preceding pattern (in this case, the parenthesised bit).
Your pattern matches a year, or a year and a month, or a year and a month and a date; if you follow the parentheses, you'll see the final `?` is operating on the parens surrounding the whole of the pattern after the year.
```
^ # beginning of string
(\d\d\d\d) #year
(
-(\d{1,2}) #month after a dash
(
-(\d{1,2}) #date after a dash
)? #date optional
)? # month and date optional
$ # end of string
``` |
17,082,477 | I've stored latitude and longitude value into my sqlite table. Eg: **latitude = 16.840064** and **longitude = 96.120286**.My question is how can I check and retrieve data from sqlite database for nearest location based on device current GPS location? | 2013/06/13 | [
"https://Stackoverflow.com/questions/17082477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2555911/"
] | Whlile The answer given already (Harversine formula) is correct, but may be I simpler solution works for you:
I am using this solution to reverse geocode the nearest airfield for the given position (used in a flight logger application of mine):
1. query the database for all rows where the coordinated of the location stored in the row are 0.1 degrees smaller or larger than the given solution. This is about 11 km to either side at the equator and about 6 km in Germany.
2. For each element answered for the above query compute the distance to the given location. If there is none try a larger range for the query (e.g. 0.5 degrees).
3. Answer the element with minimal distance
For my application step one answers only one row, because airfields usually are distributed rather sparsely.
EDIT
Here is some code from the content provider, the location is part of the query URI
```
@Override
public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, String sortOrder) {
String pathSegment;
Location loc;
Object[] result;
MatrixCursor result_cursor;
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(AirfieldsTable.TABLE_NAME);
final SQLiteDatabase dbCon = this.db.getReadableDatabase();
switch( URI_MATCHER.match(uri) ) {
// ... the location is encoded in the URI used to query the provider
case NRST_AIRFIELD:
pathSegment = uri.getPathSegments().get(1);
if( DEBUG )
Log.d( TAG, "Query nearest airfield: " + pathSegment);
loc = this.parsePosition(pathSegment);
if( loc == null )
return null;
// try a range query first
result = this.rangeQuery(dbCon, loc.getLatitude(), loc.getLongitude());
if( result == null )
// range query had no hits, try a full table scan
// **Here you could enlarge the range as suggested in the text before the EDIT**
return this.nearestBruteForce(dbCon, loc.getLatitude(), loc.getLongitude());
result_cursor = new MatrixCursor(AirfieldsTable.allColumnNames());
result_cursor.addRow(result);
return result_cursor;
// ...
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
```
And here is the range query:
```
/**
* Query the airfields table for airfields near the given position.
* @param dbCon DB connection
* @param ref_lat latitude
* @param ref_lon longitude
* @return Answer the airfield nearest to the given position as array
* of objects: id, designator, latitude, longitude.
* Answer <code>null</code> if their is no airfield near the
* given position plus or minus 0.1 degrees.
*/
private Object[] rangeQuery(final SQLiteDatabase dbCon, final double ref_lat, final double ref_lon) {
if( DEBUG )
Log.d( TAG, "rangeQuery lat=" + ref_lat + ", lon=" + ref_lon);
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(AirfieldsTable.TABLE_NAME);
final String[] whereArgs = new String[] {
Double.toString(ref_lat - 0.1d), Double.toString(ref_lat + 0.1d),
Double.toString(ref_lon - 0.1d), Double.toString(ref_lon + 0.1d)
};
final Cursor crsr = qb.query(dbCon, allFields(), AirfieldsTable.RANGE_CLAUSE, whereArgs, null, null, null);
final Object[] val = this.scanForNearest(crsr, ref_lat, ref_lon);
crsr.close();
if( DEBUG )
Log.d( TAG, "scanForNearest returned " + val);
return val;
}
```
And here is the search for the airfield of minimum distance:
```
/**
* Select the airfield nearest to the given position from the
* given cursor.
* @param crsr a cursor
* @param ref_lat latitude
* @param ref_lon longitude
* @return Answer the airfield nearest to the given position as array
* of objects: id, designator, latitude, longitude.
* Answer <code>null</code> if the cursor is empty.
*/
private Object[] scanForNearest(final Cursor crsr, final double ref_lat, final double ref_lon) {
String designator = null;
long id = -1;
double lat = 0.0f, lon = 0.0f, dist = Float.MAX_VALUE;
int ctr = 0;
final float[] results = new float[1];
if( ! crsr.moveToFirst() ) {
if( DEBUG )
Log.d( TAG, "scan for nearest with empty cursor");
return null;
}
do {
ctr += 1;
final double tmp_lat = crsr.getDouble(AirfieldColumns.IDX_LATITUDE);
final double tmp_lon = crsr.getDouble(AirfieldColumns.IDX_LONGITUDE);
Location.distanceBetween(tmp_lat, tmp_lon, ref_lat, ref_lon, results);
final float tmp_dist = results[0];
if( tmp_dist < dist ) {
// first element or nearer element
designator = crsr.getString(AirfieldColumns.IDX_DESIGNATOR);
id = crsr.getLong(AirfieldColumns.IDX_ID);
lat = tmp_lat;
lon = tmp_lon;
dist = tmp_dist;
}
} while( crsr.moveToNext() );
if( DEBUG )
Log.d( TAG, "nearest is " + designator + ", dist=" + dist + ", ctr=" + ctr + ", id=" + id);
final Object[] val = {
id,
designator,
lat,
lon };
return val;
}
```
nearestBruteForce() is straightforward: Get a cursor from a full table scan and call scanForNearest(). | ```
Location.distanceTo (Location locationFromDb)
```
Looks like you will need to create a Location object out of each of the entries in your database and use the above function |
117,428 | In this context, why does he use "come"?
>
> Oh! Quick. Here they **come**. [Oxford English Daily Conversation Episode 2](https://youtu.be/YXf3NmGRfv4?t=24m24s)
>
>
>
Why doesn't he use "are coming" or "have been coming" ?
>
> They are coming here / Here they are coming.
>
>
>
> They have been coming here / Here they have been coming.
>
>
>
**Update:**
Can you please recommend an article or reference where we can use "Simple Present" with *now* events. So I can read and learn more about this usage.
**Update 2:**
I have read this article that describes **[When Should I Use The Present Simple Tense?](http://www.perfect-english-grammar.com/present-simple-use.html)**
>
> **We can also use the present simple for short actions that are happening now**. The actions are so short that they are finished almost as soon as you've said the sentence. This is often used with sports commentary, or in demonstrations.
> He takes the ball, he runs down the wing, and he scores!
> First I put some butter in the pan and turn on the cooker.
>
>
>
Is this apply on "Here they *come*"? | 2017/01/28 | [
"https://ell.stackexchange.com/questions/117428",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/47521/"
] | Shakespeare's usage of Hark! followed by present simple:
Mistress, upon my life, I tell you true;
I have not breathed almost since I did see it.
He cries for you, and vows, if he can take you,
To scorch your face and to disfigure you.
[Cry within]
**Hark, hark! I hear him, mistress. fly, be gone**!
Comedy of Errors
[V, 1]
And hark, what noise the general makes!
Coriolanus
[I, 4]
First Senator
Hark you! they come this way.
[A march afar]
All's Well That Ends Well
[III, 5]
Widow
Hark, how they knock!
Romeo and Juliet
See this BOOK: [that describes this phenomenon under the use of simple present entitled "CURRENT ACTIVITIES: WHEN SAYING IS DOING"](https://books.google.com/books?id=skyftLKdKq0C&pg=PA200&lpg=PA200&dq=performative%20act%20%2B%20description%20%2B%20%22here%20they%20come%22&source=bl&ots=TlV8DKiDiR&sig=62Rp1dR-Qo-79Glr6pgAzAvQBOc&hl=en&sa=X&ved=0ahUKEwjc4Yj72JzSAhXp7IMKHdccCVUQ6AEIHTAB#v=onepage&q=lesson%20five&f=false)
Also, further along in the book is the sentence: /Here they come/ explained in relation to this Current Activity Idea.
This is a type of performative verb, too: /Here they come/ is as if the speaker is actually "doing" the action. In fact, she or he is describing a current activity. | The use of the bare infinitive "come" in
>
> Here they **come**.
>
> There they **go**!
>
>
>
is more of a warning and has the feeling of
>
> Beware! Here they come!
>
>
>
and is used for emphasis. In your example, the reporter is using to as a *call-to-action*, since they want to film a segment. He could have easily said
>
> Look! They're coming!
>
>
>
but it would not have the same "feeling". "Here" is not necessary with "coming" since it already implies "coming here" / "coming this way".
I realize this can be confusing since in the same video they also use
>
> [Look out, she's coming.](https://www.youtube.com/watch?v=YXf3NmGRfv4&feature=youtu.be&t=4m35s)
>
>
>
to essentially meaning the same thing. |
57,622,311 | I am a spark beginner and trying to solve a question from the Northwind Dataset where I need to list products whose prices are above the average price on a databricks notebook.
I tried this:
```
query6 = sparkDF7.select("ProductName","UnitPrice").agg({'UnitPrice':'mean'}).filter("UnitPrice>avg(UnitPrice)").show()
```
I've went through similar answers but they just won't work. Any help?
It throws me this error:
```
AnalysisException: 'Resolved attribute(s) UnitPrice#225 missing from avg(UnitPrice)#1350,avg(UnitPrice#225)#1355 in operator !Filter (UnitPrice#225 > avg(UnitPrice#225)#1355).;;\nProject [avg(UnitPrice)#1350]\n+- !Filter (UnitPrice#225 > avg(UnitPrice#225)#1355)\n +- Aggregate [avg(UnitPrice#225) AS avg(UnitPrice)#1350, avg(UnitPrice#225) AS avg(UnitPrice#225)#1355]\n +- Project [ProductName#221, UnitPrice#225]\n +- Relation[ProductID#220,ProductName#221,SupplierID#222,CategoryID#223,QuantityPerUnit#224,UnitPrice#225,UnitsInStock#226,UnitsOnOrder#227,ReorderLevel#228,Discontinued#229] csv\n'
``` | 2019/08/23 | [
"https://Stackoverflow.com/questions/57622311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11655370/"
] | Try this
```
public static void hideKeyboardFrom(Context context, View view)
{
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
```
For kotlin
```
fun hideKeyboard(context : Context, view : View)
{
val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
``` | 1. First of all you will call hide keyboard method.I have show type of hide keyBoard methods given in below.If you want use your like methods.
```
public void hideKeyboard(View view, Context context) {
try {
if (view != null) {
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} catch (Exception Ex) {
}
}
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
```
2. Then you will call Dialog.
Conclusions first you call hide method and after that Dialog.So When call hide method then hide keyboard and and again calling Dialog after call dialog then open. |
13,385,714 | The problem is that I have a table product and my update script doesn't work aparently. It allwas return false.
**Product.class**
```
@DatabaseTable(tableName = "Product")
public class Product {
@DatabaseField(index = true, generatedId = true)
private int productId;
@DatabaseField
private String name;
@DatabaseField
private int quantity;
//@DatabaseField(canBeNull = true)
//private Integer categorie;
//http://logic-explained.blogspot.com.ar/2011/12/using-ormlite-in-android-projects.html
@DatabaseField
private int categorie;
//@ForeignCollectionField
//private ForeignCollection<Categorie> itemsCategorie;
@DatabaseField
private String description;
@DatabaseField
private String photo;
Product() {
}
public Product(int productId, String name, int quantity, int categorie, String description, String photo) {
super();
this.productId = productId;
this.name = name;
this.quantity = quantity;
this.categorie = categorie;
this.description = description;
this.photo = photo;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return description;
}
public void setAddress(String address) {
this.description = address;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCategorie() {
return categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public CharSequence getDesc() {
return null;
}
}
```
**my script updateProduct**
```
public boolean updateProduct(Product p) {
boolean ret = false;
if (productDao != null) {
try {
productDao = getDao(Product.class);
UpdateBuilder<Product, Integer> updateBuilder = productDao
.updateBuilder();
updateBuilder.updateColumnValue("name", p.getName());
updateBuilder.updateColumnValue("quantity", p.getQuantity());
updateBuilder.updateColumnValue("categorie", p.getCategorie());
updateBuilder.updateColumnValue("description", p.getDesc());
updateBuilder.updateColumnValue("photo", p.getPhoto());
// but only update the rows where the description is some value
updateBuilder.where().eq("productId", p.getProductId());
// actually perform the update
String str = updateBuilder.prepareStatementString();
// UPDATE `Product` SET `name` = 'gcd' ,`quantity` = 1
// ,`categorie` = 1 ,`description` = ? ,`photo` = '' WHERE
// `productId` = 0
if (productDao.update(updateBuilder.prepare()) != 1) {
ret = false;
} else {
productDao.refresh(p);
ret = true;
}
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
```
**then I call it with a function like this, but allways return false :(**
```
public boolean updateProduct(Product p) {
boolean ret = false;
try {
ret = getHelper().updateProduct(p);
} catch (Exception e) {
e.printStackTrace();
ret =false;
}
return ret;
}
```
I can create and delete but I can not update . I tried everything.
If you please take a moment to answer my question I will appreciate. | 2012/11/14 | [
"https://Stackoverflow.com/questions/13385714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1415089/"
] | The solution was
Simply get the Instance of the object Product from the DB then modify to finaly send to the updateProduct method.
for example first I need to create any method first to get an objet by ID
```
// get the Instance calling to the getProductByID
Product p = getHelper().getProductByID(p.getId())
//modify any value of the product
p.setFirstName("asd");
//call the update
ret = getHelper().updateProduct(p);
```
then my objects is Updated. | Put attention for the object Id(should be the same) and use the natif function update(Product); |
31,968,448 | In the Java Mongo DB driver version 3 the API has changed as compared to the version 2. So a code like this does not compile anymore:
```
BasicDBObject personObj = new BasicDBObject();
collection.insert(personObj)
```
A Collection insert works only with a Mongo Document.
Dealing with the old code I need to ask the question:
What is the best way to convert a BasicDBObject to a Document? | 2015/08/12 | [
"https://Stackoverflow.com/questions/31968448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417291/"
] | I think the easiest thing to do is just change your code to use a Document as opposed to BasicDBObject.
So change
```
BasicDBObject doc = new BasicDBObject("name", "john")
.append("age", 35)
.append("kids", kids)
.append("info", new BasicDBObject("email", "john@mail.com")
.append("phone", "876-134-667"));
```
To
```
import org.bson.Document;
...
Document doc = new Document("name", "john")
.append("age", 35)
.append("kids", kids)
.append("info", new BasicDBObject("email", "john@mail.com")
.append("phone", "876-134-667"));
```
and then insert into the collection
```
coll.insertOne(doc);
```
You'll need to change other bits of code to work with MongoDB 3+
MongoDatabase vs. DB
MongoCollection vs DBCollection | ```
@SuppressWarnings("unchecked")
public static Document getDocument(BasicDBObject doc)
{
if(doc == null) return null;
Map<String, Object> originalMap = doc.toMap();
Map<String, Object> resultMap = new HashMap<>(doc.size());
for(Entry<String, Object> entry : originalMap.entrySet())
{
String key = entry.getKey();
Object value = entry.getValue();
if(value == null)
{
continue;
}
if(value instanceof BasicDBObject)
{
value = getDocument((BasicDBObject)value);
}
if(value instanceof List<?>)
{
List<?> list = (List<?>) value;
if(list.size() > 0)
{
// check instance of first element
Object firstElement = list.get(0);
if(firstElement instanceof BasicDBObject)
{
List<Document> resultList = new ArrayList<>(list.size());
for(Object listElement : list)
{
resultList.add(getDocument((BasicDBObject)listElement));
}
value = resultList;
}
else
{
value = list;
}
}
}
resultMap.put(key, value);
}
Document result = new Document(resultMap);
return result;
}
``` |
33,319,689 | I used this code to send parameter
>
> {
> "email":"email@domain.com",
> "password":"pass"
> }
>
>
>
```
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", "email@domain.com"));
params.add(new BasicNameValuePair("password", "pass"));
```
but web developer change format to this format
>
> {
> "data":{
> "email":"email@domain.com",
> "password":"pass"
> }
> }
>
>
>
how can I update my code to works. | 2015/10/24 | [
"https://Stackoverflow.com/questions/33319689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3240583/"
] | *Microdata* is the name of a specific technology, *metadata* is a generic term.
Metadata is, like you explain, data about data. We’d typically want this metadata to be machine-readable/-understandable, so that search engines and other consumers can make use of it.
In the typical sense, metadata is data **about the whole document** (e.g., who wrote it, when it was published etc.). This goes into the [`head` element](http://www.w3.org/TR/2014/REC-html5-20141028/document-metadata.html#the-head-element) (which "represents a collection of metadata for the Document"), where you have to use the [`meta` element](http://www.w3.org/TR/2014/REC-html5-20141028/document-metadata.html#the-meta-element) and its [`name` attribute](http://www.w3.org/TR/2014/REC-html5-20141028/document-metadata.html#attr-meta-name) (unless the value is a URI, in which case you have to use the [`link` element](http://www.w3.org/TR/2014/REC-html5-20141028/document-metadata.html#the-link-element) and its [`rel` attribute](http://www.w3.org/TR/2014/REC-html5-20141028/document-metadata.html#attr-link-rel)), as this is defined to "represent document-level metadata".
Microdata is not involved here.
If the data is **about entities described in that document** (or the entity which represents the document itself), we typically speak of [*structured data*](https://webmasters.stackexchange.com/a/82219/17633). An example for such an entity could be a product and its price, manufacturer, weight etc.
[Microdata](https://html.spec.whatwg.org/multipage/microdata.html) is one of several ways how to provide structured data like that. [Others](https://stackoverflow.com/a/27175699/1591669) are [RDFa](http://www.w3.org/TR/rdfa-in-html/), [Microformats](http://microformats.org/), and also [`script` elements used as data block](https://stackoverflow.com/a/30798784/1591669) (which can contain something like JSON-LD). | Metadata: using data to provide information about data. For instance, if you are collecting data about prices of different commodities and you added a small section at the top of the questionnaire to collect information about the name of the enumerator, time of interview, duration of interview etc., such information is a metadata.
Microdata: data from individual observations of interest. |
36,281 | I have an idea as to why it might be valid, but I would like confirmation, rebuttals, or maybe just better answers. | 2016/06/28 | [
"https://philosophy.stackexchange.com/questions/36281",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/16858/"
] | An appeal to authority is almost never valid. However, if it is declared as such and accepted by both parties, it is alright to use it. First thing to know is that it is an informal fallacy. So it is wrong or right depending on the way it is used or more precisely what inference does the person using it wants the other party to draw.
If the inference to be drawn is about the truth of a belief or proposition, then such appeal is never valid. If the person putting appeal to authority uses it to justify his belief or having a particular belief, then it may be not be fallacious to use it. Here hidden assumption is that it is justified to have those beliefs that are held by experts in a field. | An appeal to authority is not a valid A PRIORI argument. The only way an appeal to authority would be even useful is if you are unable to evaluate the argument itself (that is, it is either hidden or you are unable to make valid inferences about arguments!). The appeal to authority is an a posteriori inductive inference. |
18,981,167 | Hey i have created database. And i am adding a through insert query but there is nothing added into database
here is my code of DBManager.java
```
package com.database;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DBManager {
public SQLiteDatabase mDatabase;
public MyDBHandler mDBhandler;
private String[] allEvents = { MyDBHandler.COLUMN_ID,
MyDBHandler.COLUMN_ICON, MyDBHandler.COLUMN_EVENTNAME };
public static final String TAG = "MyActivityTag";
public DBManager(Context context) {
mDBhandler = new MyDBHandler(context);
Log.d(TAG, "db manager created");
}
public void open() throws SQLException {
mDatabase = mDBhandler.getWritableDatabase();
}
public void close() throws SQLException {
mDBhandler.close();
}
public void addEvent(Event event) {
Log.d(TAG, "addEvent method in eventmanager with icon and name :"
+ event.getIcon() + event.getEventName());
String insertQuery = " INSERT INTO " + MyDBHandler.TABLE_EVENTS + "("
+ MyDBHandler.COLUMN_ICON + "," + MyDBHandler.COLUMN_EVENTNAME
+ ")" + " VALUES ( ' " + event.getIcon() + " ' , '"
+ event.getEventName() + " ' )";
mDatabase.execSQL(insertQuery);
}
public void deleteEvent(String eventname) {
Log.d(TAG, "in deleteEvent method in DBManager");
String deleteQuery = "Select * FROM " + MyDBHandler.TABLE_EVENTS
+ " WHERE " + MyDBHandler.COLUMN_EVENTNAME + " = \""
+ eventname + "\"";
mDatabase = mDBhandler.getWritableDatabase();
Cursor cursor = mDatabase.rawQuery(deleteQuery, null);
Event event = new Event();
if (cursor.moveToFirst()) {
event.setID(Integer.parseInt(cursor.getString(0)));
mDatabase.delete(MyDBHandler.TABLE_EVENTS, MyDBHandler.COLUMN_ID
+ " = ?", new String[] { String.valueOf(event.getID()) });
cursor.close();
}
Log.d(TAG, "Event deleted and database closed");
mDatabase.close();
}
public ArrayList<Event> getallEvents() {
Log.d(TAG, "getallEvents in DBmanager");
ArrayList<Event> events = new ArrayList<Event>();
Cursor cursor = mDatabase.query(MyDBHandler.TABLE_EVENTS, allEvents,
null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Event event = cursorToEvent(cursor);
events.add(event);
} while (cursor.moveToNext());
}
cursor.close();
return events;
}
private Event cursorToEvent(Cursor cursor) {
Event event = new Event();
event.setID(cursor.getInt(0));
event.setEventName(cursor.getString(1));
return event;
}
}
```
I am getting no error log but when i am checking in database there is nothing added there.
My MainActivity.java
```
package com.database;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.ajay.database.R;
public class MainActivity extends Activity {
private DBManager mDbManager;
private EditText mName;
public CustomListAdapter mAdapter;
public ArrayList<Event> mEvents;
public ListView mListview;
public String TAG = "MyActivityTag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Attendance Tracker");
mDbManager = new DBManager(this);
mDbManager.open();
Log.d(TAG, "Dbmanager.open called");
mEvents = mDbManager.getallEvents();
mAdapter = new CustomListAdapter(MainActivity.this, mEvents);
mListview = (ListView) findViewById(R.id.listview);
mListview.setAdapter(mAdapter);
}
public void addClick(View view) {
Log.d(TAG, "Add button clicked");
Event event = new Event();
mName = (EditText) findViewById(R.id.eventNameText);
event.mEventName = mName.getText().toString();
event.setIcon("icon");
mDbManager.addEvent(event);
mAdapter.add(event);
mAdapter.notifyDataSetChanged();
mName.setText(null);
}
@Override
protected void onResume() {
mDbManager.open();
super.onResume();
}
@Override
protected void onPause() {
mDbManager.close();
super.onPause();
}
}
```
and customAdapter.java
```
package com.database;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import com.ajay.database.R;
public class CustomListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Event> mEventList;
public DBManager mDBManager;
public static final String TAG = "MyActivityTag";
public CustomListAdapter(Context context, ArrayList<Event> list) {
Log.d(TAG, "Custom Adapter constructor is called");
this.context = context;
mEventList = list;
mDBManager = new DBManager(context);
}
@Override
public int getCount() {
return mEventList.size();
}
@Override
public Object getItem(int position) {
return mEventList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void add(Event event) {
mEventList.add(event);
notifyDataSetChanged();
Log.d(TAG, "Event Added");
}
public void remove(Event event) {
mEventList.remove(event);
notifyDataSetChanged();
Log.d(TAG, "Event Deleted");
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Event event = mEventList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.event_list_row, null);
}
TextView mEventName = (TextView) convertView
.findViewById(R.id.eventName);
mEventName.setText(event.getEventName());
TextView mIcon = (TextView) convertView.findViewById(R.id.iconName);
mIcon.setText(event.getIcon());
final ImageButton mDeleteButton = (ImageButton) convertView
.findViewById(R.id.deleteButton);
mDeleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Delete Button clicked");
Log.d(TAG, "Event want to delete is " + event.getEventName());
mDBManager.deleteEvent(event.getEventName());
remove(event);
Log.d(TAG, "Database refreshed");
notifyDataSetChanged();
}
});
return convertView;
}
}
```
and MyDBHandler.java
```
package com.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MyDBHandler extends SQLiteOpenHelper {
protected static final int DATABASE_VERSION = 1;
protected static final String DATABSE_NAME = "eventDB.db";
protected static final String TABLE_EVENTS = "Event";
public static final String COLUMN_ID = "id";
public static final String COLUMN_ICON = "icon";
public static final String COLUMN_EVENTNAME = "eventname";
public static final String TAG = "MyActivityTag";
public MyDBHandler(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_EVENTS_TABLE = " CREATE TABLE " + TABLE_EVENTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_ICON + " TEXT,"
+ COLUMN_EVENTNAME + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
Log.d(TAG, "Table Created in database");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
onCreate(db);
Log.d(TAG, "database updated");
}
}
```
And i dont want to use CustomValues i just want to add data through execSQL() only | 2013/09/24 | [
"https://Stackoverflow.com/questions/18981167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2192384/"
] | check your configuration file in MAMP, the password isn't defined
The reinstallation doesnt rewrite conf files | Try resetting your root password via the console. [Instructions can be found here.](http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html)
The instructions cover Windows and \*Nix.
The reason why when you re-installed MAMP/WAMP/LAMP/MySQL etc and it doesn't remove the password is because it saves the config files, and when you remove MySQL it doesn't delete the config files relating to the passwords.
I've had this issue on Windows and Linux - But I can see it affects Mac's too.
Edit: I am assuming you have console access, because you mention MAMP - If you don't, try your host' control panel, it will have an option for Mysql there. |
37,046,133 | I have problem very similar to this [PDF Blob - Pop up window not showing content](https://stackoverflow.com/questions/21729451/pdf-blob-pop-up-window-not-showing-contnet), but I am using Angular 2. The response on question was to set responseType to arrayBuffer, but it not works in Angular 2, the error is the reponseType does not exist in type RequestOptionsArgs. I also tried to extend it by BrowserXhr, but still not work (<https://github.com/angular/http/issues/83>).
My code is:
```
createPDF(customerServiceId: string) {
console.log("Sending GET on " + this.getPDFUrl + "/" + customerServiceId);
this._http.get(this.getPDFUrl + '/' + customerServiceId).subscribe(
(data) => {
this.handleResponse(data);
});
}
```
And the handleResponse method:
```
handleResponse(data: any) {
console.log("[Receipt service] GET PDF byte array " + JSON.stringify(data));
var file = new Blob([data._body], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
```
I also tried to saveAs method from FileSaver.js, but it is the same problem, pdf opens, but the content is not displayed. Thanks | 2016/05/05 | [
"https://Stackoverflow.com/questions/37046133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2602241/"
] | I had a lot of problems with downloading and showing content of PDF, I probably wasted a day or two to fix it, so I'll post working example of how to successfully download PDF or open it in new tab:
**myService.ts**
```
downloadPDF(): any {
return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' })
}
}
```
**myComponent.ts**
```
this.myService.downloadPDF().subscribe(
(res) => {
saveAs(res, "myPDF.pdf"); //if you want to save it - you need file-saver for this : https://www.npmjs.com/package/file-saver
var fileURL = URL.createObjectURL(res);
window.open(fileURL); / if you want to open it in new tab
}
);
```
**NOTE**
It is also worth mentioning that if you are extending `Http` class to add `headers` to all your requests or something like that, it can also create problems for downloading PDF because you will override `RequestOptions`, which is where we add `responseType: ResponseContentType.Blob` and this will get you `The request body isn't either a blob or an array buffer` error. | **ANGULAR 5**
I had the same problem which I lost few days on that.
Here my answer may help others, which helped to render pdf.
For me even though if i mention as responseType : 'arraybuffer', it was unable to take it.
For that you need to mention as responseType : 'arraybuffer' as 'json'.([Reference](https://github.com/angular/angular/issues/18586))
Working code
```
downloadPDF(): any {
return this._http.get(url, { responseType: 'blob' as 'json' }).subscribe((res) => {
var file = new Blob([res], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
```
Referred from the below link
<https://github.com/angular/angular/issues/18586> |
47,758 | Let's say that I bought 500 shares of company ABC while the stock was doing well, and paid $10 per share for a total of $5,000. Then over the next year (while I was overseas, let's say) the company tanked and dropped to $2 per share. Since I had no safeties in place to trigger a sell off, I now own 500 shares worth $1000.
After I get over my initial frustration at the loss, I realize that even though only at a fraction of it's initial value, ABC is now regularly fluctuating between $2 and $3. I decide rather than taking an immediate $4000 loss, to start trading on smaller increments and take advantage of the regular fluctuations in price.
I purchase another 100 shares of ABC at $2, and then sell it a week later when the price hits $3. Because I am calculating capital gains using FIFO, I record a $700 loss on the 100 shares, but now I am still $100 richer. Assuming the price shortly turns around and hits $2 again, I repeat the process again and over the next several months I (hopefully) begin to recover a portion of my losses, all while avoiding short-term capital gains.
Neglecting transaction fees, are there any drawbacks to this approach? | 2015/05/04 | [
"https://money.stackexchange.com/questions/47758",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/27605/"
] | Stop trying to make money with your emergency fund. It's purpose is to sit there idly waiting for a bad day. A day when you need that cash (liquid) not in a bank or a line-of-credit.
The few dollars you might make trying to chase interest/investments with your emergency fund aren't worth it if a true emergency came up and you couldn't get to your cash in time.
Once you have a fully funded EF then start investing heavily. That's your future game plan. Not the EF. | Why can't you have both?
If you do have both credit and an emergency fund, and an emergency occurs, you can draw from the line of credit first. Having debt + cash is a much more stable situation than having neither, because then you have the option to use the cash to pay off the debt, or use the cash to pay other expenses. If you just have cash, when you spend it it's gone and there's no guarantee anyone is going to lend you any money at that point. |
1,493,359 | If $x\_n:=\sqrt{n}$, show that $(x\_n)$ satisfies $\lim|x\_{n+1}-x\_n|=0$, but that it is not a Cauchy sequence.
We see that
$$|x\_{n+1}-x\_n|=|\sqrt{n+1}-\sqrt{n}|=|(\sqrt{n+1}-\sqrt{n})\cdot\frac{\sqrt{n+1}+\sqrt{n}}{\sqrt{n+1}+\sqrt{n}}|=\bigl|\frac{1}{\sqrt{n+1}+\sqrt{n}}\bigr|$$
This seems to simplify nicely, but I am not quite sure where to proceed.
Relevant definitions:
1. $\lim(x\_n) = x$ if and only if for $\varepsilon>0$, $\exists k\in\mathbb{N}$ such that for all $n\geq k$, $|x\_n-x|<\varepsilon$.
2. A sequence $(x\_n)$ is a Cauchy sequence if for every $\varepsilon>0$, $\exists h\in\mathbb{N}$ such that for all $n,m\geq h$, $|x\_n-x\_m|<\varepsilon$. | 2015/10/23 | [
"https://math.stackexchange.com/questions/1493359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/250846/"
] | Take $\epsilon=\frac12$. For any $h\in \mathbb{N}$, choose $n=h$ and $m=4h$. Then $|x\_m-x\_n|=|\sqrt{4h}-\sqrt{h}|=|2\sqrt{h}-\sqrt{h}|=\sqrt{h} \ge 1$ which contradicts the definition of Cauchy sequence for above $\epsilon$. | You have shown that
$$|x\_{n+1}-x\_n|=\frac1{\sqrt{n+1}+\sqrt n}\ ,$$
and this clearly approaches $0$ because $\sqrt{n+1}$ and $\sqrt n$ both approach $\infty$. (There is no need to use the definition with $\epsilon$ etc unless you have been instructed to do so.)
The easy way to show that $x\_n$ is not Cauchy is to note that any Cauchy sequence is convergent (in $\Bbb R$), and $x\_n=\sqrt n$ is not convergent. |
16,610,698 | Recently I downloaded a file using the following link
```
git clone git://github.com/mapserver/mapcache.git
```
Inside the downloaded mapcache folder I can not find a configure file to do "./configure". But the installation help file tell:
>
> Unix compilation instructions
> -----------------------------
>
>
> If you are using a git clone rather than a tarball distribution, you
> must first run autoconf in the root directory, to create the configure
> file from configure.in:
>
>
> $ autoconf
>
>
> For unix users, the compilation process should resume to:
>
>
> $ ./configure
>
>
> $ make
>
>
> (as root)
>
>
> make install-module
> ===================
>
>
> The installation script takes care of putting the built module in the
> apache module directory.
>
>
>
To do `./configure` there should be a configure file isn't it? Please show me how to make one to get rid of this problem. | 2013/05/17 | [
"https://Stackoverflow.com/questions/16610698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1662802/"
] | maintainer speaking ...
mapcache and mapserver are switching to cmake for the next release and the docs for the master branch need updating. You can either use the branch-1-0 branch to continue using autoconf builds, or use cmake with master:
```
$ mkdir build
$ cd build
$ cmake ..
$ make
$ sudo make install
``` | The help file tells you exactly what you need to do
>
> If you are using a git clone rather than a tarball distribution, you must first run autoconf in the root directory, to create the configure file from configure.in
>
>
>
If you don't already have `autoconf` installed you'll need to install it in the normal way for your distribution. |
1,085,801 | How do I get the selected value from a dropdown list using JavaScript?
```html
<form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form>
``` | 2009/07/06 | [
"https://Stackoverflow.com/questions/1085801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127986/"
] | ```
var selectedValue = document.getElementById("ddlViewBy").value;
``` | There are two ways to get this done either using JavaScript or jQuery.
**JavaScript:**
```
var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;
alert (getValue); // This will output the value selected.
```
**OR**
```
var ddlViewBy = document.getElementById('ddlViewBy');
var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;
var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;
alert (value); // This will output the value selected
alert (text); // This will output the text of the value selected
```
**jQuery:**
```
$("#ddlViewBy:selected").text(); // Text of the selected value
$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'
``` |
43,096 | Over the past 2 years myself and a colleague have built an online statistical analysis application using a mixture of silverlight, wcf and R. I (a c# programmer) wrote all the silverlight and wcf stuff whilst my colleague (a statistician) came up with the stats algorithms and wrote the R code.
Now we think that this app is fairly unique - a rich gui online statistics application that is much more intuitive than all the other online stat apps that I've seen. But despite this we don't really know where to go with the project, mainly for the following reasons:
1) Its fairly complicated stuff - without the mix of programming and stats skills it would be difficult for anyone to "get into" the project and contribute.
2) We are stalled by a lack of a proper place to host the site. Currently it sits on the family windows 7 media centre, not exactly the best place to host it as it could interfere with the missus trying to watch Corrie/Friends/Oprah etc.
Soo, anyone got any ideas on how to move forward with this? I guess that my strength is programming not marketing so despite working hard at this for the past couple of years I feel that I've reached a dead end!
Also, does anyone know of any free windows hosting for open source projects? If I could find a proper place to put the app I might feel re-energised about the whole thing.
The source code is on codeplex at: <http://silverstats.codeplex.com>, whilst the app is currently hosted at <http://silverstats.co.uk>
Edit: to answer some of the points raised:
I don't have any documentation so that is a valid point and something that I need to look at. However, I do believe that it is easy to use - try it yourself! It is drag and drop based and fairly intuitive (as long you have some stats knowledge). One point though: Its not aimed at statistians! Its aimed at people who need to do stats to do their job (which is why it is easy to use). Personally on an ease of use basis it beats the like of Rcmdr hands down! You are quite right that the R and stats geeks will continue to tap away at R and SAS and produce their scripts. So, to answer another question: Is it scriptable - of course not because that would defeat the ease of use concept, you might as well fire up R and tap away...
Does it produce graphics: yep - output is nice and clean in html with some expalantory text for the people scared by stats.
Is it validated, yes and no...the project is a spin off from our closed source (but free!) stats package called InVivoStat (google it) which was built with the same aim: to make statistics easy for non-statisticians, in this case scientists working in the life sciences. The R scripts that InVivoStat uses are fully GxP validated with evidence hosted on the InVivoStat website. This project (SilveR) uses the same scripts, so you could argue that a bit of revalidation is required as the interface has changed, but I am fully confident that the R scripts are correct. | 2011/02/03 | [
"https://softwareengineering.stackexchange.com/questions/43096",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/15431/"
] | To answer JBRWilkinson : yes, there is [www.crossvalidated.com](http://www.crossvalidated.com), a stackexchange site for statistics and well past beta. So that's a first channel to find both programmers and customers.
I agree with Lenny222 : you have to present a very clear case why your application is to be preferred, by showing :
* it is easy to use
* it is complete, i.e. all necessary statistical techniques are implemented.
* it is correct, meaning that the results can be trusted
* it is readible, meaning the output actually means something
* it is able to produce custom graphics that explain the analysis in a straightforward way
* it allows for scripting an analysis, so any analysis can be reproduced exactly
The latter point is extremely important, as you have to be able to repeat any published analysis on demand. I know it's not done like this for every publication, but at our university a statistical package will never be used if you can't script the analysis.
I hope I don't disappoint you too much, but you have to be realistic in this. R adepts are unlikely to jump on it as they like coding more and there are some very fine GUIs using R already on the "market" like [JGR](http://www.rforge.net/JGR/) and [Rcmdr](http://socserv.mcmaster.ca/jfox/Misc/Rcmdr/). Statisticians using other programs (SAS, SPSS, Statistica, Stata, SPlus, ...) will probably keep on coding in the scripting language they like, and all the rest will just use the program they've been taught at university, or the one available on the servers of the college / company.
Maybe your best shot is showing the R community that your application can beat the other ones mentioned here and forms the bridge towards R coding for the students we have. If your application can do that, I'll be the first one to promote it here in statistical education. But you'll have to show it first, and I can tell you the competition is rather strong...
EDIT :
Given your further comments (and my look at the application), your best shot will be to provide an analysis guide, not only explaining the program but also explaining how to analyse different kinds of data with it, which statistics to use when, how to interprete results,... The application looks neat to me and can indeed be an extra value, but as the customers you aim for are no statisticians whatsoever, they need a lot more guidance. Make the guide visible on Google, and the rest will follow hopefully.
You could attempt a publication in a journal related to the field of research you're aiming at (as a letter to the editor or so maybe), but that's not going to be easy... | Are you looking for more programmers to contribute to the code or are you really wanting people to start making use of using the app/library that you've developed?
Identify your target market and go find some early adopters. Is there a StackExchange community related to statistics? Is MathOverflow suitable? |
545,297 | [](https://i.stack.imgur.com/sxE0z.jpg)
[](https://i.stack.imgur.com/DOKvm.jpg)
I’m trying to simulate a half wave rectifier for a -84dBm 2.4GHz AC signal.
The rectifier doesn’t seem to be giving me the correct waveform - the negative half cycle isn’t blocked?
Also sort of confused about how I’m supposed to pick the capacitance value.
Would appreciate any help and guidance. | 2021/01/28 | [
"https://electronics.stackexchange.com/questions/545297",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/275276/"
] | As @BrianDummond pointed out, Vf is way larger than your test voltage, the diode doesn't conduct at all.
Also the capacitance of the diode is maximum 2pF according to the datasheet for the BAS70, which corresponds to 33ohm@2.4GHz. In series with 10pF//50ohm, calculate the output voltage from that and you will probably figure out why you are seeing this amplitude at the output.
[](https://i.stack.imgur.com/8RD9pm.png)
[](https://i.stack.imgur.com/F0qjYm.png) | >
> The rectifier doesn’t seem to be giving me the correct waveform - the
> negative half cycle isn’t blocked?
>
>
>
The capacitor is the problem, you have made a nice low pass filter and the cap is filtering. Try 1pf
To pick the right value, you would need to find the equivalent series resistance of the diode, which will be hard because it changes.
Also if this is to be built in the real world, the simulation will not reflect reality unless you put in resistance of the traces on a PCB or resistance from wire that will be used between components. The cap is also probably ideal (with no ESR) so make sure the cap has ESR of a real capacitor (the ESR can be found in most datasheets for capacitors) and the capacitor and resistor should have a few nH of inductance in series with them (terminals on SMT or through hole devices have inductance that can make a difference in the GHz range. |
573,309 | What is the purpose and meaning of a cable wound around and passed through a cylindrical ferrite, that black non-conductive ceramic metal ? | 2021/06/29 | [
"https://electronics.stackexchange.com/questions/573309",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/-1/"
] | I see a 2 pin header for an unshielded cable. These wires will make much better antennas than the trace stub to the test points.
There is what looks like a differential LC filter on the PCB next to it, and the inductors look pretty chunky, so I assume this is not a highspeed signal line.
So for noise immunity, I think you should focus on stuff like:
* what kind of signal you have in these 2 wires (two signals, or differential)
* is it a sensitive signal that needs shielding? or not?... or something like a power supply that doesn't really care
* put some thought in the LC filter design, look a the self resonance frequency of the inductor, would a ferrite bead be better?
* If it's a differential signal, would a common mode choke be useful? These also have leakage inductance, so for example if you replace your 2 inductors with a CM choke you can save a part and have both common mode and differential mode filtering...
* Also your filter caps will have less inductance if you replace the skinny trace to the ground via with a wider track. You can also use several vias.
* Whether these are 2 signals or a differential pair, where does the common mode / return current flow?
* The filter caps dump the noise from the cable into GND at their via, making this bit of GND something more like "chassis ground". This current will return somehow to close the loop, through the ground plane. What is its path? It should not go through the GND of a sensitive analog circuit. That's why it is usually safer to put all the connectors on the same edge with their filter caps there, so the mess of common mode noise current is contained in that part of the ground plane. | Yes, test points can absolutely be noise sources if the test-pointed node is high-impedance. For high-frequency signals they also can be a source of distortion due to the discontinuity they introduce.
First issue, the **antenna**.
As you've drawn them, the test points form small antennas. This makes them prone to picking up RF noise from within and outside your system.
* For digital, any test point with an impedance above 10k (like internal pull-up/down on logic ICs) can be vulnerable to RF pickup.
* For Analog, sensitivity depends on the circuit impedance and the required signal/noise ratio.
In both cases, if the test-pointed node is low impedance *and high-frequency signal integrity isn’t a concern* then the test points won't be such an issue. (I’ll get into the SI issue below.)
How does this issue come up? Any RF source near your system (like a cell phone) could be an 'aggressor source' of RF that can upset its operation. For example, remember PC speakers that would 'chatter' whenever a cell phone was nearby? That's external RF interference.
Part of product qualification is one particularly nasty test: **EMC susceptibility**. This test is designed to suss out the target system's vulnerability to an aggressor RF signal. The test setup directs high-power RF at the target over a wide band of frequencies.
During the susceptibility test, those antennas formed by test points will get bathed in this powerful RF signal, and if the test-pointed node is vulnerable (high impedance and/or sensitive), that RF will get into your circuit causing it to malfunction, like those cheap-ass PC speakers.
If you absolutely need the antenna-style TP's, and if your circuit allows it, you can mitigate the effects of noise pickup by adding capacitance to ground at the test point. This will shunt aggressor RF energy to ground. This technique is useful for static signals like logic strap options or audio-frequency analog. It's not necessarily a good choice for any critical signal.
Now, for the second issue (and buried lede): **impedance discontinuity**. Test points like you’ve shown introduce a *signal stub*. Stubs cause reflections which will mess up a high-frequency signal, be it digital or analog. This will distort a high-speed signal, possibly causing your system to malfunction or at least not perform as well.
If you still absolutely need the test point, reduce its effect by repositioning it so that it’s *directly on the trace with no stub*. This also fixes the antenna problem by, well, eliminating the antenna. |
10,918,526 | I want to call my method getSelectedLayouts in my jsp page, where the method is
```
public Iterable<Layouts> getSelectedLayouts(String Subject){
Session sess=getCurrentSession();
return sess.createCriteria(Layouts.class, Subject).list();
}
```
Inside class LayoutManager. I passed LayoutManager into my jsp page using a Spring Bean
```
<custom:useSpringBean var="layoutManager" bean="LayoutManager">
```
the jsp page asks for the subject
```
<form method="post">
<label for="subjectName">SubjectName:</label>
<input type="text" name="subjectName" size="50" id="subjectName">
<input class="button" type="submit" value="Search Layout" name="submit">
</form>
```
Which I then pass to
```
<jsp:useBean id="subjectName" class="LayoutManager">
<c:if test="${param.submit!=null}">
(here's where I want to call my getSelectedLayouts method)
</c:if>
```
I've been trying with scriplets, including variations of
```
<jsp:setProperty name="layout" property="*"/>
((LayoutManager)pageContext.getAttribute("layoutManager")).getSelectedLayout((Layouts)pageContext.getAttribute("layout"));
```
or just
```
<jsp:setProperty name="layout" property="*"/>
list<Layouts> = LayoutManager.getSelectedLayouts(layout);
```
Where Layouts is my object class
Please tell me if I need to give any other information
Edit: When I try
```
LayoutManager layoutManager = new LayoutManager();
String subjectNa = request.getParameter("subjectName");
Iterable<Layouts> bla = layoutManager.getSelectedLayouts(subjectNa);
```
I get the error list
```
org.apache.jasper.JasperException: An exception occurred processing JSP page /search.jsp at line 72
Iterable<Layouts> waters = layoutManager.getSelectedLayouts(subjectNa);
java.lang.NullPointerException
com.amazon.basalt.examples.octane.tomcat.LayoutManager.getCurrentSession(LayoutManager.java:37)
com.amazon.basalt.examples.octane.tomcat.LayoutManager.getSelectedLayouts(LayoutManager.java:50)
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
root cause
java.lang.NullPointerException com.amazon.basalt.examples.octane.tomcat.LayoutManager.getCurrentSession(LayoutManager.java:37)
com.amazon.basalt.examples.octane.tomcat.LayoutManager.getAllLayouts(LayoutManager.java:68)
org.apache.jsp.search_jsp._jspService(search_jsp.java:221)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
``` | 2012/06/06 | [
"https://Stackoverflow.com/questions/10918526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428913/"
] | * Maybe something deleted `/tmp/.s.PGSQL.5432` socket - a `/tmp/` cleaning service for example.
* Maybe you'll be able to connect using `:host => 'localhost'` as connection argument for `PG::Connection.new()` — it will avoid problems with locating proper path for Unix socket or file permissions problems.
* If you do not want to use `localhost` (it probably is a little slower than a socket) then you can find where it is using `lsof | grep PGSQL` command as operating system administrator — if it is for example `/var/run/postgres/.s.PGSQL.5432` — you would use `:host => '/var/run/postres/'`. | I faced same issue and when I checked server.log I can see it was not able to find that var/postgres folder and some of the conf files.
I did this, however I lost my data in that case
```
brew uninstall postgres
brew install postgres
initdb `brew --prefix`/var/postgres/data -E utf8``
```
That worked well for me and everything back to normal. |
52,442,906 | Here am using this two media query ,as I read ,**First MediaQuery** would affect background-color if size of screen size is equal or less then 340px ,where as **2nd MediaQuery** would effect if size of screen is less then or equal to 360px...
```
@media only screen and (max-width: 340px) {
#arf_recaptcha_hruwj8 iframe {
background-color: blue;
}
}
@media only screen and (max-width: 360px) {
#arf_recaptcha_hruwj8 iframe {
background-color: red;
}
}
```
What i thought is if size is under 340px,**1st query** would effect and because we are under 340px now. not in 360px.But instead of becoming blue ,it remain red only.
1.Could You please explain me this confusion ?
2.How to write media query so that when its **between 341px and 360px** It should be **red** and when **<=** 340px i have to be **blue**. | 2018/09/21 | [
"https://Stackoverflow.com/questions/52442906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10299728/"
] | Just swipe your media query and check it will work for sure.
```
@media only screen and (max-width: 360px) {
iframe {
background-color: red;
}
}
@media only screen and (max-width: 340px) {
iframe {
background-color: blue;
}
}
``` | It's about precedence(CSS Specificity). Last one always applies if you are applying using same selector. As It reads code/file from top to bottom.
```
#idid{
height: 50px;
width: 50px;
background-color: red;
}
@media only screen and (max-width: 360px) {
#idid {
background-color: black;
}
}
@media only screen and (max-width: 340px) {
#idid {
background-color: blue;
}
}
```
JSBin link: [JSBin LInk](https://jsbin.com/rebumasala/edit)
You can also try css specificity here: [CSS Specificity checker](https://specificity.keegan.st/) |
20,035,920 | I am trying to select a single row at random from a table. I am curious as to why the two statements below don't work:
```
select LastName from DataGeneratorNameLast where id = (ABS(CHECKSUM(NewId())) % 3)+1
select LastName from DataGeneratorNameLast where id = cast(Ceiling(RAND(convert(varbinary, newid())) *4) as int)
```
Both statements return, at random, either 1 row, no rows, or multiple rows. For the life of me I can't figure out why. Just adding top 1 to the query only solves the problem of multiple rows - but not of no rows returned.
Yes I could do the same thing by selecting top 1 and ordering by newid(). But the mystery of why this does not work is driving me crazy.
Thoughts on why I get multiple rows back?
Here is the table I am using to select from:
```
Create Table dbo.DataGeneratorNameLast
(
[Id] [int] IDENTITY(1,1) NOT NULL,
LastName varchar(50) NOT NULL,
)
Go
insert into DataGeneratorNameLast (LastName) values ('SMITH')
insert into DataGeneratorNameLast (LastName) values ('JOHNSON')
insert into DataGeneratorNameLast (LastName) values ('Booger')
insert into DataGeneratorNameLast (LastName) values ('Tiger')
``` | 2013/11/17 | [
"https://Stackoverflow.com/questions/20035920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1334903/"
] | The `newid()` gets evaluated for every row it is compared against, generating a different number. To do what you want, you should generate the random value into a variable before the select and then reference the variable.
```
Declare @randId int = (abs(checksum(newid())) % 3) + 1;
select LastName from DataGeneratorNameLast where id = @randId;
```
As Martin said in comments to this. Rand() would behave differently, only being evaluated once per query. | I've Had a similar issue and fixed it by making the ID a PRIMARY KEY.
NEWID() is computed per-row. Without a primary key, there is no access pattern other than a table scan, and the filter is checked for each row, so a different value is computed for each row, and you get however many rows match.
With the key, a seek is available, so the predicate is computed once and used as a search argument for a seek. |
47,950 | I have a photo with a resolution of $1024 \times 768$ which means $786432$ pixels in total. Let's suppose it's a 24-bit color RGB image (so 1 pixel = 3 bytes = 24 bits) and I want to hide information by only modifying the last bit of a color value. What is the maximum number of bytes that I can hide in this photo? | 2017/06/03 | [
"https://crypto.stackexchange.com/questions/47950",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/48055/"
] | This is one of those answers that - depends.
The amount of data that can be hidden inside an image depends on the image. This is one of the concepts that most steganographers miss. We have to go to the definition of steganography. Hiding a secret message with emphasis on the hiding part. That means that a message may or may not be contained within the pixels of an image, creating plausible deniability. If you overtly don't bother to hide it, you might as well traditionally encrypt the message with AES, append it to an email and add "Secret message attached" to the subject heading.
It is also a requirement that the message is compressed /encrypted or generally whitened. Whist encryption is not absolutely necessary for steganography to be successful, the message has to be converted to almost randomly distributed bits. Any uncompressed /unencypted pattern can be easily discovered via heuristic or frequency analysis of the image. After all, image noise is almost uniformly random. If compression is used, the amount of data is becomes contingent on it's type and therefore it depends.
From a capacity and mathematical deniability perspective, the following type of image is optimum:-
[](https://i.stack.imgur.com/ERZMf.png)
It's just random noise in all three colour channels. If the least significant bit contained the compressed message, and the message was textual, you might expect 9 Mbits of capacity£. You may have issues of plausible deniability though if you're sending many of these images without a really good excuse. And they'd have to be in the form of a lossless format, which again is uncommon. Tools like OpenPuff can use lossy formats but that then reduces the message capacity.
This is also a problem image:-[](https://i.stack.imgur.com/UGmaD.png)
Here the whole mountain side is blown out. Image analysis would easily identify manipulation of the least significant bits of the mountainside as they're all meant to be exactly 255,255,255. Almost half of the image can't be used. The steganographic tool would have to determine this. An image with deep shade presents the same problem featuring an expected RGB of 0,0,0 for that part of the image. So again the message size depends.
So you're left with using images like:-
[](https://i.stack.imgur.com/NAOAO.jpg)
In this instance you might get 9-18 Mbits of text$, but you're reduced to sending grainy images all the time for this message capacity. The sensor noise will mask the whitened message, especially if you use less than 1 bit per channel per pixel. And they have to be lossless formats like BMP /JPEG2000 /TIFF or PNG. None of these are particularly common in the social Facebook world, compromising the plausible deniability argument. A lossy format will reduce the message size again.
Algebraically, you can form an equation like:-
capacity = (usable %age) X (encoded bits) x (no.pixels)
which represents the difficult relationship of:-
capacity = F(artistic composition, SNR, image size)
In summary, the message size is very difficult to quantify without a detailed analysis of your photo. Why don't you post it? The most important take away here is that the issue with steganography is not encrypting a message in an image, but being able to deny that there is one in the first place. This is similar to the deniability issues with disc encryption software like TrueCrypt.
£ I'm assuming that a large sample of English prose can be compressed to 2 bits /byte. Capacity = 1024\*768\*3\*4 =~ 9e6 bits where 4 is the compression ratio.
$ In an image this noisy (low SNR), it might be possible to utilise 2 bits per image byte for the message. Or even more? | If you are using an uncompressed format. And using all the lsbs in all color channels. You get 3 bits per pixel. So786432\*3/8 bytes for the entire photo. |
517,935 | Hope someone can help me. I am using c# and I am somewhat new to it.
I am loading a text file into my app and splitting the data on "," I am reading part of string into a `<list>` when the data is read there is a lot of duplicates that vary depending on the txt file that I load. Can someone tell me how to check the and remove any and all duplicates that come up. There is no way of knowing what duplicates will show up as there is infinite possibilities that it could be.
Thanks for the help in advance | 2009/02/05 | [
"https://Stackoverflow.com/questions/517935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | A simple/dirty example follows:
```
public List<string> RemoveDuplicates(List<string> listWithDups)
{
cleanList = new List<string>();
foreach (string s in listWithDups)
{
if (!cleanList.Contains(s))
cleanList.Add(s);
}
return cleanList;
}
```
As a warning: String.Split on very large strings can cause consume huge amounts of memory and cause exceptions. | [Here's](http://www.kirupa.com/net/removingDuplicates.htm) an article with some examples and explanations in C#. Basically, you just keep track of the uniques, and check each element.
Alex |
6,014,438 | I want to display a dialog box on a button click. Here is my code, but it is not working.
```
AlertDialog.Builder builder = new AlertDialog.Builder(
getApplicationContext());
builder.setCancelable(true);
builder.setTitle("Title");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6014438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/746921/"
] | try this,
instead of passing getApplicationContext() pass this;
```
AlertDialog.Builder builder = new AlertDialog.Builder(this);
``` | This is a very old post however I have made a class that I think it can help to keep the code clean
<https://github.com/houmanka/DialogMaker>
You dont need to worry about the OnClickListener all have been taking care of. Just override the methods and you are done. Also I put the support for Standard and Neutral too.
Cheers
Hope it helps someone.
H. |
23,966,209 | Please spare me if this is a newbie question, I'm coming from Java and the concept of pointers just seems foreign to me.
```
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
```
So... the code is telling me that skView is a *pointer* but you can access the object that the pointer is pointing to. Shouldn't the code below the correct way to do it because \*skView means that you are accessing the actual object the pointer is pointing to?
```
*skView.showsFPS = YES;
*skView.showsNodeCount = YES;
```
Here is The C Programming Language guide to pointers
```
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to int */
ip = &x; /* ip now points to x */
y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
ip = &z[0]; /* ip now points to z[0] */
```
It's saying that you need to use that \*ip keyword in order to access the value of the pointer? I'm just confused here... | 2014/05/31 | [
"https://Stackoverflow.com/questions/23966209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3693386/"
] | You are confused by [dot syntax](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW10).
You wrote this:
```
skView.showFPS = YES;
```
You think `skView.showFPS` means “access the field `showFPS` in the `struct` or `union` variable `skView`”, because that's what it means in C (and C++).
But you are mistaken. In that statement, `skView` is a pointer to an Objective-C object. When the compiler sees a dot after a pointer-to-object, it transforms the expression in one of two ways.
If the expression is the left-hand side of an assignment, as in your example, then it transforms the expression to this:
```
[skView setShowFPS:YES];
```
On the other hand, suppose the expression is *not* the left-hand side of an assignment. For example:
```
BOOL showingFPS = skView.showFPS;
```
Then the compiler transforms the expression like this:
```
BOOL showingFPS = [skView showFPS];
```
In other words, the compiler transforms dot notation (when applied to an object pointer) into either a getter or setter message, depending on the context.
I've omitted some details in the explanation. You can override the names of the getter and setter messages if you want, [using an `@property` declaration](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW5).
If you really want to access an instance variable of an object directly, and the declaration of the instance variable is visible to you, you can do this:
```
skView->_showFPS = YES;
```
or equivalently this:
```
(*skView)._showFPS = YES;
```
(Note that `.` binds more tightly than prefix `*`, so you need the parentheses.)
**However, this is almost always a bad idea.** You should almost never access an object's instance variables directly from outside the object. And even inside an object's implementation, it's often better to use properties with accessor methods instead of naked instance variables. | For regular C, you're sort-of correct.
If you were to do something like this:
```
struct my_struct {
int a;
int b;
};
struct my_struct my_object = {1, 2};
struct my_struct * my_ptr = &my_object;
```
then you can access the members by dereferencing the pointer:
```
int n = (*my_ptr).a;
```
or without dereferencing it by using the `->` operator:
```
int n = my_ptr->a;
```
But the dot-syntax you see with Objective-C is something different to this. The compiler knows you're dealing with an Objective-C object, and transforms it into a message call.
It one sense, it's slightly unfortunate that Objective-C uses syntax which is the same as that you can use to access regular C `struct` members, but which actually does something very different. On the other hand, that syntax was introduced precisely because it's familiar to C programmers doing something kinda-sorta similar with `struct`s. Either way, it's important not to confuse the two. |
125,252 | I have recently joined a new company in Estonia which is active in software development, and i have worked there for 1.5 month. I am in a trial period currently (which is 4 month).
I regret about my decision to join this company. The supervisor does not communicate clearly, and then criticizes with bad tone. As a result, I wish to leave the company, as soon as possible, since I am sure the problem is not fixabl.
I have read [this](https://www.job-hunt.org/job_interviews/answering-why-leaving-current-job.shtml), and i know, i should talk positively about my previous company. Also, I read [this question](https://workplace.stackexchange.com/questions/21081/several-short-term-jobs-in-the-resume), which advises to be honest with the next employer, and not hide previous experiences.
I would like to not hide it, but ***i am wondering how to justify it for the next employer?*** And probably, my current employer will not give me a positive recommendation.
One option would be:
* When i joined my current company, it was my best option, but right now, i feel your company can be a better option for me, because the type of product which you develop is more suit to me.
How convincing is it?
What are the other options to explain it? | 2018/12/24 | [
"https://workplace.stackexchange.com/questions/125252",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/94396/"
] | It's still within probation, so it simply wasn't a good fit.
An interview process doesn't always work out perfectly - your new employer will be aware of that.
I would suggest to prepare questions to ask your future manager during the next interview to avoid this happening again. This also shows you've learned from this experience, are interested in having a better result this time, and in general, questions are good to have ready in interviews.
You could, for example, describe one of the situations you found yourself in at this job, and ask your manager how s/he would handle it.
Good luck finding a better job :) | There is a reason you are changing your job. That's the justification.
Build up a list of the things that you shouldn't have had to endure, and then rewrite them again and again until you have the most polite (and forgiving) delivery of the incidents. Admit your shortcomings where they were applicable, and your realization that your efforts to repair them were not noticed. Then seriously consider throwing them all away by replacing them with a summary.
How you present this justification is important.
>
> I joined my current company, it was my best option, but right now, i
> feel your company can be a better option for me, because the type of
> product which you develop is more suit to me
>
>
>
This is a horrible presentation of your justification to leave, it makes you seem fickle. You don't mention the real reasons, instead you said "I changed my mind". If asked, repling with
>
> I will be leaving my current company because my manager attempts to motivate
> through insults and threats. I could stay there, but many others have left
> and I believe that at my current company, I have no upward or lateral path
> out of his team, as he doesn't recognize people for positive
> accomplishments. If you don't mind, I'd prefer focusing on the good I
> can offer you company, and I'd rather not talk about my current manager further.
>
>
>
And then never say another bad word about your employer. Focus on the good you can do (and be recognized for) elsewhere. If pressed, you have the memory of the events to fall back on, remembered in a way that doesn't paint you as a vindictive employee. |
6,311,126 | I understand what the warning says. This is exactly how scoping rules work. I appreciate that some people want a nanny. I don't. How can I disable this warning? | 2011/06/10 | [
"https://Stackoverflow.com/questions/6311126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271594/"
] | ```
NSString *foo;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshadow-ivar"
- (void)myFunctionWithShadow_ivarWarningsIgnored {
NSString *foo = @"...";
NSLog(@"This shouldn't get a warning %@", foo);
}
#pragma clang diagnostic pop
- (void)myFunctionWithShadow_ivarWarningsNotIgnored {
NSString *foo = @"...";
NSLog(@"and this should %@", foo);
}
```
Good Luck! :) | Update for Xcode 8.3 - Bug in compiler yields "Declaration shadows a local variable" in some instances when it intentional... and the nanny panics.
For example in Objective C:
Given
```
typedef BOOL ( ^BoolBoolBlock ) ( BOOL );
```
And the nature of Apple Blocks will make any variable declared in the immediate outer scope to a Block, a global to the block (pseudo globals). This results in the warnings (and errors if warnings == errors in your settings) on the line `BOOL theResult = false;`:
```
- (BoolBoolBlock) boolBoolBlock {
BoolBoolBlock theResult = nil;
theResult = ^BOOL ( unused BOOL is ) {
BOOL theResult = false; // hides (shadows) the outer theResult (a good thing)
/*
call back code goes here,
all variables local in scope to this method are global to the block so be careful
*/
return theResult;
};
return theResult;
}
```
The nanny sees `BoolBoolBlock theResult = nil;` getting shadow-blocked by `BOOL theResult = false;` which is actually intentional for two reasons in this case:
1. by convention in my code ALL return values are theResult no matter what
2. is a positive side effects because I am morally opposed to globals.
In other words this entire construct is setup to block the pseudo global mechanisms of Apple Blocks and put structure on that chaos. Blocking the method's "theResult" from use in the block that the method returns is a *good thing* ... yet the nanny has a hissy fit.
To calm the nanny down (get rid of warnings or possibly errors if you have the discipline to set warnings as errors), you simply make this setting change in your Project File -> Build Settings -> filter on "Other" -> Hidden Local Variables -> change to "No" ... or visually:
[](https://i.stack.imgur.com/iBPU5.png) |
47,183,879 | I have a Custom `UIView` with an XIB. This custom `UIView` has a `UICollectionView` which is connected to an `IBOutlet`. In the view setup, the `UICollectionView` is initialised properly and is not nil.
However in the `cellForItemAtIndexPath` method, I get this error:-
>
> Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key selectorCollectionView.'
>
>
>
If I remove the datasource and delegate, I do not get any error. If I add them Iget an error at this line:-
```
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selectorCell", for: indexPath) as! SelectorCell
```
Please help!
Edit: I have attached screenshots of my setup
[](https://i.stack.imgur.com/VXD9A.png)
[](https://i.stack.imgur.com/52qEK.png)
[](https://i.stack.imgur.com/CeWXw.png)
[](https://i.stack.imgur.com/H1KpO.png)
I have uploaded the project here too <http://www.fast-files.com/getfile.aspx?file=148623> | 2017/11/08 | [
"https://Stackoverflow.com/questions/47183879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2585955/"
] | Maybe a sync issue. Happens sometimes:
1. Try cut outlets loose and reconnect them.
2. Make sure Collection Reusable View identifier is defined in xib file:
[](https://i.stack.imgur.com/OCmjL.png)
3. Make sure collection-view cell's custom class is define in xib file:
[](https://i.stack.imgur.com/bb1nF.png)
**EDIT:**
I dug into your project and here are my findings
UICollectionView should be init' in `awakeFromNib` method (override it):
```
override func awakeFromNib() {
super.awakeFromNib()
let cellNib = UINib(nibName: String(describing: "SelectorCell"), bundle: nil)
selectorCollectionView.register(cellNib, forCellWithReuseIdentifier: "selectorCell")
selectorCollectionView.dataSource = self
selectorCollectionView.delegate = self
}
```
loadViewFromNib should be looking like this (Remove collection view init'):
```
func loadViewFromNib() -> UIView {
let nib = UINib(nibName: "SelectorView", bundle: nil)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
```
Subclass SelectorTableViewCell likewise.
```
class SelectorTableViewCell: UITableViewCell {
@IBOutlet weak var selectorView: SelectorView!
}
```
In `Main.storyboard` - custom class `UITableViewCell` to `SelectorTableViewCell` and connect `SelectorView` inside `contentView` to 'SelectorTableViewCell''s outlet.
That's it i think. [Here](https://ufile.io/m2wt0) is the project: | In our case, the problem was making the wrong connection in Storyboard. Click on the custom class in Storyboard -- not the File Owner -- then connect the IB outlet to the variable in the custom class. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.