text:
Q: Loading a script in the  section I have a javascript for a specific page that I do not wish to be loaded in my header section. Is it possible to load it in the  section of the HTML.
Currently I have all my js code inside the  but I want to remove it to a seperate js file that I can load.
I tried using this but it did not work.
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.5.1.min.js"></script>

Thanks

A: Q1 : I have a javascript for a specific page that I do not wish to be loaded in my header section. Is it possible to load it in the section of the HTML.
-Yes you can load javascript any where you want, if writing inline code then make sure you add script tag around your code.
-also you can request files like in body
Q2: Currently I have all my js code inside the but I want to remove it to a seperate js file that I can load.
-- no problem in that, thats even better practice.
Q3 Requesting external file
to request external files you write below written fashion
<script src="http://file_name.js" type="text/javascript"></script>

A: It's not only possible (ref), it's frequently a good idea.
Putting your scripts as late in the page as possible, which frequently means just before the closing </body> tag, means the browser can parse and display your content before stopping to go download your JavaScript file(s) (if external) and fire up the JavaScript interpreter to run the script (inline or external).
Putting scripts "at the bottom" is a fairly standard recommendation for speeding up the apparent load time of your page.

A: Yes it is possible. Try and see.
For debugging, hardcode the jquery full path.
It is sometime recommended to load it at the end of the of the body, to make the main content of the page load faster.

A:
Is it possible to load it in the section of the HTML.

Yes.
From the spec:
<!ELEMENT BODY O O (%block;|SCRIPT)+ +(INS|DEL) -- document body -->

SCRIPT is among the elements that may be a child of the BODY elements. Numerous other elements may also have SCRIPT children.

<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.5.1.min.js"></script>

When I run echo base_url() I get my the hostname of my server. This would result in a URL such as example.comjs/query-1.5.1.min.js. You probably should drop that PHP snippet entirely and just use: src="/js/jquery-1.5.1.min.js" which would resolve to http://example.com/s/query-1.5.1.min.js.

A: Yahoo engineers recommendation for higher performance is to include your scripts at the end of your HTML, just before </body> tag. Therefore, it's even better.
To see where the problem is, you gotta first make sure that your js file is loading. User Firebug and go to scripts tab. Do you see your script? If not, then something is wrong with your path.

A: it should work...
Did you try to view the generated source and see if the PHP code indeed generated the right path?
beside that, it is recommended to load jQuery from a CDN such as google's :
https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js


text:
Q: How to write that the sum of two numbers is an element of set {1, 2, .., 8} in set theory? Is it $\quad a+b\in\{1, 2, ..., 8\}\quad$ or $\quad (a+b)\in\{1, 2, ..., 8\}$?
And is it $\quad S'=S\cup\{a+b\}\quad$ or $\quad S'=S\cup\{(a+b)\}$?
What is the most correct?

A: It is completely fine to write $a+b \in \lbrace 1,\ldots, 8 \rbrace$. Parentheses are (mostly) used when there is a risk of confusion about the order in which to apply the operations. Since $a + (b \in \lbrace 1,\ldots, 8 \rbrace)$ does not have any meaning whatsoever, it is not necessary to use parentheses. In the same vein, $S' = S \cup \lbrace a + b \rbrace$ is completely fine (and preferable).

A: Both notations are correct.
I would prefer $$ \quad a+b\in\{1, 2, ..., 8\}\quad$$ and
$$\quad S'=S\cup\{a+b\}\quad$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Razor components not compiling correctly in a .NET Standard library I have converted a library to .NET Standard 2.0 to be a Razor Component library:
I changed the SDK type to Razor:
<Project Sdk="Microsoft.NET.Sdk.Razor">

and added the references to the Razor component libraries
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components" Version="3.1.8" />
    <PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="3.1.8" />
  </ItemGroup>

However when editing components I find the compilation process is failing. For example it fails to correctly map a @bind=.. attribute in a HTML tag and the Razor components don't seem to compile correctly.

A: This is caused by a missing _Imports.razor file, which is normally created if you create a Razor Component Library directly. This brings the correct Component library into scope for Razor compilation. Create this in the root of the library.
The content should contain at least this line:
@using Microsoft.AspNetCore.Components.Web

You can bring other namespaces into scope as well if you desire.


text:
Q: Full screen background video that covers all available space Basically I want the video to behave the same way background-size:cover works - covering all available space - example here: http://www.aaronvanderzwan.com/maximage/examples/html5video.html. I got it resizing proportionally and centering - but it still doesn't cover all available space.
Javascript:
$(document).ready(function(e){

  var $item = $(".video");
  var proportions =  $item.width() / $item.height()

  // shim layer with setTimeout fallback
  window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            function( callback ){
              window.setTimeout(callback, 1000 / 60);
            };
  })();

  // usage:
  // instead of setInterval(render, 16) ....
  (function animloop(){
    requestAnimFrame(animloop);
    resize();
  })();

  function resize(){

    // center the item
    $item.css({"top": "50%", "margin-top":-parseInt($item.height()/2)})
    $item.css({"left": "50%", "margin-left":-parseInt($item.width()/2)})

    // scale it
    if($(window).width() / $(window).height() < proportions){
      scaleProportionalByHeight($(window).height())
    }else{
      scaleProportionalByWidth( $(window).width() )
    }
  }

  function scaleProportionalByWidth ( newWidth ) {
    $item.width(newWidth);
    $item.height(newWidth / proportions);
  }

  function scaleProportionalByHeight ( newHeight  )  {
    $item.height(newHeight);
    $item.width(newHeight * proportions);
  }

})

html:
<video class="video"  loop autoplay muted autobuffer="autobuffer">
  <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
</video>

A: Can't you just use CSS ?
like this:
HTML
<video loop autoplay muted autobuffer="autobuffer" id="myVideo">
    <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
</video>

CSS
video#myVideo{
    position: fixed; right: 0; bottom: 0;
    width: auto; height: auto; z-index: -100;
    min-width: 100%; min-height: 100%;
    background-size: cover;
}


text:
Q: In the Library of Count Dracula Am thinking about this question from the book Analysis $1$ by Herbert Amann and Joachim Escher:
In the library of Count Dracula no two books contain exactly the same number of
words. The number of books is greater than the total number of words in all the books.
These statements suffice to determine the content of at least one book in Count Dracula's
library. What is in this book?
My reasoning: If there is a total of $n$ words in all books, then there can be at most $n$ different books (since each book must have a different number of words). So how can there be more books than the total number of words in all books?
Am assuming there are no books with $0$ words.

A: I was reading this in Amann's Analysis 1 last night (I know, strange bedtime reading). I thought I would flesh out my take on it since the question is still unanswered (even if the comments state the solution).
You are forced to assume that one book has only blank pages:
Let $n$ be the number of books and $x_i$ the number of words in the $i$-th book. I interpret "The number of books is greater than the total number of words in all the books" as
$$
x_1 + \cdots + x_n < n
$$
If $x_i > 0$ for all $i$ you get
$$
  x_1 + \cdots + x_n \geq 1 + \cdots + 1 = n
$$
which contradicts the previous inequality. So at least one of the $x_i$ has to be $0$.
Now, if you bring in the additional assumption $x_i\neq x_j$ for $i\neq j$, you can prove that the only options are $n=1, x_1=0$, or $n=2, x_1 = 0, x_2=1$:
You have $n$ non-negative numbers $x_1,\dots, x_n$ which are all different. Also $x_i < n$ for all $i$ otherwise the sum would be $\geq n$. Since there are only $n$ integers between $0$ and $n-1$, you have, up to a relabeling of the books, $x_i = i - 1$. But then
$$
  x_1 + \cdots + x_n = 0 + 1 + \cdots + (n-1) = \frac{(n-1)n}{2}< n
$$
which reduces to
$$
  n(n - 3) < 0
$$
and the only solutions for $n$ an integer are $n = 1$ and $n = 2$.


text:
Q: Prove this vector identity using vector identities Let $f$, $g$ and $h$ be any $C^{2}$ scalar functions. Using the standard identities of vector calculus, prove that;
$$ \nabla \cdot \left( f\nabla g \times \nabla h \right) = \nabla f \cdot \left(\nabla g \times \nabla h \right)$$

Here is my working out so far;
  using identity 8
  $$ \nabla \cdot \left( f\nabla g \times \nabla h \right) = \nabla h \cdot \left(\nabla  \times f\nabla h \right) - f\nabla g \cdot \left( \nabla \cdot \nabla h \right)  $$ and the div of a scalar is a vector hence $$  = \overrightarrow H \cdot \left(\nabla  \times f\nabla \overrightarrow G \right) - f\nabla \overrightarrow G \cdot \left( \nabla \cdot \overrightarrow H \right) $$ and then using vector identity 10 gives me $$= \overrightarrow H \cdot \left(f\nabla  \times \overrightarrow G +\nabla f  \times \overrightarrow G\right) - f\nabla \overrightarrow G \cdot \left( \nabla \cdot \overrightarrow H \right) $$  and now I don't know whats next?

Here are the vector identities listed below

A: HINT: Use identity 7 with $\mathbf{F}=\nabla g\times\nabla h$.

A: HINT: Use Identity 8 with $\mathbf{F} = f\nabla g$, $\mathbf{G} = \nabla h$:
$$
\nabla \cdot (f\nabla g\times \nabla h)= \nabla h\cdot \big(\nabla \times (f\nabla g)\big)- f\nabla g\cdot \big(\nabla\times (\nabla h)\big).
$$
Notice $\nabla \times (\nabla h) = 0$. Then use Identity 10 on $\nabla \times (f\nabla g)$.


text:
Q: sp_OACreate returning (0x80131051) SQL 2016 x64, assembly targeting x64 I know there are tons of answers regarding issues with 32/64 bit conflicts, but in this scenario everything is lined up to run in a 64 bit process.
I am helping a customer upgrade from SQL Server 2008 R2 x64 to a new instance on SQL Server 2016 x64.
The customer has some old procedures (hundreds) that use a sequence of  sp_OACreate/Method/Destroy to excirsise our products COM interfaces coded in C# and exposed to COM and targets x64. Registered using the x64 version of RegAsm and is strong named and loaded in the GAC.
In my environment I have SQL 2008 R2 runnign and this all works as expected. I installed SQL 2016 and I repro the issue.
(I understand that it would be best to use a different approach however they are resistant to changing things as there are hundreds of places this is used.)
I also tested creating the object in a VB script and this works as expected. is able to run a VBScript in a 64-bit process and call CreateObject.
EXEC @hr = sp_OACreate 'Satori64.CASSTask', @TaskObject OUT, 4
EXEC sp_OAGetErrorInfo @TaskObject, @ErrorSource out , @ErrorDescription out

