No touchpad and cursor issues in ubuntu 14.04

Question: So I just got ubuntu and even when running the live disk I had an issue where I couldn't click most of the time and the mouse would jump left every 3 seconds
I thought once I got installed and updated it would be fine.
Now I can click fine but it still jumps and the touchpad doesn't work at all.
I have an ASUS laptop with touchscreen (which works perfectly) and a logitech g300 mouse.
After some searching I figured out how to do basic stuff with xinput and when I did an xinput list command i got this:
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Logitech Gaming Mouse G300                id=10   [slave  pointer  (2)]
⎜   ↳ USBest Technology SiS HID Touch Controller    id=13   [slave  pointer  (2)]
⎜   ↳ PS/2 Logitech Wheel Mouse                 id=16   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ Logitech Gaming Mouse G300                id=11   [slave  keyboard (3)]
    ↳ USB2.0 UVC HD Webcam                      id=12   [slave  keyboard (3)]
    ↳ Asus WMI hotkeys                          id=14   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=15   [slave  keyboard (3)]

Instantly noticed that I don't have a ps/2 mouse so no idea why but it doesn't detect my touchpad and has added a duplicate generic device for my usb mouse.
If I disable id 16 then everything is golden until i restart and have to repeat the command. How can I fix this up so I can get my touchpad working and the duplicate mouse removed permanently?
Thank you
EDIT 1:
After further attempts I have found that
sudo modprobe -r psmouse

sudo modprobe psmouse proto=imps

Also stops the cursor jumping and removes the generic mouse device (id=16)
But I just found if i then touch the touchpad things get hectic and keyboard stops working properly and mouse clicking doesn't work.
Are there no drivers for the touchpad asus uses or something?
Comment: put the command into /etc/rc.local
Comment: that prevents the cursor jump but doesn't get the touchpad working
Comment: added the line but it doesn't run on startup - still have to enter manually
Comment: Can you add information on which command that is?
Comment: xinput set-prop 16 "Device Enabled" 0
that makes my usb mouse usable again but doesn't fix the issue of no touchpad
Answer: Found a solution that works perfectly as long as you don't use gestures or scrolling etc
Adding the line "psmouse.proto=bare" to the kernel cmd line on boot will, as I understand, emulate the basic moving and clicking tap to click etc using generic ps2 mouse drivers for the touchpad.
There appears to be no drivers or support for the touchpads use in many asus laptops so as far as I can tell this is the best solution until drivers are added.

Permanently Add a Kernel Boot Parameter Log in to the system and start
  a terminal window (Applications->Accessories->Terminal).

In the terminal window at the $ prompt, enter the command: sudo gedit
  /etc/default/grub
Enter your password when prompted by [sudo]. At the line beginning with
  "GRUB_CMDLINE_LINUX_DEFAULT" add psmouse.proto=bare to the text inside the
  double-quotes after the words "quiet splash".
  (Be sure to add a SPACE after "splash" before adding
  your new parameter.) Click the Save button, then close the editor
  window.
In the terminal window at the $ prompt, enter the command: sudo
  update-grub
Restart the system.
Answer: Reinstall the driver package:
sudo apt-get --purge autoremove xserver-xorg-input-synaptics && sudo apt-get install xserver-xorg-input-synaptics

Then reboot.
Comment: tried this and no change - touchpad still doesn't show up in xinput list TT


Why this code which uses windsor Castle doesn't work?

Question: I have an MVC application which uses Windsor everywhere and it works fine everywhere with Windsor Castle, but now I am adding a new code into it and it is not working properly.
I configured Castle with the following code:
<code>   public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<IFileUploadService>().ImplementedBy<FileUploadService>().DependsOn(Parameter.ForKey("x").Eq(
            "test")).LifeStyle.PerWebRequest);
    }
</code>
The FileUploadService is defined as follow:
<code>  public class FileUploadService : IFileUploadService
{

            public FileUploadService(string x)
    {
      // use x
    }
 }
