text:
Q: Display enum in ComboBox with spaces I have an enum, example:
enum MyEnum
{
My_Value_1,
My_Value_2
}

With :
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

But now my question: How can I replace the "_" with " " so that it becomes
items with spaces instead of underscores? And that a databound object still
works

A: If you are able to modify the code defining the enum, so you could add attributes to the values without modifying the actual enum values, then you could use this extension method.
/// <summary>
/// Retrieve the description of the enum, e.g.
/// [Description("Bright Pink")]
/// BrightPink = 2,
/// </summary>
/// <param name="value"></param>
/// <returns>The friendly description of the enum.</returns>
public static string GetDescription(this Enum value)
{
  Type type = value.GetType();

  MemberInfo[] memInfo = type.GetMember(value.ToString());

  if (memInfo != null && memInfo.Length > 0)
  {
    object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attrs != null && attrs.Length > 0)
    {
      return ((DescriptionAttribute)attrs[0]).Description;
    }
  }

  return value.ToString();
}

A: Try this...
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum))
                           .Cast<MyEnum>()
                           .Select(e => new { Value = e, Description = e.ToString().Replace("_"," ") })
                           .ToList();
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";

...although, I would be more inclined to use a "Description" attribute (as per Steve Crane's answer).

A: Fill the combobox manually and do a string replace on the enum.
Here is exactly what you need to do:
comboBox1.Items.Clear();
MyEnum[] e = (MyEnum[])(Enum.GetValues(typeof(MyEnum)));
for (int i = 0; i < e.Length; i++)
{
    comboBox1.Items.Add(e[i].ToString().Replace("_", " "));
}

To set the selected item of the combobox do the following:
comboBox1.SelectedItem = MyEnum.My_Value_2.ToString().Replace("_", " ");

A: If you have access to the Framework 3.5, you could do something like this:
Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(e=> new
                {
                    Value = e,
                    Text = e.ToString().Replace("_", " ")
                });

This will return you an IEnumerable of an anonymous type, that contains a Value property, that is the enumeration type itself, and a Text property, that will contain the string representation of the enumerator with the underscores replaced with space.
The purpose of the Value property is that you can know exactly which enumerator was chosen in the combo, without having to get the underscores back and parse the string.

A: If you're using .NET 3.5, you could add this extension class:
public static class EnumExtensions {

    public static List<string> GetFriendlyNames(this Enum enm) {
        List<string> result = new List<string>();
        result.AddRange(Enum.GetNames(enm.GetType()).Select(s => s.ToFriendlyName()));
        return result;
    }

    public static string GetFriendlyName(this Enum enm) {
        return Enum.GetName(enm.GetType(), enm).ToFriendlyName();
    }

    private static string ToFriendlyName(this string orig) {
        return orig.Replace("_", " ");
    }
}

And then to set up your combo box you'd just do:
MyEnum val = MyEnum.My_Value_1;
comboBox1.DataSource = val.GetFriendlyNames();
comboBox1.SelectedItem = val.GetFriendlyName();

This should work with any Enum. You'd have to make sure you have a using statement for the namespace that includes the EnumExtensions class.

A: I think that this is not very good idea to map internal enum name into user space. What if you refactor your enum value? So I suggest you to take a look at this article (Localizing .NET Enums). Using technique described in this article, you can not only replace '_' with spaces, but also make different enum representation for different languages (using resources).

A: I like Kelsey's answer although I would use another variable other than 'e' such as 'en' so the answer can be used in event handlers with less hassle; 'e' in event handlers tends to be the EventArgs argument.
As for the LINQ and IEnumerable approach, it seems to me to be more complex and difficult to adapt for non-WPF ComboBoxes with .NET 3.5


text:
Q: How many graphs can i create in one Titan DB? I have a situation where each user of the system can have their own graph of million vertices and lot more edges. I want to implement it as separate graph for each user.

*

*So, if there are a billion plus users, how many graphs can i created
in a clustered Titan DB with DynamoDB backend?

*Should i create multiple separate TitanDB instances and spread the load if a limitation exists?
The reason i need this is that most activity on the graph is within what the user owns. Cross user activity can be low and sporadic.
I looked at this Titan Graph DB Limitations document for limitations but it only talks of limits on vertices and edges. Also, all documentation links when we search for on google are hitting the DataStax homepage with no niformation where in there i can find the documentation.
Also, Can you let me know how to create separate graph instances as needed?

A: You can have multiple graphs within the same persistence layer. For example with Cassandra if you had the following configs:
conf1:
   storage.cassandra.keyspace=name1
conf2:
   storage.cassandra.keyspace=name2
conf3:
   storage.cassandra.keyspace=name3

Then you could create multiple graphs within that persistence layer using:
graph1 = TitanFactory.open(conf1)
graph2 = TitanFactory.open(conf2)
graph3 = TitanFactory.open(conf3)

If you are asking how do you create multiple graphs within the same TitanFactory.open(), that you cannot do in a straightforward manner.
What you can do is create several disconnected graphs in the same graph. For example:
graph1 = TitanFactory.open(conf)
//Create One Disconnected Graph
v1 = graph.addVertex();
v2 = graph.addVertex();
v1.addEdge("edge", v2);
//Create Another Disconnected Graph
v3 = graph.addVertex();
v4 = graph.addVertex();
v3.addEdge("edge", v4);

The above effectively gives you two sub-graphs within the same graph.
My personal recommendation is that if you don't need any connections between your graphs then you should use multiple graphs. I.e. graph1, graph2, and graph3 as I specified above. This will make scaling easier in the long run. Of course be very certain that connections are not needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make elements fade in/out when scrolling I am working on a website for a friend (https://www.nicoledavis.org) and am having a difficult time getting each section of the website to fade in/out when scrolling up/down. I don't want the text/images to be visible until you scroll down to it.
I have tried this tutorial (https://eddyerburgh.me/animate-elements-scrolled-view-vanilla-js) but am not sure where the animation codes should go in order to tell it which parts to animate.
Here is the HTML code I currently have for each section I'd like to have fade in/out when scrolling:

{anchor-link-1:text}

{anchor-content-1:content}

{anchor-link-2:text}

{anchor-content-2:content}

{anchor-link-3:text}

{anchor-content-3:content}

{anchor-link-4:text}

{anchor-content-4:content}

I don't want to remove the anchor feature because that is what makes the website transition smoothly between each section.
I currently don't have anything set up for the animation feature because the tutorial I mentioned above did not work for me. I'm assuming I put things in the wrong places, or am missing something.
I'm expecting to see each container/section to fade in/out when scrolling up and down the website. Thank you in advance for any help!

A: If you follow the tutorial from the link you provided (https://eddyerburgh.me/animate-elements-scrolled-view-vanilla-js) you simply need to make sure to add the css code for the animation and the js code to trigger the animation on elements.
The tutorial says to add the 'hidden' class to all elements you want to animate.

(function() {
  var elements;
  var windowHeight;

  function init() {
    elements = document.querySelectorAll('.hidden');
    windowHeight = window.innerHeight;
  }

  function checkPosition() {
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      var positionFromTop = elements[i].getBoundingClientRect().top;

      if (positionFromTop - windowHeight <= 0) {
        element.classList.add('fade-in-element');
        element.classList.remove('hidden');
      }
    }
  }

  window.addEventListener('scroll', checkPosition);
  window.addEventListener('resize', init);

  init();
  checkPosition();
})();
@keyframes fade-in {
    from {opacity: 0; transform: scale(.7,.7)}
    to {opacity: 1;}
}
.fade-in-element {
  animation: fade-in 1.4s;
}

.hidden {
  opacity: 0;
}

VISIBLE

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
    luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
    purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.</p

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

FADE IN

Aenean iaculis nunc eget diam euismod feugiat. Nullam nec ligula sed velit iaculis eleifend at sed nisi. Nam nibh ipsum, elementum imperdiet eleifend eget, pharetra et dui. Vestibulum sodales libero at orci rhoncus, nec tempor libero sagittis. Morbi
      luctus dolor ut risus lobortis semper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed vulputate purus. Morbi a urna varius, ornare ipsum ut, laoreet elit. Phasellus mattis, magna et accumsan accumsan,
      purus augue rutrum erat, a ultrices felis felis a neque. Donec consequat pretium eros ac tristique. Pellentesque mollis elementum molestie. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean convallis fringilla suscipit.

A: If I am using this code below to keep my anchors and the content that is already present, would the word "hidden" still go after "main-wrap", or would it need to be placed elsewhere?

{anchor-link-1:text}

{anchor-content-1:content}


text:
Q: how to avoid two socket with same port number python Now here is sample for the server part of socket.
I want to have serverSocket and connectionSocket with different port number, but for now, they are using same port number.
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print ('The server is ready to receive')
while 1:
 connectionSocket, addr = serverSocket.accept()

 sentence = connectionSocket.recv(1024)
 capitalizedSentence = sentence.upper()
 connectionSocket.send(capitalizedSentence)
 connectionSocket.close()

if they are using same port number, would there be some collision?

A: There is nothing to avoid, and there is really no easy way to avoid it - this is how TCP is supposed to work.
In TCP there are 2 kinds of sockets:

*

*listening server sockets

*connected sockets

The server sockets start listening to incoming connections with listen; and wait for client connections with accept. Clients create a socket that is connected to the server address (host, port). When the server accepts a connection, a new connected socket is created between the (client_address, client_port) and (server_address, server_port). The TCP stack on the server can see from status bits easily if the packet is a connection request, or destined to an already connected socket. If it is a communication between already connected sockets, then it finds out the file descriptor that is bound on the local address and local port and is connected with the source address, source port of the remote end.
The connected socket will have the same port as the listening server socket; both Ende of the socket know 4 things: local address, local port, remote address and remote port. You can have 1 server socket bound on 10.20.30.40:12345 at the same time with thousands of sockets connected from 10.20.30.40:12345 to thousands distinct addresses.
There is really congestion only in the connection attempt phase; the server_socket.listen(1) means that the server will queue just 1 incoming connection; subsequent connections will be rejected until the incoming connection is accepted.
From Linux manual pages, listen(2) on the backlog argument of sock.listen:

The backlog argument defines the maximum length  to  which  the
  queue of pending connections for sockfd may grow.  If a connection request arrives when the queue is  full,  the  client  may
  receive  an error with an indication of ECONNREFUSED or, if the
  underlying protocol supports retransmission, the request may be
  ignored so that a later reattempt at connection succeeds.

A: Althouh I've never used raw sockets in Python, I guess this question more generally deals with how TCP and IP work.
When a server listens for connections on a port, clients will connect to that port, and the TCP connection can be identified by the quadruple (server_addr, server_port, client_addr, client_port), so there is no ambiguity when packets belonging to different connections will be sent or recieved, because the (client_addr, client_port) part will be different for each of them.
That said, there is no conflict in the addressing.
However, note that it is common that servers fork (or spawn a thread) after accepting each request, so that the main proces (or thread) can keep acceprint connections while other connections are handled by the forked processes (or threads). In your case, instead, once your server starts processing a request, it computes the response before calling accept() again, so any other client will have to wait before having its request served.


text:
Q: AJAX cant load URL I am trying to use the youtube "api" for search

http://suggestqueries.google.com/complete/search?q=INPUT&client=firefox&hl=cs

but the site returns with a content-disposition: attachment; header and downloads a file (f.txt) with a JSON response.
Is there a way to obtain the JSON as a string in javascript?
(I am sure there is. Youtube has to do it somehow)
jQuery-less please if possible.

A: Not sure how you are trying to access API in browser directly. It will not work that way. Make an AJAX call to the same API and you will get error message as,

XMLHttpRequest cannot load http://suggestqueries.google.com/complete/search?q=india&client=firefox&hl=cs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://null.jsbin.com' is therefore not allowed access.

Reason?
Because this API is meant for google internal products so it will not work normally.
Cross-domain restriction is relatively common and making a JSONP based request can solve this.
Try this,
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?",
{
    "hl":"en",
    "jsonp":"suggestCallBack",
    "q":'ind', // query term
    "client":"firefox"
});

suggestCallBack = function (data) {
    console.log(data);
};

Now this is a JQuery based solution but AJAX call can be made easily without JQuery also but I never tried making JSONP call without JQuery.


text:
Q: INSERT INTO table IF count(*) < 5 I'm trying to make a MySQL Procedures which will insert data into table if count(*) from the same table is less than 5 rows.
The logic is:
Declare @count INT;
SET @count = (SELECT COUNT(*) FROM table);
IF (@count = 1)
INSERT INTO table(item1, item2, item3) VALUES('item 1', 'item 2', 'item 3');

A: You are missing proper syntax for code block.
It should contain BEGIN .. END and IF ... THEN .. END IF blocks.
Example:
BEGIN
  Declare @count INT;
  SET @count = (SELECT COUNT(*) FROM table);
  IF (@count = 1) THEN
    INSERT INTO table(item1, item2, item3) VALUES('item 1', 'item 2', 'item 3');
  END IF;
END;

And if you want to insert, only if the count is less than 5 then,
Change:
  IF (@count = 1) THEN

To:
  IF (@count < 5) THEN


text:
Q: Unable to extract the tar file in python because of permission issue I am unable to extract the tar file in python.
This is the code base am using to extract the tar file in Python.
file_path = os.path.join(extracted_tar_files, file.strip('.tar'))
tf = tarfile.open(os.path.join(files_directory, file))
tf.extractall(file_path)
tf.close()

Some of the tar files are working fine. Some of the tar files am getting the following error.

*** PermissionError: [Errno 13] Permission denied: '\home\piercer\etc.sudoers'

Can you please help here. Thank you!

A: the file seems to belong to someone else and you seem to have no read permissions. as is to be expected for a sudoers file. you could change the permissions:
$ sudo -E chown $USER /home/piercer/etc.sudoers

A: tar.extractall(file_path, numeric_owner=True)

This creates file owner by the user who runs the script.


text:
Q: how to construct a rudimentary function $h$ used in the paper ''scales in $L(\mathbb{R})$'' A rudimentary function is a function finitely generated by the following schemata:

*

*$f(\langle x_{1} , ... , x_{k} \rangle ) = x_{i}$,

*$f(\langle x_{1} , ... , x_{k} \rangle ) = x_{i}\setminus x_{j}$,

*$f(\langle x_{1} , ... , x_{k} \rangle )= \{ x_{i},x_{j}\}$

*$f(\langle x_{1} , ... , x_{k} \rangle ) =h(g_{1}( x_{1},...,x_{k} ),...g_{l}(x_{1},...,x_{k})) $

*$f(\langle x_{1} , ... , x_{k} \rangle ) = \bigcup_{y \in x_{1}} g( y,x_{2},...,x_{k} )$

For a list of properties of rudimentary functions see for example page 234 of http://www.math.cmu.edu/~laiken/papers/FineStructure.pdf
In Steel's paper ''Scales in $L(\mathbb{R})$'' he claims that it is easy to construct a rudimentary function $h$ such that for every finite $F \subseteq ON$:
\begin{gather} h''\{F\}\times \mathbb{R} = \{ \langle G_{0},G_{1},G_{2} \rangle \ |  G_{i} \subseteq F \ \text{for} \ 0 \leq i \leq 2\} \end{gather}
Please, could anyone give me a hint on how to construct such $h$?


text:
Q: mouse move event on listview of a dialog box in MFC I have created a dialogbox. On which I have created two list views.
I have created a sub class for list view.
I wanted to know where is mouse, I mean on which list view.
After that I will find the index of list view using CListCtrl::HitTest().
Now I am getting the index using HitTest but Mouse move is common for both List view.
So how I can distinguish the list view in mouse move event.
Finally I am going to create the tooltip according to list view and index of that list view.

A: CListCtrl inherits form CWnd. You can get the mouse pointers coordinates implementing CWnd::OnMouseMove. You mainly have two options:

*

*either subclass the CListCtrl and implement OnMouseMove as you want in the derived class

*either implement OnMouseMove in the parent window (dialog window) and test the coordinates of the mouse against the coordinates of the two list controls.

Whatever solution you pick keep in mind that OnMouseMove is called very often and the implementation of the function must be very light otherwise it will load the computers resources and the application will lag.
HTH,
JP.

A: If all you really want is to display a tool-tip whenever the mouse hovers over some control you have, there's no need getting your hands so dirty with hit-tests, mouse coordinates, etc. Just use windows' built-in mechanism for that.
Assuming that your dialog class is the parent of the two list views:

*

*From the dialog's OnCreate() call EnableToolTips().

*Add a handler to the message map, such as: ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnTtnNeedText).