ErrorSource = "ODSOLE Extended Procedure"
ErrorDescription = "Class not registered"
hr = "-2147221164" (80040154)

EXEC @hr = sp_OACreate 'Satori64.CASSTask', @TaskObject OUT, 1
EXEC sp_OAGetErrorInfo @TaskObject, @ErrorSource out , @ErrorDescription out

ErrorSource = "ODSOLE Extended Procedure"
ErrorDescription = ""
hr = "-2146234287" (80131051)

After doing more research and reviewing the procmon logs I see that the way SQL Server looks up a COM object is very different from the way vbscript finds and loads it.
Thanks to some comments I dove deeper and reviewed procmon logs to see what might be happening. Between SQL 2008 R2 and 2016 the file and registry access is similar. the 2008 log shows that the Assembly is laded and the expected object is found and created.  The 2016 log show that it is able to find the assembly but then promptly fails unexpectedly.  While this helped it didn't answer what was going wrong.
So, I looked deeper to see if I could find why the assembly is not loading.
I added:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"LogFailures"=dword:00000001
"ForceLog"=dword:00000001
"LogPath"="C:\\Temp\\Fusion\\"

and reviewed the logs for the two versions:
Successful SQL R2 2008
*** Assembly Binder Log Entry  (11/18/2019 @ 10:06:54 PM) ***

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Program Files\Microsoft SQL Server 2008\MSSQL10_50.MSSQL2008\MSSQL\Binn\sqlservr.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = Satori64, Version=4.7.1.1, Culture=neutral, PublicKeyToken=ac6bbd3b7853cfdf
 (Fully-specified)
LOG: Appbase = file:///C:/Program Files/Microsoft SQL Server 2008/MSSQL10_50.MSSQL2008/MSSQL/Binn/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = sqlservr.exe
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Download of application configuration file was attempted from file:///C:/Program Files/Microsoft SQL Server 2008/MSSQL10_50.MSSQL2008/MSSQL/Binn/sqlservr.exe.config.
LOG: Configuration file C:\Program Files\Microsoft SQL Server 2008\MSSQL10_50.MSSQL2008\MSSQL\Binn\sqlservr.exe.config does not exist.
LOG: No application configuration file found.
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Satori64, Version=4.7.1.1, Culture=neutral, PublicKeyToken=ac6bbd3b7853cfdf
LOG: Found assembly by looking in the GAC.
LOG: Binding succeeds. Returns assembly from C:\windows\Microsoft.Net\assembly\GAC_64\Satori64\v4.0_4.7.1.1__ac6bbd3b7853cfdf\Satori64.dll.
LOG: Assembly is loaded in default load context.

Unsuccessful SQL 2016
*** Assembly Binder Log Entry  (11/18/2019 @ 10:08:37 PM) ***

The operation failed.
Bind result: hr = 0x80070002. The system cannot find the file specified.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Program Files\Microsoft SQL Server\MSSQL13.SQLSERVER\MSSQL\Binn\sqlservr.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = Satori64, Version=4.7.1.1, Culture=neutral, PublicKeyToken=ac6bbd3b7853cfdf
 (Fully-specified)
LOG: Appbase = file:///C:/Program Files/Microsoft SQL Server/MSSQL13.SQLSERVER/MSSQL/Binn/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = sqlservr.exe
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Program Files\Microsoft SQL Server\MSSQL13.SQLSERVER\MSSQL\Binn\sqlservr.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Satori64, Version=4.7.1.1, Culture=neutral, PublicKeyToken=ac6bbd3b7853cfdf
LOG: Fusion is hosted. Check host about this assembly.
LOG: Assembly is not in CLR Loaded list. Asking host assembly store.
LOG: Try host assembly store with assembly satori64, version=4.7.1.1, culture=neutral, publickeytoken=ac6bbd3b7853cfdf, processorarchitecture=amd64.
LOG: Try host assembly store with assembly satori64, version=4.7.1.1, culture=neutral, publickeytoken=ac6bbd3b7853cfdf, processorarchitecture=msil.
LOG: Try host assembly store with assembly satori64, version=4.7.1.1, culture=neutral, publickeytoken=ac6bbd3b7853cfdf.
WRN: Host assembly store does not contain this assembly.
ERR: Unrecoverable error occurred during pre-download check (hr = 0x80070002).

Here I am at a bit of a loss.  SQL could load the assembly, but for some reason not when accessing it through COM.
I decided to start from scratch and create a new assembly, with the absolute minimum references, a single class with a single method.
I strongly named it, registered it with RegAsm (x64) loaded it to the GAC.
This shows the exact same results. sp_OACreate works in 2008 R2 with no problem. Fails in 2014, and 2016.
Any ideas will be greatly appreciated!


text:
Q: What is the composition of relations like this? With no transitive relations between them? Given

$ R_1 = \{(1,2),(5,3)\}\quad\quad R_2 = \{(6,4),(5,7)\}$
What is $R_2 \circ R_1$?

Because in my understanding, using the example

$ R_3 = \{(1,2),(3,4)\} \quad\quad R_4 = \{ (2,5),(6,7)\}$
Then $R_4\circ R_3 = \{(1,5)\}.\;$ Am I correct?

So given that case, if $R_2 \circ   R_1 = (a,b),\;a$ comes from $R_1$, right? While $b$ comes from $R_2$?

A: We have by definition (assembled from your example)
\[ R_2 \circ R_1 = \{(a,b) \mid \exists c : (a,c) \in R_1, (c,b) \in R_2\} \]
In the $R_4 \circ R_3$ example $(1,5) \in R_4 \circ R_3$ as we can "plug in" $2$ in the middle where $(1,2) \in R_3$, $(2,5) \in R_4$.
If there is no "matching" pair from $R_1$ and $R_2$ as it is in your case, there is no $(a,b)$ fulfilling the condition for being a member of $R_2 \circ R_1$, we have by definition $R_2 \circ R_1 = \emptyset$.


text:
Q: Trigger a JScript webresource with a workflow on Dynamics CRM I have a request to if a case on CRM is created between 00:00 to 17:45 and not on weekends, to assign the case to a specific user.
I'm facing an issue that I can not trigger the Jscrip web resource to check the time, once the JS web resources only trigger onload or onsave the form.
Does anyone know how can I trigger that Js without having to open the case or when the case is created?
Thanks

A: There is no way to run JS from Workflow. The only solution for you is to implement the same functionality as your webresource has using WF/Custom Workflow Actions.


text:
Q: What is the shortest way to run same code n times in Swift? I have a code that I need to run exactly n times in Swift. What is the shortest possible syntax for that?
I am currently using the for loop but it is a lot of typing.
for i in 0..<n { /* do something */ }

Is there a shorter/nicer way for running same code n times in Swift?

A: Speaking of syntax, you might define your own shortest syntax:
extension Int {
    func times(_ f: () -> ()) {
        if self > 0 {
            for _ in 0..<self {
                f()
            }
        }
    }

    func times(_ f: @autoclosure () -> ()) {
        if self > 0 {
            for _ in 0..<self {
                f()
            }
        }
    }
}

var s = "a"
3.times {
    s.append(Character("b"))
}
s // "abbb"

var d = 3.0
5.times(d += 1.0)
d // 8.0

A: ABakerSmith's answer updated for Swift 4:
extension Int: Sequence {
    public func makeIterator() -> CountableRange<Int>.Iterator {
        return (0..<self).makeIterator()
    }
}

Use:
for i in 5 {
    //Performed 5 times
}

A: Sticking with a for loop - you could extend Int to conform to SequenceType to be able to write:
for i in 5 { /* Repeated five times */ }

To make Int conform to SequenceType you'll could do the following:
extension Int : SequenceType {
    public func generate() -> RangeGenerator<Int> {
        return (0..<self).generate()
    }
}

A: Shorter and (I think) clearer:
for i in 1...n { } // note: this will fail if n < 1

or
for i in n { }

A: You have several ways of doing that:
Using for loops:
for i in 1...n { `/*code*/` }

for i = 0 ; i < n ; i++ { `/*code*/` }

for i in n { `/*code*/` }

using while loops:
var i = 0
while (i < n) {
    `/*code*/`
   ` i++`
}

var i = 0
repeat {
   ` /*code*/`
    `i++`
} while(i <= n)

A: for _ in 1...5 {
  //action will be taken 5 times.
}

A: In Swift, what you have is the shortest syntax for performing a loop operation.

Swift provides two kinds of loop that perform a set of statements a
certain number of times:
The for-in loop performs a set of statements for each item in a
sequence.
The for loop performs a set of statements until a specific
condition is met.

If you want to run it infinite times, well try using a while.

A: There are a lot of answers here, highlighting just how creative you can be, with Swift.
I needed an array so I did this
extension Int {
    func of<T>(iteration: (Int) -> T) -> [T] {
        var collection = [T]()
        for i in 0..<self {
            collection.append(iteration(i))
        }
        return collection
    }
}

fun strings() -> [String] {
    return 4.of { "\($0) teletubby" }
}

A: you could use functional programming on a range instead of a loop, for shorter and "nicer" syntax for example
(0..<n).forEach{print("Index: \($0)")}

Other answers mention defining your own syntax for that. So - that can be fine for a tiny personal project, or as a learning experience. But defining your own syntax for something so trivial and basic in a large project would be maintenance and readability hell.

A: You could do something like this:
10⨉{ print("loop") }

Using a custom operator and an extension on Int:
infix operator ⨉ // multiplication sign, not lowercase 'x'

extension Int {
    static func ⨉( count:Int, block: () ->Void  ) {
        (0..<count).forEach { _ in block() }
    }
}

A: for-loops are a common way to repeat code. Here is an example of using a for-loop to hide six outlets, versus writing the same code for six outlets. Plus if you make another outlet all you have to do is add it to the array.
let array = [outLet0, outlet1, outlet2, outLet3, outLet4, outLet5]

for outlet in array {
  outlet.hidden = true
}

Versus writing it like this:
outlet0.hidden = true
outlet1.hidden = true
outlet2.hidden = true
outlet3.hidden = true
outlet4.hidden = true
outlet5.hidden = true

A: The only loop shorter than that is an infinite while loop:
while (true) {
}

But you would still have to increase a counter and check it in the loop to break the loop, and in the end it wouldn't be shorter.

A: ONLY 5 CHARACTERS (not including n or code)
r(){}

If you're just testing things and need a REALLY short line, try this. Emphasis on using this for testing, not in production, because no one will know what is going on without documentation.
define this somewhere globally
func r(_ n : UInt, _ c: @escaping () -> Void) { for _ in 0..<n { c() } }

call this when you want to run it
r(5) { /*code*/ }