</code>
I am sure that the installer line is calling (Debug shows that the line is runs at the start of application.
I have a Controller which is defined as follow:
<code>   public FileUploadController(IConfiguration Configuration, IFileUploadService fileUploadService)
    {
        this.Configuration = Configuration;
        this.fileUploadService = fileUploadService;
    }
</code>
When I run this application, I am getting this error:
<code>   Can't create component 'FileUploadService' as it has dependencies to be satisfied.
   FileUploadService is waiting for the following dependencies:

    Keys (components with specific keys)
    - x which was not registered.
</code>
What is the problem? I have similar code which they are working.
Answer: I found the problem:
The above code works on Windsor 3.x but my application uses 2.5.
the correct way of doing this in version 2.5 is as follow:
<code>  container.Register(Component.For<IFileUploadService>().ImplementedBy<FileUploadService>().Parameters(Parameter.ForKey("x").Eq(
        "test")).LifeStyle.PerWebRequest);
</code>


Excel 1004 error vlookup

Question: i have this line:
LArticol.Caption = Application.WorksheetFunction.VLookup(Serie.Value,[TEST], 2, 0)

And my error is Run-time error 1004
I've try with
LArticol.Caption = Application.WorksheetFunction.VLookup(Serie.Value,ThisWorkbook.Sheets("ELECTRICE").Range("TEST"), 2, 0)

but...same thing
i really need help
CODE:
Private Sub Serie_Change()
    LArticol.Caption = Application.WorksheetFunction.VLookup(Serie.Value,ThisWorkbook.Sheets("ELECTRICE").Range("TEST"), 2, 0) End Sub

    Private Sub UserForm_Initialize()
Call Serii
End Sub

Serii module
Sub Serii()
Dim Ssheet As Worksheet
Set Ssheet =
ThisWorkbook.Sheets("ELECTRICE")
If Ssheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
    sslr = 3 Else
    sslr = Ssheet.Cells(Rows.Count, 1).End(xlUp).Row
End If
For X = 3 To sslr
    UserForm1.Serie.AddItem Ssheet.Cells(X, 1)
Next X
End Sub

Comment: How is `Serie` declared? Is that a single cell?
Comment: Are you sure that the value in `Serie` is located in the first column of `Test`?  If it is not in there it will through an error.
Comment: Believe your code looks good. Can you post how you've declared Serie as nbayly asked?
Comment: Please do not put code in the comments.  Please edit your original post instead.
Comment: @ScottCraner sorry for the inconvenience
Comment: It looks like `Serie` is a control object on the UserForm. This code will definitely 1004 if the value is not found in the range specified by the VLOOKUP function.
Comment: Serie is combobox
Comment: @DavidZemens the value from "Serie.Value" show me what value i've in the cell but...it's something wrong at range...i don't know..
Comment: If you do `Debug.Print ThisWorkbook.Sheets("ELECTRICE").Range("TEST").Address`, what output do you get?
Comment: @DavidZemens if i'll put this above _"LArticol.Caption = Application.WorksheetFunction.VLookup(Serie.Value, ThisWorkbook.Sheets("ELECTRICE").Range("Test"), 2, 0)"_ ?
Comment: Yes, you put it above that line and step through code using F8 key. Or you can do `?ThisWorkbook.Sheets("ELECTRICE").Range("TEST").Address` in the Immediate pane in the VBE.
Comment: same thing...error 1004
Comment: That will suggest that no such range named "Test" exists in the worksheet.
Comment: but is it...... this is in name manager: name-TEST
Refers to:
=ELECTRICE!$A$3:$H$1048576
Comment: Does simple `Debug.Print Range("Test").Address` produce the same 1004?
Comment: And just to be certain, the error raises on the `Debug` statement? Also, please include the *full text* from Error Description.
Answer: Is ELECTRICE the active sheet? Application.WorksheetFunction.VLookup operates on the active sheet unless you tell it otherwise.
Also,
ThisWorkbook.Sheets("ELECTRICE").Range("TEST")

will return $A$3:$H$1048576. If you want it to return ELECTRICE!$A$3:$H$1048576 then you should use
ThisWorkbook.Names("TEST").RefersTo

Keep in mind too that this requires the named range's scope to be defined as Workbook and not a specific sheet.
Comment: _Run-Time ERROR '1004'_
_Unable to get the vlookup propery of the worksheetfunction class_

I've try "ThisWorkbook.Sheets("ELECTRICE").Range("TEST").Address" too, the "ELECTRICE" is sheet1...all is right...but i don't know how to get the value from another chell in other type...all i get is error 1004...

Excel 1004 error vlookup


Array to string conversion error in resource controller in laravel8

Question: I am using laravel8. I created resource controller. when I am using get method for that then it is giving error.
My route is:
Route::resource('/details', [App\Http\Controllers\detailController::class]);

In resource controller, I have index method:
 public function index()
{
   echo 'dd';
}

when I run http://127.0.0.1:8000/details
I am getting error.
ErrorException
 Array to string conversion
 http://127.0.0.1:8000/details

Answer: You just have to remove array syntax form the controller name
Route::resource('/details', App\Http\Controllers\detailController::class);


how to start a plain text http2 communication directly?

Question: I am using netty client, and I'm sure the server support http/2. Can I start a plain text http/2 request directly? I don't want to send a http/1.1 request, and upgrade to http/2 with 101 return code.
Comment: What error message do you get when you try?
Comment: I just follow the example:
DefaultFullHttpRequest upgradeRequest =
                    new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
ctx.writeAndFlush(upgradeRequest);

It seems that there is no "HttpVersion.HTTP_2_0".

If I set a buffer with magic word: "PRI...":
ctx.writeAndFlush(Http2CodecUtil.connectionPrefaceBuf());
Nothing will be sent.
Comment: As far as I know http/2 is only available via TLS because the only way to establish a connection works via ALPN (Application-Layer Protocol Negotiation) which is an extension to TLS.
Comment: http/2 can run over plain text. Infact I have done it. I just want to skip: http/1.1 request,  response 101 (Switching Protocols).
Answer: What you are asking for is known as 'h2c with prior knowledge': the client already knows the server supports HTTP/2 and can directly start talking HTTP/2 without first negotiating.
Not all servers support this, and some will require opening up a separate port specifically for this purpose.
I'm not sure how to configure the Netty client to do this, but you could look at the sources for the Netty gRPC client (https://github.com/grpc/grpc-java/tree/master/netty/src/main/java/io/grpc/netty) for inspiration: this client can be configured to directly start talking HTTP/2 by choosing NegotiationType.PLAINTEXT.


Can vim use the system clipboard(s) by default?

Question: I am running into several problems because vim's tabs are, for the lack of a better term, god awful. I want to start using multiple Gnome tabs instead, each with a different instance of vim. Everything should work fine, however, only the system buffer + can be used to share text. This makes all the commands two key strokes longer:
y y becomes " + y y
y w becomes " + y w
d ' k becomes " + d ' k
This is especially so when one considers that a simply yank/paste operation like so
y y p
becomes
" + y y " + p
Is there anyway to instruct vim to always use the system clipboard(s)?
EDIT see Here for more information on using multiple instances of vim across Gnome Terminal Tabs
Comment: whoever voted to close this, could you please clarify why you think this is not a good question.
Comment: No it is true Vim does not just fit into what is now the standard workflow with out some nudging and the problems are in fact God awful to people who learned programming after things stopped being really really god awful.
Comment: @puk:  Why the need to call Vim's tabs "godawful" or "useless" just because they don't fit your idiosyncratic workflow?  They're obviously useful; a huge number of people use and (enjoy using) Vim's tabs to make editing easier.  Having said that, it would be an interesting project to write a plugin that adds functionality you describe in other SO question.  E.g., each tab could have a `t:buffers` variable to hold buffer list for each tab and a `tabbuffers` navigation and other operations could be created with restriction to buffers only in a tab's `t:buffers` list.
Comment: Can you explain why you don't like vim's tabs? Also, some people do not recommend to have more than one vim instance: [One Vim ... just one](http://vimeo.com/4446112)
Comment: @mMontu I don't want 1 bufer/tab, but I still want to be able to group my buffers in different tabs. Vim does not allow this. All buffers are global. I discuss it here http://stackoverflow.com/questions/8756459/is-there-any-plugin-way-to-manage-multiple-projects-in-vim
Comment: possible duplicate of [How to make vim paste from (and copy to) system's clipboard?](http://stackoverflow.com/questions/11489428/how-to-make-vim-paste-from-and-copy-to-systems-clipboard)
Answer: I found a solution to my problem vim.wikia.com: Accessing the system clipboard. If you add the following to your .vimrc file
set clipboard=unnamedplus

for linux or
set clipboard=unnamed

for Windows.
Everything you yank in vim will go to the unnamed register, and vice versa.
Comment: I believe you can use both at the same time, like:
`set clipboard=unnamed,unnamedplus`.
Mind you VIM has to be build with +X11, +clipboard and +xterm_clipboard. On windows it goes like this by default, I suppose.
Comment: Note that this is not a perfect solution, if you copy a line outside of vim, it's not the same as yanking `yy`, so if you paste it `p` it will get pasted in place, not on the next `p` or previous `P` line
Comment: @puk you echo my sentiment. I have gotten used to just specifying the register. On occasion I even just `:let @+=@"` or similar
Comment: @sehe what does `:let @+=@` do?
Comment: @puk nothing! `:let @a=@b` assigns the contents of _register_ b to _register_ a, though. Next, _register_ `+` is the X clipboard and _register_ `"` is the _unnamed register_ (used by default)
Comment: On Arch-derivatives, you get the clipboard enabled CLI `vim` when installing `gvim` or another GUI version of `vim` (see [note](https://wiki.archlinux.org/index.php/Vim#Installation)).
Comment: While this is the correct solution, it is confusing because it uses the term "unnamed register" wrong (or at least in a confusing way). The unnamed register is `"`, and that's where things you yank/delete go by default without any configuration. Setting the `unnamedplus` option makes it so that everything that goes to the unnamed register also goes to the `+` register (i.e., the system clipboard) and vice versa.
Comment: In order to get this working for me, I had to use `unnamed` for my vim in terminal and `unnamedplus` for my neovim in vscode.
Answer: By the way, if you just want to use the terminal's native copy/paste handling, suggest setting
:se mouse-=a

and just doubleclick/rightclick as you're used to in your terminal.
That said, I love vim split windows and the fact that you can use the mouse to drag window dividers/position the cursor (heresy!). That requires mouse+=a... (and will work over ssh/screen sessions as well!).
I'm used to doing things like this instead:
:%retab|%>|%y+|u

and have commands like that on recall. Note that the "+ register is coded in the command line. To copy the last visual selection to the clipboard,
:*y+

or
:'<,`>y+

Comment: can you please explain in a little more detail what `:se mouse-=a` does. Personally I'm not a big fan of the windows, I prefer the buffers. Buffers > windows >>>tabs
Comment: @puk: I've started to appreciate windows for diffmode + quickfix. I started to appreciate tabs for multiple diff-sets (e.g. `:tabedit a|vert diffsplit b`). I do use `:set guioptions=agim switchbuf=usetab`. To remove the UI suckiness and slowness
Comment: having done what you suggest for a long time, I highly recommend puk's answer from above: `set clipboard=unnamed[plus]`
Comment: @Millimetric I'm set in my ways (I've come to rely on separate clipboards and hate non-standard settings in my vim - too many different systems). ***But***: on your recommendation, I will give it a whirl for a good few weeks. Cheers
Answer: Possible workaround:
"Ctrl-c to copy in + buffer from visual mode
vmap <C-c> "+y

"Ctrl-p to paste from the + register in cmd mode
map <C-v> "+p

"Ctrl-p to paste from the + register while editing
imap <C-v> <esc><C-v>

Comment: I thought about that, but then you'd need a new shortcut for `yw`, `y{`, `y}`, `y%`, `D`...
Comment: I found a keyboard with just enough buttons http://rlv.zcache.com/piano_organ_keyboard_birthday_greeting_card-p137438190127093559zvjk9_400.jpg
Comment: If you're going to use this solution, consider using vnoremap, noremap, and inoremap respectively.


ValueError: Found input variables with inconsistent numbers of samples: [100, 7]

Question: Currently trying to have the program guess the animal based on the feature that is included in the zoo database.
 When I run this code it gets the error ''ValueError: Found input variables with inconsistent numbers of samples: [100, 7]''. It shows the error happens on this line ''X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)''
def zoo_that():
    zoodatabase = pd.read_csv('C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/zoo.csv', header = 0)
    classtypes = pd.read_csv('C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/class.csv',header = 0,)
    zoodatabase_v2 = zoodatabase.merge(classtypes,how = 'left',left_on = 'class_type',right_on = 'Class_Number')
    X = zoodatabase_v2.loc[:, 'hair':'catsize']
    Y = zoodatabase_v2.loc[:, 'class_type':'Class_Number']
    testing_size = 0.2
    seed = 2
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

    # Test options and evaluation metric|
    scoring = 'accuracy'

    models = []
    models.append(('LR', LogisticRegression()))
    models.append(('LDA', LinearDiscriminantAnalysis()))
    models.append(('KNN', KNeighborsClassifier()))
    models.append(('CART', DecisionTreeClassifier()))
    models.append(('NB', GaussianNB()))
    models.append(('SVM', SVC()))
    # evaluate each model in turn
    results = []
    names = []
    for name, model in models:
        kfold = model_selection.KFold(n_splits=4, random_state=seed)
        cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
        results.append(cv_results)
        names.append(name)
        msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
        print(msg)

    # Make predictions on validation dataset
    LR = LogisticRegression()
    LR.fit(X_train, Y_train)
    predictions = LR.predict(X_validation)
    print("Accuracy score\n",accuracy_score(Y_validation, predictions))
    print("Confusion matrix\n",confusion_matrix(Y_validation, predictions))
    print("Final Report\n",classification_report(Y_validation, predictions))
    print(scoring)

zoo_that()
Traceback (most recent call last):

  File "<ipython-input-20-396e334d1676>", line 1, in <module>
    zoo_that()

  File "C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/Final Submission.py", line 35, in zoo_that
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

  File "D:\Anaconda\lib\site-packages\sklearn\model_selection\_split.py", line 2031, in train_test_split
    arrays = indexable(*arrays)

  File "D:\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 229, in indexable
    check_consistent_length(*result)

  File "D:\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 204, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])

ValueError: Found input variables with inconsistent numbers of samples: [100, 7]

Picture of the files
  [1]: https://i.stack.imgur.com/OaJmO.jpg [This is the Class Csv][1]
  [2]: https://i.stack.imgur.com/FL0by.jpg [This is the Zoo Csv][2]
Comment: Could you show us a snippet of the data in the zoo.csv and class.csv files please?
Answer: The problem is with this part:
X = zoodatabase_v2.loc[1:101,'hair':'catsize']
Y = zoodatabase_v2.loc[0:6,'Class_Type':'Animal_Names']

X is a DataFrame with length 100 (1:101), and Y is a Series with length 6. To train a model (supervised learning), you need to give target labels for ALL input records. Also, you need to give a single target label, whereas currently it looks as if you are giving 2 ('Animal_Names' and 'Class_Type'). If you remove the subsetting, it should work. i.e.
X = zoodatabase_v2.loc[:, 'hair':'catsize']
Y = zoodatabase_v2.loc[:, 'Class_Type']

should work fine.
Comment: I got this error when I tried to run this ValueError: bad input shape (60, 2)
Comment: What is it that you are trying to predict? The class type or the animal name? (Updated my answer to work for guessing the animal name.
Comment: I am trying to predict class type
Comment: Updated my answer to predict class type
Comment: Can you please mark the answer as the "Accepted Solution"? :)


How can we make jquery terminal screen adjustable?

Question: I am using jquery terminal to run commands in my project, in that I want to make its screen adjustable, I am unable to do that, can anybody help me?
Comment: Welcome to Stackoverflow. Please read this carefully before asking https://stackoverflow.com/help/on-topic
Comment: what you mean by adjustable?
Comment: adjustable means that I want to change its width from my mouse pointer, just like we do in any popup, to make it large or smaller in width
Answer: You can create jQuery Terminal inside jQuery UI dialog or maybe use resizable from jQuery UI

$('.wrapper').resizable();
$('.term').terminal();

.wrapper {
    width: 400px;
    height: 200px;
}
.term {
    height: 100%;
}

codepen demo
Comment: Thank you so much, I will try this and will let you know the result.
Comment: I also used handles, because I wanted it from left side. https://stackoverflow.com/questions/6871558/jquery-ui-resizable-left-bottom-handle-to-resize
Comment: @NitishaTambi if the answer solve your question you can mark it as the right answer by clicking check mark icon.


The Requested URL Was not found on this server. Problem with cpanel while hosting React app

Question: Hy fellow Developers,
I have added homepage to my package.json
I did make a build then zipped it and then uploaded it in public_html folder in cpanel
then unzipped it, and removed all the files other than the files of build folder, my public_html folder, looks like this
As i go to my website i.e strea.com everything woks fine, but as soon as i try to go on any other links like /contact it gives errors
The requested URL was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Please help me rectify this situation.
If you need any additional information please do let me know
Answer: The solution to that is to change your routing method from BrowserRouter to HashRouter.
Let me know if you encounter any other issue.
Comment: not a good answer, your answer suggests that REACT SHOULD REMOVE BrowserRouter altogether


How NSSet compares values in array to remove duplicates when using SetWithArray

Question: I have NSArray and I want to remove duplicates from it. I know that using this method
    [NSSet setWithArray:[arrAllValues valueForKey:@"value"]]
I also know that it invokes method specified in valueForKey parameter. But I don't know what method NSSet invokes to compare objects in array.
    My problem is that I want to compare property named "value", but I want to return array of the object that contains the property and not the property. Can I do that?
Thanks !!!
Comment: Please refer this question: http://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objective-c
Answer: It compares them using the NSObject protocol reference method:
<code>- (BOOL)isEqual:(id)anObject
</code>
therefore, you can override this method in your class to implement the desired behavior, as a note just like you would do it in Java, you should also override hash.
Comment: Thanks for the Answer Oscar!!! It worked!! I just didn't know what methods to override!!


How to constrain multiple generic types?

Question: Here's a simple syntax question (I hope), I know how to constrain one generic type using the where clause, but how to constrain two generic types?
Maybe the easiest way is to write down what my best guess as to the syntax was.
public class GenericDaoGetByIdTests<TDao, TComponent> : BaseDaoTests
  where TDao : IDao<TComponent>, TComponent : EDC2ORMComponent {
    public void GetByIdTest(int id) { }
}

This gives me an error.  Anyone know what the proper syntax is?
Answer: Use two 'where' keywords, for example I have a declaration like this:
public interface IParentNodeT<TChild, TSelf>
    where TChild : IChildNodeT<TSelf, TChild>, INodeT<TChild>
    where TSelf : IParentNodeT<TChild, TSelf>
{
    TChild childRoot { get; set; }
}

Answer: This should work:
public class GenericDaoGetByIdTests<TDao, TComponent> : BaseDaoTests
  where TDao : IDao<TComponent> where TComponent : EDC2ORMComponent {
    public void GetByIdTest(int id) { }
}

you just repeat the where.


How do I change the behavior of the Nautilus popup search box?

Question: Nautilus has a specific function, which name I don't know, but the behavior is:

Typing a symbol from the keyboard opens a small box on the lower right part of the window and selects the first relevant file or folder in the current folder in the window
typing more symbols selects the relevant file or folder  or no selection if the searched string doesn't exist in the current folder.
The backspace key deletes the last symbol used and again selects the appropriate file or folder.

Now this was in Ubuntu natty 11.04, in Oneiric 11.10 the behavior is like in the following:

Typing a symbol selects relevant file/folder, i.e. same as in natty.
typing more symbols... - the same as in natty
Backspace opens the upper directory in the tree and the small search box in lower right corner stays with the last searched string.
Typing anything from the keyboard adds more to that string even in the new folder and the only way to search from the beginning is to select the string /with the mouse/ and delete it with del button /backspace returns in upper folder in the tree/ and type again to search.

Not very user friendly and very annoying :-)
Now, what should I do? Is there any work around and how can I appropriately file this as a bug?
Answer: It looks like this is a known issue and a fix is in progress. Let's hope it is released soon!
Comment: Was fixed & no longer an issue


Django 2.2 | Cookie with name "sessionid" is not create while anonymous user open site

Question: I'm using PostgreSQL with Django 2.2.
I'm trying to set cart id on the session but every time session gets none value while the user login or not. Even if I tried to open website in incognito mode sessionid cookie is not create with anonymous users. Because of that every time it create a new cart where user is login or not.
views.py
def index(request):
    context = {}
    res = getCart(request)
    context.update(res)
    return render(request, 'index.html', context)

def getCart(request):
    lines = []
    order = {}
    cartQuantity = 0
    if request.session.get('cart'):
        cart = Cart.objects.get(pk=request.session.get('cart'),state='draft')
        lines = cart.cartlines_set.all()
        cartQuantity = int(cart.getQuantity)
    if not order:
        cart = Cart.objects.create(customer_id=request.user, state='draft')
        request.session['cart'] = cart.id
        lines = cart.cartlines_set.all()
        cartQuantity = int(cart.getQuantity)

    return {'lines': lines, 'cart':cart, 'cartQuantity': cartQuantity}

** url.py **
urlpatterns = [
    path('', shop, name="shop"),
]

settings.py
SESSION_SAVE_EVERY_REQUEST = True
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Custom moduels
    'cart.apps.cartConfig',
]

Answer: It happens because the passing args into the function works in such a way.
You're modifying a copy of the request, but the view returns not modified one.
Closest to your case example:
request = "I'm a true request"
def change_request(request):
    request = "I want to change request"
    return {'foo': 'bar'}

change_request(request)

{'foo': 'bar'}
print(request)

"I'm a true request"
As you can see it's not modified.
Solution
Return the same request instance (that you want to modify) as you have got from args.
Example:
def view_name(request):
    payload = {
        # your data
    }
    request.session['foo'] = 'bar'
    return render(request, 'index.html', payload)

Comment: Thanks for an answer that help me but what is the best way to update request objects from other methods? Just like in this scenario.
Comment: just return you updated object, like request = func_that_updates_request(request). Such function needs to return modified request.


'GROUPING SETS ( ) ' function groups the fields in the reverse order in SQL Server

Question: select continent , country , city , sum(units_sold)
from Sales
group by GROUPING SETS (continent,country,city)

While executing the above query, the result set is first grouped by city, country and then continent.
I expected the result set to be grouped by continent first, country second and city third , as I have specified in the grouping sets. But the query returns the resultset in reversed order.enter image description here
Comment: Demonstrate what your expected results are, the *image* (which again, is not helpful), is correct for what you asked; you asked to group your data in 3 different sets: one set `continent`, another set on  `country` and the last set on `city`.
Comment: [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Answer: Order in SQL is never guaranteed, the server is always free to order it as it sees fit, unless you specify ORDER BY.
You can use the GROUPING function to determine which columns are grouped. It will return 1 if the column has been rolled up.
SELECT
  continent,
  country,
  city,
  SUM(units_sold)
FROM Sales
GROUP BY GROUPING SETS (
  (continent),
  (country),
  (city)
)
ORDER BY
  GROUPING(continent),
  continent,
  GROUPING(country),
  country,
  GROUPING(city),
  city;


Android program with unused Swing code inside

Question: I am designing a new software which is going to be Swing based Java application. I am currently completely decoupled the GUI layer and business layer hoping to porting my application to Android someday. When I am porting it to Android I am planing to just write a new inheritance to my GUIAbstractFactory.
Will Android API build my code base which has unused Swing dependencies or I will be forced to delete those classes who reference Swing?
Answer: It should compile fine so long as the rt.jar of a J2SE is on the compilation class-path.
Comment: Wow!  It's nice to have someone thank me for edits, a lot of people complain..  :)
Comment: Well, I did write "programram" instead of writing "program" :) and forgot to spell check. In my opinion you prevented utter shame of me,a senior software programmer who can not spell "program".


Access website password protected with credentials in the http link

Question: I have a website "A" that is password protected with credentials stored in the DB and another website "B" with a single set of credentials stored in the web.config.
I would like to give access to site B to the users of site A after they login.
I know I should change the way the credentials are handled in site "B" and manage one set of shared credentials for both sites but I am wondering if there is a way to access site "B" from site "A" with a link without having to recode the access credentials logic of site"B". Is it possible to pass the credentials within the link between two asp.net websites?
Answer: It is possible to use sign sign on credentials. You need to set machinekeys in the Config to be the same as a start. You should then be able to share auth tickets IIRC.
Have a read through this.
http://msdn.microsoft.com/en-us/library/ms972971.aspx
Comment: Thank you. It looks quite interesting. I will study the reference.
Answer: I suppose that what you ask cannot be done. Site B wants to check the user's credentials in order to provide him with the respective priveleges (this is the meaning of authentication). This is not possible if site B does not have access to the credentials repository of A.
On the other hand, if B has access to the A's users repositoty, you could just use it for users to authenticate directly in site B, building the respective functionality in site B. If A is using normal ASP.NET membership API, this should be fairly easy. Otherwise, you could implement your own membership API provider, using any kind of custom credentials repository. You could check this for ASP.NET Membership API.
Hope I helped!
Comment: Thanks but as I said in my question, before I start coding the access logic of site B I like to investigate on alternatives. Otherwise I could simply rebuild the access on site B and share the same database of site A for credentials. The answer from ThelTGuy could be a viable alternative.


Drawing straight line graph with large scale

Question: I was given the equation:
$$y(x) = 10000x + 150000 ,~~ 0 \lt x \lt 60$$
and was asked to draw the graph.
I know that it is a positive straight line intercepting through $150000$, but I don't know how to represent this on a graph as the scale is so large. When I tried to emulate it on my calculator I couldn't see the graph (presumably because its so large).
So how would I show this on a graph?
Comment: Shouldn't it be like this: http://www.wolframalpha.com/input/?i=plot+10000+x+%2B+150000%2C+%7Bx%2C+0%2C+60%7D
Answer: To graph the function, go to the "Window" screen. Set the $y$ limits to $y_{min}=-200,000,y_{max}=200,000$. Also, set the $x$ limits to $x_{min}=0,x_{max}=60$. Then, your graph will appear as a straight line intercepting through $150,000$.
Comment: and what about the condition 0 < x < 60?
Comment: @joe See my edited answer.
Comment: When drawing this graph on paper should I scale it down? if not how would i set up each axis?
Comment: @joe Draw the graph as it appears on the calculator, however, be sure to write the scale, i.e., $y$ ranges from $-200,000$ to $200,000$, and $x$ ranges from $0$ to $60$.
Answer: Hint
If you plot this on paper, use 1 cm to represent 5 units along the $x$ axis (this will make a 12 cm $x$ axis) and use 1 cm to represent 50000 units along the $y$ axis (this will make a 15 cm $y$ axis).


Not receiving any new missions in grand theft auto 5

Question: I seem to be stuck in a part of the game, no missions are showing on the radar.
I have just finished a mission with a plane and a submarine,
Then in the next heist as Trevor I took masks,a garbage truck,and uniforms.
And now there are no missions to do.
What do I do?
Comment: You might need to swap characters. Try running around on Franklin or Michael for a bit. Trevor might start the new mission by phoning one of them, but that can't happen while you play him.
Answer: I encountered this problem myself aswell, The thing i did to fix this was to just walk/drive around with all 3 characters.
When doing this you will usually be contacted by someone that will give you further information (giving you another objective).


javascript date issue - 0 into 1?

Question: I've created a little script for displaying a calendar but the month is 1 digit out. EG June displays 5 instead of 6.
take a look here: http://jsfiddle.net/jwoodcreative/vgTN7/
What am I doing wrong...?
Answer: In JavaScript months start from 0. Just add 1 to it. From the MDN article (emphasis added):

The value returned by getMonth is an integer between 0 and 11. 0
  corresponds to January, 1 to February, and so on.

This is defined in the ECMAScript specification:

Months are identified by an integer in the range 0 to 11, inclusive.

Here's an updated fiddle.
Comment: Thanks, that's solved it. Will accept answer in 10 mins (wont let medo it yet)
Answer: Check out the docs https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

month
      Integer value representing the month, beginning with 0 for January to 11 for December.

javascript date issue - 0 into 1?


How to use Parseval' identity( Plancherel)?

Question: (May be this is very basic question for MO)
Let $f\in L^{2} (\mathbb R)$ with $\lim_{t\to \pm \infty} f(t)=0.$ Put
$$F_{n} (x)= \frac{1}{2\pi} \int_{-n}^{n}e^{itx} f(t) dt \ (n=1,2,...)$$
Fix $\alpha \in (0, \infty)$ and we define $H_{n}(x)$ as follows:
$$\frac{1}{2\pi}\int_{-n}^{n} e^{itx} (f(t+\alpha) -f(t-\alpha))dt = (e^{-i\alpha x}- e^{i\alpha x})F_{n}(x) + H_{n}(x)$$

My Question: Can we expect to prove: $H_{n}(x) \to 0$ as $n\to \infty$ in $L^{2}(\mathbb R)$ ?

I guess some where we need to use Parseval' identity( Plancherel); but I am bit confused, how to use it.
Thanks
Comment: Please do not ask questions simultaneously on Math.StackExchange and on MathOverflow. Pick just one site and wait a few days for an answer. Posting simultaneously to both sites leads to duplication of effort and is frowned upon by both communities. Finally, your question is certainly more appropriate at Math.StackExchange.
Comment: I am migrating the question to MSE, with an additional request that the question be closed there as a duplicate. Cross-posting is very much frowned upon.
Answer: As proposed in (How to use Parseval' s( Plancherel' s) identity?), You can use that
$$\int_{-n}^ne^{itx} f(t+α)\,dt=\int_{-n+α}^{n+α}e^{i(t-α)x}f(t)\,dt
=e^{-iαx}\int_{-n+α}^{n+α}e^{itx}f(t)\,dt$$
etc. to reduce the expression for $H_n$ to integrals over the segments $[\pm n-α,\pm n+α]$. Then apply the asymptotic behavior of $f$ for large arguments.


