text:
Q: Call standard arduino functions from assembly I'm attempting to learn Assembly for the Arduino Uno, currently, I'm using the Arduino IDE and a .S file in which I overwrite the setup and loop functions. I want to make the Arduino receive a serial character and do something depending on what character it received. However, I can't seem to find how to call standard Arduino functions from the .S file. Specifically, I want to call the Serial.begin, Serial.read and Serial.available functions. If someone could point me in the right direction I would much appreciate it.
Edit:
I was able to call C functions from assembly (the delay function in this case) and pass it parameters. Now i've tried to do the same for "Serial.begin(9600)" with the folowing code:
.extern Serial.begin
setup:
  ldi r22, 0b10000000 ; set 9600 as a long for the first parameter
  ldi r23, 0b00100101
  clr r24
  clr r25
  call Serial.begin ; call serial begin
...

the idea is to move 9600 in the registers r22:r25 as I understand that is where it will expect the first parameter. I am positive there is a better way to do this but thats the way I came up with. Compiling this yields the error: "undefined reference to `Serial.begin'"
if anyone could help me I would appreciate it.


text:
Q: java.util.logging.FileHandler - проблема перезаписи файлов cmds = Logger.getAnonymousLogger();
File lf = new File(getDataFolder(), "commands.log");
FileHandler fh = new FileHandler(lf.getAbsolutePath(), true);
fh.setFormatter(new XSimpleFormatter("%date [%level] %msg"));
cmds.addHandler(fh);

И вот сама проблема - по идее должно быть два файла - commands.log и commands.log.lck, но при каждом перезапуске начинают плодиться commands.log.0, commands.log.1 и так далее. Где ошибка?
UPD: log4j и прочие предлагать пока не надо. Меня util.logging пока устраивает во всем, кроме вышеописанной проблемы
A: Нет никакой ошибки, все правильно. Конструктор FileHandler(String pattern) где pattern - это маска файлов используемых для вывода.
Прочтите внимательно документацию
A: Если я правильно понял вопрос, то после каждой записи лога, файл нужно закрывать fh.close()
чтобы он не лочился.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Attachment not appearing in Outlook 2016 I created an email with Windows.ApplicationModel.Email.EmailMessage and I added an Attachment to it with the code below:
var stream = RandomAccessStreamReference.CreateFromFile(file);
var attachment = new EmailAttachment(file.Name, stream);
emailMessage.Attachments.Add(attachment);
await EmailManager.ShowComposeNewEmailAsync(emailMessage);

In the default Mail client found on Windows 10, the attachment appears as an attachment. However the attachment does not appear at all in Outlook 2016 with the same code. Any suggestions how to fix this?
EDIT: So apparently this is an issue with Windows 10 and all email clients with the exception of the standard Windows 10 mail client according to this.

A: In the meantime the docs are mentioning it too:

Attachments that you add to an email by using the EmailAttachment class will appear only in the Mail app. If users have any other mail program configured as their default mail program, the compose window will appear without the attachment. This is a known issue.

Seems that nothing changed to this day.


text:
Q: Ical.net viewing event data from calendar in .net and c# I've set up a console app to test out Ical.net. I have this code that is pulling the occurrences of these events from the calendar (which is working great); but I want to be able to view the other details that exist within these event objects; and I don't see in the documentation how to view the details.
Here is my code:
var calendar = new Calendar();
var recurrenceRule = new RecurrencePattern("FREQ=DAILY");

var vEvent = new CalendarEvent
{
    Start = new CalDateTime(DateTime.Parse("2018-10-01T07:00")),
    End = new CalDateTime(DateTime.Parse("2018-10-01T08:00")),
    Description = "Test Description on event object",
    Name = "Event Title 1",
    RecurrenceRules = new List<RecurrencePattern> { recurrenceRule }
};
calendar.Events.Add(vEvent);

recurrenceRule = new RecurrencePattern("FREQ=DAILY;INTERVAL=4;WKST=SU");
vEvent = new CalendarEvent
{
    Start = new CalDateTime(DateTime.Parse("2018-10-01T07:00")),
    End = new CalDateTime(DateTime.Parse("2018-10-01T08:00")),
    Description = "Test2 event description yo!",
    Name = "Event Title 2",
    RecurrenceRules = new List<RecurrencePattern> { recurrenceRule }
};
calendar.Events.Add(vEvent);

var searchStart = DateTime.Parse("2018-10-01");
var searchEnd = DateTime.Parse("2018-10-31");
var occurrences = calendar.GetOccurrences(searchStart, searchEnd);

foreach (var item in occurrences)
{
    Console.WriteLine(item.ToString());
}

Console.ReadLine();

Updated
I was able to view some of the event details by adding the following before my Console.ReadLine();
Code Addition:
foreach (var item in calendar.Children)
{
    Console.WriteLine(item.Name);
}

My only issue now is how would I tie up the occurrence date, this item.name, and the event description together into one object / things that reference each other?
Complete Code:
    var calendar = new Calendar();
var recurrenceRule = new RecurrencePattern("FREQ=DAILY");

var vEvent = new CalendarEvent
{
    Start = new CalDateTime(DateTime.Parse("2018-10-01T07:00")),
    End = new CalDateTime(DateTime.Parse("2018-10-01T08:00")),
    Description = "Test Description on event object",
    Name = "Event Title 1",
    RecurrenceRules = new List<RecurrencePattern> { recurrenceRule }
};
calendar.Events.Add(vEvent);

recurrenceRule = new RecurrencePattern("FREQ=DAILY;INTERVAL=4;WKST=SU");
vEvent = new CalendarEvent
{
    Start = new CalDateTime(DateTime.Parse("2018-10-01T07:00")),
    End = new CalDateTime(DateTime.Parse("2018-10-01T08:00")),
    Description = "Test2 event description yo!",
    Name = "Event Title 2",
    RecurrenceRules = new List<RecurrencePattern> { recurrenceRule }
};
calendar.Events.Add(vEvent);

var searchStart = DateTime.Parse("2018-10-01");
var searchEnd = DateTime.Parse("2018-10-31");
var occurrences = calendar.GetOccurrences(searchStart, searchEnd);

foreach (var item in occurrences)
{
    Console.WriteLine(item.ToString());
}

foreach (var item in calendar.Children)
{
    Console.WriteLine(item.Name);
    //result: Event Title 1, Event Title 2
    //Does not have access to even description, start, or end values.
}

Console.ReadLine();

A: Children returns a list of ICalendarObject.
If you want to retrieve the event details, you have to cast back to CalendarEvent:
foreach (ICalendarObject item in calendar.Children)
{
    Console.WriteLine(item.Name);

    if (item is CalendarEvent calendarEvent)
    {
        Console.WriteLine(calendarEvent.Description);
        Console.WriteLine(calendarEvent.Start);
        Console.WriteLine(calendarEvent.End);
    }
}

Output:

Event Title 2
  Test2 event description yo!
  01/10/2018 07:00:00
  01/10/2018 08:00:00

To get the source event from the occurrences, you can do this:
foreach (var item in occurrences)
{
    var sourceEvent = item.Source as CalendarEvent;
    Console.WriteLine(sourceEvent.Description);
    Console.WriteLine(sourceEvent.Start);
    Console.WriteLine(sourceEvent.End);
}


text:
Q: What is the difference between symbols? I checked that :xyz == 'xyz' is false. But we can call functions inside rails with :index or 'index'. Please clear my wonder.

A: :xyz and 'xyz' are indeed different. That does not contradict with the fact that a method can take either type of argument. For example, Array#* can take a String or Integer as an argument:
["a", "b"] * "foo" # => "afoob"
["a", "b"] * 2 # => ["a", "b", "a", "b"]

but that does not mean that "foo" is the same as 2.
And if you follow the logic you are implying, it would mean that all objects in Ruby are the same.

A:
I checked that :xyz == 'xyz' is false. But we can call functions inside rails with :index or 'index'. Please clear my wonder.

There is nothing mysterious about this.
Symbol#== is a method just like any other method. The person who wrote it, wrote it in such a way that it returns false. She could have written it to return true or return 42 or format your harddisk, but she decided to return false.
Rails methods are methods just like any other method. The person who wrote them, wrote them in such a way that accepts either Symbols or Strings. She could have written them to accept only Symbols or only Strings or to accept only Strings on even days of the week, only Strings on odd days of the week, and only Integers during a full moon, but she decided to accept both Strings and Symbols.
The developers who write Rails and the developers who write Ruby are free to do in their methods whatever they want, just like you are free to do whatever you want in methods you write. You can write a method that accepts Strings, you can write a method that accepts Symbols, you can write a method that accepts both, you can write a method that accepts neither. It's your choice, just like it is the choice of the Rails and Ruby developers.
It implies absolutely nothing about the relationship between Symbols and Strings.

A: My guess is that you've come across Rails' use of HashWithIndifferentAccess. This allows you to access a Hash using either a Symbol or a String.
In other words, params[:a] is the same as params["a"] because internally, HashWithIndifferentAccess converts all the keys to strings.
See the documentation for more information.

A: :xyz is a symbol. A symbol is an instance of the class Symbol.
"xyz" is a string. A string is not a Symbol.
Therefore, :xyz=='xyz' is not true. Because the instance of Symbol that is :xyz is not equivalent to the instance of String xyz.


text:
Q: Access denied mysql I'm having this strange error, spent the last hour on this and I'm still not sure to understand.
Yersterday, I could connect to mysql without any problem may that be from a remote source or locally.
Today, using mysqlworkbench, the tcp/ip works where as yersterday both standard tcp/ip and tcp/ip over ssh was working.
When I'm logged through ssh

*

*mysql -u user -p -h localhost works

*mysql -u user -p -h mydomain.com works

*mysql -u user -p -h mydomain.com(actual ip) works

*mysql -u user -p -h 127.0.0.1 do not work

mysql user config: 'user'@'%'
my.cnf config: bind-adress: mydomain.com (the actual ip)
 #/etc/hosts
 127.0.0.1       localhost
 127.0.1.1       ubuntu

Also, interesting enough, even If I input localhost as MYSQL hostname for mysqlworkbench, the connection still can't be made.
EDIT 1:
I added user@127.0.0.1 to user,host and the connection at 127.0.0.1 still can't be made.
EDIT 2:
Commenting #bind-address: mydomain.com (the actual ip) fixed the problem but this seems like a lazy fix, I would like to keep my IP for the actual address.


text:
Q: Why isn't Ohm's law working for this simple circuit? I have a 70W 12V-500V DC power converter, and something in these pictures is not adding up.
I run the 500V output through a high-voltage 332kΩ resistor.
Now, using the left multimeter I monitor the current through the circuit, and it runs up around 320mA.  Using the right multimeter I first check the voltage on the power supply leads: 511V.  (So right away we know something's off -- the supply isn't even getting warm after a few minutes of testing.)