*Implement OnTtnNeedText() in the dialog class. Example:
BOOL CMyDialog::OnTtnNeedText(UINT id, NMHDR *pNMHDR, LRESULT *pResult)
{
    TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
    pTTT->hinst = AfxGetResourceHandle();
    switch ( pNMHDR->idFrom )
    {
        case IDC_LV_LEFT:
            pTTT->lpszText = "I'm lefty!";
            break;
        case IDC_LV_RIGHT:
            pTTT->lpszText = "I'm righty!";
            break;
    }
    return TRUE;
}

And that's more or less it. Refer to this for more information: article


text:
Q: How to navigate back/up using Xamarin and MVVMCross I'm asking this question to create a record of this for myself, I found out the answer by looking around but I feel like it took me way too long to figure this out. Assuming I was using the wrong keywords in my searches I am trying to link the keywords I used in my searches to this question and hopefully help someone else.
I was trying to navigate back to the previous activity using the OnOptionsItemSelected method. This is how Android allows you to listen to actionbar button presses.
public override bool OnOptionsItemSelected(IMenuItem item)
{
    if (item.ItemId != global::Android.Resource.Id.Home) return base.OnOptionsItemSelected(item);

    ViewModel.BackNavigationButtonCommand.Execute();
    return true;
}

I was enabling the back button by using:
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);

The SetDisplayHomeAsUpEnabled callback however did not go to OnOptionsItemSelected.

A: The answer to this solution is using the activity attribute:
[Activity(
    Label = "Project Wavelength"
    , Icon = "@drawable/icon"
    , Theme = "@style/Theme.AppCompat.Light.DarkActionBar"
    , ScreenOrientation = ScreenOrientation.Portrait
    , LaunchMode = LaunchMode.SingleTop)]

LaunchMode = LaunchMode.SingleTop for returning to an existing activity in the backstack.
[Activity(Label = "DevicesWithSensorsForRoom"
    , Icon = "@drawable/icon"
    , ScreenOrientation = ScreenOrientation.Portrait
    , Theme = "@style/Theme.AppCompat.Light.DarkActionBar"
    , ParentActivity = typeof(RoomsOverviewActivity)
    , LaunchMode = LaunchMode.SingleTop)]

ParentActivity = typeof(RoomsOverviewActivity) for defining the parent to return to.
I don't know if there is an MVVMCross solution to this using the viewmodels. This however works for me right now. If there is a MVVMCross solution I'd like to hear it.
The OnOptionsItemSelected and SetDisplayHomeAsUpEnabled are not necessary with these attributes.