jQuery mouseleave fast

Question: I give here a simplified case. I have 2 divs one over the other. When mouseenter the top one (blue) fadeOut and the one behind (red) fadeIn. When mouseleeve it all comes to the original situation.
It works well. The only problem comes when the user mouseleeve fast, probably when the top div (blue) is still there. How can it come to the original situation in this case?
You can check your answer here: http://jsfiddle.net/Narcis/ywTBe/
HTML:

CSS:
#blue{
    position:absolute;
    top:100px; left:100px;
    width:100px; height:100px;
    background:blue;
    z-index:1;
}

#red{
    position:absolute;
    top:100px; left:100px;
    width:100px; height:100px;
    background:red;
    z-index:0;
}

JQUERY:
$(function () {
    $("#blue").mouseenter(function () {
        $("#blue").fadeOut("normal");
        $("#red").fadeIn();
    });

    $("#red").mouseleave(function () {
        $("#blue").fadeIn("normal");
        $("#red").fadeOut();
    });
})

Answer: Here is the jsfiddle: http://jsfiddle.net/JZSRk/
        $(function(){
        $("#blue").mouseenter(function() {
            $("#blue").fadeOut("normal");
            $("#red").fadeIn();
        });
        $("#blue").mouseleave(function() {
            $("#blue").fadeIn("normal");
            $("#red").fadeOut();
        });
        })