A: Swift is so awesome, just write your own function or extension and you got it ;) 100 of options there, everyone can do it its own way just look at those answers here.
Or better, write it as you already do, as is common when apps are build in team, as everyone would do it differently anyway and all projects need those extension to be written again or own libs to have and maintain just for stupid thing, that you can write just by some standard way, as you already did with your for loop.


text:
Q: MVVM with Room and LiveData - How to get List from LiveData I am creating a TODO List application where the user can add tasks to do. There are a few categories of tasks. And I have the following situation:
        viewModelMainActivity = new ViewModelProvider(this).get(ViewModelMainActivity.class);
        viewModelMainActivity.getAllJob().observe(this, new Observer<List<Task>>() {
            @Override
            public void onChanged(List<Task> tasks) {

                if(tasks.size() == 0) {

                    linearLayoutActivityMain.setVisibility(View.VISIBLE);

                } else {

                    linearLayoutActivityMain.setVisibility(View.INVISIBLE);
                }

                taskAdapter.setTasks(tasks);
            }
        });

I get a list of tasks from the job category and from other categories. Thanks to LiveData in ViewModel, the list will be updated when a task is added or deleted.
In addition, I have a spinner that allows you to select a category of tasks to display tasks from a selected category.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    switch (position) {

        //How to get a List?
        case 0:
            Toast.makeText(this, "0", Toast.LENGTH_SHORT).show();
            break;
        case 1:
            Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
            break;
        case 2:
            Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
            break;

    }
}

How can I display a list of tasks from a selected category since the data type in ViewModel is LiveData, and only data in the form of List is obtained in the onChanged() method?

A: A look at your ViewModel would be nice, but from what I undertand its that you type in your viewmodel is just liveData.
Well in your ViewModel, you can set an other type to a liveData
EX :
String toto = LiveData<String>()

A: First tell the view model about the spinner selection and let viewmodel decide what to do
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position long id) {
    viewModelMainActivity.onCategorySelected(position);
}

Inside viewModel
public void onCategorySelected(int categoryId){
  TODO 1 you should have two live data one to hold all the tasks and the other one for the category tasks
  TODO 2 here filter the tasks based on category and the updated the live data
}

A: LiveData from Room always returns you a completely new list. You have to replace your old List with a new one.
Do not have LiveData from Room in your ViewModel


text:
Q: Update system application Good day.
We are creating a Control System sales in school cafeterias in C # with WPF and this system will be implemented in 18 schools in our network. ( Schools are scattered throughout the city and , therefore, the system updates will be made automatically by the Internet ) .
Researched ClickOnce ( got to develop something like that ) and we understand that this type of update is not feasible .
We created a system update using DotNetZip API but errors occurred saving file in the directory where the system files as incompatibility among other problems was installed .
My question is as follows :
Does anyone have any experience in this matter that could share with me , or any example of situation ( like it is) so we can apply here in our system ?
I'll put here the snippet of code that updates the system to create , analyze it if anyone wants it , it will be easier to understand the problem .
The logic of this code search an XML file available system version and compares it with the version of the assembly . If the version is higher, then down to a temp directory update files and transfer to the directory where the application was installed . The problem that occurs is that some types of files appear as if they are running even after they have been finalized with the main application .
I appreciate the help .
Main form that calls the updater
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var doc = new XmlDocument();
    doc.Load("http://www.meusite.org.br/Cantina/arquivoXML.xml");
        if (doc.DocumentElement != null)
        {
            var node = doc.DocumentElement.SelectSingleNode("/Application/Version");
            var node1 = doc.DocumentElement.SelectSingleNode("/Application/ZipFile");
            if (node != null)
            {
                var version = node.InnerText;
                var versionAssembly =     System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                if (Convert.ToDouble(version) > Convert.ToDouble(versionAssembly))
                {
                    Process.Start("Updater.exe");
                }
            }
        }
     }

Updater system:
using System.Diagnostics;
using Ionic.Zip;
using System.Xml;
using System.IO;

namespace Updater
{
public class Program
{
    private static void Main()
    {
   Process[] process = Process.GetProcessesByName("IASD.ASCS.WPF");
    foreach (Process proc in process)
    {
        if (!proc.HasExited)
            proc.Kill();
    }
    XmlDocument doc = new XmlDocument();
    doc.Load("http://www.meusite.org.br/Cantina/arquivoXML.xml");
    if (doc.DocumentElement != null)
    {
        XmlNode node1 = doc.DocumentElement.SelectSingleNode("/Application/ZipFile");
        if (node1 != null)
        {
            string zipfile = node1.InnerText;
            const string end = ("http://www.meusite.org.br/Cantina/");
            string file = (end + zipfile);
            ZipFile zipFile = ZipFile.Read(file);
            {
                foreach (var zipEntry in zipFile)
                {
                    zipEntry.Extract(@"c:\IASD\CantinaEscolar\Temp",ExtractExistingFileAction.OverwriteSilently);
                }
            }
            string dirTemp = @"c:\IASD\CantinaEscolar\Temp";
            string dirInstalacao = @"c:\IASD\CantinaEscolar\";
            string[] arquivos = Directory.GetFiles(dirTemp);
            foreach (string item in arquivos)
            {
                string nomedoarquivo = Path.GetFileName(item);
                if (nomedoarquivo != null)
                {
                    string destino = Path.Combine(dirInstalacao, nomedoarquivo);
                    File.Copy(item, destino, true);
                }
            }
            string[] arquivosApagar = Directory.GetFiles(dirTemp);
            foreach (string item in arquivosApagar)
            {
                File.Delete(item);
            }
            Process.Start("IASD.ASCS.WPF.exe");
        }
    }
    const string nomeExecutavel2 = "Updater.exe";
    foreach (Process pr2 in Process.GetProcessesByName(nomeExecutavel2))
      {
        if (!pr2.HasExited) pr2.Kill();
      }
    }
  }
}

In this example I am determining which location the system will be installed but will I need to provide the user installs in any directory on your computer (which is another problem that I could not work around).

A: When you are doing an update and the application is still running you can do it anyway but you have to rename all files and then paste the new ones. The application will keep running normally till the next application restart.
Our process looks like this:

*

*Check for updates

*Download update zip

*Rename all files to *.old

*Extract the zip file to the application location

*Close (kill) and restart application

*Delete *.old files on startup

We never had any problems with this behaviour, but maybe you wan't to implement a mutex for your application so you can be sure there is only one instance running at the same time.

A: After you start off the download in the Window_Loaded event, the original process keeps running. This when the downloader tries to replace the exe file and any files it is using it will fail.
After starting the updater, Process.Start("Updater.exe"); you need to exit the current process and make sure it is not running at all. You can do this by adding the following line:
if (Convert.ToDouble(version) > Convert.ToDouble(versionAssembly))
{
    Process.Start("Updater.exe");
    Application.Exit(); // Assumes a WinForms app
}


text:
Q: Conditional based where condition in sequelize Node JS I am trying to execute a query in sequelize, in which the where conditions have to be added based on the request parameters
router.get("/getsearchdata",(req, res) => {
    var searchquery =[
        {model:ProvidersCategories,attributes:["category_id"],
        include: [
            {model:Categories,attributes:["category_id","category_name"]},
        ]
        }
        ]

    if(req.query.agency && req.query.agency!=''){
        searchquery.where = {
        $and: [
        {agencyName: {$like: '%' + req.query.agency + '%'}},
        ]
    }
    }

    Providers.findAll({
        include:searchquery
    }).then(providerData =>{
        if(!providerData) {
        res.status(404).send({reason:'no data found'});
        } else {
        res.status(200).send(providerData);
        }
    });
    });

I have three tables "providers", "categories" and "provider_Categories". I am trying to join the three tables and get the providers.
In the request i.e req, if there is an input req.query.agency != '' then an if condition has to added where agencyName like "% + req.query.agency + %", if input req.query.agency == '' then there should be no if condition. For which I have tried the above code. But the where condition is not getting concatenated to the main query even if there is input req.query.agency
What is the right way to write where conditionally

A: Your variable searchquery is an array and you can't assign a where property to it. What you should do, is just passing a where object to the query options object:
    router.get("/getsearchdata", (req, res) => {
        var whereClause;

        if (req.query.agency && req.query.agency != '') {
            whereClause = {agencyName: {$like: '%' + req.query.agency + '%'}};
        }

        Providers.findAll({
            include: [
                {
                    model: ProvidersCategories, attributes: ["category_id"],
                    include: [
                        {model: Categories, attributes: ["category_id", "category_name"]},
                    ]
                }
            ],
            where: whereClause
        }).then(providerData => {
            if (!providerData) {
                res.status(404).send({reason: 'no data found'});
            } else {
                res.status(200).send(providerData);
            }
        });
    });


text:
Q: Resolving promises on filter I have a filter and I can't get it to resolve the promise. It is using a model called 'patient' that hasMany 'addresses' and I want to filter out the address that has an addressType of 'Primary'. The filter seems to be working but only will return a promise. Thank you in advance for the help.
Patient controller
App.PatientController = Ember.ObjectController.extend

  primaryAddress: Em.computed 'model.@each.addresses', ->
    @get('model.addresses').then (addresses)->
      addresses.filterBy 'addressType', 'Primary'

Solution (Thanks to @GJK)
  primaryAddress: Em.computed 'model.addresses.@each', ->
    @get('model.addresses').filterBy('addressType', 'Primary').get('firstObject')

A: The most obvious issue that I can see is that you're not watching the @each property of the addresses. Your property depends on model.@each.addresses, which means that your model is an array, and you're observing the addresses property on each item in that array. But you're not observing the content of the addresses array, just the array itself.
It seems to me that you should use model.addresses.@each as your dependent property. This will observe all addresses on a single model, including observing the contents of the addresses array (which updates when the promise resolves).
EDIT: Also, I didn't quite read far enough apparently. You shouldn't be calling then on the promise. Treat it as if it's already resolved, and it'll be updated when it does resolve. So use this instead:
App.PatientController = Ember.ObjectController.extend
  primaryAddress: Em.computed 'model.addresses.@each', ->
    @get('model.addresses').filterBy 'addressType', 'Primary'

The first time this property comptues, the promise will be unresolved so the filter won't return anything. But when the promise resolves, the property will update and the filter will work like you expect it to.


text:
Q: IntPtr vs UIntPtr This should be simple: I see everywhere people use IntPtr, is there any reason I should use UIntPtr instead?

A: Doesn't seem like there would be a good reason to.  From the docs:

Remarks
...
The IntPtr type is CLS-compliant,
  while the UIntPtr type is not. Only
  the IntPtr type is used in the common
  language runtime. The UIntPtr type is
  provided mostly to maintain
  architectural symmetry with the IntPtr
  type.