text:
Q: Proper way of averaging histograms How does one go about averaging multiple histograms of a quantity $x,$ if the individual histograms do not have the same range, that is, $R_i=\text{max}(x_i)-\text{min}(x_i)$ will be different for two different $i$ values (where $i$ here is indexing over the realizations of the experiment/histogram). Only common point between them is that the bin size is fixed, $b=1.$
How can I perform the averaging whilst making sure that no discrepancy arises for values of $x$ that do not occur in all histograms (as $R_i$'s can be different)? I am interested solely in the methodology here.

A: So I've had a look around and this is the best answer I have found:
http://se.mathworks.com/matlabcentral/answers/59865-how-to-combine-different-histograms
From what I understand you have to adjust the range your bins cover in every histogram so that there is a universal range for them all; $R$ instead of $R_i$. I think you can do this by creating empty bins in each histogram. Then you can just add them together and take the average normally (by dividing by the number of histograms).
Hope that helps.


text:
Q: how to set the controller to respond as plain text in Grails I need to create an API for monitoring and for that need that the response will be plain text , not json or xml
What I did is:
checked my application yaml that it contains text:
 types:
        all: '*/*'
        atom: application/atom+xml
        css: text/css
        csv: text/csv
        excel: application/vnd.ms-excel
        xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        form: application/x-www-form-urlencoded
        html:
          - text/html
          - application/xhtml+xml
        js: text/javascript
        json:
          - application/json
          - text/json
        multipartForm: multipart/form-data
        pdf: application/pdf
        rss: application/rss+xml
        text: text/plain
        hal:
          - application/hal+json
          - application/hal+xml
        xml:
          - text/xml
          - application/xml

added to my controller: static responseFormats = ['all'], tried also static responseFormats = ['text']
in my method did:
respond mystring, formats:['text']

But still grails trying to convert it to JSON and throwing http 406 error
How can I configure my controller to work with plain text
Thanks

A: I figure out how to do it
i used render instead of respond in my method which solved the problem, still not sure why it is not possible with respond
class MonitorApi4Controller {

   static responseFormats = ['text']
   static allowedMethods = [ monitorScrape: "GET"]

   MonitorService getMonitorService(){
       return ApplicationContextHolder.getBean('monitorService')
   }

   def monitorScrape(){
       def message = getMonitorService().serviceMethod()
       render message
   }
}


text:
Q: Trigonometry problem involving vectors An airplane is headed 123 degrees with an air speed of 310 mph with a wind of 40 mph on a bearing of 200 degrees. Find the ground speed to the nearest mph, and the true course of the airplane to the nearest degree.
I tried to draw the vectors but I am unable to figure it out.Please help me.


text:
Q: Document not appearing in Smart Search results I inherited a Kentico 11-managed site, and taking care of it is only a small part of my responsibilities, so I'm far from being a Kentico expert even though it's been a year and a half. The site (there is only one) includes a custom Page type called Publication. The original developers created a Smart Search index on this type, which has always seemed to work fine. But there is one particular instance (at least - there could be others we haven't noticed, but as far as we've seen it's just this one) that simply does not show up in Smart Search results. If we enter any substring of its title, or even the full, exact title, as a search term, it just does not appear in the results. Other pages of the type appear as the first or second result in those circumstances.
We've tried rebuilding the index several times, and unpublishing and republishing the page, and I've compared its row in the custom table to others that are very similar, and have found nothing to explain why this might be happening. The Form and Metadata properties are identical to those of instances that are normally searchable. Where else ought we to look for a possible explanation? What might be causing just this one instance to fail to be indexed?


text:
Q: Rails: Could not find bcrypt-ruby-3.0.1 in any of the sources I read infinitely many stackoverflow articles on missing gems in ruby but I still fail in solving the problem. Here is the situation:
nicolamac:Proj a$ rails new MyGreatApp
[...]
nicolamac:Proj a$ cd MyGreatApp/
[...]
nicolamac:MyGreatApp a$ bundle install
[...]
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

But if I do:
nicolamac:MyGreatApp nicolagreco$ rails generate devise:install

I get
Could not find bcrypt-ruby-3.0.1 in any of the sources

How can I solve this problem?
Thanks

A: Try to install it by adding to your Gemfile:
gem "bcrypt-ruby"

an then run
bundle install


text:
Q: R: Automatic selection of covariates in GWR I am performing geographically weighted regression (GWR) and I have 4 covariates and 1 dependent variable. I want to find the best combination of covariates that yields the lowest AIC score. But having 4 covariates means that I have to search among 24 models (4! = 4 * 3 * 2 = 24). I was wondering if there is an automatic way to do that in R, that is, to search for the best model. Here is the code using all the covariates:
    library(raster)
    library(spgwr)
    library(ggplot2)
    library(maptools)
    library(beepr)

    block.data = read.csv(file = "path/block.data.csv")

    x = as.data.frame(block.data$x)
    y = as.data.frame(block.data$y)

    coordinates(block.data) = c("x", "y")

    eq1 <- ntl ~ pop + tirs + evi + ebbi

   abw <- gwr.sel(eq1, data = block.data, adapt = T, gweight = gwr.Gauss); beep(7)

    abw

    ab_gwr <- gwr(eq1,
                  data = block.data,
                  adapt = abw,
                  gweight = gwr.Gauss,
                  hatmatrix = T,
                  se.fit = T); beep(7)

    ab_gwr

My data can be found here.

A: You can construct and manipulate formulae as character objects and convert them to formulae. Here's something:
covars = names(block.data)[-1]
L = unlist(sapply(1:4,
  function(n)combn(covars, n,
      FUN=function(x){
        as.formula(
       paste("ntl ~",paste(x,collapse=" + "))
   )},simplify=FALSE)))
L
[[1]]
ntl ~ pop
<environment: 0x56154e19f260>

[[2]]
ntl ~ tirs
<environment: 0x56154e1a0ee0>
[etc]
[[15]]
ntl ~ pop + tirs + evi + ebbi
<environment: 0x56154e3ee048>

Each element of L is a formula.
> abw <- gwr.sel(L[[1]], data = block.data, adapt = T, gweight = gwr.Gauss);
> ab_gwr <- gwr(L[[1]],
   [etc]

Now write a loop or *apply call over all of L, extract the AIC, and with Jeffrey Evans' comments in your head and all the other critiques of GWR considered, write your paper...

A: Here is a riff on @Spacedman's approach that provides an all parameters combination formula object that can be passed to lapply to iterate models.
p <- names(block.data)[-which(names(block.data) %in% "ntl")]
 id <- unlist(lapply(1:length(p), function(x) combn(1:length(p), x,
              simplify=FALSE)), recursive=FALSE)
   ( f <- lapply(id, function(x) as.formula(paste("ntl ~ ", paste(p[x], collapse="+")))) )
 res <- lapply(f, function(x) {
   abw <- gwr.sel(x, data = block.data, adapt = T, gweight = gwr.Gauss)
   gwr(x, data = block.data, adapt = abw, gweight = gwr.Gauss,
   hatmatrix = TRUE, se.fit=TRUE) } )


text:
Q: condition [32,1,1,1], then [16,64,64,3], and else [16,64,64,3] must be broadcastable I have issue in code. I run code after 1 epochs program terminate and also change batch size but can't work. I also search on google this error but can't find any solution.Any Expert Please Checkout my error
Full Code Link Colab Link :https://colab.research.google.com/drive/1kPDPIXliTR1Wxc8vzJ5wjgxoM7fzgnwG?usp=sharing
self.probability = tf.Variable(0.0)
self.augmenter = keras.Sequential(
    [
        layers.InputLayer(input_shape=(image_size, image_size, 3)),
        # blitting/x-flip:
        layers.RandomFlip("horizontal"),
        # blitting/integer translation:
        layers.RandomTranslation(
            height_factor=max_translation,
            width_factor=max_translation,
            interpolation="nearest",
        ),
        # geometric/rotation:
        layers.RandomRotation(factor=max_rotation),
        # geometric/isotropic and anisotropic scaling:
        layers.RandomZoom(
            height_factor=(-max_zoom, 0.0), width_factor=(-max_zoom, 0.0)
        ),
    ],
    name="adaptive_augmenter",
)

def call(self, images, training):
if training:
augmented_images = self.augmenter(images, training)
    augmentation_values = tf.random.uniform(
        shape=(batch_size, 1, 1, 1), minval=0.0, maxval=1.0
    )
    augmentation_bools = tf.math.less(augmentation_values, self.probability)

    images = tf.where(augmentation_bools, augmented_images, images)
return images

def update(self, real_logits):
current_accuracy = tf.reduce_mean(step(real_logits))
accuracy_error = current_accuracy - target_accuracy
self.probability.assign(
    tf.clip_by_value(
        self.probability + accuracy_error / integration_steps, 0.0, 1.0
    )
)

Error
InvalidArgumentError: condition [8,1,1,1], then [32,128,128,3], and else [32,128,128,3] must be broadcastable [[node adaptive_augmenter/SelectV2 (defined at :46) ]] [Op:__inference_train_function_5713]
Errors may have originated from an input operation. Input Source operations connected to node adaptive_augmenter/SelectV2: adaptive_augmenter/Less (defined at :44) IteratorGetNext (defined at :1)
adaptive_augmenter/adaptive_augmenter/random_zoom/transform/ImageProjectiveTransformV3 (defined at :38)
Function call stack: train_function


text:
Q: avilable fields in list view In the application i work, we allow users to create their own list view. But they complain about un-wanted fields listed in available field list. For those fields they have access but they are actually used only for calculation purpose not meant to be displayed.
Any suggestion to remove the unwanted fields from available fields in the list view?


text:
Q: Getting "Adding a deleted or invalidated object to a Realm is not permitted" from realm I have used the realm in one of my projects and added Firebase to identify the crashes. Now, in one of the crash, I am getting following error in Firebase but did not get more details.

"Adding a deleted or invalidated object to a Realm is not permitted"

I have used below code everywhere, where I am trying to delete the object from the realm.
let realm = try! Realm()
do {
    try realm.write {
        realm.delete(object)
    }
} catch let error as NSError {
    // handle error
    Crashlytics.sharedInstance().setObjectValue(error.localizedDescription, forKey: "key")
}

Am I missing anything?
Thank you for your help


text:
Q: Distribution of number of offsprings at n=10 (Galton Watson Process) I have the following branching process problem.
Let Zn denote the population size at time n. It takes on the following probabilities:
Z = 0 with probability 0.5
Z = 4 with probability 0.5

I need to find the distribution of $X_{10}$ i.e the family size at the 10th generation.
I tried to use moment generating function by making use of its properties to find distribution of Z first but i didnt go so far with that attempt.
Any help is appreciated thank you!


text:
Q: Platform-dependent data output In order to aid myself with displaying debugging information, I decided to create the following tiny function that would dynamically switch between displaying data in RStudio's internal data browser and simple character-based output, depending on capabilities of the platform, where my modules are being sourced at:
View <- function (...) {
  if (.Platform$GUI == "RStudio")
    View(...)
  else
    print(...)
}

This function is located, along with other utility functions, in the module <PROJ_HOME>/utils/debug.R. All modules that need these functions, include it via source("../utils/debug.R").
Running my project's code on my Amazon EC2 instance's Linux console is fine. However, running it on the same virtual machine via RStudio Server results in the following error message:
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?

It seems to me that R gets confused as to which View() function needs to be called. Initially, I assumed that RStudio overloads the utils::View() and I tried to call it explicitly, but it failed. Then I thought that RStudio somehow defines its View() implementation in global environment, so that it just needs to be called View() without package/library reference. However, as I you see, it doesn't work either. Another potential reason of the error might be that I overestimated the "smartness" of R in terms of my use of ... arguments.
So, what is wrong and how to fix it?

A: RStudio hooks the View function. One approach might be to see if anyone has overridden the View function from utils, and to call the override if it exists. What about this?
View <- if (identical(utils::View, View)) print else View


text:
Q: How can I increase movement speed Is there  a command or hack in the original Fallout game to increase the run speed?  Sometimes navigating between areas of map locations (Hub, Necropolis, etc) is a bit of a drag.

A: You can check Sfall mod for Fallout 1 which increases movement and combat speed.
More info here.

Increase movement and combat speed to up to 10x normal.


text:
Q: Angular $resource cache not working I would like to cache resources in my MEAN-stack application.
In the client I use a service that calls the server, where I put a trace to see if the cache is working (and I see this trace everytime I reload the page).
In this example I retrieve a list of cities.
My controler:
angular.module('mean.cars').controller('CarsController', ['$scope', '$http', '$stateParams', '$location', 'Global','Cities',
    function ($scope, $http, $stateParams, $location, Global, Cities) {

$scope.cities = Cities.query();

My service:
angular.module('mean.sol').factory('Cities', ['$resource',  function($resource) {return $resource('cities/', {}, {list : {method : 'GET', cache : true } });}]);

I also tried with these solutions:
mod.factory('Cities', ['$resource',  function($resource, $cacheFactory) {return $resource('cities/', {}, {list : {
        'get': { method:'GET', cache: $cacheFactory },
    'query': { method:'GET', cache: $cacheFactory, isArray:true } } });}]);

Or:
mod.factory('Cities', function($resource){
return $resource('cities/', {},
    {get:
        {
            cache: true,
            method: 'GET'
        }
    }
);

})
All is working but nothing is cached. It always calls my server.
I tried many solutions, for example replacing $resource by $cacheFactory, but it's not working. I can't find the good way to do that.
Did I forget something?

A: Ok I find the problem:
I change my service like this:
mod.factory('Cities', ['$resource', function($resource) {return $resource('cities/', {}, {'query' : {method : 'GET', cache : true, isArray:true } });}]);

-> 'query' instead of 'list' and add isArray:true.


text:
Q: Github Desktop (macos) - Update from master vs Merge into Current Branch I have looked around quite a bit but could not find an answer specific to Github Desktop.
I have two main branches Master and Develop.
When I develop a new feature I do the following:

*

*Create a feature branch from Develop

*When I am happy with the new feature I switch back to Develop

*Select Merge into Current Branch to update develop

*Delete the feature branch

Sometimes though, I need to do a little fix in Master. The approach that I use is the same, but now I would like to update Develop with the bug fix in Master (if needed).
At the moment I do the following:

*

*Select the Develop branch

*Then Update from master

*Solve conflicts if any

*Continue my development in Develop

The fact is that there is a different option available in Github Desktop, Merge into current branch.
I have never used it, but I would like to understand if I should.


text:
Q: Grails password change: Allow only "new" passwords I need to improve security in a website built on grails.
The requirement is that when a user changes its password, it shouldn't be able to choose from any of the previous N passwords.
Does anyone know a module for this? Should I roll my own?
Any thoughts / tips will be appreciated.
Thanks in advance

A: It depends on your requirements. There are several security plugins available, for a list see the "Providing login and page level security" heading at http://www.grails.org/Security
If you want to role your own just create a domain class that contains old passwords, associate it with a specific user, and if the new password is in the list of old passwords stored in your domain don't allow the user to sue it.

A:
The requirement is that when a user changes its password, it shouldn't be able to choose from any of the previous N passwords.

Please push back on this requirement. It's inane and doesn't improve security a bit. Every time you make users change passwords, you're increasing the odds that they will simply write it down and stick it to their monitor. Preventing them from reusing old passwords makes it even worse.
This is a security "best practice" like bleeding and leaches used to be a medical best practice; everybody was doing it out of ignorance.

A: It's not difficult to roll your own.
Make use of GORM event beforeSave, check compare the password and either cancel or proceed with the same given the result of the comparison.


text:
Q: numbering tcolorbox toc I'm writing a quite large document and would like to make a toc of used boxes. I'm using the tcolorbox package because i like the way it gives you freedom to modify the appearance of the boxes. While generating the toc using the options provided by the package i get extra numbering within the toc. I suspect it's because the tcblistof generates it's own numbers and i use them as well in the title of the box. I would like to get rid of those numbers. In front of the title in the tcblistof.
here's a MWE that gives the problem:
\documentclass[numbers=noenddot,12pt,footinput=true,headinput=true,cleardoublepage=empty,twoside,svgnames,colorlinks=true]{scrbook}
\usepackage{scrlfile}
\PreventPackageFromLoading{mathpazo}
\usepackage[parts,pdfspacing,manychapters,dottedtoc,drafting]{classicthesis}
%manychapters,eulerchapternumbers,eulermath,listings,linedheaders
\usepackage{lmodern}
\usepackage{textcomp}
\usepackage[T1]{fontenc}
\usepackage[outer=7cm, inner=1.5cm, marginparwidth=4.5cm,marginparsep=.6cm, textheight=674pt]{geometry}%showframe
\usepackage[dutch]{babel}
\usepackage{xspace}
\usepackage{tocbibind}
\usepackage{graphicx}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[font=footnotesize,font=rm,labelfont={bf,rm},format=plain,style=default]{caption}
\usepackage{subcaption}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{float}
\usepackage[utf8]{inputenc}
\usepackage[framemethod=tikz]{mdframed}
\usepackage[most,listings]{tcolorbox}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage{arsclassica}
\usepackage{threeparttable}

\usepackage{lipsum}

\setcounter{tocdepth}{1}

\newtcolorbox[auto counter,number within=chapter,list inside=box]{test}[2][]{
enhanced,
colback=red!25,
colframe=red!25,
fonttitle=\bfseries,
coltitle=black,
arc=0pt,outer arc=0pt,
drop shadow,
title=Box~
\thetcbcounter.\quad#2,#1}

\begin{document}

\tableofcontents

\tcblistof[\chapter*]{box}{Lijst van Boxen}

\chapter{Test}

\lipsum[1]

\begin{test}{Example}
This is an example
\end{test}

\chapter{Test continued}

\lipsum[2]

\begin{test}{Next example}
More text
\end{test}

\end{document}

what i get:
1.1 Box 1.1. Example . . . . . . . . . . . . . . . . . . . . 9
2.1 Box 2.1. Next example . . . . . . . . . . . . . . . . .  11
should be:
Box 1.1. Example . . . . . . . . . . . . . . . . . . . . 9
Box 2.1. Next example . . . . . . . . . . . . . . . . .  11

A: Add this to your preamble
\makeatletter
\def\tcb@addcontentsline#1#2{%
  \ifx\kvtcb@listentry\@empty%
    \ifx\kvtcb@title\@empty%
      \ifx\tcbtitletext\@empty%
        \addcontentsline{#1}{#2}{{\ignorespaces\kvtcb@savedelimiter}}%
      \else%
        \addcontentsline{#1}{#2}{{\ignorespaces\tcbtitletext}}%
      \fi%
    \else%
      \addcontentsline{#1}{#2}{{\ignorespaces\kvtcb@title}}%
    \fi%
  \else%
    \addcontentsline{#1}{#2}{\kvtcb@listentry}%
  \fi%
}
\makeatother

A: This should work; with [...] I denote all that precedes \begin{document} in your file:
[...]

\makeatletter % no indent for entries
\renewcommand{\l@tcolorbox}{\@dottedtocline{1}{0pt}{2.3em}}
\makeatother

\begin{document}

\tableofcontents

\begingroup
% temporarily make \numberline do nothing
\renewcommand\numberline[1]{}
\tcblistof[\chapter*]{box}{Lijst van Boxen}
\endgroup

A: The text for the list can be set explicitely with list entry, here:
list entry=Box~\thetcbcounter.\quad#2,

All together, this gives:
\documentclass[numbers=noenddot,12pt,footinput=true,headinput=true,cleardoublepage=empty,twoside,svgnames,colorlinks=true]{scrbook}
\usepackage{scrlfile}
\PreventPackageFromLoading{mathpazo}
\usepackage[parts,pdfspacing,manychapters,dottedtoc,drafting]{classicthesis}
%manychapters,eulerchapternumbers,eulermath,listings,linedheaders
\usepackage{lmodern}
\usepackage{textcomp}
\usepackage[T1]{fontenc}
\usepackage[outer=7cm, inner=1.5cm, marginparwidth=4.5cm,marginparsep=.6cm, textheight=674pt]{geometry}%showframe
\usepackage[dutch]{babel}
\usepackage{xspace}
\usepackage{tocbibind}
\usepackage{graphicx}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[font=footnotesize,font=rm,labelfont={bf,rm},format=plain,style=default]{caption}
\usepackage{subcaption}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{float}
\usepackage[utf8]{inputenc}
\usepackage[framemethod=tikz]{mdframed}
\usepackage[most,listings]{tcolorbox}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage{arsclassica}
\usepackage{threeparttable}

\usepackage{lipsum}

\setcounter{tocdepth}{1}

\newtcolorbox[auto counter,number within=chapter,list inside=box]{test}[2][]{
enhanced,
colback=red!25,
colframe=red!25,
fonttitle=\bfseries,
coltitle=black,
arc=0pt,outer arc=0pt,
drop shadow,
title=Box~\thetcbcounter.\quad#2,
list entry=Box~\thetcbcounter.\quad#2,
#1}

\begin{document}

\tableofcontents

\tcblistof[\chapter*]{box}{Lijst van Boxen}

\chapter{Test}

\lipsum[1]

\begin{test}{Example}
This is an example
\end{test}

\chapter{Test continued}

\lipsum[2]

\begin{test}{Next example}
More text
\end{test}

\end{document}


text:
Q: Java7 WatchService - How to detect rename/move of the actual watched directory I'm using WatchService for synchronization data files with the application workbench. When I rename/move the watched directory I don't get any event nor the WatchKey won't become invalid. I still get events from the renamed directory but as far as I know there no way to find out the actual Path for the WatchKey besides WatchKey.watchable() which however still returns original directory path. I would like to avoid need of locking the watched directory against changes since I want to keep the application as lightweight as possible.
I have experienced this problem with JDK 7u10 on Windows 7
Do you know any workaround for this issue without locking the directory or watching all directories to the root?
UPDATE
On Linux I have observed the same behavior.
So far it seems I have three options now.
1) Rely on user's discipline that he/she won't move the data directories. I don't really like this options since it might lead to undefined behavior.
2) Use more extensive non-standard native library
3) Create hierarchy of watchdogs on superior directories. These would accept only ENTRY_DELETE events since this event (or OVERFLOW) must appear at the moment the actual watched directory is moved or deleted and thus invalid.

A: My understanding is that renaming a directory will generate file system events on the old and new parent directories, not on the directory that is renamed.   According to the answer to Can iNotify tell me where a monitored file is moved?, the OS cannot tell you where something was moved to unless you are monitoring the destination directory.  (And besides, in Java 7/8 MOVE events aren't handled by the watch service implementation.)
UPDATE
You could try the jpathwatch project that adds support for (platform specific) extended events using the standard Java7 WatchService APIs.
References:

*

*documentation - http://jpathwatch.wordpress.com/

*javadoc - http://jpathwatch.sourceforge.net/


text:
Q: MongoDB import/ export using Node.js How to perform import and export operation in MongoDB using Node.js? The code which we use in MongoDB for this is
mongoimport --collection Newimport --file filename.json
mongoexport --db test --collection CollectionName --out outputFileName.json

I need to perform this using Node.js

A: Try to create Child process in NodeJS and try execute mongoimport or mongoexport commands
More on this on following links :
http://nodejs.org/api/child_process.html
http://krasimirtsonev.com/blog/article/Nodejs-managing-child-processes-starting-stopping-exec-spawn


text:
Q: Superscripts and bold dots If I type
$\boldsymbol{\ddot\xi}^{\,n}$

I get

whereas on removing \boldsymbol and \, I get

How do I get the superscript to appear like this also with \boldsymbol?

A: You should load the bm package. Compare
\documentclass{article}
\usepackage{amsmath}

\begin{document}

$\boldsymbol{\ddot\xi}^{\,n}$

\end{document}

which gives

with
\documentclass{article}
\usepackage{amsmath,bm}

\begin{document}

$\boldsymbol{\ddot\xi}^{\,n}$

\end{document}

which gives


text:
Q: Pass a columns output to sub-query I  have this prcodeure below:
PROCEDURE return_information (i_vcust_cd IN VARCHAR2,
                           i_vplace_of_ship IN VARCHAR2,
                           i_vstatus IN VARCHAR2,
                           i_vdate_to IN VARCHAR2,
                           i_vdate_from IN VARCHAR2,
                           o_Cresultset OUT SYS_REFCURSOR)
                          as

BEGIN

 OPEN o_Cresultset for

SELECT
rownum as seq,
ship_cust_cd as place_of_shipment,
c.FIRM_NM_LOCL as customer_name,
DD.src as source,
DD.part_no as part_number,
p.PART_NM_ENG as part_name,
p.main_mdl as vehicle_type,
sale_qty as sales_qty,
sale_prce as sales_price,
sale_amt as sales_amount,
(select  ROUND(NVL(b.sale_prce,0) *  NVL(a.appl_rate,0),0) as sale_prce FROM
 SALE_PRICE_APPLY_RATE a, PARTS_SALES_PRICES b,
 (SELECT P.src,
      P.part_no,
      part_src,
      rcpt_prce,
      prce_grad_cd,
      decode(substr(main_mdl,1,1),  'C','C','S','S','P') as flag
FROM parts P
     WHERE P.src            =    'M'              -- SOURCE
  AND P.part_no  =  '90887656') c   -- PART NUMBER. current part no is temp.
WHERE a.CUST_CD = i_vcust_cd                                        --RETRUN                dealer CODE(cust_cd)
 and a.sratm0_flag = c.flag
 and a.PRCE_APPL_CD = 'DW'                                      -- RETRUN     dealer infor(prce_cd)
 and b.src = c.src
 and b.part_no = trim(c.part_no)
 and b.prce_cd = a.PRCE_APPL_CD) as return_price,            --RETURN_PRICE,
 req_remark as remark,
 status as status,
 DD.reg_dt as registered_date,
 cnfm_dt as completed_date,
PRE_SLIP_YEAR||PRE_SLIP_DEPT_CD||PRE_SLIP_SEQ as return_statement,
NEW_SLIP_YEAR||NEW_SLIP_DEPT_CD||NEW_SLIP_SEQ as  shipment_statement

FROM   DOMESTIC_ORDER_DIRECT_DELIVERY DD,
   CUSTOMERS C,
   PARTS P
 WHERE  RETURN_CUST_CD =  i_vcust_cd   -- Login dealer code
 AND    ship_cust_cd LIKE NVL(i_vplace_of_ship, '%')   -- place of return
 AND    STATUS LIKE NVL(i_vstatus, '%') -- 100,300,900,ALL
 AND    DD.RETURN_CUST_CD = C.CUST_CD
 AND    DD.SRC = P.SRC
 AND    DD.PART_NO = trim(P.PART_NO)
 AND    dd.REG_DT >= i_vdate_from -- date from
 AND    dd.REG_DT <= i_vdate_to-- date to
 ;
 end return_information;

The problem I'm having is that I need to calculate 'return_price' but it uses a part number that is identical to 'part_number' column. However, without passing in a part number I am unsure how to map the part number output in the cursor to the where clause in the subquery that returns 'return_price'


text:
Q: Get total count of executed queries in sql server of any database with filtered any date how can i get the total count of executed queries of any database with in date range. also if it can provide the list of executed queries text, and their execution time. this will help me to optimize my queries.
Thanks


text:
Q: updating part of string in c++ Is there any way to update the part of a string by passing it in a function?
std::string str = "hello world";

I want to reverse part of the string for example from index 4 to 8.
I have a function that reverses a string from start index to end index. How I can pass the string from index 4 to 8 to that function so that it will be updated automatically in the str string.

A: Why don't you just use std::reverse?
std::string str = "hello world";
std::reverse ( str.begin() + 4, str.begin() + 8 );

A: Write a function that takes begin/end iterators. See, for example std::reverse(). Usage example for std::vector is on the same page.

A: You can pass the string by reference:
void foo( std::string & inputString )
{
  //anything you do here will directly affect the string passed.
}

For example:
void foo( std::string & str )
{
    str.append("World!");
}

int main()
{
    std::string a = "Hello, ";
    foo(a);
    std::cout << a;
    return 0;
}

will print out "Hello, World!". Another choice is to pass the begin and end iterators of the string. A lot of std functions work like that.


text:
Q: как открыть один файл сразу в двух окнах Sublime3 как открыть один и тот же файл сразу в двух окнах Sublime3

A: Использовать меню File / New View into File. В одном из окон создастся копия файла, которую можно будет перетащить в другое окно.

A: Откройте два разных файла в вашем Sublime, перетащите одну вкладку на рабочий стол, она выйдет в отдельное окно. Затем перетащите файл который вам нужен, в первое, а затем и во второе окно, закройте не нужные вкладки, и у вас будет открыт один файл в двух окнах.


text:
Q: await is a reserved word Asyncdata vue I am trying to use axios but I keep getting await is a reserved word. I am using vue.js.
import axios from '~/plugins/axios'
export default {
  layout: 'dashboard',
  asyncData ({ params, error }) {
    let { data } = await axios.get('/api/users')
    return { users: data }
  }
}


text:
Q: Wicket: update model via TextFields in a ListView I am coding a simple panel that renders uploaded images and their alt texts using ListView. I am able to show the uploaded images and also their alt texts from database, but I can't find the solution to update alt texts via TextFields.
Here's the model for presenting data, works as expected:
this.listModel = new LoadableDetachableModel<Object>() {
    protected Object load() {
    ArrayList<SingleImage> images = SingleImageDao.getImagesByPageId(pageId);
    return images;
    }
};

And here's the setListView() method:
this.setListView(new ListView("imageListItem", this.listModel) {
    protected void populateItem(final ListItem item) {
    final SingleImage singleImage = (SingleImage) item.getModelObject();

    item.add(new AttributeModifier("id", singleImage.getId()));
    item.add(new Image("imageListItemImg",
        new ContextRelativeResource(uploadedImgDir
            + singleImage.getFileName())));

    final TextField altText = new TextField<String>("altText", new PropertyModel<String>(singleImage, "altText"));
    item.add(altText);
    }
});
this.listView.setReuseItems(true);

There's also a button that should save the changes:
this.saveButton = new AjaxButton("saveButton") {
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form form) {
    target.add(listContainer);
    }
};

listContainer is a WebMarkupContainer that wraps the ListView. Any ideas how to update the altText fields?
EDIT: Tom asked for complete Java class and HTML page.
Java class:
public class ImageListPanel extends Panel {
    private final String uploadedImgDir = "img//uploaded//";
    private int pageId;
    private IModel<?> listModel = null;
    private ListView<?> listView = null;
    private WebMarkupContainer imageListContainer = null;
    private WebMarkupContainer listContainer = null;
    private Form<?> actionButtons = null;
    private AjaxButton saveButton = null;

    public ImageListPanel(String id, final int pageId) {
        super(id);
        this.pageId = pageId;

        this.listModel = new LoadableDetachableModel<Object>() {
            protected Object load() {
                ArrayList<SingleImage> images = SingleImageDao.getImagesByPageId(pageId);
                return images;
            }
        };

        this.setListView(new ListView("imageListItem", this.listModel) {
            protected void populateItem(final ListItem item) {
                final SingleImage singleImage = (SingleImage) item.getModelObject();

                item.add(new AttributeModifier("id", singleImage.getId()));
                item.add(new Image("imageListItemImg",
                    new ContextRelativeResource(uploadedImgDir
                        + singleImage.getFileName())));
                final TextField altText = new TextField<String>("altText", new PropertyModel<String>(singleImage, "altText"));
                item.add(altText);
            }
        });

        this.listView.setReuseItems(true);

        this.imageListContainer = new WebMarkupContainer("imageListContainer");
        this.listContainer = new WebMarkupContainer("listContainer");
        this.setActionButtons(new Form<Void>("actionButtons"));
        this.saveButton = new AjaxButton("saveButton") {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form form) {
                target.add(listContainer);
                listContainer.add(new AttributeModifier("class", "passive"));
            }
        };
        this.imageListContainer.setOutputMarkupId(true);
        this.listContainer.setOutputMarkupId(true);
        add(this.imageListContainer);
        this.imageListContainer.add(this.listContainer);
        this.listContainer.add(this.listView);
        this.listView.setOutputMarkupId(true);
        this.getActionButtons().setOutputMarkupId(true);
        this.getActionButtons().add(this.saveButton);
        this.imageListContainer.add(this.getActionButtons());
    }

    public int getPageId() {
        return pageId;
    }

    public void setPageId(int pageId) {
        this.pageId = pageId;
    }

    public WebMarkupContainer getListContainer() {
        return listContainer;
    }

    public void setListContainer(WebMarkupContainer listContainer) {
        this.listContainer = listContainer;
    }

    public ListView<?> getListView() {
        return listView;
    }

    public void setListView(ListView<?> listView) {
        this.listView = listView;
    }

    public Form<?> getActionButtons() {
        return actionButtons;
    }

    public void setActionButtons(Form<?> actionButtons) {
        this.actionButtons = actionButtons;
    }
}

HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <wicket:panel>

                        <input wicket:id="altText" class="altText" type="text" size="40" />

            <form wicket:id="actionButtons">

                    <input wicket:id="saveButton" id="saveButton" type="submit" value="Save" />

            </form>

    </wicket:panel>

EDIT 2: updated code, the ListView is now wrapped inside a Form.
Java class:
public class ImageListPanel extends Panel {
private final String uploadedImgDir = "img//uploaded//";
private int pageId;
private IModel<?> listModel = null;
private ListView<?> listView = null;
private WebMarkupContainer imageListContainer = null;
private WebMarkupContainer listContainer = null;

public ImageListPanel(String id, final int pageId) {
    super(id);
    this.pageId = pageId;

    this.listModel = new LoadableDetachableModel<Object>() {
        protected Object load() {
            ArrayList<SingleImage> images = SingleImageDao.getImagesByPageId(pageId);
            return images;
        }
    };

    this.setListView(new ListView("imageListItem", this.listModel) {
        protected void populateItem(final ListItem item) {
            final SingleImage singleImage = (SingleImage) item.getModelObject();

            item.add(new AttributeModifier("id", singleImage.getId()));
            item.add(new Image("imageListItemImg",
                new ContextRelativeResource(uploadedImgDir
                    + singleImage.getFileName())));
            final TextField altText = new TextField<String>("altText", new PropertyModel<String>(singleImage, "altText"));
            item.add(altText);
        }
    });

    this.listView.setReuseItems(true);
    Form formListView = new Form("formListView", this.listModel) {
        protected void onSubmit() {
            ArrayList<SingleImage> images = (ArrayList<SingleImage>) listModel.getObject();
            for (SingleImage singleImage : images) {
                System.out.println(singleImage.getAltText());
            }
        };
    };

    this.imageListContainer = new WebMarkupContainer("imageListContainer");
    this.listContainer = new WebMarkupContainer("listContainer");
    this.imageListContainer.setOutputMarkupId(true);
    this.listContainer.setOutputMarkupId(true);
    add(this.imageListContainer);
    this.imageListContainer.add(this.listContainer);
    //this.listContainer.add(this.listView);
    this.listContainer.add(formListView);
    formListView.add(this.listView);
    this.listView.setOutputMarkupId(true);
}

public int getPageId() {
    return pageId;
}

public void setPageId(int pageId) {
    this.pageId = pageId;
}

public WebMarkupContainer getListContainer() {
    return listContainer;
}

public void setListContainer(WebMarkupContainer listContainer) {
    this.listContainer = listContainer;
}

public ListView<?> getListView() {
    return listView;
}

public void setListView(ListView<?> listView) {
    this.listView = listView;
}

}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <wicket:panel>

                <form wicket:id="formListView">

                            <input wicket:id="altText" class="altText" type="text" size="40" />

                </form>
                <input type="submit" value="submit" />

    </wicket:panel>

A: If I understand correctly, you want to display a list of images each with a text field to edit its alt-text and store it in the database. In the code you posted you have to change the following:

*

*surround the whole list with the form. Currently, the input field is not part of the form and thus the user input cannot be posted to the server-side Wicket code. In your setup, the whole listview will be added of the form then instead of the parent panel.

*implement form.onSubmit(). In the onSubmit()-method you can access the value of the input textfield via singleImage.getAltText() and store in the database.


text:
Q: How to test rake tasks with Whenever Gem? I'm trying to execute a simple rake task using whenever gem but the code isn't being executed.
I already set the environment to development, I updated the cron using the whenever --update-crontab command and the rake task works well if I run the command on console. But, when I run the server the log file is not being generated.
I saw a question here too with the same problem but it was solved setting the environment to development, but didn't work out for me.
My rake task:
namespace :testando do
  task :consulta => :environment do
    produto = Produto.first
    puts produto.nm_produto
  end
end

My schedule.rb:
set :output, "#{path}/log/cron_log.log"
set :environment, 'development'

every 1.minute do
  rake "testando:consulta"
end

I'm using rails 5.0.0.1 and I'm programing in Cloud9, so I think the OS is Ubuntu.
What's missing ?
Update:
I followed the instructions of the main answer in this topic Cron job not working in Whenever gem
And it worked! The task is running even with the server not being started (with "rails s" command).

A: please run crontab -l to see if you have updated the crontab successfully


text:
Q: Regex add leading zeros to DD.MM.YYYY string I was sure something like this had been answered before in some manner however I only managed to find reveresed versions like MM/DD/YYYY etc or special characters like / - and had little luck converting them as my regex knowledge is terrible.
The closest thread I found was this
I am struggling to find a clean approach using regex and javascript to add trailing zeros to the below string format?
dd.mm.yyyy

Eg 1.1.1998 => 01.01.1998 || 10.1.1998 => 10.01.1998
my current approach is along the lines of
const addLeadingZeros = (input: string) => {
   return input.replace(/.([1-9])(?!\d)/g, '.0$1');
}

A: How about:
input.replace(/(?<=^|\.)(\d)(?=\.|$)/g, '0$1');

It means: "replace all digits preceded by the beginning of a line or a dot and followed by a dot or the end of the line". This example works only for day and month parts.
Example (browser console outputs):
"01.01.1998".replace(/(?<=^|\.)(\d)(?=\.|$)/g, '0$1');
← "01.01.1998"
"1.01.1998".replace(/(?<=^|\.)(\d)(?=\.|$)/g, '0$1');
← "01.01.1998"
"1.1.1998".replace(/(?<=^|\.)(\d)(?=\.|$)/g, '0$1');
← "01.01.1998"

(Note: this is not a solution I particularly recommend, I just focused on the asked point.)

A: My solution:
const addLeadingZeros = (input: string) => {
   return input.replaceAll(/\d*(?<![\d])[\d](?=[.])/g, '0$&');
}

The regex: \d*(?<![\d])[\d](?=[.])
You can find the explanation about it here.

const addLeadingZeros = (input) => {
   return input.replaceAll(/\d*(?<![\d])[\d](?=[.])/g, '0$&');
}

console.log(addLeadingZeros('01.02.3456'))
console.log(addLeadingZeros('1.2.2001'))
console.log(addLeadingZeros('01.2.1234'))
console.log(addLeadingZeros('1.12.1998'))
console.log(addLeadingZeros('3.04.2021'))
console.log(addLeadingZeros('5.6.01'))
console.log(addLeadingZeros('5.06.01'))
console.log(addLeadingZeros('05.6.01'))
console.log(addLeadingZeros('7.8.1'))
console.log(addLeadingZeros('7.08.1'))
console.log(addLeadingZeros('07.8.1'))

A: You can also use this regex /^\d\.|(?<=\.)\d\./g it will select the first number and the number after the first dot, so it will only select date and month on your format.
You can use this like the code bellow
let regex = /^\d\.|(?<=\.)\d\./g;
console.log("8.8.2014".replace(regex,
str => `0${str}`));
console.log("25.06.2014".replace(regex,
str => `0${str}`));
console.log("9.06.2014".replace(regex,
str => `0${str}`));
console.log("08.7.2014".replace(regex,
str => `0${str}`));
console.log("1.1.1998".replace(regex,
str => `0${str}`));

Now I'm gonna explain it part by part
regex
The regex is broken by a | which tells it to either match expression before it or after it.
The first part is ^\d\., if you know the basics of regex, you'll know that it means see if there is a number right after which there is a dot at the beginning, it selects the date if there is only one digit representing it.
The second part is (?<=\.)\d\., this part first sees if there is a dot before the string that is to be selected, then it sees if there is only one number after it then a dot. It will select the month if there is only one digit representing it.
Here the first part (?<=.) tells java script to seek for dot but not select it, if there is no dot before the number it won't select the string.
Now the last part g makes it select every instance of string which is matched.
So for the first example it selects the strings "8." and "8."
.replace
.replace is a string function taking two argument, first the string/regex to match, in my code it is a regex.
Second is a string or a callback that returns a string, in my code it's a callback.
The callback can get the an argument which is the matched string.
Then I add the "0" before the matched string with a template string.
So the ending output is
08.08.2014
25.06.2014
09.06.2014
08.07.2014
01.01.1998

Hope my explanation helped.
I might be wrong at some places, as I'm still learning and use regex or even the callback of replace not very often.
Hope there weren't many mistakes.
If I'm wrong somewhere please let me know.


text:
Q: Can't return anything other than 1 or 0 from int function I wish my first post wasn't so newbie. I've been working with openframeworks, so far so good, but as I'm new to programming I'm having a real headache returning the right value from an int function. I would like the int to increment up until the Boolean condition is met and then decrement to zero. The int is used to move through an array from beginning to end and then back. When I put the guts of the function into the method that I'm using the int in, everything works perfectly, but very messy and I wonder how computationally expensive it is to put there, it just seems that my syntactic abilities are lacking to do otherwise. Advice appreciated, and thanks in advance.
int testApp::updown(int j){

if(j==0){
    arp =true;

}
else if (j==7){
    arp = false;

}

if(arp == true){
    j++;

}

else if(arp == false){
    j--;

}

    return (j);

}

and then its called like this in an audioRequest block of the library I'm working with:
for (int i = 0; i < bufferSize; i++){

 if ((int)timer.phasor(sorSpeed)) {

            z = updown(_j);
            noteOut = notes [z];

            cout<<arp;
            cout<<z;

        }

EDIT: For addition of some information. Removed the last condition of the second if statement, it was there because I was experiencing strange happenings where j would start walking off the end of the array.
Excerpt of testApp.h
int z, _j=0;
Boolean arp;

EDIT 2: I've revised this now, it works, apologies for asking something so rudimentary and with such terrible code to go with. I do appreciate the time that people have taken to comment here. Here are my revised .cpp and my .h files for your perusal. Thanks again.
#include "testApp.h"
#include <iostream>
using namespace std;

testApp::~testApp() {

}

void testApp::setup(){

sampleRate          = 44100;
initialBufferSize   = 1024;

//MidiIn.openPort();
//ofAddListener(MidiIn.newMessageEvent, this, &testApp::newMessage);

j = 0;
z= 0;
state = 1;

tuning = 440;
inputNote = 127;
octave = 4;
sorSpeed = 2;
freqOut = (tuning/32) * pow(2,(inputNote-69)/12);
finalOut = freqOut * octave;

notes[7] = finalOut+640;
notes[6] = finalOut+320;
notes[5] = finalOut+160;
notes[4] = finalOut+840;
notes[3] = finalOut+160;
notes[2] = finalOut+500;
notes[1] = finalOut+240;
notes[0] = finalOut;

ofSoundStreamSetup(2,0,this, sampleRate, initialBufferSize, 4);/* Call this last ! */

}

void testApp::update(){

}

void testApp::draw(){

}

int testApp::updown(int &_j){

int tmp;

if(_j==0){
    arp = true;
}

else if(_j==7) {
    arp = false;
}

if(arp == true){
    _j++;
}

else if(arp == false){
    _j--;
}

tmp = _j;
return (tmp);

}

void testApp::audioRequested    (float * output, int bufferSize, int nChannels){

    for (int i = 0; i < bufferSize; i++){

        if ((int)timer.phasor(sorSpeed)) {

            noteOut = notes [updown(z)];

            }

    mymix.stereo(mySine.sinewave(noteOut),outputs,0.5);

    output[i*nChannels    ] = outputs[0];
    output[i*nChannels + 1] = outputs[1];

    }
}

testApp.h
class testApp : public ofBaseApp{

public:
    ~testApp();/* destructor is very useful */
    void setup();
    void update();
    void draw();

    void keyPressed  (int key);
    void keyReleased(int key);
    void mouseMoved(int x, int y );
    void mouseDragged(int x, int y, int button);
    void mousePressed(int x, int y, int button);
    void mouseReleased(int x, int y, int button);
    void windowResized(int w, int h);
    void dragEvent(ofDragInfo dragInfo);
    void gotMessage(ofMessage msg);

    void newMessage(ofxMidiEventArgs &args);

    ofxMidiIn MidiIn;

    void audioRequested     (float * input, int bufferSize, int nChannels); /* output method */
    void audioReceived  (float * input, int bufferSize, int nChannels); /* input method */

    Boolean arp;
    int     initialBufferSize; /* buffer size */
    int     sampleRate;
    int    updown(int &intVar);

    /* stick you maximilian stuff below */

    double filtered,sample,outputs[2];
    maxiFilter filter1;
    ofxMaxiMix mymix;
    ofxMaxiOsc sine1;
    ofxMaxiSample beats,beat;
    ofxMaxiOsc mySine,myOtherSine,timer;

    int currentCount,lastCount,i,j,z,octave,sorSpeed,state;
    double notes[8];
    double noteOut,freqOut,tuning,finalOut,inputNote;

};

A: It's pretty hard to piece this all together. I do think you need to go back to basics a bit, but all the same I think I can explain what is going on.

*

*You initialise _j to 0 and then never modify the value of _j.

*You therefore call updown passing 0 as the parameter every time.

*updown returns a value of 1 when the input is 0.

Perhaps you meant to pass z to updown when you call it, but I cannot be sure.
Are you really declaring global variables in your header file? That's not good. Try to use local variables and/or parameters as much as possible. Global variables are pretty evil, especially declared in the header file like that!


text:
Q: Условный оператор в sql выходит с ошибкой Почему этот запрос выдаёт ошибку?
IF ((SELECT COUNT(*) FROM `messages` WHERE `time` = '2016-09-05 18:07:00.000000' AND `author` = 'user') = 0) THEN
    UPDATE `messages` SET `text`='test', `author`='user', `time`='2016-09-05 18:07:00.000000', `ticket`='111';
END IF;

#1064 ошибка в первой строке. Нужно вставить строку в таблицу, если с определёнными колонками не найдены такие же строки (id может не совпасть, всё остальное строго). (Пробую выполнять пока в phpmyadmin.) Протестировал запрос в самом if без этой конструкции. Он выполняется, но как только пытаюсь условие поставить - выходит ошибка. Что я не так делаю?

A: Такие инструкции как IF можно применять только внутри хранимых процедур. К языку запросов SQL они никакого отношения не имеют.
Ваш запрос можно переписать так:
UPDATE `messages`
   SET `text`='test', `author`='user', `time`='2016-09-05 18:07:00.000000', `ticket`='111'
 WHERE NOT EXISTS(
    SELECT 1 FROM `messages`
     WHERE `time` = '2016-09-05 18:07:00.000000' AND `author` = 'user'
 )

Так же обратите внимание, что в случае если условие выполнится, т.е. не будет найдено ни одной записи удовлетворяющей условию, данный update поменяет значение во всех строках таблицы, так как никаких условий указывающих на то, какие строки должны быть изменены нет.


text:
Q: AVFoundation library: Sound Will Not Play Working on my second app...
Have buttons going to individual images and when app moves to new image. I want to play sound, but its not working...
in .h file:
#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

#import "SoundController.h"

@interface BoatController : UIViewController {

}

@property (nonatomic, retain) UIView *Cruise_Ship;

@property (nonatomic, retain) UIView *Speed_Boat;

@end

in .m file:
#import "BoatController.h"

@implementation BoatController

@synthesize Cruise_Ship;

@synthesize Speed_Boat;

- (void)viewDidLoad {
[super viewDidLoad];

}

-(void)View01
{
    UIView * containingView = Cruise_Ship;
    [self.view removeFromSuperview];
    [containingView addSubview:Cruise_Ship];
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"boathorn01",CFSTR ("wav"), NULL);
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

-(void)View2
{
    UIView * containingView = Speed_Boat.superview;
    [self.view removeFromSuperview];
    [containingView addSubview:Speed_Boat];
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"nautical010",CFSTR ("wav"), NULL);
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

@end

Any ideas?  Trying to move from a controller via buttons to various pictures.  Navigation works, but sounds do not play.

A: You can use:
system("afplay path")


text:
Q: Locate data in out-of-source cmake build without need of copy I'm porting my game engine to linux and don't know how to locate my data without copying it. Before the data was in myproject/bin together with the produced exectuable.
With cmake default structure, the binaries go under myproject/build/source/launcher/release/launcher.exe separated from the data. I can locate it with visual studio, setting the working directory to the same path(myproject/data). But I would like a general solution directly from cmake. Mosts answers I've read copy the data to each build or generate a path variable pointing to the data. There's to much data to have duplicates for debug/release and it just doesn't feel right to copy it.
What is the best option here? What is most common in game development?

A: You could try https://github.com/caseymcc/CreateLaunchers, with Visual Studio/Windows it will create a .user file(vs debug info) and a batch file that you can set the command, command line args, path to dlls, working directory and any other environment variables you need.
On linux it will produce a shell script with the same info.


text: Q: xmlworker' Itextsharp with sharepoint picture library we are using xmlworker from ITextSharp to render nustache html templates to pdf, and the problem comes when getting images from picture libraries in sharepoint. the xmlworker has no autenthication (at least I don't know) so sharepoint doesn't return the images. Any clue?


text:
Q: NASA world wind map - open navigation URL new window after clicking on custom Placemark Please suggest me how to perform following scenario using world wind map on the web:
open navigation URL new window after clicking on custom Placemark

I have tried to register or add event dynamically place work canvas but no luck.
Please refer following code.

self.createPlacemark = function(location) {

    var placemark,
        placemarkAttributes = new WorldWind.PlacemarkAttributes(null),
        highlightAttributes,
        placemarkLayer = new WorldWind.RenderableLayer("Placemarks"),
        latitude = location.lat,
        longitude = location.long;

    // Set up the common placemark attributes.
    placemarkAttributes.imageScale = 1;
    placemarkAttributes.imageOffset = new WorldWind.Offset(
        WorldWind.OFFSET_FRACTION, 0.5,
        WorldWind.OFFSET_FRACTION, 0.5);
    placemarkAttributes.imageColor = WorldWind.Color.WHITE;

    newA = document.createElement('a');
    newA.setAttribute('href', "http://lochalhost");
    newA.setAttribute('target', '_blank')
    newA.innerHTML = "link text";
    //newA.click();
    newA.addEventListener("click", function() {
        alert('Hello');
    });

    //Create the custom image for the placemark.
    var canvas = document.createElement("canvas"),
        ctx2d = canvas.getContext("2d"),
        size = 40,
        c = size / 2 - 0.5,
        innerRadius = 2,
        outerRadius = 10;

    canvas.width = size;
    canvas.height = size;
    canvas.id = Math.random().toString(36).substring(2);

    var gradient = ctx2d.createRadialGradient(c, c, innerRadius, c, c, outerRadius);
    gradient.addColorStop(0, 'rgb(255, 0, 0)');
    gradient.addColorStop(0.5, 'rgb(0, 255, 0)');
    gradient.addColorStop(1, 'rgb(255, 0, 0)');

    ctx2d.fillStyle = gradient;
    ctx2d.arc(c, c, outerRadius, 0, 2 * Math.PI, false);
    ctx2d.fill();

    canvas.addEventListener("click", function() {
        window.open("https://www.google.com", "_blank");
    });

    // Create the placemark.
    placemark = new WorldWind.Placemark(new WorldWind.Position(latitude, longitude, 1e2), false, null);
    placemark.altitudeMode = WorldWind.RELATIVE_TO_GROUND;

    // Create the placemark attributes for the placemark.
    placemarkAttributes = new WorldWind.PlacemarkAttributes(placemarkAttributes);
    // Wrap the canvas created above in an ImageSource object to specify it as the placemark image source.
    placemarkAttributes.imageSource = new WorldWind.ImageSource(canvas);
    placemark.attributes = placemarkAttributes;

    // Create the highlight attributes for this placemark. Note that the normal attributes are specified as
    // the default highlight attributes so that all properties are identical except the image scale. You could
    // instead vary the color, image, or other property to control the highlight representation.
    highlightAttributes = new WorldWind.PlacemarkAttributes(placemarkAttributes);
    highlightAttributes.imageScale = 1.2;
    placemark.highlightAttributes = highlightAttributes;

    // Add the placemark to the layer.
    placemarkLayer.addRenderable(placemark);

    // Add the placemarks layer to the WorldWindow's layer list.
    wwd.canvas.appendChild(newA);
    wwd.addLayer(placemarkLayer);
};

https://worldwind.arc.nasa.gov/web/examples/


text:
Q: Backtest not showing any results for a SMA crossover script in tradingview Trying below script in Pine Script version 5. No errors in scripts. But, it doesn't show any results in backtest. Can anyone please help?
code
bold
italic

quote
****//@version=5

strategy(shorttitle='Long on MA Crossover',title='Long Strategy with MA Crossover', overlay=true, initial_capital = 20000, currency = currency.USD, process_orders_on_close=true, default_qty_type = strategy.cash, default_qty_value = 20000, commission_type=strategy.commission.percent, commission_value=0.075)

//Backtest dates
fromMonth = input.int(defval = 1,    title = "From Month",  minval = 1, maxval = 12)
fromDay   = input.int(defval = 1,    title = "From Day",    minval = 1, maxval = 31)
fromYear  = input.int(defval = 2019, title = "From Year",   minval = 1970)
thruMonth = input.int(defval = 1,    title = "Thru Month",  minval = 1, maxval = 12)
thruDay   = input.int(defval = 1,    title = "Thru Day",    minval = 1, maxval = 31)
thruYear  = input.int(defval = 2112, title = "Thru Year",   minval = 1970)

showDate  = input.bool(defval = true, title = "Show Date Range")

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)        // backtest start window
finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)        // backtest finish window
window()  => time >= start and time <= finish ? true : false       // create function "within window of time"

len1 = input.int(9, minval=1, title="MA1")
len2 = input.int(50, minval=1, title="MA2")
len3 = input.int(100, minval=1, title="MA3")
len4 = input.int(200, minval=1, title="MA4")

ma1 = ta.sma(close, len1)
ma2 = ta.sma(close, len2)
ma3 = ta.sma(close, len3)
ma4 = ta.sma(close, len4)

Take_profit= ((input (3))/100)

longTakeProfit = strategy.position_avg_price * (1 + Take_profit)

closeLong = close > longTakeProfit or ta.crossover(ma2,ma1)

//Entry
strategy.entry("buy", strategy.long, limit=close[1], when = ta.crossover(ma1,ma2) and ma2 > ma3 and ma3 > ma4 and window())

//Exit
strategy.close("sell", when = closeLong and window())****

A: the error is in the last line , strategy.close("sell", when = closeLong and window())
when you use the strategy.close() function then you have to provide the same trade id as in the strategy.entry() function , you have placed a unknown id "sell" which is never used to enter any trade with this ID.
The following is the updated code and working code.
//@version=5
strategy(shorttitle='Long on MA Crossover',title='Long Strategy with MA Crossover', overlay=true, initial_capital = 20000, currency = currency.USD, process_orders_on_close=true, default_qty_type = strategy.cash, default_qty_value = 20000, commission_type=strategy.commission.percent, commission_value=0.075)

//Backtest dates
fromMonth = input.int(defval = 1,    title = "From Month",  minval = 1, maxval = 12)
fromDay   = input.int(defval = 1,    title = "From Day",    minval = 1, maxval = 31)
fromYear  = input.int(defval = 2019, title = "From Year",   minval = 1970)
thruMonth = input.int(defval = 1,    title = "Thru Month",  minval = 1, maxval = 12)
thruDay   = input.int(defval = 1,    title = "Thru Day",    minval = 1, maxval = 31)
thruYear  = input.int(defval = 2112, title = "Thru Year",   minval = 1970)

showDate  = input.bool(defval = true, title = "Show Date Range")

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)        // backtest start window
finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)        // backtest finish window
window()  => time >= start and time <= finish ? true : false       // create function "within window of time"

len1 = input.int(9, minval=1, title="MA1")
len2 = input.int(50, minval=1, title="MA2")
len3 = input.int(100, minval=1, title="MA3")
len4 = input.int(200, minval=1, title="MA4")

ma1 = ta.sma(close, len1)
ma2 = ta.sma(close, len2)
ma3 = ta.sma(close, len3)
ma4 = ta.sma(close, len4)

Take_profit= ((input (3))/100)

longTakeProfit = strategy.position_avg_price * (1 + Take_profit)

closeLong = close > longTakeProfit or ta.crossover(ma2,ma1)

//Entry
strategy.entry("buy", strategy.long, limit=close[1], when = ta.crossover(ma1,ma2) and ma2 > ma3 and ma3 > ma4 and window())

//Exit
strategy.close("buy", when = closeLong and window())


text:
Q: how to translate this PHP code to PDO form , because i am getting undefined function in PHP 7 (using XAMPP)? This is my PHP file, but i am getting fatal error : undefined function mysql_connect, i have searched it and it looks like i have to use PDO instead of mysql_connect on PHP 7 , and i dont know how so i need help please, I want this code as PDO, thanks for your time
<?php

// connection , which gives fatal exception : undefined function..

$con = mysql_connect("localhost",'root','');

//error handling

if (!$con)

 {

  die("Could not connected".mysql_error());  else
{

//select the DB name in PhpMyAdmin

  mysql_select_db("tm-mobile",$con);

//Vlidation

if (!empty($_POST['owner_name']) && !empty($_POST['owner_email']))
{

  $owner_id=$_POST['owner_id'];

  $owner_name=$_POST['owner_name'];

  $owner_email=$_POST['owner_email'];

  $owner_password=$_POST['owner_password'];

  $market_name=$_POST['market_name'];

//SQL statement

$sql =  "UPDATE owner_table SET owner_id = '$owner_id',owner_name =

  '$owner_name' , owner_email = '$owner_email', owner_password =

  '$owner_password'  ,  market_name = '$market_name' ";

  $re = mysql_query ($sql,$con);

//Close the Connection

mysql_close();

   }

}

?>

A: <?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('SET CHARACTER SET utf8');
    if (!empty($_POST['owner_name']) && !empty($_POST['owner_email'])) {
        $owner_id = $_POST['owner_id'];
        $owner_name = $_POST['owner_name'];
        $owner_email = $_POST['owner_email'];
        $owner_password = $_POST['owner_password'];
        $market_name = $_POST['market_name'];

        $statement = $pdo->prepare('UPDATE `owner_table` SET `owner_id` = :owner_id, `owner_name` = :owner_name,
                              `owner_email` = :owner_email, `owner_password` = :owner_password, market_name = :market_name;');
        $statement->bindParam(':owner_id', $owner_id, PDO::PARAM_INT);
        $statement->bindParam(':owner_name', $owner_name, PDO::PARAM_STR);
        $statement->bindParam(':owner_email', $owner_email, PDO::PARAM_STR);
        $statement->bindParam(':owner_password', $owner_password, PDO::PARAM_STR);
        $statement->bindParam(':market_name', $market_name, PDO::PARAM_STR);
        $statement->execute();
        echo $statement->rowCount();
    }
} catch (PDOException $e) {
    die('Cannot connect: ' . $e->getMessage());
}

here it is, take look at some tutorials, for example http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers and also use where in INSERT/REPLACE/UPDATE/DELETE queries because it can be dangerous


text:
Q: Is there possibility to invoke other methods/instructions before main() when running the code
Possible Duplicate:
Can you print anything in C++, before entering into the main function?

Is there any possibility to run any other instructions before int main() is invoked?
int main(){cout<<"a";}

and before that call in main() there is call for cout<<"b"; somewhere before. Maybe this #define thing can help.

A: Global objects are constructed before main() runs. So you can define a class, put your code in its constructor, and then declare a global instance of that class:
class temp
{
public:
    temp()
    {
        cout << "before main" << endl;
    }

    ~temp()
    {
       cout << "after main" << endl;
    }
};

temp t;

int main()
{
    cout << "in main" << endl;
    return 0;
}

Global variables are also initialized before main() runs.  You can define a function that returns a value, then call that function and assign the value to a global variable in its declaration, like @jrok showed.
Some compilers also support a #pragma startup statement to execute a user-defined function at startup (and corresponding #pragma exit statement for shutdown):
void beforeMain()
{
    cout << "before main" << endl;
}
#pragma startup beforeMain

void afterMain()
{
    cout << "after main" << endl;
}
#pragma exit afterMain

int main()
{
    cout << "in main" << endl;
    return 0;
}

A: You don't need a define. Just create a global object (in the same file) and its ctor (or anything else you use to initialize it, such as calling a function) will run before main is invoked.
Edit: likewise, those global objects will be destroyed after main exits, so their destructors will run at that time.