Comment: try your fiddle, if you mouseleave fast, (before the red fadeIn) it does not come back
Answer: You can make it work like this -
Html

Js
$(function () {
    $("#wrapper").mouseenter(function () {
        $("#blue").stop(true, true).fadeOut("normal");
        $("#red").stop(true, true).fadeIn();
    });

    $("#wrapper").mouseleave(function () {
        $("#blue").stop(true, true).fadeIn("normal");
        $("#red").stop(true, true).fadeOut();
    });
});

Demo ---> http://jsfiddle.net/ywTBe/1/

jQuery mouseleave fast


Android background services and alarms

Question: Recently encountered with a problem when Android 4.4 killed my app's Service and AlarmManager when device going into a sleep mode (START_STICKY param doesn't helps). I tried a lot of things, but nothing works as I need.
In my task manager app I always see a lot of processes of non-default apps such as Google+, Skype, Google Drive end some else that working in real time and never were killed by the system.
I want to ask more experienced developers how to create Service or Alarm that will not be killed by the system or this is impossible on some Android assemblies?
Answer: This is not a kind of programming answer, because the reason of not working is not inside Your code. I stumpled about that too before two weeks. My service allways stopped and I never understood why, until I detected the "Power Saving" Option inside the settings (my device Huawei Ascend Mate 7) Navigate:
Settings --> Power Saving --> on the top Power Info --> keep running after screen off.
Here You can enable or disable apps, that should run in the background if the screen goes to sleep.
Also if it is not the correct answer, It´s too long for a comment, and maybe it helps others with this problem.
Comment: Oh my God... I spent on this problem one day, I tried a lot of things but  solution was in Power Saving mode whitelist ))))
Comment: :) ...... I was also suprised with my problem. Sometimes we should also read manuals from our devices :)
Answer: We do this with our existing app to keep the user within our app even if the home button is hit.  I modified the code a little so I could post an example. We are running Android 4.4.3.
You can keep your activity running by running a background service.  You keep the task in the forefront of the device. First, get the task Id and start the service
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       int taskID = getTaskId();
       Intent intent = new Intent(this, ServiceKeepInApp.class);
       intent.putExtra("TaskID", taskId);
       startService(intent);
    }
 }

Your service class, keep alive with a handler:
public class ServiceKeepInApp extends Service {

private boolean sendHandler = false;
private int taskID = -1;

Handler taskHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        ActivityManager activityManager = (ActivityManager)getSystemService(Service.ACTIVITY_SERVICE);
        if (taskID != -1) {
          if (activityManager.getRecentTasks(2, 0).get(0).id != taskID) {
              activityManager.moveTaskToFront(taskID, 0);
          }
        }

        if (sendHandler) {
            taskHandler.sendEmptyMessageDelayed(0, 1000);
        }
    }
};

@Override
public void onCreate() {
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
       taskID = extras.getInt("TaskID");
    }
    super.onCreate();
    sendHandler = true;
    taskHandler.sendEmptyMessage(0);
}

@Override
public void onDestroy() {
    super.onDestroy();
    sendHandler = false;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

This is untested code - so buyer beware.
Comment: This answer is off topic but interesting and I will save it for the future. Can U told me for what task did U write this code?
Comment: @AskQuestion Sure, we are doing electronic diary data tracking on Nexus  7 tablets and we needed to keep the app alive and running at all times and not let them venture onto other apps.

Android background services and alarms


Difference between arguments with and without quotes for a Perl script in csh

Question: Is there a difference between arguments with and without quotes for a Perl script?
Eg. myscript -option "SomeValue" vs myscript -option SomeValue
The shell is csh
Comment: That depends on your shell. Look for 'quoting' or something similar in its manual.
Comment: edited  and added csh as shell after @Biffen comment. In csh they are behaving in a similar fashion.
Comment: If the arguments only alpha-numeric than there is no difference. But if the arguments contains -- for example space, e.g.: -option "Some Value" then it will be different.
Answer: If the argument has space, then while parsing, if the srgument is in quotes, the entire value will be picked up while using $ARGV[$i] where $i refers to the position of the argument. Else the value only up to the first space will be picked up.


CGPath with outline

Question: I am trying to draw a CGPath that has a stroke for it's stroke.
Basically I want a draw a line using CGPath. I then want to go back and draw lines on both sides of the last CGPath giving it the effect that it is outlines.
This line can bend and turn in any way but I always need the two lines on the outside to follow.

EDIT: I need to be able to make the middle of the line transparent but the outlines solid black.
Comment: refer this url http://stackoverflow.com/questions/5434874/draw-a-line-by-using-cgpath
Answer: Use CGPathCreateCopyByStrokingPath to create a new path by stroking your old path at some width. Then draw your new path using kCGPathFillStroke.
- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicsGetCurrentContext();

  CGMutablePathRef path = CGPathCreateMutable();
  CGPathMoveToPoint(path, NULL, 50, 50);
  CGPathAddLineToPoint(path, NULL, 200, 200);

  CGPathRef thickPath = CGPathCreateCopyByStrokingPath(path, NULL, 10, kCGLineCapButt, kCGLineJoinBevel, 0);
  CGContextAddPath(context, thickPath);

  CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
  CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
  CGContextSetLineWidth(context, 3);
  CGContextDrawPath(context, kCGPathFillStroke);

  CGPathRelease(thickPath);
  CGPathRelease(path);
}