A: Well according to Microsoft UIntPtr is provided mostly for architectural symmetry.  Another interesting point is that UIntPtr is not CLS compliant.
On the surface it would seem that IntPtr is the preferred option.  However, if you know you will be doing pointer arithmetic then UIntPtr may be a better choice since in the off chance there were some obscure problem dealing with negative values.

A: There is a big difference.. For example, on a 32-bit application, new UIntPtr(0xC01E0001) results in a pointer at 3223191553, but IntPtr(0xC01E0001) results in a System.OverflowException: "Arithmetic operation resulted in an overflow". That is, because 0xC01E0001 is greater than MaxValue for Int32.
So if one still wants such a pointer, a negative integer needs to be used as internal value for IntPtr, like
unchecked((IntPtr)(int)0xC01E0001)

To answer your question: For values greater than Int32.MaxValue it is easier and somehow cleaner to use UIntPtr. It is probably always the best solution, since pointers are always considered unsigned.


text:
Q: PDF in iframe cached How to use an iframe to dynamically open multiple pdf files (one at a time according to what the client will click on) but not cache them on the client machine, because if that file content on the server got changed (added new pages to it for example), the client will still get the older version unless he/she clears the browser's cached files

A: If you suffix the url to the pdf file with a unique query string parameter, that you change whenever the pdf file is changed, the browser will cache each version of the file separately
Example:
change http://site/myFile.pdf
to http://site/myFile.pdf?v=f955b055-d551-4762-8313-a2417dc70568

A: Add headers in the response to avoid caching in donwstream servers
HttpContext.Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
HttpContext.Response.AppendHeader("Pragma", "no-cache");
HttpContext.Response.AppendHeader("Expires", "0");

A: You will need to disable response cacheing for the files. In the case of ASP.NET MVC, it's as simple as the following:
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will be applied to all actions in Controller, unless those actions override with their own decoration
    public class FilesController : Controller
    {
        public ActionResult GetFile(string id)
        {
             return File();//do file
        }
    }


text:
Q: С#. С чего начать? Привет! Хочу начать изучать C#. Не подскажете литературу какую-нибудь, сайты? Очень хочется, так как Delphi для моих задач никак не подойдёт, а C# отлично подходит :)
A: Ну есть начинать изучать C#, было бы хорошо знать C++ хотя бы основы.
А так Эндрю Троелсен - Язык программирования C# (тут будет год стоять, выбирай на наиболее поздний)
Очень хорошая книга.
A: Эндрю Стиллмен и Дженнифер Грин "Изучаем C#" Книга из серии HeadFirstLab...меня буквально затянула, до нее языки программирования не знал вообще(сами языки то не проблема была никогда выучить, а вот понять, что-куда и зачем(это я про ООП), до этой книги было сложно).
Сейчас легко усваиваю книги посложнее(Герберд Шильдт), даже взялся за ASP.
A: Герберт Шилдт - C# 4.0. Полное руководство.
Отличный учебник без всяких излишеств. Далее (говоря наперёд и может быть это послужить как источник вдохновения для изучения C#) могу посоветовать смотреть в сторону XAML и Metro-приложений, т.к релиз Win8 всё ближе и ближе, а там если вы не знаете сотворили свой магазин приложений, а окошками пользуются как я слышал ~90% всех пользователей компьютеров, а это очень много и как вы знаете в магазине можно продавать.
A: Вот почитай http://rghost.ru/37068398, я с него начинал, а про C++ не согласен, я знал только VB и всё и выучил C# на базовом уровне без всяких С++... Ну и конечно же MSDN!!!


text:
Q: Want to update the progress bar from activity for each item on uploading item and adding it to recyclerview I'm creating a chat app in which I want to upload files with progress showing but could not able to update UI as upload progress.
I created an interface ProgressUpdateListener in the class MultipartUtility used to upload file and creating a object of MultipartUtility and progress listener in which I call PublishProgress to update progress for AsyncTask.
Created one interface in Activity and used to update progress in adapter
/* to get progress update from MultiUtility class using interface in actviity */
MultipartUtility multipart = new MultipartUtility(strings[0], charset, new MultipartUtility.ProgressUpdateListener() {
    @Override
    public void onProgressUpdate(final long progress, final String msg_id) {
        //Toast.makeText(ChatRoom.this, progress+"", Toast.LENGTH_SHORT).show();
        Log.e("DataP", progress + "");
        publishProgress(String.valueOf(progress), msg_id);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mOnDataChangeListener.onDataChanged(progress, msg_id);//activity interface function
                dataBaseHelper.updateProgress(msg_id, (int) progress);
                chatAdapter.notifyDataSetChanged();
            }
        });
    }
});

/* to get update in adapter from activity using interface function of activity */
activity.setOnDataChangeListener(new ChatRoom.OnDataChangeListener() {
    @Override
    public void onDataChanged(long progress, String msg_id) {
        try {
            Log.e("ProgressInAdapter", progress + " ****** " + msg_id);
            if (object.getId().equalsIgnoreCase(msg_id)) {
                object.setProgress((int) (progress * 10));

                dataSet.set(listPosition, object);

                ((MyVideoHolder)holder).pbProgress.setProgress(object.getProgress());
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
});

A: You have to store Viewholder position and progress on change, use this position while update progress bar.
 If  ViewHolder.getAdapterPosition() == position => Then we are at right viewholder, update UI, otherwise do nothing
You have to initialize listener inside onBindViewHolder and pass to Asynctask to update correct ViewHolder

  public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int position) {

// listener passed to asynctask to call on progress change
        viewHolder.update( new OnProgressUpdate() {
                @Override
                public void onProgress(DownloadUpdate update1,String msg1) {
//  check whether listener called for right position of item list
                    if(update1.getPosition() == RecyclerView.NO_POSITION ||
                    update1.getPosition()!= viewHolder.getAdapterPosition()) return;

                    viewHolder.bar.setProgress(update1.getProgress());
                    viewHolder.bar.setMax(update1.getMaxProgress());
                    viewHolder.msg.setText(msg1);
                }
            };);

    }

You have to maintain state outside list because ViewHolder are re-used, order of viewholder is not sure to store state.
I have implemented and tested with custom class to store progress and  implementation here


text:
Q: Passthrough e-cig (without battery) I'm looking to build myself a passthrough e-cigarette and here is the schematic I came up with :

simulate this circuit – Schematic created using CircuitLab
My question is will this work ? I mean in theory I think it should but is there practical things I'm missing ? I remember in school I saw that switches can do crazy things when pressed, would a step down voltage regulator be able to handle being connected directly to a button ? Is a Cinch cable suitable for such electrical values (less than 5v coming out of the buck converter and 1.8Ohm of resistance for the heating resistance).
Thanks in advance to anyone willing to help.


text:
Q: How do I attach metadata to a text corpus with quanteda? I am using quanteda to create a text corpus and trying to attach metadata, but I keep getting an error. I have used this code before on another dataset, but for some reason it's not working with my current dataset. The code is:
dfm.ineq1 <- corpus(df.ineq$speech,
                        docnames=df.ineq$speechID,
                        docvars=select(party))

The error I get is:

Error in select_(.data, .dots = lazyeval::lazy_dots(...)) :    object
  'party' not found

I also tried to put party in quotes and got this error:

Error in UseMethod("select_") :    no applicable method for 'select_'
  applied to an object of class "character"

The party column is pretty straight forward. The values are:
"Democratic"  "Republican"  "N/A"         "Independent"

Any ideas on what might be going wrong?

A: An even easier way: use the fact that the corpus constructor method is defined for data.frame objects.
dfm.ineq1  <- corpus(df.ineq, text_field = "speech")

This will automatically load the text field in speech correctly, and include speechID and party as docvars.

A: I realized I forgot to put the dataframe in the select parenthesis!
dfm.ineq1 <- corpus(df.ineq$speech,
                        docnames=df.ineq$speechID,
                        docvars=select(df.ineq, party))


text:
Q: How do I overlay these buttons on top of an image for a background in Python Tkinter Currently, I'm attempting to create a simple main menu for a game using Tkinter as a simple GUI since it's a simple RPG game and Python however the image overlays the buttons in all circumstances.
I've tried using some other solutions like placing them or creating a window but I can't find a straight answer of how to make that either.
import tkinter
from tkinter import *
from PIL import ImageTk, Image
(PIL is from when I was using a JPG before.)

root = Tk()
content = ttk.Frame(root)
root.geometry("600x600")

background = ImageTk.PhotoImage(Image.open("bred.png"))
canvas = tkinter.Canvas(root, width=580, height=600)

content.grid(column=0, row=0)

Btn1 = Button(content, text="Play", width=5, height=1)
Btn2 = Button(content, text="Kill me", width=7, height=1, command =
root.quit)

backgroundlabel = tkinter.Label(root, image=background)
backgroundlabel.image = background

backgroundlabel.place(x=0, y=0, relwidth=1, relheight=1)

Btn1.grid(row=1, column=2, padx=(130))
Btn1.columnconfigure(1, weight=1)
Btn1.rowconfigure(1, weight=1)

Btn2.grid(row=1, column=3, pady=(130))
Btn2.columnconfigure(3, weight=1)
Btn2.rowconfigure(1, weight=1)

root.mainloop()

A: Currently your background's master is set to root while your buttons are set to a frame. The first thing you need to do is set both to the same master, i.e. changing background master to content:
backgroundlabel = tk.Label(content, image=background)

Next you need to deal with the stacking order. You can call widget.lift() to raise the buttons to top:
Btn1.grid(row=1, column=2, padx=(130))
...
Btn1.lift()

Btn2.grid(row=1, column=3, pady=(130))
...
Btn2.lift()


text:
Q: Move the check mark in MacOS dropdown I made a drop down list using the <select> and <option> tag, where every time a  new input is typed, the program creates a new option tag with value attribute to add it to the existing options in the drop down list.
However, my client uses a MacOS and he wanted to move the check mark on the drop down list to the recently added option. The check mark only moves when you click on the selected line, but in my case, I want it to also move to the recently added/typed data.
Here is the HTML code:

    <select id = 'combo-box' title = "Saved Talk" onchange="document.getElementById('userText').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
  </select>

    <input id ="userText" name="userText" type="text" onfocus="this.select()" ></input>
    <input name="idValue" id="idValue" type="hidden">
    <button id="speakText" class="toolbutton" title="Speak"></button>

And the JS:
hiddenArray(); // Access speakArray

// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
    speakArray = [];
}

function playVoice(language, text) {
  playing = text;

        //Adds option when text is spoken
        var addUserInput = document.createElement("OPTION");
        addUserInput.setAttribute("value", playing);
        addUserInput.text = playing;
        document.getElementById("combo-box").appendChild(addUserInput);

        speakArray.push(playing); // Adds recent talks to speakArray

  if(document.getElementById('mode').innerHTML=="2"){
    //After the voice is loaded, playSound callback is called
    getBotReply(text);
    setTimeout(function(){
        loadVoice(language, playSound);
    }, 4000);
  }
  else{
            loadVoice(language, playSound);
  }
}

A: I've figured it out in the end. Here is the code:
 hiddenArray(); // Access speakArray

// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
    speakArray = [];
}