Then I use the right multimeter to check the voltage across the resistor: 12V!

I verified the resistor's value with both meters.  If all of this is true then Ohm's law suggests that either the voltage across the resistor should be .320mA * 332kΩ = 106kV, or else the current through the circuit should be 511V / 332kΩ = 1.5mA.
(Of course the right multimeter itself is providing a path for current, but its resistance should be very high.  Indeed: when I remove the right multimeter from the circuit the current increases only 2-3mA.)
My best guess is that the output of the converter is not very smooth DC, or has some characteristic that is causing these multimeters to produce erroneous values.  If so, what characteristic might that be, and how can I adjust for it?
BTW, here's a close-up of the DC converter.  Maybe the design will be familiar to someone.

And in case the wiring isn't clear from the photos, here's how it was connected

simulate this circuit – Schematic created using CircuitLab
And here's some more information.  First, to remove all doubt, here's the resistor being measured after all this, so it does not appear to have fried.
And here is the whole shebang.  If the ammeter on the DC supply can be trusted, and this power converter doesn't have the ability to produce power out of thin air, then the true circuit current is under 3.6mA.  (This is consistent with the fact that I have observed no heat buildup on any component whatsoever.)  In which case the question is: Why is the Extech reading ~320mA?  If I switch the Extech to µA scale it reads around 3180 (still not right).  The other multimeter reads 0A at all scales, which is consistent with the voltage drop seen across the resistor (which implies 36µA true current).

Epilogue: I opened the Extech multimeter to find its 250mA fuse blown.  Replacing that made it behave normally.  Evidently it just has a very confusing failure mode!

A: Can't see much on your photo. But one thing is certain: Ohm's law is tough, but just. You haven't connected something right.

A: At a guess, your 332k resistor is about a 37 ohm resistor. The power supply has gone into current limit. Your nominal current (500 volts, 70 watts) is about 140 mA, so your real current is about twice this, which seems credible. Start by running your supply with no load and verifying that it will put out 500 volts no load. Then measure the resistance of your resistor. If both of those tests are OK, in the words of Gregory Kornblum,

You haven't connected something right

and looking at your tangle of wires I'm not surprised.

A: Based on your voltage measurement, it looks like your resistor is about 38 ohms, not 332,000 ohms. The current limit on your ExTech multimeter is 200 mA according to the datasheet. The meter is showing about 60% over that limit. My guess is that you either partially blew a fuse or triggered some internal current limiting circuit, so most of the voltage is being dropped across the current meter. Alternately, if the resistor actually was 336k, it might have burned out and failed short after dissipating 0.75W. You'd probably have noticed a smell if that were the case, though.


text:
Q: Android opengl-es collision detection This has been giving me a headache for a couple of days so I have finally accepted defeat and am going to ask here.
My game consists of cubes of varying sizes which have to be moved around in a small area. I have the cube movement working perfectly, the only thing I can't seem to get my head around is collision detection.
The ground is completely flat so I don't need to worry about the Y-Axis, the coordinates of the cube are relative to the centre of the cube at ground level. I should probably also add that each level is made up of multiple rectangular ground planes which are positioned adjacent to each other.
Any suggestions as to how this could be done (pseudo code is fine) with minimal cpu usage are welcome. Thanks very much.

A: Collision detection is very simple with things like cubes or spheres.
you can use either sphere to sphere detection which is basically drawing an imaginary sphere around the cubes and then checking if distance between the two centre points of the spheres is less than the sphere radius. like so:-
float x, y, z;
x = SmallModel->GetX() - LargeModel->GetX();
y = SmallModel->GetY() - LargeModel->GetY();
z = SmallModel->GetZ() - LargeModel->GetZ();

float collisionDist = sqrt( x*x + y*y + z*z );

if (collisionDist < sphereRadius)
{
    // Collision occurred…
}

or you can use bounding boxes which is more suited here as the above is not as accurate where as bounding boxes will be exact since you are using cubes and they are axis aligned.
The process here is also fairly simple: there is a collision if the min and max of each cube lies within each other. I.e. collision if:
Cube1XMin > Cube2XMin && Cube1XMax < Cube2XMax &&
Cube1YMin > Cube2YMin && Cube1YMax < Cube2YMax &&
Cube1ZMin > Cube2ZMin && Cube1ZMax < Cube2ZMax

so you will need to declare 6 variables for each cube as above and these min and max values are found by first knowing the size of the cube and secondly knowing the position of the cubes.
So if a cube is 10 * 10 * 10 and positioned at 100,0,100
then
     xmin = 95
     ymin = -5
     zmin = 95
     xmax = 105
     ymax = 5
     zmax = 105
find the values for the other cubes and run the above equation and you should find out if you have a collision.
For handling a collision you need to move the cubes back to the frame before and then maybe have them bounce back, i think it is possible to get stuck inside each other if you do not move them back by a frame first.
To save on CPU usage you can probably send the calculations to the GPU using shaders but thats a different topic


text:
Q: Give an example of a surjective function $f : P(\mathbb R \times \mathbb R) \to \mathbb Q$, or prove that none exists. The question is the same like above. How to know if there is a surjection from a power set of $\mathbb Z$ to set $\mathbb Q$.

A: Map one-element subsets $\{(p,q)\}\subseteq\mathbb Z\times\mathbb Z$ having $q>0$ into $p/q\in\mathbb Q$. This already covers all rational numbers.
Map all the other subsets (including those one-element sets $\{(p,q)\}\subseteq\mathbb Z\times\mathbb Z$ where $q\le 0$) wherever you want, e.g. into $0$.


text:
Q: git push request from branch to master I am new to GIT and GITHUB and was doing some hands-on and bit curious whats the best practices when working in the branch.
I did the following :

*

*Created a branch (lets say branch9).

*Added a new file, then git add , git commit.

*I didn't merge it with master "git merge master"

*Instead I used this cmd "git push origin master" (so pushing the contents directly to master instead of pushing it to branch9)

*I see some weird things. I created a pull request from GITHUB and merged the files to master but after few mins the merge disappears.

What is the correct sequence of steps I need to do while working on branching in GIT?
Do I need to merge the contents from branch9 to master in local repo (git merge master) and then git push origin master?

A: If you create a branch, you are supposed to push that branch:
git checkout -b branch9
# git add + commits
git push -u origin branch9

# some more commits
git push

Note the second push does not specify origin anymore: see "Why do I need to explicitly push a new branch?".
Then you can create a pull request from branch9 to master if you want, or if you are the only one working on the repo, you can merge locally your branch9 to master.
If there were no commits on master, that merge would be a fast-forward one, which explains why the merge disappear: master simply update itself to reflect branch9 HEAD.


text:
Q: How to download an Adobe connect recorded meeting when not the host? How to download an  Adobe connect recorded meeting when not the host?

I know that as the host, I could download a Adobe connect recorded meeting follows: go to https://my.adobeconnect.com > Meetings > select your meeting > Recording > Select your recording > Actions > Make Offline.