Comment: How do I draw two differents CGPath and give each its own color?
Answer: The simplest solution would just be to stroke the path twice. First with black at a bigger stroke width and then stroke the same path again using the blue color with a slightly smaller stroke width.
Edit:
If I remember correctly you can use CGPathCreateCopyByStrokingPath(...) to create a new path that you then can both stroke and fill. Then you could use semi-transparent colors.
From the documentation:

CGPathCreateCopyByStrokingPath
Creates a stroked copy of another path.
CGPathRef CGPathCreateCopyByStrokingPath(
                                         CGPathRef path,
                                         const CGAffineTransform *transform,
                                         CGFloat lineWidth,
                                         CGLineCap lineCap,
                                         CGLineJoin lineJoin,
                                         CGFloat miterLimit
                                         );

Parameters
path
The path to copy.
transform
A pointer to an affine transformation matrix, or NULL if no transformation is needed. If specified, Quartz applies the transformation to elements of the converted path before adding them to the new path.
lineWidth
The line width to use, in user space units. The value must be greater than 0.
lineCap
A line cap style constant—kCGLineCapButt (the default), kCGLineCapRound, or kCGLineCapSquare. See "CGLineCap".
lineJoin
A line join value—kCGLineJoinMiter (the default), kCGLineJoinRound, or kCGLineJoinBevel. See "CGLineJoin".
miterLimit
The miter limit to use.
Comment: I want the middle color to be simi-transparent though. Adding a black larger line behind it would make that impossible.
Comment: I get what you are saying now, Thanks for the help.
Comment: @David what is the alternative for swift 3 of this API
Comment: @VivekSehrawat A quick online search shows that it's [`copy(strokingWithWidth:lineCap:lineJoin:miterLimit:transform:)`](https://developer.apple.com/reference/coregraphics/cgpath/2427133-copy).
Comment: @DavidRönnqvist - Thanks i got it

CGPath with outline


Indetermiante form limits question.

Question: I have a simple question. I learned these things years ago but cannot recall how to prove this. I am interested in the right hand limit
$$\lim_{x \rightarrow 0^{+}} \frac{1}{\sqrt{x}} e^{-\tfrac{a}{2x}}$$
where $a$ is just some constant different to zero.
My intuition is that this goes to zero as the exponential decays much faster than the square root.
I tried to use L'Hôpital but it didn't help. Did I make a mistake or do I just need to keep applying it over and over again.
\begin{gather}
f(x) = e^{-\frac{a}{2x}}
\\
g(x) = \sqrt{x}
\\
\frac{f'(x)}{g'(x)} = -(\frac{a}{2x^2}e^{-\frac{a}{2x}})(2\sqrt{x})
\end{gather}
Am I just missing something? I feel like I am forgetting something very very basic. I also considered expanding the exponential in Taylor series but that didn't really help
Comment: Make the substitution $x=1/y$.
Comment: I suppose $a$ is a _positive_ non-zero constant?
Comment: Thanks @Mindlack. I think that works out ok. Is that a standard kind of technique or did you just know from practice? .
Comment: @StackTD. Yes, we can assume a positive
Comment: TCD: I wouldn't say it is a standard technique because in general, substitutions in limits are little more than rewriting stuff with no change in viewpoint (the expression can definitely look simpler, but it is sort of artificial, we just split the complexity). Moreover, that's a rather standard example, so that is practice (try and understand what happens to all the derivatives of the function when the argument goes to $0$).
Answer: It's simpler if you do $\sqrt{x}=1/t$, so the limit becomes
$$
\lim_{t\to\infty}te^{-at^2/2}=
\lim_{t\to\infty}\frac{t}{e^{at^2/2}}
$$

Indetermiante form limits question.


Liquid error "No such template" in Rails

Question: I'm getting the following error in my Liquid view:
Liquid error: No such template 'sliders/slider' #<Liquid::LocalFileSystem:0x99319b8>

The file structure in my liquid code (which saves in the database) has the following code:
{% include 'sliders/slider' %}

and in my view where I render the Liquid content is as follows
<%
Liquid::Template.file_system = Liquid::LocalFileSystem.new("sliders/slider")
@template = Liquid::Template.parse(<page code>) %>
<%= raw @template.render(<variables>)  %>

<%= Liquid::LocalFileSystem.new("sliders/slider") %>

And in app/views/sliders/ I have a file called '_slider.erb'.
But if I do a <%= render :partial => "sliders/slider" %> it shows the file
Am I missing something here? I'm using Rails 3 with Liquid 2.2.2 and on Linux.
Answer: I think your partial filename should be: _slider.liquid for it to work properly.


How to open .mrc files

Question: I've just downloaded some .mrc files. But I couldn't find the right application to open it. I'm using Ubuntu 11.10 What application should I have to open them?
Comment: Depends on what the files are. [This site](http://file-types.cryer.info/m/mrc/index.htm) lists three file types which have the extension `.mrc`.
Comment: Edelweiss, Can you come back and either accept an answer or answer your own question and accept that answer? Were you able to resolve this issue?
Answer: I would try opening a file in gedit or another plain text editor.
Assuming these are very small files (2 kilobytes or smaller), they are usually mIRC script files, for use with the Windows IRC client of the same name.

How to open .mrc files


How do I make water that can't flow for adventure maps?

Question: I'm trying to build a race for the wool style map, and I've seen tons of other maps in versions all the way up to 1.16 that have underwater sections without walls to hold the water in. I know they aren't using barriers, because they can still fire arrows into the water, and they aren't using a fill command, because that isn't fast enough to stop the water. As well as that, it's entirely in vanilla, since I can download the map and play it and not have any problems on a vanilla profile. So how do they do it? I do have world edit at my disposal if the solution requires it.
Comment: That doesn't work, the water automatically updates.
Comment: im pretty sure `//fill`ing with air should just do that
Comment: I tried exactly that earlier and the water just flows back into the spot I filled. And when I put that in to a repeating command block, it's not fast enough to prevent the water from flowing out a bit
Comment: Use `/setblock  water`.
Comment: @JohnKlubertanz just to be clear, you did `//fill` like the world edit command and not `/fill` like the minecraft command, right?
Comment: Re "it's entirely in Vanilla": Once the blocks that border the water have been removed without updating the water (which doesn't need to be a Vanilla capability), it will remain afloat like this until it's updated by something else. Also, I'm pretty sure nonexistant blocks are removed without causing block updates.
Answer: Place structure void blocks around spaces you don't want the water flowing into.
To get a structure void, use this command:
<code>give @s minecraft:structure_void 1
</code>
The structure void's hitbox is a small cube in the middle of the block that can be broken to turn the block into air. Water will never flow into its space while it is active.
Comment: Oh my god. I can't believe I completely forgot about structure voids! Thank you for reminding me, you're the best!


Error "Specified cast is not valid" in query

Question: I have a funny problem. I want to execute this query, but this error happen:
"Specified cast is not valid."
Can any body help me?
here is my code:
 string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(connStr);
        SqlCommand sqlcmd = new SqlCommand();
        sqlcmd = new SqlCommand("SELECT max(ID) FROM AddNews ", sqlconn);

        sqlconn.Open();
        int ID = ((int)sqlcmd.ExecuteScalar());
        sqlconn.Close();

Comment: It is exactly an integer!
Comment: check the return type of "sqlcmd.ExecuteScalar());"
Answer: There is a case the you may not have results and the return can be null.
You better try
int? MaxID = sqlcmd.ExecuteScalar() as int?;

and check if the MaxID is not null.
Answer: The result is cast to an int at the SQL level. The returned value will be an int, or defaulted to 0 if null.
You can use Convert.ToInt32(sqlCmd.ExecuteScalar()) instead of (int) or (int?)sqlCmd.ExecuteScalar() ?? 0;
Answer: you have to change as follow

int ID=int.Parse(cmd.ExecuteScalar().ToString());

Answer: Instead of ((int)value) use Convert.ToInt32(value). It will work.
Answer: sqlcmd.ExecuteScalar());

it returns an object not an int.
try this
Object s= cmd.ExecuteScalar()
int x=Integer.Parse(s.ToString))

Answer: you can test if your value is an int first
int ID;
int.TryParse(sqlcmd.ExecuteScalar(), out ID);


How to check if user has different role in mvc