function playVoice(language, text) {
  playing = text;

  //Adds option when text is spoken
  var addUserInput = document.createElement("OPTION");
  addUserInput.setAttribute("value", playing);
  addUserInput.text = playing;
  document.getElementById("combo-box").appendChild(addUserInput);

  document.getElementById("combo-box").value = playing;

  speakArray.push(playing); // Adds recent talks to speakArray

  if(document.getElementById('mode').innerHTML=="2"){
    //After the voice is loaded, playSound callback is called
    getBotReply(text);
    setTimeout(function(){
        loadVoice(language, playSound);
    }, 4000);
  }
  else{
            loadVoice(language, playSound);
  }
}

So what I did here is asign the value of the combo box (select tag) to the recently added option (variable playing).


text:
Q: Cookie not working after mod rewrite rule I have a simple cookie used to set the chosen language:
$lang = $_GET['lang'];
$myLang = $_COOKIE["myLang"];

if (!isset($_COOKIE["myLang"])){
    setcookie("myLang", "en", $expire);
    include "languages/en.php";
    $myLang = "en";
    }else{
    include "languages/$myLang.php";
}

// One year to expire
$expire = time()+60*60*24*30*12;

// Put $languages in a common header file.
$languages = array('en' => 1, 'fr' => 2, 'nl' => 3);

if (array_key_exists($lang, $languages)) {
    include "languages/{$lang}.php";
    setcookie("myLang", $lang, $expire);
    $myLang = $lang;
}

After using some rewrite rules, it just doesn't work anymore. I tried the following:
setcookie("myLang", "en", $expire, "/" , false);

.htaccess file:
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    Options +Indexes
    RewriteEngine On
    RewriteBase /
    RewriteRule ^sort/([^/]*)/([^/]*)$ /3arsi2/sort.php?mode=$1&cat=$2 [L]
    RewriteRule ^category/([^/]*)$ /3arsi2/category.php?cat=$1 [L]
    RewriteRule ^category/([^/]*)/([^/]*)$ /3arsi2/category.php?cat=$1&lang=$2 [L]
    RewriteRule ^search/([^/]*)$ /3arsi2/search.php?mode=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^u/([^/]+)/?$ 3arsi2/user.php?user=$1 [NC,L]
    RewriteRule ^u/([^/]+)/(images|videos|music)/?$ 3arsi2/user.php?user=$1&page=$2 [NC,L]
    RewriteRule ^([^\.]+)$ 3arsi2/$1.php [NC,L]
</IfModule>

A: Never mind. I just need to do the following:
setcookie("myLang", "en", $expire, "/");

Now everything is back to normal.
Hopefully this will save someone else time in the future.
Peace.


text:
Q: Fancybox open twice programmatically 2.06 I am trying to open fancybox programmatically. Not through link. Once user click addform and i create form manually and show the form in fancybox. sout variable contains the form html.
$.fancybox({
                            openEffect  : "none",
                            closeEffect : "none",
                            autoDimensions    : false,
                            width             : 620,
                            height            : "auto",
                            content : sOut
                        });
Then call this
$.fancybox.close();
My problem now is when i clcked same button the fancybox not showing up again. if you have done this let me know. How to close properly fancybox so i can reopen.

A: Probably, you must remove the below command in fancybox code:
'hideOnContentClick': true


text:
Q: Error trying to understand timeseries dimensions I am trying to calculate rolling daily correlations on 2 stock prices (type xts), AGL and BIL (OHLC data below):
library(RODBC)
library(quantmod)
library(xts)
library(TTR)

dput(my.AGL)
structure(c(28500, 27800, 28699, 28440, 28569, 28600, 26650,
27250, 26910, 27450, 28814, 27950, 28950, 28740, 29250, 28765,
27429, 27584, 27534, 28072, 27122, 27050, 28406, 28030, 28211,
27349, 26618, 26509, 26560, 27200, 27203, 27900, 28665, 28694,
28836, 27698, 27090, 26600, 27079, 27206), .Dim = c(10L, 4L), .Dimnames = list(
    NULL, c("days.Open", "days.High", "days.Low", "days.Close"
    )), index = structure(c(1312988460, 1313074860, 1313420460,
1313506860, 1313593260, 1313679660, 1314025260, 1314111660, 1314198060,
1314284460), tzone = "", tclass = c("POSIXt", "POSIXct")), class = c("xts",
"zoo"), .indexCLASS = c("POSIXt", "POSIXct"), .indexTZ = "", tclass = c("POSIXct",
"POSIXt"))

my.AGL
                    days.Open days.High days.Low days.Close
2011-08-10 17:01:00     28500     28814    27122      27203
2011-08-11 17:01:00     27800     27950    27050      27900
2011-08-15 17:01:00     28699     28950    28406      28665
2011-08-16 17:01:00     28440     28740    28030      28694
2011-08-17 17:01:00     28569     29250    28211      28836
2011-08-18 17:01:00     28600     28765    27349      27698
2011-08-22 17:01:00     26650     27429    26618      27090
2011-08-23 17:01:00     27250     27584    26509      26600
2011-08-24 17:01:00     26910     27534    26560      27079
2011-08-25 17:01:00     27450     28072    27200      27206

I then create a series using ROC:
my.AGL.roc <- ROC(my.AGL[,4])

From the feedback below, I gathered that ROC is not compatible with 2.13.1, so, to create log returns I replaced the ROC function with:
my.AGL.lret <- log(my.AGL[,4]) - log(lag(my.AGL[,4], 1)

replacing the first NA observation with:
my.AGL.lret[ is.na(my.AGL.lret) ] <- 0

 my.AGL.lret
                      days.Close
2011-08-10 17:01:00  0.000000000
2011-08-11 17:01:00  0.025299427
2011-08-15 17:01:00  0.027050178
2011-08-16 17:01:00  0.001011175
2011-08-17 17:01:00  0.004936565
2011-08-18 17:01:00 -0.040264398
2011-08-22 17:01:00 -0.022195552
2011-08-23 17:01:00 -0.018253440
2011-08-24 17:01:00  0.017847304
2011-08-25 17:01:00  0.004679017

However, both suggestions yield the same result in terms of the error. The reason I am using xts, is that I want to merge my resulting rolling correlation with my original price series.
> rollapply(my.AGL.lret, 30, mean)
Error in `colnames<-`(`*tmp*`, value = "days.Close") :
  attempt to set colnames on object with less than two dimensions
> rollmean(my.AGL.lret, 30)
Error in `colnames<-`(`*tmp*`, value = "days.Close") :
  attempt to set colnames on object with less than two dimensions

I am sure I am doing something silly, but I would appreciate it if someone could please explain how the dimensions are handled? With my limited knowledge I have created a return series, which is still a time series.
dim(my.AGL.roc)
[1] 406   1

Thanks in advance
Ed

A: There's nothing wrong with TTR::ROC under R-2.13.1.  You can use TTR::runCor to calculate the rolling correlation between your two price series.
library(quantmod)
my.AGL <-
structure(c(32020L, 32810L, 33000L, 33394L, 33650L, 34205L, 34140L,
33400L, 34300L, 32975L, 33179L, 33450L, 33700L, 34180L, 35000L,
34140L, 33600L, 34300L, 32020L, 32460L, 32811L, 33157L, 33599L,
34205L, 33299L, 33155L, 33106L, 32850L, 33020L, 33400L, 33539L,
34000L, 34461L, 33480L, 33400L, 33250L), .Dim = c(9L, 4L), .Dimnames = list(
    NULL, c("days.Open", "days.High", "days.Low", "days.Close"
    )), index = structure(c(1262646025, 1262732404, 1262818810,
1262905220, 1262991623, 1263250801, 1263337207, 1263423608, 1263510020
), tzone = "", tclass = c("POSIXct", "POSIXt")), .indexCLASS = c("POSIXct",
"POSIXt"), .indexTZ = "", class = c("xts", "zoo"))

my.AGL.roc <- ROC(Cl(my.AGL))
my.BIL.roc <- ROC(Op(my.AGL))  # since OP didn't provide BIL data
runCor(x=my.AGL.roc,y=my.BIL.roc,n=3)
#                              [,1]
# 2010-01-04 17:00:25            NA
# 2010-01-05 17:00:04            NA
# 2010-01-06 17:00:10            NA
# 2010-01-07 17:00:20 -0.6614544157
# 2010-01-08 17:00:23 -0.8643698058
# 2010-01-11 17:00:01  0.0001661546
# 2010-01-12 17:00:07  0.8768496736
# 2010-01-13 17:00:08  0.3459987310
# 2010-01-14 17:00:20  0.0289108044

UPDATE:
zoo's rollapply doesn't work with xts objects in this case because of a fundamental design difference between xts and zoo objects.  xts objects always have a dim attribute, whereas zoo objects can be a vector.  The rollapply calculation "drops" to the lowest dimension, which reduces the input xts object to a vector and you can't set column names on a vector.
Adding xts rollapply methods has been on my to-do list and this won't be a problem once those are available.

A: The first observation in my.AGL.roc is probably NA.
From the ?rollmean:

The default method of rollmean does not handle inputs that contain NAs. In such cases, use rollapply instead.

rollapply(my.AGL.roc, 30, mean)


text:
Q: How to restrict options in HTML form based on database contents? I'm looking for a way to dynamically restrict the options in a search form, based on the actual database contents. I'm aiming to both speed up searching and avoiding empty results...
I have no idea what terminology to use to describe this (so I may be searching badly), and I don't have many concrete examples, but here is one: the
Rendition Project database search. There are four "dropdown" form fields, with over 20 options under the first, over 30 options under the second and so on.
The behaviour that interests me in the given example is the following: If you set the first field to the first option [Afghanistan], immediately the second field's options are reduced to two [Afghanistan/COBALT and Afghanistan/all]; and vice versa if you have a clean form sheet and set the second field to Afghanistan/BROWN then there's only 2 options under the first field [Turkey and Pakistan].
This is clearly an elegant way to reduce searches to manageable sizes. To a large extent, webshops like Amazon also display this behaviour by whittling down product categories and then allowing ticking boxes by brand or quality-rating ("three or more stars" etc), or pack-size and other ad-hoc categories, but (a) this is much more advanced than I need and (b) this is far from the instant feedback of the example, requiring reload (as expected for querying a db with millions of items; or probably querying a temporary table with the thousands of initial results).
I have a database with a similar number of product items [a few hundred] and search criteria [five]; as in the given example some field values are much more "sensitive" (as in, different values drastically increase/reduce database results), where some combinations of five search criteria give a few dozens of results BUT there's also combinations of three search criteria that already give empty results. [E.g. for a hardware store, clearly a "0--25$" price search will contain many dozens of results for screws-and-nails, but zero for chainsaws.]
So I don't want my visitors to have to find the "sensitive" values by trial and error! In the given sample you can see the sensitivity before your eyes, and hence set/release the four values as needed.
It's for a website written in WordPress, which so far isn't using any external plugins [a load-data-from-CSV plugin was used to read the data in, and a self-written plugin defines a Custom Post Type and its taxonomies and so forth; presentation by self-written theme], just default form fields and so forth. Default database and so forth.

A: What you ask is a complicated procedure. The generic answer that you have to work with, is AJAX. Such data manipulation as you describe, is not possible in the HTML level (especially the sensitive information, that if it's handled at that point, it means it's been already exposed, and the attacker just needs to press an F12 - on windows).
In simple terms:

*

*On keypress, make ajax search request for available fields with the
given string.

*Backend retrieves and provides all the possible results that start with the given string.

*Present the available values upon AJAX success.

And just to make it clear, this is not an HTML issue. HTML is just responsible for formatting what you want to present at this point.


text:
Q: htop inaccurate on macOS I'm trying to monitor the resource usage on an iMac 'remotely' (it's actually in Target Display Mode), so I installed htop via Homebrew.
The problem is, htop doesn't seem to be accurate in displaying what processes are using CPU resources. For instance, in the screenshot, all of the cores are 100% busy but htop displays nothing (it should show the 'FahCore_a7' process as consuming all the CPU, if I look at Activity Monitor on the target this is what's happening). This happens remotely via SSH or logged into the target directly.
How can I get htop to show resource usage correctly or is there another command I could use?