text:
Q: POST contact form 7 in addeventlistener wordpress I'm new in javascript and I'm trying to post my contact form 7 data to my another page using addeventlisterner it's working in my console but once I add my ajax it'not... Can someone check my codes if what is wrong? Thanks
Here's my code with working console
    document.addEventListener( 'wpcf7mailsent', function( event ) {

    var inputs = event.detail.inputs;

    if ( '1286' == event.detail.contactFormId ) {

        var fullname = document.getElementById('very-special-field').value;
        var msisdn = document.getElementById('mobile-number').value;
        var username = document.getElementById('username').value;
        var email = document.getElementById('email').value;
        var company = document.getElementById('company').value;
        var account_type_id = document.getElementById('account_type_id').value;

        form_data = {
            fullname,
            msisdn,
            username,
            email,
            company,
            account_type_id

        }

        alert('hi');

        console.log(form_data);

    }

`}, false );

BUT if i add my ajax it's not working
document.addEventListener( 'wpcf7mailsent', function( event ) {

    var inputs = event.detail.inputs;

    if ( '1286' == event.detail.contactFormId ) {

        var fullname = document.getElementById('very-special-field').value;
        var msisdn = document.getElementById('mobile-number').value;
        var username = document.getElementById('username').value;
        var email = document.getElementById('email').value;
        var company = document.getElementById('company').value;
        var account_type_id = document.getElementById('account_type_id').value;

        form_data = {
            fullname,
            msisdn,
            username,
            email,
            company,
            account_type_id

        }
        $.ajax({
          type: "POST",
          url: http://myurl.com,
          data: JSON.stringify(form_data),
          success: success,
         dataType: 'json'
        });

        alert('hi');

        console.log(form_data);

    }

}, false );

Can someone help me? :( Am I doing this right?

A: try this script
    document.addEventListener( 'wpcf7mailsent', function( event ) {

        var inputs = event.detail.inputs;

        if ( '1286' == event.detail.contactFormId ) {

            var fullname = document.getElementById('very-special-field').value;
            var msisdn = document.getElementById('mobile-number').value;
            var username = document.getElementById('username').value;
            var email = document.getElementById('email').value;
            var company = document.getElementById('company').value;
            var account_type_id = document.getElementById('account_type_id').value;

            form_data = {
                fullname,
                msisdn,
                username,
                email,
                company,
                account_type_id

            };

            jQuery.ajax({
              type: "POST",
              url: 'http://myurl.com',
              data: JSON.stringify(form_data),
              success: function(data) {
                console.log(data);
              },
              error: function(data) {
                console.log(data);
              },
             dataType: 'json'
            });
            alert('hi');
            console.log(form_data);
        }

    }, false );


text:
Q: Calling Scala Method from C++ does anyone know if there is possibility to call a scala method from C++?
The reason I do this is I have a robust and powerful C++ back end, which could receives data and lambdas from scala front end. And I want to process these data using scala lambdas in the back end.
To be honest, the first thing came to my mind is JNI, which enables us to call java methods from C++ and vice versa. And I have tried whether I can use JNI to call scala method as well. The answer is NO. Take java/lang/String for example, I tried using JNI to get some methods from it. And only those java-specific methods can be got, like toString, concat, charAt, and those scala-specific methods are unavailable, including apply, toLong. The direct reason for this is that java reflection cannot capture scala-specific elements, see here.
And I have no other solutions for this. Any suggestions please?


text:
Q: Windows indexing search - OleDbException Not Specified Error I'm getting an exception (OleDBException: Not specified Error) when trying to search in indexed files in a folder on my D-drive (D:\TaalTipsDocumenten). I know this piece of code worked in the past (2 months ago), but when trying to continue working on that project, it doesn't seem to work anymore.
During execution of the following code, I get an error on the following line:
adapter.Fill(dt);

I can say that the Datatable (dt) is filled correctly, but I still get an error on that line. Also when trying to use a OleDbDataReader with .Next() function, it runs over the results and throws me the error eventually.
var query11 = @"SELECT  System.DateCreated,
                                System.ItemName,
                                System.ItemUrl,
                                System.Size,
                                System.Search.HitCount FROM SystemIndex " +
                                @"WHERE scope ='file:D:/TaalTipsDocumenten' AND CONTAINS('" + word + "') ";

FileOverviewModel returnModel = new FileOverviewModel();
returnModel.Files = new List<FileModel>();
returnModel.Search = word;

DataTable dt = new DataTable();

using (OleDbConnection connection = new OleDbConnection(@"Provider=Search.CollatorDSO;Extended Properties=""Application=Windows"""))
using (OleDbCommand command = new OleDbCommand(query11, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
    adapter.Fill(dt);
}

The error doesn't say much (Not specified):

System.Data.OleDb.OleDbException was unhandled by user code
  ErrorCode=-2147467259
  HResult=-2147467259
  Message=Not specified error
  Source=System.Data
  StackTrace:
       at System.Data.OleDb.OleDbDataReader.ProcessResults(OleDbHResult hr)
        at System.Data.OleDb.OleDbDataReader.GetRowHandles()
        at System.Data.OleDb.OleDbDataReader.ReadRowset()
        at System.Data.OleDb.OleDbDataReader.Read()
        at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)
        at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
        at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
        at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
        at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
        at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
        at TaalTips.Controllers.HomeController.Search(String word) in D:\Projects\TaalTips\TaalTips\Controllers\HomeController.cs:line 40
        at lambda_method(Closure , ControllerBase , Object[] )
        at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
        at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
        at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
        at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
        at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult)
        at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
        at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
        at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
        at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
   InnerException:

I tried some things already:

*

*Restart Windows Search Service

*Remove index from the folder and add it again

*Restart computer

*Make sure all connections are closed

*Create a different folder and try on that one (same error)

*Use OleDbDataReader and reader.Next(), but gives same error

Someone has any idea?
Thanks in advance !

A: This is not a answer but instead a suggestion.
I would try eliminating the DataAdapter, see if you get the same exception via DataTable.Load as per Test1 or perhaps as in Test2 trying to cycle through the results.
Neither are meant to be a solution but rather a way to see if the exception is caused perhaps by reading specific data, perhaps from excessive rows etc.
Note, in Test2 I did one column. I would try that or all columns allow the loop to run and see if a specific row throws an exception then from there see if a specific column value is the issue.
using System;
using System.Data;
using System.Data.OleDb;

namespace Demo
{
    class Class1
    {
        void Test1()
        {
            var word = "Place a hard code value here";
            var query11 = @"SELECT  System.DateCreated,
                                System.ItemName,
                                System.ItemUrl,
                                System.Size,
                                System.Search.HitCount FROM SystemIndex " +
                                            @"WHERE scope ='file:D:/TaalTipsDocumenten' AND CONTAINS('" + word + "') ";

            DataTable dt = new DataTable();

            using (OleDbConnection connection = new OleDbConnection(@"Provider=Search.CollatorDSO;Extended Properties=""Application=Windows"""))
            {
                using (OleDbCommand command = new OleDbCommand(query11, connection))
                {
                    connection.Open();
                    try
                    {
                        dt.Load(command.ExecuteReader());
                        Console.WriteLine(dt.Rows.Count);
                    }
                    catch (Exception)
                    {
                        // place break-pointhere

                    }

                }
            }
        }
        void Test2()
        {
            var word = "Place a hard code value here";
            var query11 = @"SELECT  System.DateCreated,
                                System.ItemName,
                                System.ItemUrl,
                                System.Size,
                                System.Search.HitCount FROM SystemIndex " +
                                            @"WHERE scope ='file:D:/TaalTipsDocumenten' AND CONTAINS('" + word + "') ";

            using (OleDbConnection connection = new OleDbConnection(@"Provider=Search.CollatorDSO;Extended Properties=""Application=Windows"""))
            {
                using (OleDbCommand command = new OleDbCommand(query11, connection))
                {
                    connection.Open();
                    try
                    {
                        var reader = command.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine($"Date: {reader.GetDateTime(0)}");
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // place break-pointhere

                    }

                }
            }
        }
    }
}


text:
Q: Margin or Padding CSS to Add Space between Two Objects Good Afternoon Everyone,
Ok so Im using Joomla and I've added some Custom Text to a Component. The Top of the Test has a Margin which seems to work in adding some space, the Bottom of text also has Margin BUT no space is added between it and the next object.
Custom Class for the Custom Text
#albumstats {
    width: 100%;
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 5px;
    padding-bottom: 30px;
}

Link To Page ---> http://macthedj.com/mixtapes/K/2-kodak-black/8-lil-b-i-g-pac.html
If anyone can provide an explanation on how to achieve this goal of adding space at the bottom of the Text, that would be greatly appreciated.

A: You should add

 at end of #albumstats, Because this children has float: left, elements that have float don't detect by their parent

After add this, the margin and padding will be apply

A: Use float: left; on #albumstats, like:
#albumstats {
  float: left;
}

Hope this helps!


text:
Q: error after farm solution deployed after i deploy a farm solution to sharepoint 2010 web application i saw below error some times in browser what it is and how to solve this error,

CS0042: Unexpected error creating debug information file
  'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET
  Files\root\bf3fce1a\adf83866 \App_GlobalResources.PDB' --
'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET
  Files\root\bf3fce1a\adf83866\App_GlobalResources.pdb:  The process
  cannot access the file because it is being used by another process

here after i redeploy i got below error in visual studio

Error occurred in deployment step 'Activate Features': Feature with Id
  '2227c19c-e944-438a-b769-e58d48181de8' is not installed in this farm,


text:
Q: Spree of divisare.com spam A spam campaign to promote content hosted on divisare.com is currently under way.  As of right now, there are 11 posts over 48 hours in the Metasmoke archive for spam posted on SE:
https://metasmoke.erwaysoftware.com/search?body=divisare.com
The spree started on Ask Ubuntu on Saturday, then moved to Math Overflow a few hours ago, and is now most recently hitting Super User and Server Fault.
(I note that all of these are sites which are not subdomains under the stackexchange.com domain umbrella, though they are all members of the Stack Exchange network.)
The divisare.com site looks like it allows new users to upload random content (it's supposed to be about architecture, but the spam posts are unrelated to this topic), so I'm guessing what happened here is that spammers discovered this and are going unnoticed by the site's management (or maybe they noticed, but are not yet getting their shields up properly).
I'm creating this meta post mainly to have something to link to when sending a complaint to divisare.com, but to keep this nominally as a question, can somebody confirm or correct my observations so far?

A: Sent the following to the address in their "contact us" dropdown.

I'm contacting you to alert you to a spam campaign which involves your
  site.
I have posted some details here:
https://meta.stackexchange.com/questions/299387/spree-of-divisare-com-spam
Briefly, it looks like the spammer is abusing your site to host their
  spam content, and posting spam messages linking to that content on
  Stack Exchange sites (basically forum spam or blog spam, though Stack
  likes to think of itself as "not a forum" and definitely isn't a
  blog).
Victims of similar attacks in the past have temporarily disabled new
  uploads by users who do not have a previous history on the site until
  the spammers go away,  though how exactly to cope obviously depends on
  your site and its community.
Thanks in advance for your expedient attention to this matter,
--
  tripleee
  just a regular user on Stack Exchange who decided to complain


text:
Q: Wordpress loading a .txt file and encoding as UTF-8 is not working correctly I'm loading a txt file and try to display the content in the right format.
With a clean php file it is working correctly but I'm not able to do it inside of wordpress functions.php.
Source from the txt file:
#Neue und moderne Wohnung N�he Bahnhof#
First I did a test with a clean php file.
<?php
$data_immo = file_get_contents('data/unload.txt');
$objects = explode('IDX3.01#GARAIO REM#', $data_immo);
$output = array_shift($objects); // hidden the first <li>-element

echo '{';
foreach ($objects as $item) {

        $data_details = preg_split ("/\#/", $item);

        $object_title = utf8_encode($data_details[14]);
        $object_title = html_entity_decode($object_title);
        var_dump($object_title)
}
echo '},';

Output is correct:
index.php:18:string 'Neue und moderne Wohnung Nähe Bahnhof' (length=38)
After that I did the same in Wordpress (functions.php)
Head looks like that:
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {{ function('wp_head') }}
</head>

But my dump of the $object_title is wrong:
/api_test/web/app/themes/timber/functions.php:175:string 'Neue und moderne Wohnung N�he Bahnhof' (length=42)
So why is Wordpress not able to encode my txt file correctly.
Any help would be great.
Cheers


text:
Q: Removing levels from data frame read from CSV file - R I tried loading the baseball statistics from this link. When I read it from the file using
data <- read.csv("MLB2011.csv")

it seems to be reading all fields as factor values. I tried dropping those factor values by doing:
read.csv("MLB2011.xls", as.is= FALSE)

.. but it looks like the values are still being read as factors. What can I do to have them loaded as simple character values and not factors?

A: You aren't reading a csv file, it is an excel spreadsheet (.xls format). It contains two worksheets bat2011 and pitch2011
You could use the XLConnect library to read this
library(XLConnect)
# load the work book (connect to the file)
wb <- loadWorkbook("MLB2011.xls")

# read in the data from the bat2011 sheet
bat2011 <- readWorksheet(wb, sheet = 'bat2011')

readWorksheet has an argument colType which you could use to specify the column types.

Edit
If you have already saved the sheets as csv files then
as.is = TRUE or stringsAsFactors = FALSE will be the correct argument values


text:
Q: Do these word mean the same thing? I've tried google but found nothing on this topic and my final option was stack overflow.
Does Valid attribute names, Valid attribute reference and Attribute reference mean the same thing?

A: Yes, probably putting "valid" as a prefix is just a way to affirmate that you have to create an attribute reference that makes sense or just to follow good habits.
There goes a post to good habits when creating variables/references:
https://towardsdatascience.com/data-scientists-your-variable-names-are-awful-heres-how-to-fix-them-89053d2855be


text:
Q: Using materialize how do i center a tabs in nav-content https://i.imgur.com/JBI7id0.png
So basically i am having an issue. I have no problem in moving any of the tabs to the right or left side. But when i try to center all the tabs i'm having no luck.
So in the image above i am trying to get TEST 1, TEST 2, DISABLED TAB AND TEST 4 to be centered on the page.
I am using the Extended Navbar with Tabs example on their website.

      Logo
      menu

Sass

Components

JavaScript

Test 1

Test 2

Disabled Tab

Test 4

  ```

A: You can use display flex on tabs-transparent class, justify-content: center will position them horizontally and as extra align-items: center will position them vertically.

.tabs-transparent {
display:flex;
align-items: center;
justify-content: center;
}
<div class="nav-wrapper">
      <a href="#" class="brand-logo">Logo</a>
      <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a>
      <ul id="nav-mobile" class="right hide-on-med-and-down">
        <li><a href="sass.html">Sass</a></li>
        <li><a href="badges.html">Components</a></li>
        <li><a href="collapsible.html">JavaScript</a></li>
      </ul>
    </div>
    <div class="nav-content">
      <ul class="tabs tabs-transparent">
        <li class="tab"><a href="#test1">Test 1</a></li>
        <li class="tab"><a class="active" href="#test2">Test 2</a></li>
        <li class="tab disabled"><a href="#test3">Disabled Tab</a></li>
        <li class="tab"><a href="#test4">Test 4</a></li>
      </ul>
    </div>
  </nav>```


text:
Q: How to aggregate minute-based data to weekly data I've got data like this:
        Date     Time Global_active_power
1 16/12/2006 17:24:00               4.216
2 16/12/2006 17:25:00               5.360
3 16/12/2006 17:26:00               5.374
4 16/12/2006 17:27:00               5.388
5 16/12/2006 17:28:00               3.666
6 16/12/2006 17:29:00               3.520

Since I need to conduct a time-series analysis, I may need to aggregate these minutes-based data to daily-based, weekly-based, monthly-based, or quarter-based data. However, I've tried to use to following code to get monthly- and quarter-based data (based on function as.yearmon and as.yearqtr):
agg_Month <-aggregate(tmp_hPower,by=list(as.yearmon(tmp_hPower$Date,'%d/%m/%Y')),
FUN = mean, na.rm = TRUE )

It seems that there is no function like as.yearweek, so how can I obtain daily-based, weekly-based data, and even hour-based data?

A: This is fairly simple if you convert your data.frame to an xts object.
# original data
tmp_hPower <- read.table(text="        Date     Time Global_active_power
1 16/12/2006 17:24:00               4.216
2 16/12/2006 17:25:00               5.360
3 16/12/2006 17:26:00               5.374
4 16/12/2006 17:27:00               5.388
5 16/12/2006 17:28:00               3.666
6 16/12/2006 17:29:00               3.520")
# xts object from original data
library(xts)
x <- with(tmp_hPower, xts(Global_active_power,
  as.POSIXct(paste(Date,Time), format="%d/%m/%Y %H:%M:%S")))
# use period.apply and endpoints to aggregate to any frequency
period.apply(x, endpoints(x, "hours"), mean)  # hourly
period.apply(x, endpoints(x, "days"), mean)   # daily
period.apply(x, endpoints(x, "weeks"), mean)  # weekly

A: Here's an option using the dplyr package:
library(dplyr)
library(lubridate)
library(zoo)

# Fake data
set.seed(4999)
dat = data.frame(time=seq(as.POSIXct("2015-01-01"),
                          as.POSIXct("2016-12-31"), length.out=1000),
                 value=rnorm(1000))

You can add time groups that will allow you to summarize by week, month, etc.
dat = dat %>%
  mutate(year_day = paste0(year(time),'-', yday(time)),
         year_week = paste0(year(time),"-",strftime(time,"%W")),
         year_mon = as.yearmon(time),
         year_qtr = as.yearqtr(time))

Now, summarise by week. You can summarize by day, month, etc., in a similar way.
dat.by.week = dat %>%
  group_by(year_week) %>%
  summarise(value=mean(value))

Also, you don't actually have to add the time groups to your original data. You can just do the whole thing on the fly. For example:
dat.by.week = dat %>%
  mutate(year_week = paste0(year(time),"-",strftime(time,"%W"))) %>%
  group_by(year_week) %>%
  summarise(value=mean(value))


text:
Q: Collections Counter - How to remove "counter" from output The output is:
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Can I remove the "Counter" word?
from collections import Counter

word = "hello"

print(Counter(word))

A: To convert a Counter back into a normal dictionary, just do this:
d = dict(Counter(word))

Now it'll look as usual when you print it:
print(d)

It really doesn't make any difference, though. Counter is a dictionary after all. I guess it's ok if you want it to look pretty when printing it.

A: Of course, you can pass the object to json.dumps. json only sees the dictionary, not the subclass
from collections import Counter
import json

word = "hello"
c = Counter(word)

print(json.dumps(c))

result:
{"l": 2, "o": 1, "h": 1, "e": 1}

that avoids to create a copy as a basic dictionary just to display it properly.
More ways to print the contents using just loops on key/values and prints: Formatting output of Counter
Another way is to force basic dict representation method:
print(dict.__repr__(Counter(word)))

result:
{'h': 1, 'o': 1, 'e': 1, 'l': 2}

A: You can remove the string 'Counter()' with the function strip():
c = Counter('AA')

print(repr(c).strip('Counter()'))
# {'A': 2}

or
print(c.__repr__().strip('Counter()'))
# {'A': 2}

Alternatively you can use string slicing. It should be more efficient (according to @jonrsharpe):
print(c.__repr__()[8:-1]))
# {'A': 2}


text:
Q: Using controls in a LongListSelector I'm using a LongListSelector to display a list of complex objects and update the datatemplate (a control) depending on the number of items in the bound objects list property.
I have tried the following.

*

*Accessing the data in the OnItemRealized event to try and get the bound control and update it via a method call.
Not sure if possible

*Adding a property to the control being bound which adds controls to a wrap panel when the property is set.
The set accessor in the controls property is never hit.
Hopefully it's clear what im trying to achieve.

*

*Is it possible to call functionality in a property being bound to as shown in my control

*If not is it possible to access the control being bound and call exposed functionality that way

If anyone could shed any light on my issue i would greatly appreciate it!
Data Template
<DataTemplate x:Key="LLS_SomeTemplate" >
            <MyApp:ObjectTemplate SomeObjects="{Binding SomeEntities}"/>
</DataTemplate>

Object being bound
public class SomeObject
{
    public ObservableCollection<Entities> _SomeEntities { get; set; }
    public ObservableCollection<Entities> SomeEntities
    {
        get
        {
            if (_SomeEntities == null)
                _SomeEntities = new ObservableCollection<Entities>();

            return _SomeEntities;
        }
        set
        {
            _SomeEntities = value;
        }
    }

    public SomeObject()
    {
    }
}

Control Property
public static DependencyProperty SomeObjectsProperty = DependencyProperty.Register("SomeObjects", typeof(ObservableCollection<Entities>), typeof(ObjectTemplate), new PropertyMetadata(new ObservableCollection<Entities>()));

public ObservableCollection<SomeObject> SomeObjects

    {
    get
    {
        return (ObservableCollection<SomeObject>)GetValue(SomeObjectsProperty);
    }
    set
    {
        SetValue(SomeObjectsProperty, value);

        if (value != null && value.Count > 0)
        {
            foreach (SomeObject eLink in value)
            {
                //Add a new control to a wrap panel for each object in the list
            }
        }
    }
    }

A: There are few ways how CLR set up dependency properties. You must avoid perform operations in setter. Create value changed event handler instead:
public static DependencyProperty SomeObjectsProperty = DependencyProperty.Register("SomeObjects", typeof(ObservableCollection<Entities>), typeof(ObjectTemplate), new PropertyMetadata(new ObservableCollection<Entities>(), new PropertyChangedCallback(OnSomeObjectsPropertyChanged));

private static void OnSomeObjectsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    (d as ObjectTemplate).UpdateSomeObjects(e.NewValue as SomeObjects);
}

public void UpdateSomeObjects(SomeObjects value)
{
    if (value != null && value.Count > 0)
    {
        foreach (SomeObject eLink in value)
        {
            //Add a new control to a wrap panel for each object in the list
        }
    }
}

Hope it helps you to solve your problem


text:
Q: How to use Valo fonts in custom theme The new Valo theme in Vaadin 7.3 and later comes bundled with some fonts:

*

*Lato

*Lora

*Open Sans

*Roboto

*Source Sans Pro
I'm struggling with adding these Valo fonts into my custom theme.
This is what I have but it doesn't seem to work.
styles.scss
$v-font-family: 'Lato', sans-serif, 'Open Sans';

@import "../valo/valo";

.myTheme {

@include valo;

@import "myRules";

}

This is what I get in the console:
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) http://name/name/VAADIN/themes/myTheme/Lato-regular-webfont.woff
It should point to http://name/name/VAADIN/themes/valo/Lato-regular-webfont.woff
I guess I forgot about something but I've searched and it's not mentioned in the Book of Vaadin.

A: The problem is resolved, I was missing this:
$v-relative-paths: false;

source: http://vaadin.com/download/book-of-vaadin/current-br/html/themes.valo.html

Theme Compilation and Optimization
$v-relative-paths (default: false) This flags specifies whether
  relative URL paths are relative to the currently parsed SCSS file or
  to the compilation root file, so that paths are correct for different
  resources. Vaadin theme compiler parses URL paths differently from the
  regular Sass compiler (Vaadin modifies relative URL paths). Use false
  for Ruby compiler and true for Vaadin compiler.


text:
Q: Interpreting equation of a plane I have encountered a question on multiple integrals in which the equation $x=2y$ is referred to as a vertical plane. How can we interpret the equation $x=2y$ as the equation of a plane? How will it look like?

A: Imagine a 3D axes with any point being define by the function x = 2y. Any point is given by (x,y,z). Using some 3D graphing software could show you how it will look.

A: $x-2y+0z=0$
http://www.wolframalpha.com/input/?i=plane+x%3D2y
$\vec{n}=\{1,-2,0\}$


text:
Q: Merge two commits in remote repository Repository of one rather small project occupies >200 megabytes. Here is how the history looks like:
...
1) regular commit
2) regular commit
3) commit which adds 100mb of useless files + does something useful
4) regular commit
5) commit which removes all of the useless files
6) regular commit
...

I want to reduce the size of the repository. Also the useful changes of commit 3 shouldn't be lost. Is there a way to combine commits 3 and 5 into one in the remote repository?

A: You can use interactive rebase with the command:
git rebase -i

and write a rebase plan similar to this:

*

*pick commit 1

*pick commit 2

*pick commit 3

*squash commit 5

*pick commit 4

*pick commit 6

*....

After the sucessfull rebase you can force-push the modified branch:
git push -f

Be aware that rewriting a part of the history that has already been pushed may force other users to perform a rebase on the new history and to deal with the possible conflicts.


text:
Q: Android Phonegap Get Locale I'm trying to get locslization details of the phone. But it returns an error. Following is the code I hae used, which is the sample of PhoneGap API document (http://docs.phonegap.com/en/2.2.0/cordova_globalization_globalization.md.html).
 function checkLocale() {
  navigator.globalization.getLocaleName(
    function (locale) {alert('locale: ' + locale.value + '\n');},
    function () {alert('Error getting locale\n');}
  );
}

Your help on this would be greatly appreciated.
Thanks.

A: I read documentation of your link, and it says that it's needed to give permissions in android:
Permissions
Android
In app/res/xml/config.xml
<plugin name="Globalization" value="org.apache.cordova.Globalization" />

Hope that it helps you.
Regards, Daniel

A: I solved it adding permission in phonegap config.xml.
    <access origin="*"/> <!-- allow all pages -->
    <!--
        <access origin="http://phonegap.com" />                    - allow any secure requests to http://phonegap.com/
        <access origin="http://phonegap.com" subdomains="true" />  - same as above, but including subdomains, such as http://build.phonegap.com/
        <access origin="http://phonegap.com" browserOnly="true" /> - only allows http://phonegap.com to be opened by the child browser.
    -->

    <!-- Globalization plugin configuration-->
    <feature name="Globalization">
        <param name="android-package" value="org.apache.cordova.globalization.Globalization" />
    </feature>
</widget>


text:
Q: How to get the path of an embebbed resource? I included an embebbed resource in my C# project; I know its name and how to refer to it, so I was wondering if there is any way to get its absolute path...is there?

A: Embedded resource is exactly that: embedded. It means, that it's included in the assembly and does not exist as a physical file after compilation (if that's what you're looking for).

A: Like others have said, an embedded resource is embedded within the compiled assembly and does not exist on the file system; if you're looking to have the file on the file system you should change the build action to 'None' and the Copy to Output Directory to one of the copy values.
If however you do mean to embed the resource then it can be accessed by using the GetManifestResourceStream method of the Assembly class as follows:
GetType().Assembly.GetManifestResourceStream("someresourcestringhere")

(The above code assumes you are accessing the resource from a class within the same assembly).
The embedded resource normally follows the following format and this is the string you would pass in to the GetManifestResourceStream method:
default project namespace.folder name (if any).file name
Any spaces in folder names are replaced with an underscore, any spaces in file names are preserved.
Personally I have found the easiest way to get this string is to use a decompiler tool (such as Telerik's Just Decompile) to have a look inside the assembly and get the full resource name for the file you're looking for.

A: System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();


text:
Q: Is there a WINE version of Flash as a plugin to Firefox or Chrome? I've seen complaints about flash performance. Would it be possible to use WINE as a plugin to firefox in order to get better performance out of flash? (Hopefully WINE would utilize some sort of hardware optimizations) Would using WINE even give better performance?

A: No.
At best you could get this to work by running the whole browser in wine but that would be sure to decrease performance not increase performance.
The best way to overcome poor flash performance is to download videos instead of streaming them using tools such as abby (also: clive, cclive, youtube-dl). All of these are available from the Ubuntu Software Centre.

A: The best performance change I've made for Flash is to install a flash blocking extension (e.g. Chrome, Opera (builtin at opera:config#UserPrefs|EnableOnDemandPlugin), Firefox).
When I have 150 or more tabs open (not so uncommon for me) – or even just 20 :) – this really helps, yet I can still click to run any Flash applet I must use.

A: It won't help. The main problem with flash is that it can't use xv output and Wine won't help you with that. Pulseaudio also seems to help with bad flash performance, so you could try a different sound server. I wasn't successful with that on Lucid tho.
For YouTube, Vimeo and Blip.tv you could use my FlashVideoReplacer extension, which replaces the embedded video with available mp4 in order to play it with other plugins. CPU usage is reduced a lot.
https://addons.mozilla.org/en-US/firefox/addon/161869/
Also see my tutorial on flash optimization for other alternatives:
http://firefox-tutorials.blogspot.com/2010/05/flash-optimization.html

A: Pipelight! It's running flash, shockwave, silverlight and unity player through wine http://fds-team.de/cms/pipelight-installation.html

A: Go for  "lovinglinux" tutorial , i tried FlashVideoReplacer extension and it worked like a charm . thank you "lovinglinux" =)

A: Lets just cross our fingers that html5 will be the standard soon! For now use Chrome, Opera or Firefox4 beta and activate html5 on youtube. Works pretty well...


text:
Q: Socket Server controller Android App, Socket error So basically I want to create some kind of controller for my pc, where on pc, runs java socket server. The server is working, I have tried it. Also, Port Forwarding in the router is allright.  Source code is here :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_GREEN = "\u001B[32m";
    public static final String ANSI_BOLD = "\033[1m";
    public static final String ANSI_RED = "\u001B[31m";

    public static void main(String[] args) throws IOException {

        // Creating server instance
        ServerSocket serverSocket = new ServerSocket(2000);
        Socket socket = serverSocket.accept();

        System.out.println(ANSI_GREEN + "Controller connected" + ANSI_RESET);

        // Input Output streams
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

        String command = "";

        do {

            command = dataInputStream.readUTF();

            switch (command.trim()){
                case "volume up":
                    Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\volup.bat");
                    break;
                case "volume down":
                    Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\voldown.bat");
                    break;
                default:
                    // Unknown command
                    break;
            }

        }while (!command.equals("stop"));

        socket.close();

        System.out.println(ANSI_RED + "Controller disconnected" + ANSI_RESET);

    }

}

And it is supposed to interact with the android app, but I got an error and I can't quite figure out why is that so, here is the source code for ActivityMain :
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    private boolean connected;
    private DataOutputStream dataOutputStream;
    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Pripájanie na server

        try {
            socket = new Socket("172.0.0.1",2000);
            dataOutputStream = new DataOutputStream(socket.getOutputStream());

        } catch (IOException e) {
            Toast.makeText(MainActivity.this, "Not Connected!",
                    Toast.LENGTH_LONG).show();
        }

        Button VolumeUp = (Button) findViewById(R.id.VolumeUpButton);
        VolumeUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    send("volume up");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button VolumeDown = (Button) findViewById(R.id.VolumeDownButton);
        VolumeDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    send("volume down");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button DisconnectButton = (Button) findViewById(R.id.DisconnectButton);
        DisconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    send("stop");

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public void send(String command) throws IOException {
        if (socket != null){
            dataOutputStream.writeUTF(command);
        }
        else Toast.makeText(MainActivity.this, "Socket is not defined",
                Toast.LENGTH_SHORT).show();
    }

    public void disconnect() throws IOException {
        if (socket != null){
            socket.close();
        }
        else Toast.makeText(MainActivity.this, "Socket is not defined",
                Toast.LENGTH_SHORT).show();
    }

}

So if you could help me with it, I would be thankful, <3

A: Well the reason for that was silly. When I'm loading data from Stream it says nextLine which means the ending point is \n so I could never get that line because I haven't put it there.


text:
Q: Why is Heroku telling me "Your app has no databases" when it clearly does? I know the subject of migrating Heroku databases has lots of documentation but I have yet to find my answer, and nobody seems to be mentioning the error I'm getting.
I developed my app using the basic/free version of Heroku, where I get my two random dictionary words and a number.  I've got a Rails app running in this instance, populated with data.  It's what I've used to demo to management.
My company now has paid space on Heroku, including Postgres.  I've gotten my application deployed to this new space, including an empty Postgres database (I've run migrations), and now I would like to move my data over from the free/shared space, to my paid space.
I believe this is the page of directions I'm supposed to be following:
https://devcenter.heroku.com/articles/migrating-from-shared-database-to-heroku-postgres
But when I get to this step:
heroku pgbackups:capture --expire -a [my_app]

I get the error in my question, "Your app has no databases."  I've done the necessary steps, added the pgbackups add-on and so forth.  If I execute this command against my newly created paid app (with the empty database), it works fine.  But running it for my old/free/shared-db version gets the error.
I get that it does not have a paid database, no.  If I go to http://postgres.heroku.com it doesn't even show up.  But I've got data living in a database somewhere in Heroku world, and I'd like to get at it.  The documentation does lead me to believe that these are the instructions for getting off the 5mb shared space, which is what I'm on.

A: I didn't take into account some corner cases on an update I wrote for the client. A later version fixed it as I think you figured out. Sorry.


text:
Q: How to add submenu dynamically in mfc I have added a menu in my windows program using resource editor now I want to add a submenu under some specific condition.
Below is piece of my code.
This is my Menu.h file
include
class CmainWn : public CFrameWnd
{
public :CmainWn();
DECLARE_MESSAGE_MAP()
afx_msg void OnAB();
};
class CApp : public CWinApp
{
public : BOOL InitInstance();
};
This is my Menu.cpp
include"Menu.h"
include"resource.h"
CmainWn ::CmainWn()
{
Create(NULL,"Menu Testing",WS_OVERLAPPEDWINDOW,rectDefault,NULL,(LPCTSTR)IDR_MENU1);

}
BOOL CApp :: InitInstance()
{
m_pMainWnd=new CmainWn();

m_pMainWnd->ShowWindow(m_nCmdShow);

m_pMainWnd->UpdateWindow();

return true;

}
void CmainWn::OnAB()
{
AfxMessageBox("Hello");

}
BEGIN_MESSAGE_MAP(CmainWn,CFrameWnd)
ON_COMMAND(ID_A_B, &CmainWn::OnAB)

END_MESSAGE_MAP()
CApp App;
As you can see the code I have created main menu named A and one submenu named B.
I want to add one menu dynamically under B. How to do it ?

A: Sample code that has to be added to your windows resource file (projectname.rc)
IDR_MENU1 MENU
BEGIN
      POPUP "Main menu"
       BEGIN
           MENUITEM "Menu Item 1", ID_WINDOWS_TEST
           POPUP "Sub Menu"
        BEGIN
            MENUITEM "Sub Menu item 1",ID_WIN_TEXT
        END
    END
END

Viewing this in resource view would display something like this


text:
Q: how to find an upper bound of the spectral radius I've given the real valued matrix $K=K_1+K_2$, with $K_1$ and $K_2$ symmentric and positiv defined.
Further there are given this 3 matrices:

with $\omega > 0$ and

Now I tried the whole day to show this:

and this:

Could somebody help me ???
My idea was the following:
In every bracket of the matrix $M$ there is a symmetric positiv defined matrix. Hence we know    $A*B=(B*A)^t$ (here the small t means transposed).
With this in mind I tried to change the order of the brackets in M and the to use the triangle inequality to get the claim, but I didn't reached it.
I would be very happy if someone has a better idea

A: Hints. Here are a few useful facts ($X,Y$ below denote complex square matrices):

*

*$\rho(XY)=\rho(YX)$. This follows from a well-known fact that $XY$ and $YX$ have identical characteristic polynomials. (See also q311342.)

*Normal (including Hermitian) matrices are unitarily diagonalisable. I think this is taught in virtually every introductory course on linear algebra.

*When both $X,Y$ are normal, their spectral radii coincide with their induced 2-norms and hence $\rho(XY)\le\|XY\|_2\le\|X\|_2\|Y\|_2=\rho(X)\rho(Y)$.

*For any scalars $\alpha$ and $\beta$, the matrices $\alpha I+X$ and $(\beta I+X)^{-1}$ commute (provided that the latter inverse exists). This is a consequence of Cayley-Hamilton theorem when applied to the matrix $\beta I+X$.


text:
Q: My JavaScript code does not show the expected results I am trying to print objects from an API using JSON and AJAX and it works when I use console.log to view it. But my generateCreatureDiv function does not work for some reasons.
This is my code:

$(document).ready(function() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = this.responseText;
      var creatureData = JSON.parse(response);
      console.log(creatureData);

      // get a creature from the data

      for (var i = 0; i < creatureData.creatures.length; i++) {
        var creature = creatureData.creatures;
        console.log(creature[i]);
        document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]);
      }

      function generateCreatureDiv(creature) {
        var CreatureDiv = $("
");
        console.log("hoe");
        CreatureDiv.id = "CreatureInfo";
        console.log("hoe")
        $("CreatureDiv").append("
" + creature.name + "
");
        console.log("hoe");
        $("CreatureDiv").append("" + creature.image + "");
        return CreatureDiv;
        console.log("hoe");

      }

      // create a select option  for the object
      // Have a

    }

  };

  xhttp.open("GET", "https://api.myjson.com/bins/17f3jl", true);
  xhttp.send();

});
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

      <select id="SelectOption">

      </select>

A: remove the " quotes in $("CreatureDiv")  .Its not select with any ID or Class.And on your code  Already declare with var CreatureDiv = $("
"); .So change as like this
function generateCreatureDiv(creature) {
        var CreatureDiv = $("
");
        console.log("hoe");
        CreatureDiv.id = "CreatureInfo";
        console.log("hoe")
        $(CreatureDiv).append("
" + creature.name + "
");
        console.log("hoe");
        $(CreatureDiv).append("" + creature.image + "");
        return CreatureDiv;
        console.log("hoe");

      }

And change like this
document.getElementById("CreatureEntry").innerHTML += generateCreatureDiv(creature[i]);

instead of
document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]);

Because innerHTML =generateCreatureDiv(creature[i]); it will reset previous value on each time call

A: This line is erasing all of the content of your DIV for each element of your array:
document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]);

Remove the first part and just call your method and append the results?
$("CreatureEntry").append(generateCreatureDiv(creature[i]));

Also, you need to remove the quotes wherever you're referencing $("CreatureDiv") and use $(CreatureDiv).


text:
Q: How can I have a variable name in a variable in LESS? I have this code snippet:
// Color settings
.setCat(@x) {
    .cat@{x} {
        .menu-link {
            &.selected, &:hover { background: ~@{"catColor@{x}"}; }
            &:hover:after { border-top-color: ~@{"catColor@{x}"}; }
            &:only-child:after { border-top-color: transparent; }
        }
        .menu-link-submenu { background: ~@{"catColor@{x}"}; }
    }
}

.setCat(1);

I hope you can see what I am trying to do. I want the @catColor1 output which LESS then will compile into my hex color stored in that variable.
Is this possible? Is there a better way?

A: You need to nest both calls into the string. I've made the processing all go through a single new variable useColor (which you do not have to do, I just think it looks cleaner):
.setCat(@x) {
    .cat@{x} {
        @useColor: ~"@{catColor@{x}}";
        .menu-link {
            &.selected, &:hover { background: @useColor; }
            &:hover:after { border-top-color: @useColor; }
            &:only-child:after { border-top-color: transparent; }
        }
        .menu-link-submenu { background: @useColor; }
    }
}

So assuming this LESS:
@catColor1: #fff;
@catColor2: #aaa;

.setCat(1);
.setCat(2);

Produces this CSS:
.cat1 .menu-link.selected,
.cat1 .menu-link:hover {
  background: #ffffff;
}
.cat1 .menu-link:hover:after {
  border-top-color: #ffffff;
}
.cat1 .menu-link:only-child:after {
  border-top-color: transparent;
}
.cat1 .menu-link-submenu {
  background: #ffffff;
}
.cat2 .menu-link.selected,
.cat2 .menu-link:hover {
  background: #aaaaaa;
}
.cat2 .menu-link:hover:after {
  border-top-color: #aaaaaa;
}
.cat2 .menu-link:only-child:after {
  border-top-color: transparent;
}
.cat2 .menu-link-submenu {
  background: #aaaaaa;
}


text:
Q: Why does redux do `{... store}` in its applyMiddleware implementation?
Although this is about the applyMiddleware implementation I accept this being a duplicate of the question referring to the spreading operator as the core of the mental issue is exactly that.

Preamble:
I don't like magic when it comes to a point where it is actually unclear why things happen. So I was looking in the actual redux implementation.
What is the problem?
Well I saw this in the implementation of applyMiddleware:
applyMiddleware.js on github

import compose from './compose'

/**
 * Creates a store enhancer that applies middleware to the dispatch method
 * of the Redux store. This is handy for a variety of tasks, such as expressing
 * asynchronous actions in a concise manner, or logging every action payload.
 *
 * See `redux-thunk` package as an example of the Redux middleware.
 *
 * Because middleware is potentially asynchronous, this should be the first
 * store enhancer in the composition chain.
 *
 * Note that each middleware will be given the `dispatch` and `getState` functions
 * as named arguments.
 *
 * @param {...Function} middlewares The middleware chain to be applied.
 * @returns {Function} A store enhancer applying the middleware.
 */
export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, preloadedState, enhancer) => {
    const store = createStore(reducer, preloadedState, enhancer)
    let dispatch = store.dispatch
    let chain = []

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

return {
  ...store,
  dispatch
}

So it is actually spreading the whole store on the first level of the store object. But we just want to apply middleware and are not actually manipulating the store.
So why not just do the following?
return {
  store,
  dispatch
}

What would be the side-effects of doing store over ...store in this very specific implementation / in the scope of an app using it?

A: Doing store instead of ...store would completely change the meaning of the expression.
{store, dispatch} means the same as: {store: store, dispatch: dispatch}
Whereas {...store, dispatch} means expanding/merging original store object with new dispatch property.
Read more here about spread syntax.

A: I've never had the chance to do a project with React, but I did watch a few videos and I know that the idea of the framework is that store is immutable(read more about immutability here), the three dots are called Spread syntax and I think that this syntax is used in shorthand instead of Object.assign

Spread in object literals
The Rest/Spread Properties for ECMAScript proposal (stage 3) adds
  spread properties to object literals. It copies own enumerable
  properties from a provided object onto a new object.
Shallow-cloning (excluding prototype) or merging of objects is now
  possible using a shorter syntax than Object.assign.

If you change ...store to store you will completely change the behavior of the framework. I don't know what exactly the side effects will be, we need to do some testing :)
I hope this was helpful to you to understand this piece of code better. Good Luck!

A: {...store, dispatch} is the same thing as Object.assign({}, store, {dispatch: dispatch}).
{store, dispatch} is the same thing as {store: store, dispatch: dispatch}.
In case you don't know what Object.assign does : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
The result is that if there is some property foo that exists on object store, on the newly created object o, in the first case you access it via o.foo, in the second case via o.store.foo.
So it makes a real difference ;)
These notations look "magical" until you learn what they do. Then you start feeling they save you a lot of time, let you write DRY and short code.


text:
Q: Psi Ontic interpretations of QM that can be made relativistic? What Psi Ontic interpretations of QM can be made relativistic? Is the Many Worlds interpretation the only one?

A: This feels like a rather general list question so my answer's fairly short, but no, there are other $\psi$-ontic interpretations that may be made relativistic.
It's obviously less intuitive starting from this approach, and since there isn't a lot of interest in many interpretations (and many are originally derived from the Schrödinger equation), it seems understandable that $\psi$-ontic interpretations often present conceptual issues in regards to relativity - although this is an issue many $\psi$-epistemic interpretations also share outside of those that are a simple tweak to SQM.
That said, Bohmian mechanics is fairly simple to make relativistic - you can essentially replace the SE in Bohm's derivation with the Klein-Gordon equation and you're half of the way there (Nikolić, 2012).
There are relativistic GRW models also, e.g. Tumulka (2006).
Stanford encyclopedia also suggests there are various relativistic modal interpretations; but since they largely reference books I don't have access to their cited sources to discuss.
So I hope that answers your question.


text:
Q: Python_How to check if the value exists in the same column of a dataframe? I'm trying to implement =IF Z1 <> Z2, 1,"" (MS Excel formula) in python.
I have a dataframe that consists of two columns wherein I want to check if the same person is stored with the two different names which has created two unique ids for him(eg : Name[0] = 'Bran D' and Name[21] = 'Brandon D').If two IDs are created for the same person then add a new column 'C' which will have all the results. This is an iteration process. Wanted to check for more than 200 records.
Eg: If their names are not same then '1' if there is a match then put it blank
df[['Unique ID','Name']]


text:
Q: Svg image representing a node, varying node size in a force-directed graph So far I've used d3.svg.symbol() in a force-directed graph for distinguishing different node types from one another.
I'd now like to distinguish different node types by displaying node as a svg image. Following one of the examples I used the following code to display the node images:
    var node = svg.selectAll("image.node").data(json.nodes);
    var nodeEnter = node.enter().append("svg:g").append("svg:image")
    .attr("class", "node")
    .attr("xlink:href", function(d)
    {
      switch( d.source )
      {
        case "GEXP": return "img/node_gexp.svg";
        case "CNVR": return "img/node_cnvr.svg";
        case "METH": return "img/node_meth.svg";
        case "CLIN": return "img/node_clin.svg";
        case "GNAB": return "img/node_gnab.svg";
        case "MIRN": return "img/node_mirn.svg";
        case "SAMP": return "img/node_samp.svg";
        case "RPPA": return "img/node_rppa.svg";
      }
    })
    .attr("x", function(d) { return d.px; } )
    .attr("y", function(d) { return d.py; } )
    .attr("width", "50")
    .attr("height", "50")
    .attr("transform", "translate(-25,-25)")
    .on("click", function(d) {
      console.log("nodeclick");
      } )
    .on("mouseover", fade(0.10) )
    .on("mouseout", fade(default_opacity) )
    .call(force.drag);

This does display the svg images but I've two problems:
1) I want to scale the node sizes based on an attribute. From what I understand this can be done by supplying the "scale" attribute
transform="scale(something)"

to a suitable place, like to the image tag itself or to the group containing the image:
    var node = svg.selectAll("image.node").data(json.nodes);
    var nodeEnter = node.enter()
    .append("svg:g")
    .attr("transform", function(d)
    {
      var str = "scale(";
        if( d.gene_interesting_score && d.gene_interesting_score > 0 )
        {
          return str + ( (d.gene_interesting_score - minScore ) / ( maxScore - minScore ) ) + ")";
        }
        return str + 0.7 + ")";
    })
    .append("svg:image")
    ....

As it happens, the scale() transform displaces the images: they are no longer on the endpoint of the edge. How do I resize the images properly when initializing the graph, preferrably so that the controlling mechanism is within a single function (e.g. so that I don't have to control x,y,width,height separately)?
2) When the graph is zoomed, Chrome blurs the images whereas in Firefox the image remains crispy (picture). How can this blur be avoided?

Edit: Based on duopixel's suggestions, the code is now:
    var nodeGroup = svg.selectAll("image.node").data(json.nodes).enter()
    .append("svg:g")
    .attr("id", function(d) { return d.id; })
    .attr("class", "nodeGroup")
    .call(force.drag);

    var node = nodeGroup.append("svg:image")
    .attr("viewBox", "0 0 " + nodeImageW + " " + nodeImageH)
    .attr("class", "node")
    .attr("xlink:href", function(d)
    {
      switch( d.source )
      {
        case "GEXP": return "img/node_gexp.svg";
        case "CNVR": return "img/node_cnvr.svg";
        case "METH": return "img/node_meth.svg";
        case "CLIN": return "img/node_clin.svg";
        case "GNAB": return "img/node_gnab.svg";
        case "MIRN": return "img/node_mirn.svg";
        case "SAMP": return "img/node_samp.svg";
        case "RPPA": return "img/node_rppa.svg";
      }
    })
    .attr("width", nodeImageW)
    .attr("height", nodeImageH)
    .attr("transform", function(d)
    {
      var matrix = "matrix(";
      var scale = 0.7; // sx & sy
      if( d.gene_interesting_score && d.gene_interesting_score > 0 )
      {
        scale = ( (d.gene_interesting_score - minScore ) / ( maxScore - minScore ) ) * 0.5 + 0.25;
      }
      //console.log("id=" + d.id + ", score=" + scale );
      matrix += scale + ",0,0," + scale + "," + ( d.x - ( scale*nodeImageW/2 ) ) + "," + ( d.y - ( scale*nodeImageH/2 ) ) + ")";
      return matrix;
    })
    // .attr("transform", "translate(-25,-25)")
    .on("click", function(d) {
      console.log("nodeclick");
      } )
    .on("mouseover", fade(0.10) )
    .on("mouseout", fade(node_def_opacity) );

It solves the problem #1, but not the second one: by selecting
var nodeImageH = 300;
var nodeImageW = 300;

The resulting svg image contains a lot  empty space (seen by selecting the image with firebug's selection tool). The images were created in Inkscape, canvas size cropped to 50x50 which should be the correct viewing pixel size.

A: #1 You need to set the transform origin. In SVG this means that you are going to have to use a transform matrix as answered here: https://stackoverflow.com/a/6714140/524555
#2 To solve the blurry scaling modify the viewBox, width, height of your svg files to start as large images (i.e. <svg viewBox="0 0 300 300" width="300" height="300">.


text:
Q: Adding Next Button to CashAccountDetails I'm trying to add a next/previous button on the CashAccountDetails page (CATranEnq Graph).
This is what I tried this far:
using PX.Data;
using PX.Objects.GL;
using System.Linq;

namespace PX.Objects.CA
{
    public class CATranEnqExtension : PXGraphExtension<CATranEnq>
    {
        private class ActionsLabels
        {
            public const string NextAccount = "Compte suivant";
            public const string PreviousAccount = "Compte précédent";
        }

        public PXAction<CAEnqFilter> PreviousAccount;
        [PXUIField(DisplayName = ActionsLabels.PreviousAccount, MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
        [PXPreviousButton]
        public virtual void previousAccount()
        {
            CAEnqFilter filter = Base.Filter.Current;
            Account previousaccount = new Account();
            if (!filter.AccountID.Equals(null))
            {
                Account currentAccount = PXSelect<Account, Where<Account.accountID,
                                            Equal<Required<Account.accountID>>>>.Select(Base, filter.AccountID).FirstOrDefault();
                previousaccount = PXSelect<Account,
                                Where<Account.accountCD,
                                    Less<Required<Account.accountCD>>,
                                    And<Account.isCashAccount, Equal<True>>>,
                                        OrderBy<Desc<Account.accountCD>>>.Select(Base, currentAccount.AccountCD).FirstOrDefault();
            }
            else
            {
                previousaccount = PXSelect<Account,
                                    Where<Account.isCashAccount, Equal<True>>,
                                   OrderBy<Desc<Account.accountCD>>>.Select(Base).FirstOrDefault();
            }
            filter.AccountID = previousaccount?.AccountID;
        }

        public PXAction<CAEnqFilter> NextAccount;
        [PXUIField(DisplayName = ActionsLabels.NextAccount, MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
        [PXNextButton]
        public virtual void nextAccount()
        {
            CAEnqFilter filter = Base.Filter.Current;
            Account nextaccount = new Account();
            if (!filter.AccountID.Equals(null))
            {
                Account currentAccount = PXSelect<Account, Where<Account.accountID,
                                            Equal<Required<Account.accountID>>>>.Select(Base, filter.AccountID).FirstOrDefault();
                nextaccount = PXSelect<Account,
                                Where<Account.accountCD,
                                    Greater<Required<Account.accountCD>>,
                                    And<Account.isCashAccount, Equal<True>>>,
                                        OrderBy<Asc<Account.accountCD>>>.Select(Base, currentAccount.AccountCD).FirstOrDefault();
            }
            else
            {
                nextaccount = PXSelect<Account,
                                    Where<Account.isCashAccount, Equal<True>>,
                                   OrderBy<Asc<Account.accountCD>>>.Select(Base).FirstOrDefault();
            }
            filter.AccountID = nextaccount?.AccountID;
        }
    }
}

When I click on the buttons I expect to go to another CashAccount, but instead the AccountID gets used and it doesnt find the account :
https://i.imgur.com/Uo7MCWL.png

A: I had to use a CashAccount object and not an account.
CAEnqFilter filter = Base.Filter.Current;
            CashAccount previousaccount = new CashAccount();
            if (!filter.AccountID.Equals(null))
            {
                CashAccount currentAccount = PXSelect<CashAccount, Where<CashAccount.cashAccountID,
                                            Equal<Required<CashAccount.cashAccountID>>>>.Select(Base, filter.AccountID).FirstOrDefault();
                previousaccount = PXSelect<CashAccount,
                                Where<CashAccount.cashAccountCD,
                                    Less<Required<CashAccount.cashAccountCD>>>,
                                        OrderBy<Desc<CashAccount.cashAccountCD>>>.Select(Base, currentAccount.CashAccountCD).FirstOrDefault();
            }
            else
            {
                previousaccount = PXSelectOrderBy<CashAccount,
                                   OrderBy<Desc<CashAccount.cashAccountCD>>>.Select(Base).FirstOrDefault();
            }
            filter.AccountID = previousaccount?.CashAccountID;


text:
Q: How could I put my private int into the public int I want scramble an array by using Math.random multiple times but I don't know how to put the random int into scramble and use the random int multiple times.
 public static void scramble(int[] array){
  for(int i = 0 ; i < array.length - 1; i++){
     int temp = array[i];
     array[i] = array[random];
     array[random] = temp;}}

public int random (){
  return (int)(Math.random() *9) + 1;}

Output
100 101 102 103 104 105 106 107 108 109 //Default
 101 104 102 105 103 106 108 109 100 107 //Scrambled
  100 101 102 103 104 105 106 107 108 109//Then sorted

Whole Driver
    import java.lang.Math;

public class Driver03{
   public static void main(String[] args){
      int[] array = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109};
      print(array);
      scramble(array);
      print(array);

      print(array);}

   public static void print(int[] array){
      for(int x = 0; x < array.length; x++){
         System.out.print(" " + array[x]);}
      System.out.println("");}

   public static void scramble(int[] array){
      int random = random();
      for(int i = 0 ; i < array.length - 1; i++){
         int temp = array[i];
         array[i] = array[random];
         array[random] = temp;}}

   public int random (){
      return (int)(Math.random() *9) + 1;}

}

A: Firstly, you have to call the random function like that "random()" not just random
try this code:
public static void scramble(int[] array){
  int random = random();
  for(int i = 0 ; i < array.length - 1; i++){
     int temp = array[i];
     array[i] = array[random];
     array[random] = temp;}}

public static int random (){
 return (int)(Math.random() *9) + 1;}

A: Here is an implementation using the Fisher-Yates shuffling algorithm.
  public static void main( String[] args )
  {
    int[] values = new int[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 };
    System.out.println( "Start: " + Arrays.toString( values ) );
    scramble( values );
    System.out.println( "Scrambled: " + Arrays.toString( values ) );
    Arrays.sort( values );
    System.out.println( "Sorted: " + Arrays.toString( values ) );
  }

  public static void scramble( int[] array )
  {
    // Scramble using the Fisher-Yates shuffle.
    Random rnd = new Random();
    for ( int i = 0; i < array.length - 1; i++ )
    {
      int random = i + rnd.nextInt( array.length - 1 - i );
      int temp = array[ random ];
      array[ random ] = array[ i ];
      array[ i ] = temp;
    }
  }

It doesn't use Math.random() but an instance of Random instead.


text:
Q: Python Bottle template engine does not allow period It looks like the Bottle template engine does not periods in it's template variables. The following code:
from bottle import template
x = 'blah {{blah.blah}} blah'
d = {'blah.blah': 'doodah'}
template(x, **d)

Gives me this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "E:\WPy-3662\python-3.6.6.amd64\lib\site-packages\bottle.py", line 3622, in template
    return TEMPLATES[tplid].render(kwargs)
  File "E:\WPy-3662\python-3.6.6.amd64\lib\site-packages\bottle.py", line 3411, in render
    self.execute(stdout, env)
  File "E:\WPy-3662\python-3.6.6.amd64\lib\site-packages\bottle.py", line 3398, in execute
    eval(self.co, env)
  File "<string>", line 1, in <module>
NameError: name 'blah' is not defined

I need periods. I'm keeping my templates in a multi-line string array and then passing an array of dictionaries to the Bottle template engine.
How can I get around this?

A: So the problem is not with Bottle, but in how python parses the variables during eval.
The template string blah.blah When run through eval creates a variable name blah.blah, which turns into a two part notation.
blah.blah = 'doodah'

can't work.  Though it does work in a dictionary since it is a string name. If you replace the dot with an underline, it will work, because an underline is a valid variable name.


text:
Q: SonarQube 6.3: es stops with no obvious failure I was trying to bring up a new host for SonarQube. I believe my connections are fine (http get 200 for the desired port). But my es process would quit immediately with below log lines. Can anyone help explaining what might have gone wrong? Appreciate any help!
2017.11.01 23:48:52 INFO  es[][o.s.p.ProcessEntryPoint] Starting es
2017.11.01 23:48:52 INFO  es[][o.s.s.EsSettings] Elasticsearch listening on /127.0.0.1:9200
2017.11.01 23:48:52 INFO  es[][o.elasticsearch.node] [sonarqube] version[2.4.4], pid[26917], build[fcbb46d/2017-01-03T11:33:16Z]
2017.11.01 23:48:52 INFO  es[][o.elasticsearch.node] [sonarqube] initializing ...
2017.11.01 23:48:52 INFO  es[][o.e.plugins] [sonarqube] modules [], plugins [], sites []
2017.11.01 23:48:52 INFO  es[][o.elasticsearch.env] [sonarqube] using [1] data paths, mounts [[/ (/dev/xvda1)]], net usable_space [75.1gb], net total_space [78.6gb], spins? [no], types [auto]
2017.11.01 23:48:52 INFO  es[][o.elasticsearch.env] [sonarqube] heap size [990.7mb], compressed ordinary object pointers [true]
2017.11.01 23:48:52 WARN  es[][o.elasticsearch.env] [sonarqube] max file descriptors [65535] for elasticsearch process likely too low, consider increasing to at least [65536]
2017.11.01 23:48:53 INFO  es[][o.elasticsearch.node] [sonarqube] initialized
2017.11.01 23:48:53 INFO  es[][o.elasticsearch.node] [sonarqube] starting ...
2017.11.01 23:48:53 INFO  es[][o.e.transport] [sonarqube] publish_address {127.0.0.1:9200}, bound_addresses {127.0.0.1:9200}
2017.11.01 23:48:53 INFO  es[][o.e.discovery] [sonarqube] sonarqube/yhMv9glqR6i-TLWARJ2unQ
2017.11.01 23:48:56 INFO  es[][o.e.cluster.service] [sonarqube] new_master {sonarqube}{yhMv9glqR6i-TLWARJ2unQ}{127.0.0.1}{127.0.0.1:9200}{rack_id=sonarqube, master=true}, reason: zen-disco-join(elected_as_master, [0] joins received)
2017.11.01 23:48:56 INFO  es[][o.elasticsearch.node] [sonarqube] started
2017.11.01 23:48:56 INFO  es[][o.e.gateway] [sonarqube] recovered [0] indices into cluster_state
2017.11.01 23:48:58 INFO  es[][o.s.p.StopWatcher] Stopping process
2017.11.01 23:48:58 INFO  es[][o.elasticsearch.node] [sonarqube] stopping ...
2017.11.01 23:48:58 INFO  es[][o.elasticsearch.node] [sonarqube] stopped
2017.11.01 23:48:58 INFO  es[][o.elasticsearch.node] [sonarqube] closing ...
2017.11.01 23:48:58 INFO  es[][o.elasticsearch.node] [sonarqube] closed


text:
Q: RenegeIn other trajectory R (simmer package) I'm new in R.
I'm trying to simulate queueing with simmer.
I want to enable Renege from "Typhon" to "Tornado". BUT my code creates a new trajectory to "Tornado" and what I need is just one "Torando" trajectory. (see picture below).
My question is how to enable Renge to an existing trajectory? (in my case is from "Typhon" to "Tornado")
This is my code and Plot :
##----------------------------------------- 1.  all functions ------------------------------------------------

## add service
addService<- function  (path,sname,timeDist){
  updatedPath <- seize(path, resource = sname, amount = 1)%>%
    timeout(timeDist) %>%
    release(resource = sname,  amount = 1)

  return(updatedPath)
}
##abound function
addServiceRenge<- function  (trajectory,sname,timeDist,renegDist, continueTo){
  updatedPath <- renege_in(trajectory,renegDist,out= continueTo %>% log_("I left angry!") )%>%
    seize(resource = sname, amount = 1)%>%
    renege_abort()%>%
    timeout(timeDist) %>%
    release(resource = sname, amount = 1)

  return(updatedPath)
}

##----------------------------------------- 2.  all simulation parameters ------------------------------------------------

set.seed(654)
simulationTime <- 7*60
openTime<-rnorm(1,17,3)
gate_schedule<-schedule(timetable = c(0, openTime), values = c(0, Inf), period = Inf)

##----------------------------------------- 3.  Init Simulation and add all resources  ------------------------------------------------

bravePool<-simmer("brave pool")%>%
  add_resource("DoorMan",capacity=gate_schedule,queue_size=Inf)%>%
  add_resource(name="Staris",capacity=1,queue_size=Inf)%>%
  add_resource(name="Tornado",capacity=1,queue_size=Inf)%>%
  add_resource(name="Typhon",capacity=1,queue_size=Inf)%>%
  add_resource(name="Hurrican",capacity=1,queue_size=Inf)

##----------------------------------------- 4.  All trajectories, start from main trajectory and add sub-trajectories ABOVE IT it . ------------------------------------------------

swimmerToHurrican <- trajectory("to hurrican")%>%
  addService(sname = "Hurrican", timeDist = function() rexp(1,0.25))

swimmerToTornado <- trajectory("to tornado")%>%
  addService(sname = "Tornado", timeDist = function() dtriangle(1, min = 0.1, max = 0.5, mode = 0.5) )

swimmerToTyphon <- trajectory("to typhon")%>%
  addServiceRenge(sname = "Typhon", timeDist = function() rnorm(1,3,1), renegDist = function() runif(1,2,4), continueTo = swimmerToTornado)

swimmer<-trajectory("swimmer's path") %>%
  addService(sname = "DoorMan", timeDist = openTime)%>%
  addService(sname = "Staris", timeDist = function() runif(1,3.5,7.5))%>%
  branch(option=function() rdiscrete (1, c(0.4,0.061,0.364,0.175),c(0,1,2,3)) ,continue= c(FALSE,FALSE,FALSE),swimmerToTornado,swimmerToTyphon,swimmerToHurrican)

##----------------------------------------- 5.  All Generators, ALWAYS LAST. ------------------------------------------------

bravePool%>%
  add_generator(name="swimmers",trajectory=swimmer,distribution=function() rexp(1,3.5))

##----------------------------------------- 6.  reset, run, plots, outputs ------------------------------------------------
reset(bravePool)%>%run(until=simulationTime)

poolData<-get_mon_arrivals(bravePool, per_resource = T)
plot(swimmer)

A: Your code is ok, and this is expected. Internally, simmer makes an exact copy of the trajectory (to avoid issues if, for example, you remove the original one), but don't worry about it, it should work as expected.


text:
Q: Eclipse Luna (4.4.0): WindowBuilder installed but not appearing to use in "Select Wizard" menu I have installed Swing Designer, SWT Designer and WindowBuilder Core exactly as described in this tutorial.
As I wanted to create new GUI, I could not find the WindowBuilder option in the "Select Wizard" menu (File -> New -> Other...).
[I wanted to post an image of how the Wizard appear to me, but I don't have enough "reputation" or what... I hope I described my problem clearly enough]
I did everything as was done in the video. I have checked twice, that the WB is installed. When I tried to install it again, a warning was displayed that it is already installed. Also, in the folder where the Eclipse files are (C:\Program Files\eclipse\plugins\org.eclipse.wb.core.lib_1.8.0.r44x201412082350\lib), there is an evidence of the WB - something is there.
I have tried to update those plug-ins. They are the latest version now, the problem remains nevertheless.

A: Adding "-clean" to the eclipse startup arguments did solve this issue for me.
This can be added via the eclipse.ini file
Screenshot to en eclipse.ini example. I cannot add the image directly
Problem Description:

*

*The WindowBuilder did not show after the installation for me as well.

*Installing the WindowBuilder and the SWTDesigner from https://download.eclipse.org/windowbuilder/latest/ nor from http://download.eclipse.org/releases/2019-12 did work. (Both done via Eclipse Software Installer)

*after adding "-clean" the WindowBuilder was correclty displayed

Background:

*

*Explanation of -clean: https://eclipsesource.com/de/blogs/2013/08/22/eclipse-command-line-options/

*description of launcher init: https://wiki.eclipse.org/Eclipse.ini

A: Time consuming initial steps: The Distribution of the Eclipse Repository resulting from the keyword "WindowBuilder" is incomplete, in my case.
From Installing WindowBuilder Pro you get the suitable repository URL, e.g.
http://download.eclipse.org/windowbuilder/lastgoodbuild/
providing the complete list of packets.
All well displayed in a tutorial video How to Install WindowBuilder in Eclipse and Start Designer Window

A: From the information you gave me, it seems like you are not using a WindowBuilder project. To create one, go to your select wizard menu, and select SWT/JFACE project. Then you should be able to use WindowBuilder.
EDIT: The tutorial you watched is a little dicey, use this link in the "Install new software" menu: http://download.eclipse.org/windowbuilder/WB/release/R201406251200/4.4/
Select all the options there. It should work after a restart. A good rule of thumb would be to turn your antivirus off, some do not allow programs to execute programs downloaded from the internet.
P.S: Don't use WindowBuilder, code by hand instead.


text:
Q: Is there a way to stop the late method when executing Promise.race? The code below is a just simple example.
function delay(time) {
    return new Promise(function (resolve) {
        setTimeout(resolve, time);
    }).then((e) => {
        console.log(`Wait ${time}ms.`);
        return time;
    });
}

async function main() {
    let r = await Promise.race([
        delay(1000),
        delay(2000),
    ]);
    console.log(r);
}
await main();

Output:
Wait 1000ms.
1000
Wait 2000ms.

I want to stop the remaining code except the code that was executed first through Promise.race.
Is there any other way?

A: The only way to do something like this would be to put the code that runs conditionally near where you call the Promise.

function delay(time) {
    return new Promise(function (resolve) {
        setTimeout(resolve, time, time);
    })
}

async function main() {
    const firstResult = await Promise.race([
        delay(1000),
        delay(2000),
    ]);
    console.log(`Wait ${firstResult}ms.`);
}
main();

If the code you want to run conditionally is inside a function - like with your original delay function - and the function doesn't explicitly provide a way to change its execution after being called - then no, there's nothing you can do to keep that code from executing.
Most of the time when Promises are involved, no such method exists - though there are exceptions, such as with AbortController.