Question: I am working on MVC4 project. My application has 3 different role.
1. Admin
2. User
3. Superadmin
when admin logs in if he type direct page name in url for user page.. he is able to see user page also.
So how do i restrict role to see only his page.
I mean admin can see only admin pages,user can see only user page.. etc.
Comment: You can use `TempData[""].Depending upon tempdata[]  you can seperate view on pages
Answer: If you're using the inbuilt role and membership providers, you simply have to use the authorize attribute:
<code>[Authorize(Roles = "Admin")]
</code>
This can be attached to a controller or action.
Comment: no i am not using build in membership.. i have table which contains all 3 three role..anyways i am using session for roles.. but how do i send user to previous page when i check user has no role for this page ??
Comment: Unless you have a very good reason not to, I'd suggest you use forms authentication (http://www.asp.net/mvc/tutorials/older-versions/security/authenticating-users-with-forms-authentication-cs). By using session, your are bypassing all the inbuilt features which allow you to limit various pages to various roles.
Answer: Use authorize attribute on action  as below .
[Authorize(Roles = Roles.Admin)]


How can I stop a Java while loop from eating >50% of my CPU?

Question: Okay, I tested this on an empty program, and just having a while(true){} running gave me >50% on my CPU. I have a game I'm working on that uses a while loop as it's main loop, and it's CPU is at 100 all the time.
How can I get Java to repeat something over and over without eating up >50% of my CPU just to do the repeating?
Comment: @William: Please read Mystere Man's answer - it is the more correct approach, despite the greatly upvoted accepted answer.  You should be basing your game off a frame-rate timer not a CPU loop.
Comment: Further, I would encourage to change the accepted answer.
Answer: Add a sleep to put the thread into idle for some interval:
Thread.sleep
Without having a sleep, the while loop will consume all the computing resources that is available. (For example, theoretically, 100% in a single core system, or 50% in a dual core, and so on.)
For example, the following will cycle once through a while loop approximately every 50 milliseconds:
while (true)
{
    try
    {
        Thread.sleep(50);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

This should bring down the CPU utilization quite a bit.
With a sleep in the loop, the operating system will also give enough system time for other threads and processes to do their things, so the system will be responsive as well. Back in the days of single core systems and operating systems with not-so-good schedulers, loops like this could have made the system very unresponsive.

Since the topic of use of while loops for a game came up, if the game is going to involve a GUI, the game loop must be in a separate thread or else the GUI itself will become unresponsive.
If the program is going to be a console-based game, then threading is not going to be an issue, but with graphical user interfaces which are event-driven, having a long-living loop in the code will make the GUI unresponsive.
Threading and such are pretty tricky areas of programming, especially when getting started, so I suggest that another question be raised when it becomes necessary.
The following is an example of a Swing application based in a JFrame which updates a JLabel that will contain the returned value from System.currentTimeMillis. The updating process takes place in a separate thread, and a "Stop" button will stop the update thread.
Few concepts the example will illustrate:

A Swing-based GUI application with a separate thread to update time -- This will prevent lock up of the GUI thread. (Called the EDT, or event dispatch thread in Swing.)
Having the while loop with a loop condition that is not true, but substituted with a boolean which will determine whether to keep the loop alive.
How Thread.sleep factors into an actual application.

Please excuse me for the long example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TimeUpdate
{
    public void makeGUI()
    {
        final JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JLabel l = new JLabel();

        class UpdateThread implements Runnable
        {
            // Boolean used to keep the update loop alive.
            boolean running = true;

            public void run()
            {
                // Typically want to have a way to get out of
                // a loop. Setting running to false will
                // stop the loop.
                while (running)
                {
                    try
                    {
                        l.setText("Time: " +
                                System.currentTimeMillis());

                        Thread.sleep(50);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }

                // Once the run method exits, this thread
                // will terminate.
            }
        }

        // Start a new time update thread.
        final UpdateThread t = new UpdateThread();
        new Thread(t).start();

        final JButton b = new JButton("Stop");
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                t.running = false;
            }
        });

        // Prepare the frame.
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(l, BorderLayout.CENTER);
        f.getContentPane().add(b, BorderLayout.SOUTH);
        f.setLocation(100, 100);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new TimeUpdate().makeGUI();
            }
        });
    }
}

Some resources about threading and using Swing:

Threads and Swing
Lesson: Concurrency
Comment: That was my first thought, but you beat me to it :)
Comment: Note that polling (sleeping for some amount of time) is perfectly fine for the example code (updating a text label with the current time). But for processing complex event queues, it's generally better to block on the presence of entries in the event queue (using a monitor)
Comment: Thread.sleep(0) too, forcing a context switch. See answer below.
Answer: Thread.Sleep may not be the whole answer.  For most games, there's way too much CPU for the amount of work needed.  Simply sleeping for a set amount of time isn't all that efficient, since you will likely either still burn too many resources, or not enough.  You typically want to time your work in some way.
If you think about it, the screen only updates at a certain rate, typically less than 100 times per second.  I'm not familiar with the Java api's for this sort of thing, but what you want is to find out the refresh speed of the monitor and then update only a single time between each refresh.
Further, you don't need a loop like that for your main loop, you can use timers to call your update code at a regular interval.  This is even more efficient.
Answer: You are indeed busy-waiting, meaning you are grinding your CPU constantly on checking one or more conditions until they are true.
Thread.sleep() is not the solution. Using wait() and notify() methods allows you to do just what you are trying, but much more efficiently. Basically, this mechanism allows a thread to sleep on an object until the object decides something has happened and wants to wake all the threads sleeping on it.
Code exmaples can be found here and here.
This should be your solution, and not hiding your busy-wait with a timer.
Comment: Using java.util.concurrent is probably going to be better.
Answer: While yes, you could do a
Thread.sleep(50)

like the accepted answer suggest, you could also call
Thread.sleep(0)

This will tell the processor to do a context switch. Other threads waiting to be executed (like the GUI drawing thread) will then be executed and the machine will stop feeling slow.
The sleep(0) way will also maximise the time given by the OS to you application because the thread will immediatly go back in the processor's queue (instead of waiting 50ms before doing so) so if no other thread where waiting, you thread will continue being executed.
Comment: yield is not recommended because it's behavior is not standard depending on the platform. see http://www.javamex.com/tutorials/threads/yield.shtml
Answer: Usually in a game loop you will pause for a bit... for example: http://developers.sun.com/mobility/midp/articles/game/
Answer: It seems like your thread is busywaiting.  That is to say, it is trapped in a loop in which it does nothing.  In such a situation, it will chew up a lot of cpu cycles to no effect.
As mentioned by others, Thread.sleep is the answer.
Answer: That's swing-related, but the idea stays the same: try to use Observer pattern instead of wile(true).
Answer: How about a Quartz-Spring based scheduler that keeps doing the work over and over again in repeated intervals.
Answer: If there is an interrupt it is probably for a reason. A better way to handle this is
try {
    while (true) {
        Thread.sleep(50);
    }
} catch (InterruptException e) {
    Thread.currentThread().interrupt();
}

However this loop doesn't do anything, so I suggest you just delete it. It is fairly rare that you want to busy wait for a condition (In which case the Condition class is a better choice) usually you can transform the same behaviour not to need a loop at all.


I accidentally turned on screen reader with my keyboard

Question: I had my keyboard on my lap, and I adjusted my sitting position. I accidentally pressed some keys while doing this. I heard a robotic voice saying that the screen reader was turned on. After that, I got a barrage of narration each time I typed anything.
I was able to turn off screen reader in the Accessibility settings. However, I am unsure how it got turned on in the first place. The only window in the forefront of my screen was chromium.
Does anyone know what keyboard shortcut I may have pressed?
Answer: According to the official documentation, it's Super + Alt + S
https://help.ubuntu.com/stable/ubuntu-help/a11y-screen-reader.html.en#:~:text=Press%20Super%20%2B%20Alt%20%2B%20S%20.


Why is updatedTransactions never called?

Question: After the user purchase the item, by entering email and password and paying, the method updatedTransactions is never called. The item is regularly bought but, without calling updatedTransactions methor I can't execute the code to add the item to the app. I noticed that the item is bought because if I run the code to restore an item bought, everything goes fine and the product gets installed into the app.
Here is the code I copied to buy the product:
<code>-(IBAction)buyProduct:(id)sender {

    NSLog(@"Purchasing: %@", self.product.productIdentifier);

    SKPayment *payment = [SKPayment paymentWithProduct:self.product];
    [[SKPaymentQueue defaultQueue] addPayment:payment];

}
</code>
Follows the code to restore the product:
<code>-(IBAction)restoreProduct:(id)sender {
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
</code>
I noticed that in this last piece of code I have the following line:
<code>[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
</code>
Should I add this line in the buy part too?
Comment: Check out the StoreKitSuite sample by apple: https://developer.apple.com/library/ios/samplecode/sc1991/Introduction/Intro.html
Answer: I solved this issue by adding the following code in the buyProduct method:
<code>-(IBAction)buyProduct:(id)sender {

    NSLog(@"Purchasing: %@", self.product.productIdentifier);

    SKPayment *payment = [SKPayment paymentWithProduct:self.product];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; //added line
    [[SKPaymentQueue defaultQueue] addPayment:payment];

}
</code>
Now the method updatedTransactions is called before making the payment and after the payment.
With the following code you can check if everything went good or bad:
<code>for(SKPaymentTransaction *transaction in transactions) {
        if (transaction.transactionState == SKPaymentTransactionStatePurchased) {
            [self unlockRemoveiAD];
            [OKalertView show];
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }

        if (transaction.transactionState == SKPaymentTransactionStateFailed) {
            [alertView show];
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }

    }
</code>
Comment: You should addTransactionObserver as soon as possible, best place for this is App delegate method didFinishLaunchingWithOptions
Comment: @TimurSuleimanov What if I add the observer later such as after my app intro video finish?
Comment: @jayatubi Then it's possible, that Apple will send you a transaction, but you won't receive it, because you didn't add an observer, so you won't handle user's transaction. It can be auto-renewable subscription transaction, not sure, but possible, cancel transaction(when user canceled purchase) or restore in-app purchase transaction.


find the fixed points of $\dot{\theta} = \omega - a\sin{\theta}$ for $a > \omega $

Question: I am working through an example in Strogatz's dynamical systems book (second edition, example 4.3.1, page 99). and came across something in one of his examples. The problem is to find the fixed points in the flow of a system given below and then find the stability at both of the fixed points.
The equation is given by:
$$
\dot{\theta} = \omega - a\sin{\theta} \
$$
Now to find the fixed points in the flow I would set $\dot{\theta} = 0$, and solve for $\theta$, so:
$$
0 = \omega - a\sin{\theta} \\
sin{\theta}^* = \frac{\omega}{a}\\
$$
But the book also gives an additional solution:
$$
\cos{\theta}^* = \pm \sqrt{1 - (\omega/a)^2}
$$
The question is how did Strogatz arrive at this second solution for $\cos{\theta}^*$? From the plot of the system it is obvious that there are 2 fixed points in the domain of the equation, but I was not sure how he arrived at this second fixed point.  Any suggestions would help. Thanks.
Comment: I added the page info as you asked.
Comment: It would be helpful if you said *which* example in the book you are referring to. (Example number? Page number? Which edition of the book?)
Answer: The fixed points are given by the condition
$$
\sin \theta^* = \omega/a
,
$$
nothing else. (And this equation has two solution per period of the sine function, if $\omega<a$.)
The second formula,
$$
\cos \theta^* = \pm \sqrt{1-(\omega/a)^2}
$$
is not an additional solution, but just a consequence of the identity
$$
\cos^2 x + \sin^2 x = 1
.
$$
(He needs that formula in order to evaluate $f'(\theta^*)$ just below.)
Comment: I fixed the $a$ issue. You are right, I mistakenly looked at the formula for the stability analysis of that root, which has a similar formula. You can remove that comment from your post if you like.
Comment: Okay this is great. Yes, this seems to make a lot more sense. Strogatz did not explain those steps, so I was just trying to make sure I understood the logic. Thanks so much.
Comment: You're welcome!


Did I just ruin the flange on our toilet?

Question: The point where the elbow joint from our flushometer meets the toilet bowl has begun leaking (dripping, really) whenever we flush (so, whenever water passes through it). I jiggled it a bit and the elbow joint popped right out. So the connection seems to be an unthreaded pipe with a plastic gasket that slides into a threaded mounting ring (is that the right term?) that then threads onto the toilet. update: it's a slip joint nut
The gasket appears to be intact, so I think I can fix this by reinforcing the seal at the threading. I have a jar of pro-dope, a tube of durst pipe thread compound and a roll of what teflon tape.
Two questions:
Am I on the right track here? and Which should I use for the best seal?
PS. What is a flushometer? Ours is a Sloan Gem for a "back spud bowl" (vs. a "top spud bowl") -- it reaches the toilet via an elbow rather than a straight pipe. Our toilet is a ways out from the wall so the joint has been extended by about 8".
Update: not using the toilet wasn't really working for us so I took a stab at using pro-dope and re-assembling.
Here's the halfway point, after I unscrewed the mounting ring slip joint nut:

And the after:

You can kind of tell from the after image that the toilet and the flushometer aren't properly aligned so the elbow joint doesn't meet the toilet at a proper 90° angle.
That worked, but there was still a tiny bead of water making its way out with every flush. I thought I'd be clever and get someone stronger than I to tighten the mounting ring slip joint nut. Bad idea: as I was watching him tighten the mounting ring I could see the flange inlet spud assembly start to turn. We tried flushing again and tons of water came out all around the flange inlet spud assembly. So now my question is, do I have to replace the flange inlet spud assembly to fix this? We tried backing the mounting ring slip joint nut back out, but that didn't help.
Comment: FYI, the joint to the pipe is a [compression fitting](http://en.wikipedia.org/wiki/Compression_fitting). The info in that article might be useful regarding understanding the original problem, though not the flooding flange.
Comment: Would appreciate any suggestions on this related [question](https://diy.stackexchange.com/questions/223784/how-to-replace-back-spud-on-toilet)
Answer: You have probably damaged the seal between your toilet and the flange. This seal is usually formed by a wax ring that forms closely to the flange and toilet base when the toilet is installed. If you've moved the toilet significantly, you may have opened up a hole in this seal where water can leak when your toilet is draining.
It's sometimes possible to improve the seal by readjusting where you've positioned the toilet. But you probably won't have a good seal unless you fully remove the toilet, scrape out the existing wax ring, and re-seat the toilet using a new wax ring. This is definitely worth doing because a leaky wax ring can drip water into your subfloor for a long time, causing rot and other damage. Plus at the same time you can turn your flange and/or flushometer so you get a better fit between the flushometer and toilet.
You've probably only damaged the wax ring. However, if your toilet remained bolted to the flange while your friend turned it, it's possible you've damaged the seal between the flange and your drain. You should inspect that when you have the toilet up.
By the way, the fitting between your flushometer and toilet is a compression fitting. These are not designed to accommodate an angled installation -- for best results the nut needs to be perpendicular to the incoming pipe. You should try to straighten the joint, and also find a new plastic compression gasket to replace the existing worn one.
Comment: My impression was she was referring to the brass flange at the back with a rubber gasket, not the floor flange the whole toilet sits on via a wax ring. Some clarification would be useful.
Comment: @bcworkz You're correct. The leak is clean water coming in to fill the bowl (thankfully).
Answer: The issues with the compression fitting have been addressed.
The brass flange fitting, the rubber gasket, and the threaded pipe is the "toilet spud". Replacements are available if the rubber is perished or the metal parts somehow damaged.
The flange nut looks pretty well bonded to the threaded portion. Soak well with WD-40 and let it soak in. There are splines inside the spud on which one would apply an internal spud wrench to keep the threaded pipe part from turning. You may find some other chunk of metal that will wedge against the splines, which in turn can be held by a conventional wrench. Holding the spud in place, remove the flange nut with a suitable tool.
Once the flange nut is removed, push the threaded pipe part inwards, but ensure it will not fall into the toilet. The part inside the toilet is conical shaped. Pushing it inwards will give enough free play that the rubber gasket can be pulled out. Once the rubber is out, there will be enough clearance in the toilet hole that the threaded pipe part can now be removed.
Examine the parts and evaluate if replacement is necessary. If the rubber is not too far gone, it may be possible to clean it, treat it with some sort of rubber treatment, and reinstall. If the rubber is cracked, hardened, rotted, or brittle, it will need to be replaced. The nut should be tightened firmly enough to ensure the rubber seals well against the toilet, but not so tight the rubber gets pushed out of position or the toilet gets cracked or broken.
Comment: The spud assembly came out exactly as described and a new spud assembly was $7. I replaced the slipnut assembly as well and I just flushed about 8 times. Not a drip.
Comment: Would appreciate any suggestions on this related [question](https://diy.stackexchange.com/questions/223784/how-to-replace-back-spud-on-toilet)


jboss memcacehd kryo flex

Question: I have a jboss 5.1 AS in which i m trying to implement session replication with memcached and kryo serialization . Everything is working fine , but i have a page in my application which has to its left some flex features . When i click on this page in the GUI , kryo serialization failes with the following stack trace :
Caused by: com.esotericsoftware.kryo.SerializationException: Unable to serialize object of type: flex.messaging.HttpFlexSession
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:493)
    at com.esotericsoftware.kryo.serialize.MapSerializer.writeObjectData(MapSerializer.java:104)
    at de.javakaffee.kryoserializers.CopyForIterateMapSerializer.writeObjectData(CopyForIterateMapSerializer.java:56)
    at com.esotericsoftware.kryo.Serializer.writeObject(Serializer.java:43)
    at com.esotericsoftware.kryo.Kryo.writeObject(Kryo.java:520)
    ... 23 more
Caused by: com.esotericsoftware.kryo.SerializationException: Unable to serialize object of type: flex.messaging.SessionMetricsTracker
Serialization trace:
destroyedListeners (flex.messaging.HttpFlexSession)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:493)
    at com.esotericsoftware.kryo.serialize.CollectionSerializer.writeObjectData(CollectionSerializer.java:86)
    at de.javakaffee.kryoserializers.CopyForIterateCollectionSerializer.writeObjectData(CopyForIterateCollectionSerializer.java:46)
    at com.esotericsoftware.kryo.serialize.FieldSerializer.writeObjectData(FieldSerializer.java:175)at com.esotericsoftware.kryo.serialize.ReferenceFieldSerializer.writeObjectData(ReferenceFieldSerializer.java:52)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:489)
    Caused by: com.esotericsoftware.kryo.SerializationException: Unable to serialize object of type: org.jboss.mx.notification.ListenerRegistry
Serialization trace:
registries (org.jboss.mx.notification.MBeanServerListenerRegistry)
listeners (org.jboss.mx.server.MBeanServerImpl)
mbeanServer (org.jboss.classloader.spi.ClassLoaderDomain)
domain (org.jboss.classloading.spi.vfs.policy.VFSClassLoaderPolicy)
delegate (org.jboss.classloader.spi.DelegateLoader)
loader (org.jboss.classloader.spi.base.BaseClassLoader)
classLoader (flex.messaging.MessageBroker)
messageBroker (flex.messaging.SessionMetricsTracker)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:493)

I have been stuck for many days now and not able to fix the issues. Please help
Answer: To serialize your HTTPSession, you need to serialize HttpFlexSession and it is probably not serializable (or you are using a strict kryo configuration by disabling serialization on Serializable objects).
You should provide to kryo a class to serialize HttpFlexSession:
Kryo kryo = new Kryo();
kryo.register(HttpFlexSession.class, new HttpFlexSessionSerializer(kryo));

Then you need to implement HttpFlexSessionSerializer.java that should extend Serializer then you should be able to serialize your flex session with kryo.

jboss memcacehd kryo flex


Xamarin Forms UWP - Display PDF

Question: Please, help me and tell me what am I missing.
My goal is to display simple PDF file (stored locally for example) in the WebView control. Can I bind path of the file to the Source property of the WebView? Or what is the correct way to show PDF in UWP?
P.S. and if the only option is to do like here - how must I add pdf.js to my project??
Answer:
My goal is to display simple PDF file (stored locally for example) in the WebView control.

If you want to display pdf in WebView control, then the methods in Display a Local PDF File in a WebView is most like the only way to solve your problem.
You can follow the steps in the xamarin official document, and here are some additional tips we need to pay attention to:

After downloading pdfjs, for UWP app, you need to copy the entire folder into the Assets folder, make sure that the folder is named "pdfjs", otherwise you will need to modify the code to change the path.
Your .pdf file should be stored into the Content folder under the Assets folder, it means you will need to create a new folder named "Content" under Assets and copy your .pdf file into this folder. Otherwise, you will also need to modify the code to change the path.
After copying your .pdf file into the "Content" folder, don't forget to change the Build Action of this file to Content like this:

Or what is the correct way to show PDF in UWP?

In uwp app, you can use Image to show PDF file, you can refer to the official PDF document sample. But I don't know if PDF can be displayed as Image in Android and IOS apps, since you're developing a cross-platform project, I think it's better to use the built-in method to solve such problem.
If a demo for xamarin UWP is needed, you can leave a comment, I will upload my demo later.
Comment: Tnanks, this was helpful! Btw, can PDFJS viewer open not only files that are located at the Assets folder?

For example:

`var uriString = "ms-appx-web:///Assets/pdfjs/web/viewer.html?file=ms-appdata:///local/Test/test.pdf";