A: The various *topcommands return approximate values, useful for a quick overview of what's going on. For detailed, precise values go for e.g. sar(1).


text:
Q: Как складывать и вычитать поступающие в БД числа от одного id? Имеется таблица в SQLite, есть столбец operation, нужно чтобы при функции 'Доход' число добавлялось к тому что там есть, и при функции 'Расходы' число от пользователя вычиталось. Как это можно реализовать в python sqlite3?
Моя запись в теле бота:
def get_sum(message):
if message.text == 'Доходы':
    bot.send_message(message.chat.id, 'Введите сумму: ')
    bot.register_next_step_handler(message, get_oper)

def get_oper(message):
value = int(message.text)
operation = '+'

BotsBD.add_record(message.from_user.id, operation, value)

Моя запись в части БД(полагаю основная ошибка в ней):
 def add_record(self, users_id, operation, value):
    """Создаём запись о расходах/доходах"""
    self.cursor.execute("INSERT INTO `records` (`users_id`, `operation`, `value`) VALUES (?, ?, ?)",
                        (self.get_user_id(users_id),
                         operation == '+',
                         value))
    return self.conn.commit()

operation в таблице SQLite имеет тип Boolean и не равно 0.

A: Как это вижу я:

*

*Создаём таблицу, в ней столбцы - user_id, balance

*Не добавляем значения, а изменяем их

Как это выглядит в коде:
def plus(self, user_id, amount):
    self.cursor.execute('UPDATE records SET balance = balance + ? WHERE user_id = ?', (amount, user_id))
    self.connection.commit()
#минус по аналогии, в запросе просто меняем знак

Важный нюанс! Нам нужно создать первую запись, для этого мы проверяем наличие записей в бд и создаём новую, если записи отсутствуют
def exists(self, user_id): #проверка наличия записей
    res=self.cursor.execute('SELECT * FROM records WHERE user_id = ?', (user_id,))
    return bool(len(res.fetchall())

def add(self, user_id): #создание новой записи
    self.cursor.execute('INSERT INTO records (user_id, balance) VALUES(?,?)', (user_id, 0))
    self.connection.commit()


text:
Q: &* for raw pointer, iterator and ... std::nullptr_t I have a template function that is enabled (through a std::enable_if) its parameter is a raw pointer, or has a std::iterator category or is a std::nullptr_t. In that function, a raw pointer (a data member) is set equal to the parameter, like that :
template<class T> void myFunction(T it)
{
    _ptr = &*it;
}

The &* works well for pointer and iterator ... but it fails for a std::nullptr_t. Is there any solution available to avoid to write 2 different functions ?
Thank you.

A: The simplest thing is to change the function to have two overloads, one for raw pointers/nullptr_t that just stores the value and one selected by SFINAE for iterators with your current implementation, although you should note that this will fail under some circumstances (in particular if iterator::value_type overloads unary operator&).

A: As always, we can solve this with a trait. This time, let's not write a full class, since a simple function overload suffices.
#include <cstddef>
#include <memory>

template <typename T>
T get_addr(T t) { return std::addressof(*t); } // #1

std::nullptr_t get_addr(std::nullptr_t np) { return np; }

Usage:
T _ptr = get_addr(it);

(This trait also works if the type pointed to by T overloads operator&.)
You're invited to guard the overload #1 with the same enable_if condition that you have in your main template.


text:
Q: JSP web design tool I was wondering what do you guys use to design the .jsp file? I know it needs to be coded, but is there an easy way to build the layout in jsp? Tables..etc

A: A graphic artist, or someone who knows how to do proper design, creates an HTML layout with flexible CSS rules.
Then, you change .html to .jsp and have at it.

A: Every modern IDE for Java has some plugin that will give you code completion to make a jsp.
Only thing that you need to now is what you are trying to represent on a page and that final product will be basic html.
So 2. options:
1. give some designer to make you all the pages you need , and then change them according to your specification or
2. Try this: Photoshop + slicing + html design (html + css - some grid system perheps) + add jsp tags :-)


text:
Q: Merge Word document data into CSV I currently have a CSV file that will have multiple different pieces of info, but it will have a document name always as the first column.  I have code that opens the CSV, then reads it into an array, but when it opens the document for merging it will open the document and merge all the rows making a total of currently 4 documents inside 1.
What I want is 1 document for each line, then close the merged document and open the next for merging then close and so forth for each line.  Each line could have different document names.
Here is the code I'm currently using:
Dim LLCODE$, FileNo$, Defendant$
Set fs = CreateObject("Scripting.FileSystemObject")
Set objTextFile = fs.OpenTextFile(UserDir$ + "combined12.csv")
objTextFile.skipline
Do Until objTextFile.AtEndofLine
    arrStr = Split(objTextFile.Readline, ",")
    LLCODE$ = arrStr(0)
    FileNo$ = arrStr(26)
    Defendant$ = arrStr(33)

    testdoc = FormDir$ + LLCODE$ + ".docx"

    Set oWord = CreateObject("Word.Application")
    With oWord
        .WindowState = wdWindowStateMaximize
        Set oDoc = Documents.Open(testdoc, ConfirmConversions:=True, ReadOnly:=False, Visible:=True)

        With oDoc.MailMerge
            .OpenDataSource Name:=UserDir$ + "combined12.csv", ConfirmConversions:=True, LinkToSource:=True
            .Execute 'Pause:=something
        End With

        ActiveDocument.SaveAs (UserDir$ + "Merge\" + FileNo$ + "-" + Defendant$ + ".docx")
        ActiveDocument.Close

        .WindowState = wdWindowStateMaximize
        'MsgBox ActiveDocument.Name
        ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
        Set oDoc = Nothing
    End With
    Set oWord = Nothing


text:
Q: Parse: Check if object exists before fetch I have a column of type array. It stores pointers to other objects.
So in my loop I have something like this:
foreach ($artworkArr as $a) {
    $a->fetch();
    $artworkName[] = $a->get('title');
}

Problem here is, fetch immediately throws an exception if the pointer points to an invalid object.
How can I check if the object exists before calling the fetch method?

A: Just try with:
foreach ($artworkArr as $a) {
    if ($a instanceof ExpectedClass) {
        $a->fetch();
        $artworkName[] = $a->get('title');
    }
}

Or if you don't know the ExpectedClass, you can use method_exists on the $a object:
method_exists($a, 'fetch')


text:
Q: Density with respect to a family of diagrams, versus a class of weights In Theorem 5.19 of Kelly's Basic Concepts of Enriched Category Theory, it is proven that a fully faithful functor $K \colon \mathcal A \to \mathcal C$ is dense if and only if $\mathcal C$ is the closure of $\mathcal A$ under colimits of a family of diagrams, by which is meant a class of pairs $(F \colon \mathcal L^\circ \to \mathcal V, P \colon \mathcal L \to \mathcal C)$ consisting of a weight and a diagram for that weight, and these colimits are $K$-absolute.
Typically, cocompletions of (enriched) categories are taken with respect to a class of weights, rather than a family of diagrams. However, I have found it difficult to find explicit comparisons between the expressivity of these approaches. I have several related questions.

*

*Is it possible to characterise those fully faithful functors $K \colon \mathcal A \to \mathcal C$ that exhibit $\mathcal C$ as a closure of $\mathcal A$ under $\Phi$-weighted colimits which are $K$-absolute (for some class of weights $\Phi$)? Is this concept strictly less general than density?

Assuming closure under weighted colimits is less general than closure under colimits of a family of diagrams:

*What are some natural examples of dense functors that are only captured by considering diagrams rather than weights?

*What are the difficulties in considering cocompletions with respect to families of diagrams, rather than cocompletions with respect to classes of weights?

I looked through several papers on these concepts, but couldn't find the answer in them, e.g. Albert–Kelly's The closure of a class of colimits; Kelly–Schmitt's Notes on enriched categories with colimits of some class; Kelly–Lack's On the monadicity of categories with chosen colimits.


text: Q: Swap the stereo Ubuntu 14.04 I installed Ubuntu 14.04, but I figure out, that the left channel is actually right and the right is left. I tried everything, from the Ubuntu forums, but without success. I'm using hp dc7600, with wired speakers, connected to the built-in sound card.


text:
Q: How to set several route params in routerLink (Angular 2) I want to set several params to my route.

With my routes :
routes = [
  { path: 'user/:user_name/:user_id', component:UserComponent}
]

Url is changing but i'm redirected to my 404 page.
Any ideas ?

A: I think what you want to do is construct a link in a function. Then in your anchor tag create a (click)=functionName() whenever the anchor is clicked.
let link = ['/somelocation', this.param, this.param];
    this.router.navigate(link);

Some Description


text:
Q: could not find monkey.apk in eclipse Hi I am building a new project but seems facing a big problem when I try to run the problem.
I have tried to clean and rebuild but it does not work.
I hope someone can help me. Thanks.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.monkey"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission           android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature android:glEsVersion="0x20000" android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data android:name="com.google.android.maps.v2.API_KEY"    android:value="AIzaSyCi43x8rh1xwonf15SQ2faHLPKCJUkzAn8" />
    <activity android:theme="@*android:style/Theme.NoTitleBar" android:label="@string/app_name" android:name="com.example.monkey.Home" android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="com.example.monkey.SettingPreferences" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.CategoryList" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.MenuList" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.MenuDetail" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.ShareMenu" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.Contact" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.News" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.NewsDetail" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.YourOrder" android:screenOrientation="portrait" />
    <activity android:name="com.example.monkey.Reservation" android:screenOrientation="portrait" />
</application>

Logcat
[2014-03-16 22:24:11 - monkey] ------------------------------
[2014-03-16 22:24:11 - monkey] Android Launch!
[2014-03-16 22:24:11 - monkey] adb is running normally.
[2014-03-16 22:24:11 - monkey] Could not find monkey.apk!

A: This has happened to me before. I solved it by doing the following:

*

*Right click your project and click "Properties".

*Select Android from the list on the left.

*Uncheck the "Is Library" checkbox.

Alternatively, you could try the following:

*

*Right click your project.

*Click Android Tools -> Fix Project Properties.

*Clean your project (Project -> Clean...).

*Try to run the project again.

Also, make sure your Android SDK Build-tools are installed. You can check this and install them by going to Window -> Android SDK Manager.
Alternative solutions could be found here if you are missing the bin directory.


text:
Q: How to get Firebase children in Android mentioned in a ArrayList? [Android] I have a Firebase project in which there are multiple events.

And I have a list of favourite events like
Favourites: [2017071227185209, 2017071271534874, 2017072819680542, 2017073111392921]
Now my method to get only these events is
Query userRef = mDatabase.child("Events");
userRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

              for(DataSnapshot snapshot : dataSnapshot.getChildren())
              {

            if(Favourites.contains(snapshot.getValue().toString))
                 {
                   //The event is favourite, get data here
                 }
              }

        }