Control.Navigate(new Uri(uriString));`

Xamarin Forms UWP - Display PDF


Make rectangle into equal grids using google map SDK in iOS

Question: I am using Google SDK in my project. I draw a rectangle for a city. I need to divide that rectangle area into equal parts and get their center point latitude and longitude in iOS.?.
I am expecting response like in image.I tried with stack overflow .But I couldn't get any result.I don't have sample code to post.
Answer: <code>let rect = CGRect(x: 0, y: 0, width: 100.0, height: 100.0) // the rect you draw. This is just example
let horizontalCount = 4
let verticalCount = 4
let horizontalStep = rect.width / CGFloat(horizontalCount)
let verticallStep = rect.height / CGFloat(horizontalCount)
var points: [CGPoint] = []

for i in 0..<horizontalCount {
    for j in 0..<verticalCount {
        points.append(CGPoint(x: rect.minX + (CGFloat(i) + 0.5) * horizontalStep, y: rect.minY + (CGFloat(j) + 0.5) * verticallStep))
    }
}

let centers = points.map({ mapView.projection.coordinate(for: $0) })
</code>
Comment: I am getting all the points with lat and long.Can you tell me how to set rectangle positions.
Comment: `mapView.projection.point(for: CLLocationCoordinate2D)` - transform CLLocationCoordinate2D to CGPoint.

`mapView.projection.coordinate(for: CGPoint)` - transform CGPoint to CLLocationCoordinate2D


Minecraft command to remove duplicate entities

Question: I am making a wireworld cellular automata, and everything is going well except for one thing: placing "wire" cells on both sides of an "empty" cell and filling the gap afterwards causes TWO "WireCell" entities instead of one because of the flood-fill method that I am using. How can I remove all but one entity from each block?
Comment: I'm pretty sure you would have to do a command per all types of entities. If that's not a problem, you can have a scoreboard and use (once)
`scoreboard players add @r[type=]  1` and
`kill @e[type=,score_=0]` or any other killing technique.
Comment: With a little bit of tweaking, I managed to make that work (I added executions with r=0, and some tags). thanks!
Comment: @zane49er If you want, you can post an answer to your own question and accept it. You can gain more reputation, and help others who have the same problem get to the answer quick! :)
Answer: you said you found out how to do it, but I'll just give this answer to show other people how to do it,
I did it in three command blocks (five if you include the two command blocks I used to make it loop, could make it loop with only one extra though)
first you'll need a scoreboard objective
/scoreboard objectives add near dummy

first set all of the sheep's scores to zero
/scoreboard players set @e[type=Sheep] near 0

this command makes each sheep in a stack add one to one other sheep in the stack, basically it counts how many is in each stack
/execute @e[type=Sheep,r=50] ~ ~ ~ /execute @e[r=0,type=Sheep,c=1] ~ ~ ~ /scoreboard players add @e[r=1,type=Sheep] near 1

then you kill one sheep that has a score that is more then two
/execute @e[type=Sheep,c=1,score_near_min=2] ~ ~ ~ /kill @e[r=0,c=1,type=Sheep]

loop the above three commands, until all sheep have a score of 1
note: I used the scoreboard objective "near" but you can use what ever you want, as long as you change the name in each command
same with the entity type, just make sure you get every time it says type=Sheep, I counted six occurrences


Partition/sort keys for querying/comparing date ranges in DynamoDB

Question: I've got a DynamoDB tickets table for a basic ticket management/calendar app.
The tickets each store a date range, and I need to query them based on whether they overlap a certain other date range.
For example, there's a scrolling calendar, and as a user scrolls into the past/future, I retrieve the tickets that appear within that visible area's date range. I also look for date conflicts, so I am checking to see whether tickets exist that overlap a certain date range.
Right now, I'm using a unique id for each ticket for the partition key (not using any sort key), using a paginated scan to get all the tickets, and checking every one in a lambda to see if date ranges overlap (ticket.start < range.end && ticket.end > range.start).
What I'm doing feels very inefficient, and I'm already running into some ProvisionedThroughputExceededException errors with light usage even though the table is set to auto-scale.
Is there a better way in DynamoDB to handle this (perhaps a smart usage of the partition/sort keys)?
Answer: Yes there's a much better approach. Assuming you have a common denominator for tickets, such as tickets for a given users calendar or for a certain company, that id would be best served as partition key. The sort key would be a timestamp.
That will allow you to easily get tickets for a given users between two dates, efficiently.
If you don't have a common denominator and you want to show all tickets that exist in the table, then consider using a single value as partition key. This blog will help:
https://aws.amazon.com/blogs/database/effective-data-sorting-with-amazon-dynamodb/
Comment: The timestamp sort key approach sounds like it'd work if I was storing a single date on each ticket, but my tickets have date ranges.
Comment: For example, how do I make sure a ticket with start date 2023-12-31 and end date 2024-01-01 gets returned whether I'm querying tickets in 2023 or 2024?
Comment: You should only act on a single date and then filter out the remainder using a filter expression. Give me all the tickets with start date between X+Y, then use a filter to filter out the ones who's end date need to meet a criteria.
Comment: I can't check the start date between X&Y because that will not return tickets that start before X but end after X (like the example I commented above). Seems the best I can do is get all the tickets that start before Y?
Comment: Talking through this has helped me find similar questions here that seems to get at the same problem (e.g., https://stackoverflow.com/questions/71360821/dynamodb-get-all-items-which-overlap-a-search-time-interval)


Fractional versions of euclidean space?

Question: This is going to be a somewhat vague question, but I'll be happy if you indulge me.
Euclidean space $\mathbb{R}^n$ is equipped with a lot of nice (algebraic, metric, topological,...) structure and has many nice properties as such, regardless of the dimension $n$ (simple-connectedness, finite-dimensionality, abelianness, having a uniform lattice, being a $\sigma$-finite measure space, and the list goes on...) . It seems interesting to me to try and find geometric/algebraic objects with non-integer dimension while trying to preserve as many properties of classical euclidean space as we can.
Some thoughts: the dimension of a vector space is always an integer so let's forget about vector spaces altogether (but stay in $\mathbb{R}^n$ for some large $n$) and interpret "dimension" as "Hausdorff dimension" (this seems geometrically intuitive to me, though I'm aware that there are many other notions of dimension in $\mathbb{R}^n$ or general metric spaces). One way of thinking of $\mathbb{R}^n$ is as a connected, simply-connected locally compact Hausdorff topological group, so I wonder now whether for every $\alpha > 0$ there is some "canonical" model of a topological group (implicitly assumed to lie in $\mathbb{R}^n$ for some $n$) with these properties and with the additional property that it is $\alpha$-dimensional (in the Hausdorff dimension sense). In the case where $\alpha$ is a positive integer, it is obvious what this model should be.
Comment: tangentially related: http://mathoverflow.net/questions/60375/is-r3-the-square-of-some-topological-space
Answer: A nontrivial metric space of Hausdorff dimension less than 1 cannot be connected,
so I'll just ignore that case.
For $\alpha \ge 1$ consider the family of metric spaces $(\mathbb{R}, d_\alpha)$
with $d_\alpha(x, y) = |x-y|^{1/\alpha}$.
With $\alpha = 1$ this just gives the usual metric structure.
It is easy to see that the topological structure does not depend on $\alpha$,
because the collection of all open balls remains the same; the same balls just
get different radii. This means that as a topological field these spaces are
all the same.
When it comes to Hausdorff measure the spaces are very different. The largest
set with $d_\alpha$-diameter $\varepsilon$ is an interval with length $\varepsilon^\alpha$. Clearly it takes $\Theta(\varepsilon^{-\alpha})$ of these intervals to cover the unit interval. Since smaller intervals don't provide a
more efficient cover, this means that $(\mathbb{R}, d_\alpha)$ has Hausdorff
dimension  $\alpha$.
In fact the $\alpha$-dimensional Hausdorff measure is equal to Lebesgue measure. (give or take a constant factor)
If there is a moral to this story, it must be that Hausdorff dimension says
very little about topological or algebraic structure.
Comment: I guess I was somewhat vague in my requirements. I would expect (among other things) that the Hausdorff dimension of the group (its given metric, actually) would be identical to the growth rate of the group. This isn't satisfied by your family of examples unless $\alpha = 1$. So this would be one relation between the algebraic structure and the metric structure which we would like to have.

Fractional versions of euclidean space?


Why does my DataGridView refresh automatically when i call a function that executes a select query and returns a datatable object?

Question: this is my function runQuery it's a member of a classe called Dconnection it returns a DataTable object:
public DataTable runQuery(string qry)
    {
        dt.Clear();
        cmd.CommandText = qry;
        con.Open();
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        dt.Load(rdr);
        con.Close();
        return dt;
    }

Here is the buttons code :
    Dconnection dcon = new Dconnection();
    DataTable dtable = new DataTable();
    private void btnFillDGV_Click(object sender, EventArgs e)
    {
        dtable = dcon.runQuery("select * from books");
        DGV.DataSource = dtable;
    }

    private void btnExecQuery_Click(object sender, EventArgs e)
    {
        dcon.runQuery("select * from books where ID =1");

    }

When i click the first button the DataGridView gets filled:
The problem is when i click the second button the DGV is refreshed automatically , please can some body explain why that's happening
Answer: Your runQuery method isn't creating a new DataTable; it reuses the same DataTable instance that is already defined as the source of the DataGridView. So when you clear and refill it, it refreshes the DataGridView.
To fix it, just instantiate a new DataTable:
public DataTable runQuery(string qry)
{
    var table = new DataTable();
    cmd.CommandText = qry;
    con.Open();
    rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    table.Load(rdr);
    con.Close();
    return table;
}

As a side note, you should avoid reusing DbConnection, DbCommand and DbDataReader objects; it's a recipe for trouble. Just create new ones when you need them, and dispose them when you're done (the easiest way is to declare them in a using block):
public DataTable runQuery(string qry)
{
    var table = new DataTable();

    using (var connection = new SqlConnection(connectionString))
    using (var cmd = con.CreateCommand())
    {
        cmd.CommandText = qry;
        connection.Open();
        using (var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            table.Load(rdr);
        }
    }
    return table;
}

Answer: Because your DataGridView has a DataTable as it's DataSource and you are clearing and reloading the DataTable.
Answer: Because you are manipulating same dt in two buttons.
 DGV.DataSource = dtable;

Here you are setting your dataSource to dtable which is returning value from your function and that is your datatable (dt). And in second button click you are Clearing your dt which is your dataSource,and your data grid view is refreshing.To prevent this define a new DataTable in your method:
public DataTable runQuery(string qry)
{
    DataTable dt = new DataTable();
    cmd.CommandText = qry;
    con.Open();
    rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    dt.Load(rdr);
    con.Close();
    return dt;
}

Don't forget, classes are reference types,in this line:
dtable = dcon.runQuery("select * from books");

You are doing:
dtable = dt;

Therefore if you make some change in dt,it will affect your dtable which is your data source.