How should I get the data in a firebase recycler view? The only method I know is putting an appropriate query which does all the filtering for you. Is there any appropriate query for this?

A: Try as below:
List<Event> eventList =  new ArrayList<>();

for (DataSnapshot data : dataSnapshot.getChildren()) {
   Event event = data.getValue(Event.class);
   if (event.isFavorite()){ // or change your logic here
      eventList.add(event);
   }
}

A: I recomand you using this method:
void checkIfEventExists(String event) {
    Query userRef = mDatabase.child("Events");
    userRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
             if(dataSnapshot.child(event).exists()) {
                 //get event data
             }
        }
    }
}

Hope it helps.


text:
Q: Derive vimfiles directory from runtimepath option I want to set a $VIMFILES variable in my vimrc file to determine in a non-platform-specific way the file path of my vimfiles directory (a la How do I get Vim home directory?). This should be trivial (in fact, I think it should be a built-in variable), but I can't figure out a robust way to do it. The method using a plugin requires you to put any code that actually uses this variable in your after directory, which (in my opinion) makes the plugin almost useless. The method using if has to determine the operating system and manually set the variable seems absurdly fragile and tedious.
So I'd like to just make the assumption that the first component of the default value of the runtimepath option is the vimfiles directory I want.
However, I have no idea how to extract the first component from rtp. This, again, seems like it should be trivial, but &rtp[0] expands to the first character of the runtimepath, because apparently &rtp is actually a string, even though it's clearly semantically a list (!!?).
So...how do I get the first component of the runtimepath? Is there a better way to do this?

A: I think I've got it:
set rtp&
let $VIMFILES=split(&rtp,",")[0]

Still seems overly manual, but it's not as ugly as I feared.


text:
Q: How can I disable automatic send / receive for Outlook 2010 for Mac? There are lots of answers to disable automatic send / receive for Outlook for Windows, but not for Mac.
Does anyone know how to do this for Outlook 2010 for Mac?
The options offer no obvious capability, I've disabled all my 'Schedules' and defined it to 'Send All' and 'Send & Receive All' manually... but nothing stops emails from going in and out of my inbox at their will!
You can see my screenshot... I've tried this both enabled and disabled.
Thanks!
Adam

A: Something to try...
In Outlook, go to Preferences >> Accounts >> Click the Advanced button at the bottom right.  Try unchecking the "Sync all IMAP folders"
I'm actually not familiar with the exchange settings, but this may point you in the right direction.


text:
Q: How to fix: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" I am a totally new to swift. I am trying to set up a screen with 3 textfields so the user can enter data. I used the code line: nameField.delegate = self , but I always get an error message: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value. Could anybody help me fixing that problem? :)
I have already tried to force unwrap the value, but that did not work.
private func configureTextFields(){
       nameField.delegate = self
       amountField.delegate = self
       dateField.delegate = self
   }

I also set up an extension at the bottom. Maybe I did a mistake there:
extension ViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

.

A: You should make sure that you aren't calling the configureTextFields function you wrote until viewDidLoad if you are calling it from the initializer, your outlets are not yet set up and will be nil. You probably want your code to look something like this:
override func viewDidLoad() {
     super.viewDidLoad()
     configureTextFields()
}

A: Make sure you connected your nameField from StoryBoard to your IBOutlet by control-dragging from the StoryBoard to the the variable?

Check Connect UI to the Code from Apple.


text:
Q: moving repository to another subdirectory in svn I will start by saying svndumpfilter failed (using this solution: Moving SVN repositories data with history as subfolders into another repository) I got the error:
At line:1 char:30
+ svndumpfilter include \trunk < E:\tmp\test1.dump > E:\tmp\test1filter.dump
+                              ~
The '<' operator is reserved for future use.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RedirectionNotSupported

after executing:
svndumpfilter include \trunk < E:\tmp\test1.dump > E:\tmp\test1filter.dump

My problem: I have a few projects as separate repositories as such:
RootDir -
     project1
     project2
     project3
     project4
     project5
     project6

3 of the projects are for the same company, so I want to move them like this:
RootDir -
     project1
     project2
     companyX -
         project3
         project5
         project6
     project4

i.e. I want to move multiple repositories to reside as subfolders in one main repository.
The repository is in a windows server 2012, and I use remote desktop to run svn command prompt on it.
I'm out of ideas

A: *

*svnadmin can not dump only subtree from repository and can not use logical path to this subtree

svnadmin dump path_to_RootDir\project3 > temp_path_in_disk\dump_file.dmp
will dump the whole repository, from which you have to extract project(3|5|6) with svndumpfilter include into one common dump. But you can dump subtrees in one command with svnrdump dump URL and get 3 files without pre-filtering

*

*If you load dump, you have to use svnadmin load command

*On load, you have to use physical path to repository-root, not logical path inside repository:

svnadmin load path_to_RootDir < temp_path_in_disk\dump_file.dmp

*

*If you want to change mount-point of data, restored from fump, you have to use --parent-dir option of load subcommand

svnadmin load --parent-dir companyX path_to_RootDir < temp_path_in_disk\dump_file.dmp

A: Note: this solves a different problem than intended by the question, which was actually asking about moving a set of repositories into subdirectories of a different repository.
It looks like you're moving projects around within the same repository, not moving between separate repositories. If this is the case, then I think you just want to use the svn mv command using two URL arguments. E.g. svn mv --parents http://example.com/RootDir/project3 http://example.com/RootDir/companyX/project3 -m "consolidate company X projects". The "--parents" option creates the intermediate directory if it does not exist.

A: The problem was i the Windows PowerShell of Windows Server 2012.
I downloaded Console 2 and used it instead of the Windows shell.
The solution suggested in "Moving SVN repositories data with history as subfolders into another repository" did the trick.
for my needs I didn't even need the svndumpfilter part.


text:
Q: How to get goal position out of ompl::base *goalptr? I am using ompl for path planning in 3D. Please guide how to get goal position (x, y, z) out of goal pointer received from this line.
const ob::Goal *Goalptr = pdef->getGoal().get();

where pdef is problem definition. and ob is ompl::base Path planner is planning paths but I can't get this goal out of it.
How should I do something like this:
x= Goalptr[0];
y= Goalptr[1];
z= Goalptr[2];

Or should i cast this Goalptr in some other type first and then do that. Pls help.

A: So this post helped me to solve the problem. I used this code to get goal position.
std::vector<double> reals;
space->copyToReals(reals, pdef->getGoal()->as<ob::GoalState>()->getState());

Then we get goal position (x,y,z) in (reals[0], reals1, reals[2]).
Thanks Christopher Oezbek and others who tried.


text:
Q: Azure local git - Problem deploying Node.js app I am trying to deploy a Node.js (Strapi v.4 to be specific) app to Azure App Services from a local git repo. However, I am getting the following message remote: info There appears to be trouble with your network connection. Retrying... when I run git push azure master from my local repo.
See below for a more detailed output:
remote: yarn install v1.22.10
remote: [1/5] Validating package.json...
remote: [2/5] Resolving packages...
remote: [3/5] Fetching packages...
remote: ..........................
remote: info There appears to be trouble with your network connection. Retrying...
remote: info There appears to be trouble with your network connection. Retrying...
remote: .
remote: info There appears to be trouble with your network connection. Retrying...
remote: .....
remote: info There appears to be trouble with your network connection. Retrying...
remote: ..........
remote: info There appears to be trouble with your network connection. Retrying...
remote: info There appears to be trouble with your network connection. Retrying...
remote: ..........
remote: info There appears to be trouble with your network connection. Retrying...

Would trying to push the repo from an internal company network be the cause of this error? This answer makes me so?

A: I got this working by removing the node_modules folder and .lock file.


text:
Q: Domain Slave Zone Definition I've been using Linode for about a year, and am still confused by 'Master' Domain Zone and 'Slave' Domain Zone terminology on their DNS Manager. The term 'Zone' in conjunction with 'Master' AND 'Slave' do not seem to be used anywhere else online except for DNS server names.
I understand a 'DNS zone' can refer to just a single domain.
What I don't understand is, in the CONTEXT of virtual hosts, when would you add a 'Slave Zone' record to the Zone File?
Also, in the case of virtual hosts residing at a single IP, would there be one Zone File, or multiple Zone Files on the associated DNS server?

A: I'm going to stick to the first paragraph. It comprises the core of your question, and the rest is muddied by a (technical) language barrier. Virtual hosts (the webserver concept) have no bearing on which zone type you use.
Within the context of Linode's DNS hosting, you can set up a zone as a master or slave:

*

*Master Zone: Linode is effectively providing the "master" server for you. The master server is where you add, remove, or modify records. This is what most users will want, as it allows them to use Linode's web interface to manage their DNS records. It is important to note that Linode is also providing slave servers in this configuration. (or to put it more simply, "master zone" means "Linode provides both the master server and the slave servers")

*Slave Zone: Setting up a slave zone indicates that you are using a service other than Linode to manage the record updates. In other words, you don't need their web interface. This is an advanced configuration that is useful to people who manage an existing DNS infrastructure, but are only interested in having Linode provide slave servers. As noted in their documentation, your master server should be configured to send DNS NOTIFY packets to the list of IP addresses they provide, and those same IPs should be allowed to execute DNS AXFR and DNS IXFR requests (zone transfers) against your master server.
Long story short: Unless you're an experienced DNS admin, stick with Linode's master zones. Slave zones are intended for power users who are only interested in having additional DNS slave servers available for their domains (i.e. they already have other slave servers), or are trying to set up a master server with complex functionality that Linode's web interface cannot provide.


text:
Q: symfony2 fallback route for permission denied Is there a way to specify a fallback route for a route if the user lacks the required role to access the requested route?
Tor example, a logged in user has access to many pages of my site. When that user requests to use a function on my site that it lacks permission for (ie needs the role ROLE_SUBSCRIBING), I would want to show a page describing the requested function, and display options for payment to become ROLE_SUBSCRIBING. Rediricting to the login form makes no sense here since the user is correctly authenticated.

A: Checkout http://symfony.com/doc/current/reference/configuration/security.html you want:
# app/config/security.yml
security:
    access_denied_url: /foo/error403

You can also do it per firewall:
# app/config/security.yml
security:

#...

    firewalls:
        somename:
            #...
            access_denied_url: /foo/error403


text:
Q: Extract k bits from any side of hex notation     int X = 0x1234ABCD;
    int Y = 0xcdba4321;

    // a) print the lower 10 bits of X in hex notation
    int output1 = X & 0xFF;
    printf("%X\n", output1);

    // b) print the upper 12 bits of Y in hex notation
    int output2 = Y >> 20;
    printf("%X\n", output2);

I want to print the lower 10 bits of X in hex notation; since each character in hex is 4 bits, FF = 8 bits, would it be right to & with 0x2FF to get the lower 10 bits in hex notation.
Also, would shifting right by 20 drop all 20 bits at the end, and keep the upper 12 bits only?

A:
I want to print the lower 10 bits of X in hex notation; since each character in hex is 4 bits, FF = 8 bits, would it be right to & with 0x2FF to get the lower 10 bits in hex notation.

No, that would be incorrect. You'd want to use 0x3FF to get the low 10 bits. (0x2FF in binary is: 1011111111). If you're a little uncertain with hex values, an easier way to do that these days is via binary constants instead, e.g.
    // mask lowest ten bits in hex
    int output1 = X & 0x3FF;

    // mask lowest ten bits in binary
    int output1 = X & 0b1111111111;

Also, would shifting right by 20 drop all 20 bits at the end, and keep the upper 12 bits only?

In the case of LEFT shift, zeros will be shifted in from the right, and the higher bits will be dropped.
In the case of RIGHT shift, it depends on the sign of the data type you are shifting.
// unsigned right shift
unsigned U = 0x80000000;
U = U >> 20;
printf("%x\n", U); // prints:  800

// signed right shift
int S = 0x80000000;
S = S >> 20;
printf("%x\n", S); // prints:  fffff800

Signed right-shift typically shifts the highest bit in from the left. Unsigned right-shift always shifts in zero.
As an aside: IIRC the C standard is a little vague wrt to signed integer shifts. I believe it is theoretically possible to have a hardware platform that shifts in zeros for signed right shift (i.e. micro-controllers). Most of your typical platforms (Intel/Arm) will shift in the highest bit though.

A:
print the upper 12 bits of Y in hex notation

*

*To handle this when the width of int is not known, first determine the width with code like sizeof(unsigned)*CHAR_BIT.  (C specifies it must be at least 16-bit.)

*Best to use unsigned or mask the shifted result with an unsigned.
#include <limits.h>

int output2 = Y;
printf("%X\n", (unsigned) output2 >> (sizeof(unsigned)*CHAR_BIT - 12));
// or
printf("%X\n", (output2 >> (sizeof output2 * CHAR_BIT - 12)) & 0x3FFu);

*

*Rare non-2's complement encoded int needs additional code - not shown.

*Very rare padded int needs other bit width detection - not shown.

A: Assuming 32 bit int, then you have the following problems:

*

*0xcdba4321 is too large to fit inside an int. The hex constant itself will actually be unsigned int in this specific case, because of an oddball type rule in C. From there you force an implicit conversion to int, likely ending up with a negative number.

*Y >> 20 right shifts a negative number, which is non-portable behavior. It can either shift in ones (arithmetic shift) or zeroes (logical shift), depending on compiler. Whereas right shifting unsigned types is well-defined and always results in logical shift.

*& 0xFF masks out 8 bits, not 10.

*%X expects an unsigned int, not an int.

The root of all your problems is "sloppy typing" - that is, writing int all over the place when you actually need a more suitable type. You should start using the portable types from stdint.h instead, in this case uint32_t. Also make a habit of always ending you hex constants with a u or U suffix.
A fixed program:
#include <stdio.h>
#include <stdint.h>

int main (void)
{
    uint32_t X = 0x1234ABCDu;
    uint32_t Y = 0xcdba4321u;
    printf("%X\n", X & 0x3FFu);
    printf("%X\n", Y >> (32-12));
}

The 0x3FFu mask can also be written as ( (1u<<10) - 1).
(Strictly speaking you need to printf the stdint.h types using specifiers from inttypes.h but lets not confuse the answer by introducing those at the same time.)

A: Lots of high-value answers to this question.
Here's more info that might spark curiosity...
int main() {
    uint32_t X;

    X = 0x1234ABCDu; // your first hex number
    printf( "%X\n", X );

    X &= ((1u<<12)-1)<<20; // mask 12 bits, shifting mask left
    printf( "%X\n", X );

    X = 0x1234ABCDu; // your first hex number
    X &= ~0u^(~0u>>12);
    printf( "%X\n", X );

    X = 0x0234ABCDu; // Note leading 0 printed in two styles
    printf( "%X %08X\n", X, X );

    return 0;
}

1234ABCD
12300000
12300000
234ABCD 0234ABCD


text:
Q: Analysing a data frame that contains a time series using stargazer I have a panel data set of 10 obs. and 3 variables.
(# of obs. 30 = 10 rows (= countries) * 2 columns  (= migration parameters) * 1col for the respective year.
My data frame consists of 3 annual data frames, so to say.
How can I apply stargazer on the whole period of time by taking into account that it is a panel data set (so max N=10)? That is, R should start over after every 11th row. I'd like to get the pretty table for descriptive statistics
The data set for the first three years:
structure(list(Population = c(21759420, 8696916, 1946351, 14689726,
8212264, 491723, 18907008, 4345386, 11133861, 657229, 22549547,
8944706, 1979882, 15141099, 8489031, 496963, 19432541, 4404230,
11502786, 673252, 23369131, 9199259, 2014866, 15605217, 8766930,
502384, 19970495, 4448525, 11887202, 689692), Distance..km. = c(7243L,
4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L, 4047L, 9140L,
7243L, 4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L, 4047L,
9140L, 7243L, 4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L,
4047L, 9140L), year = c(2008, 2008, 2008, 2008, 2008, 2008, 2008,
2008, 2008, 2008, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009,
2009, 2009, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010,
2010)), .Names = c("Population", "Distance..km.", "year"), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 50L, 51L, 52L, 53L, 54L,
55L, 56L, 57L, 58L, 59L, 99L, 100L, 101L, 102L, 103L, 104L, 105L,
106L, 107L, 108L), class = "data.frame")

I still get descriptive statistics from N=30, but it should N=10, since I'm looking for the descriptive statistics of the whole period of three years and each yearly data frame needs to be considered isolated for that.
Hope I expressed the problem comprehensibly

A: You can either use split + lapply from base R:
library(stargazer)

lapply(split(df, df$year), stargazer, type = "text")

or by:
by(df, df$year, stargazer, type = 'text')

Result:
===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,083,988.000 7,541,970.000 491,723 21,759,420
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,008.000       0.000      2,008    2,008
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,361,404.000 7,798,880.000 496,963 22,549,547
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,009.000       0.000      2,009    2,009
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,645,370.000 8,065,676.000 502,384 23,369,131
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,010.000       0.000      2,010    2,010
---------------------------------------------------------------
df$year: 2008
[1] ""
[2] "==============================================================="
[3] "Statistic     N      Mean        St. Dev.      Min      Max    "
[4] "---------------------------------------------------------------"
[5] "Population    10 9,083,988.000 7,541,970.000 491,723 21,759,420"
[6] "Distance..km. 10   5,637.500     2,385.941    2,211    9,500   "
[7] "year          10   2,008.000       0.000      2,008    2,008   "
[8] "---------------------------------------------------------------"
--------------------------------------------------------------------------
df$year: 2009
[1] ""
[2] "==============================================================="
[3] "Statistic     N      Mean        St. Dev.      Min      Max    "
[4] "---------------------------------------------------------------"
[5] "Population    10 9,361,404.000 7,798,880.000 496,963 22,549,547"
[6] "Distance..km. 10   5,637.500     2,385.941    2,211    9,500   "
[7] "year          10   2,009.000       0.000      2,009    2,009   "
[8] "---------------------------------------------------------------"
--------------------------------------------------------------------------
df$year: 2010
[1] ""
[2] "==============================================================="
[3] "Statistic     N      Mean        St. Dev.      Min      Max    "
[4] "---------------------------------------------------------------"
[5] "Population    10 9,645,370.000 8,065,676.000 502,384 23,369,131"
[6] "Distance..km. 10   5,637.500     2,385.941    2,211    9,500   "
[7] "year          10   2,010.000       0.000      2,010    2,010   "
[8] "---------------------------------------------------------------"

The disadvantage of these two methods is that they print out the tables twice (once from stargazer output, another from lapply/by). To get around this, you can use walk form purrr to only call stargazer for it's side-effects:
library(dplyr)
library(purrr)

df %>%
  split(.$year) %>%
  walk(~ stargazer(., type = "text"))

Result:
===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,083,988.000 7,541,970.000 491,723 21,759,420
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,008.000       0.000      2,008    2,008
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,361,404.000 7,798,880.000 496,963 22,549,547
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,009.000       0.000      2,009    2,009
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,645,370.000 8,065,676.000 502,384 23,369,131
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,010.000       0.000      2,010    2,010
---------------------------------------------------------------

Note:
All methods above works for latex output (type = "latex"). I only set type = "text" for demonstrative purposes.