text:
Q: CADisplayLink is unable to achieve a constant frame rate in simulator I am trying to use CADisplayLink to achieve a constant frame rate for a game loop. When testing it in a simulator I am not able achieve stable time frames. Should I consider a different approach?
Or is that just because of the simulator not being able to emulate the hardware appropriately?
According to Apple this is how to calculate FPS:
let actualFramesPerSecond = 1 / (displaylink.targetTimestamp - displaylink.timestamp)

In my plain iOS app that I've set up for testing this prints a constant frame rate:
 FPS: 59.99999875668439
 FPS: 59.99999875668439
 FPS: 59.99999875668439
 FPS: 59.99999875668439
 FPS: 59.99999875668439

However, when I calculate the FPS using the actual elapsed time, it gives something else:
 FPS: 64.35942918520792
 FPS: 58.30848150362142
 FPS: 57.640194044003465
 FPS: 64.47022656706324
 FPS: 59.392580005664115
 FPS: 60.282043174566674

Plus, when using the code for rendering some sprites it looks unstable in simulator. How is it possible that the above code snippet diverges so much from reality?
My main concern is: Why is there a constant frame rate when calculating the FPS the Apple way? Is it possible that their documentation just contains a little glitch? Besides, the 'actual' values are kind of expected when there is some load, but for an empty loop that is doing nothing?
This is the code I am using to execute my game loop:
private var previousTimeInSeconds: Double = 0

private lazy var displayLink: CADisplayLink = {
    let displayLink = CADisplayLink(target: self,
                                    selector: #selector(displayLoop))
    return displayLink;
}()

private func startLoop() {
    previousTimeInSeconds = Date().timeIntervalSince1970
    displayLink.add(to: .current, forMode: .common)
}

@objc private func displayLoop() {
    let currentTimeInSeconds = Date().timeIntervalSince1970
    let elapsedTimeInSeconds = currentTimeInSeconds - previousTimeInSeconds
    previousTimeInSeconds = currentTimeInSeconds

    //let actualFramesPerSecond = 1 / (displayLink.targetTimestamp - displayLink.timestamp) // is showing constant 59.xxx FPS
    let actualFramesPerSecond = 1 / elapsedTimeInSeconds

    print("FPS: \(actualFramesPerSecond)") // varies from 50.xxx to 70.xxx FPS
    /*
     FPS: 64.35942918520792
     FPS: 58.30848150362142
     FPS: 57.640194044003465
     FPS: 64.47022656706324
     FPS: 59.392580005664115
     FPS: 60.282043174566674
     */
}

A: I think I found the answer. Don't use Date().timeIntervalSince1970 to calculate the individual frame rates per second. It seems to be just not precise enough.
Instead, use displayLink.timestamp, which is the time value associated with the last frame that was displayed. Replace the Date() usages in my code above with timestamp and you get the expected FPS values:
FPS: 59.99999875668439
FPS: 59.99999896623196
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 29.999999430729087
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 59.99999896623196
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 59.99999875668439
FPS: 59.99999896623196

As you can see, it's mostly constant at 59 FPS, with a few drops here and there which is totally expected as there is no guarantee that CADisplayLink is called at a constant rate. But under 'labor situations' with (almost) no code to execute this is the frame rate you'd could expect.
The formular I took from Apple's documentation ("let actualFramesPerSecond = 1 / (displayLink.targetTimestamp - displayLink.timestamp)") is kind of useless if want to calculate the real frame rate times. Instead, it shows that targetTimestamp can be used to achieve a stable game loop (as the resulting value is indeed a constant). I wish the documetation could've been more clear in that.


text:
Q: How to setup a button click on server side by using Google Tag manager? I am creating a tag in the Google Tag Manager Server Side container but in trigger, I can't see a button click option like GTM web.
is that possible if yes then how to implement ??

A: There are no buttons on the server side, so naturally backend GTM is unable to have triggers like that. Judging from the question, however, you don't quite understand what the server-side tag management is and you probably should not go that way.
Just in case you're sure you need server-side GTM, the button tracking with it would be sending a request from FE to BE when the click happens (assuming no such request is already sent) and then having BE to trigger an explicit GTM event for this button click.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to horizontally align floated contents I want my copyright floated to the left and a back to top button floated to the right, but I can't align/ center them both horizontally. I tried doing display:inline-block

.wrap {
  max-width: 700px;
  width: 100%;
  padding: 3%;
  position: relative;
}
footer {
  background-color: #ecf0f1;
  clear: both;
  width: 100%;
  vertical-align: middle;
  position: relative;
  float: left;
  height: 20vh;
  display: -webkit-flex;
  display: flex;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
}
.backtotop {
  float: right;
}
.copyright {
  float: left;
}

      BACK TO TOP ↑

ALL RIGHTS RESERVED

A: You need to extend the flx properties into the the .wrap element. Then you can remove the floats completely.

.wrap {
  max-width: 700px;
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  justify-content: space-between;
}
footer {
  background-color: #ecf0f1;
  height: 20vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding:0 3em
}
p {
  margin: 0;
}
a {
  text-decoration: none;
}

    BACK TO TOP ↑

ALL RIGHTS RESERVED

A: You have a margin on your
 but not on your , if you remove it from both, or add it to both, you will achieve what you wish to accomplish.
(It's worth noting that while you didn't add the margin yourself, the browser user agent adds it in by default, unless you specify otherwise. Different browsers set different default CSS rules. Try including a reset.css or a normalise.css )


text:
Q: Attention weights for identifying influence This question concerns the application of self-attention weights for identifying influence of words in sentences.
For instance, we are performing a classification task on a set of sentences (e.g. sentiment analysis). The model takes the embedded words and feeds them into a (bidirectional) LSTM or GRU layer. The hidden states are combined by an attention vector to obtain a sentence representation that is used as an input for the classification.
For a set of sentences $S$, and the attention weights $\alpha^s = <\alpha^s_1, \alpha^s_2, \ldots, \alpha^s_n>$ for each sentence $s \in S$, we can combine attentions of all sentences into a matrix size $|W| \times |S|$ where $|W|$ is the vocabulary size and $|S|$ is the number of sentences, with column sum equal to 1 (each column is a probability distribution over words). On the other hand, sentence-class relationship forms a matrix of $|C| \times |S|$, where $|C|$ is the number of classes with each column a probability distribution over classes.
Using the above two learned probability distributions, is it possible to answer the following two questions:
1) For a particular class (e.g., excitement), what are the most influential words.
2) For a particular word, how much it influences a particular class. e.g. how much the word despise influence hatred?
Any pointers or references to similar work is highly appreciated.

A: You might want to do something like a paper called A Structured Self-Attentive
Sentence Embedding.
In this paper, they process a sentence using an RNN. Then there is a set of constant, but trained query vectors which are then used as queries in an attention mechanism. For each query vector, you get one context vector (weighted average of the RNN states), which are then concatenated and used for classification.
My guess is that you can do a little better if you do the independent projection for attention keys and values as in the Attention is all you need paper.
The main difference between the attention in sequence-to-sequence learning and in this paper is that in seq2seq models, the query vector is different for each step (it is the current state of the decoder), here the query vectors are constant.


text:
Q: Using DeviceIoControl with FSCTL_LOCK_VOLUME to lock a volume. Debugger issue I'm using DeviceIoControl with FSCTL_LOCK_VOLUME to lock a USB pen drive prior to direct disk read/write. The program works - sometimes.
I am having an issue with the lock call itself. When I step the command in Visual Studio 2008 the result is correct and the lock succeeds - every time!, when running the code (debug or not) the call fails sporadically with invalid handle. The only noticable difference is when stepping there is a half second pause - which I am happy with, but when running/debugging the call fails immediately.
Please can you give me a hint as to where this is falling down.
I think this is one for the true techies!

A: Sounds like a timing bug. Are there other threads with access to the handle? If so, one of them may be closing it before you call DeviceIoControl.


text:
Q: Why is cos -x equal to cos x? Can somebody explain to me graphically or intuitively why this is true? Because if we think in terms of the base of the triangle formed inside a unit circle it seems like it should not be negative.

A: Better to ask what $-x$ might mean itself in my opinion.  An angle of $-x$ can be viewed as a clockwise rotation whereas $x$ is anticlockwise.  Now in a unit circle you can record the $\cos$ of an angle as the horizontal distance on the $x$ axis and so intuitively the right triangle formed by rotating clockwise will have the same horizontal distance as one rotated anticlockwise.
Hope this helps.

A: See we can write it as $\cos(0-x)$ so now use $\cos(a-b)=cos(a)cos(b)+sin(a)sin(b)$ to get the desired result

A: Look at this figure. For an angle of $-\theta$, you mirror the figure vertically: you see that this does not change $\cos(\theta)$, but it does change the sign of $\sin(\theta)$

A: Intuitively $\cos(-\theta)$ measures the $x$-coordinate of a vector that measures $\theta$ degrees below the positive $x$-axis, so this is why we have $\cos(-\theta) = \cos\theta$.
Another way of seeing this is through the series representation of $\cos x$ given by
$$
\cos(-x) \;\; =\;\; 1 - \frac{(-x)^2}{2!} + \frac{(-x)^4}{4!} - \frac{(-x)^6}{6!} + \ldots \;\; =\;\; \cos x.
$$


text:
Q: Syntax error when query with "IN" - Realm js Background
Framework: React Native
Library: Realm JS
I am writing a query to search whether an ID is included in a collection
following the official doc in https://static.realm.io/downloads/files/NSPredicateCheatsheet.pdf

Left hand expression must appear in collection specified by
right hand expression. i.e. name IN {'Milk', 'Eggs', 'Bread'}

Problem
When applying this query .filtered('subcategoryId IN {"a","b"}')

Render Error: Invalid predicate: 'subcategoryId IN {"a","b"}: syntax error, unexpected '{'

I've tried different syntax on the right side collection, still doesn't work.
Anyone has similar experience?


text:
Q: Show/Hide Canvas using radio button I'm new to Javascript and Canvas, there's a lot of resources I've used and now I got confused. I'm doing a dress customization using Canvas.
This is my HTML:
 //these are my button samples
<input type="radio" id="shape1" name="round" onchange="display()" />
<input type="radio" id="shape2" name="box" onchange="display()" />

// this is where I'll display the canvas
<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"> </canvas>

So for my Javascript I have this:
  function display() {
    if (document.getElementById('shape1').checked) {
      var canvasC = document.getElementById('displaycanvas'),
          context = canvasC.getContext('2d');
           context.beginPath();
           context.arc(95,50,40,0,2*Math.PI);
           context.stroke();     }

    if (document.getElementById('shape2').checked) {
      var canvasR = document.getElementById('displaycanvas'),
          context = canvasR.getContext('2d');
            context.beginPath();
            context.rect(50, 27, 350, 400);    }
}

They are all working fine, it displays the shapes if I choose one of these buttons. My concern is how do I display only 1 shape at a time.
I'm not sure if toggle was the right thing, please tell me what is the right thing to do.  Thank you very much in advance,

A: You need to give the radios the same name to toggle them and you need to clear the canvas too.
I have used the same name for the canvas now

window.onload = function() {
  document.querySelector("#shape1").onclick = document.querySelector("#shape2").onclick = function() {
    var canvas = document.querySelector('#displaycanvas');
    context = canvas.getContext('2d');
    context.clearRect(0,0,canvas.width,canvas.height);
    context.beginPath();
    if (this.id == "shape1") {
      context.arc(95, 50, 40, 0, 2 * Math.PI);
    } else {
      context.rect(50, 27, 350, 400);
    }
    context.stroke();
  }
}
<input type="radio" id="shape1" name="shape" value="round" />
<input type="radio" id="shape2" name="shape" value="box" />
<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"></canvas>

If you want TWO canvases, you can do
window.onload = function() {
  document.querySelector("#shape1").onclick = function() {
    document.querySelector('#displaycanvas1').style.display="";
    document.querySelector('#displaycanvas2').style.display="none";
  }
  document.querySelector("#shape2").onclick = function() {
    document.querySelector('#displaycanvas2').style.display="";
    document.querySelector('#displaycanvas1').style.display="none";
  }
}

still giving the radios the same name

A: If the radio buttons have the same name attribute, they will alternate between the available ones. If they have different name attributes, they will be grouped separately.

function display() {
  var s1 = document.querySelector('#shape1').checked,
      s2 = document.querySelector('#shape2').checked;
  alert("shape1: " + s1 + ", shape2: " + s2)
}

function display2() {
  var s3 = document.querySelector('#shape3').checked,
      s4 = document.querySelector('#shape4').checked;
  alert("shape3: " + s3 + ", shape4: " + s4)
}
1-2
<input type="radio" name="shape" value="shape1" id="shape1" onclick="display()" />
<input type="radio" name="shape" value="shape2" id="shape2" onclick="display()" />

3-4
<input type="radio" name="round" value="shape3" id="shape3" onclick="display2()" />
<input type="radio" name="square" value="shape4" id="shape4" onclick="display2()" />

A: You can use the below code to achieve your requirement:

function display() {
 var canvasC = document.getElementById('displaycanvas');
 context = canvasC.getContext('2d');
 context.clearRect(0, 0, canvasC.width, canvasC.height);
    if (document.getElementById('shape1').checked) {
           context.beginPath();
           context.arc(95,50,40,0,2*Math.PI);
           context.stroke();     }

    if (document.getElementById('shape2').checked) {
            context.beginPath();
            context.rect(50, 27, 350, 400); context.stroke();     }
}
<input type="radio" id="shape1" name="round[]" onchange="display()" />
<input type="radio" id="shape2" name="round[]" onchange="display()" />

<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"> </canvas>


text:
Q: input field data compare to DB and display another values of db I have four column in database .in html has two field if I type  two fields then it compare the DB and if same when display another two column value .how its work in php
in a input field i type apple and orange its compare Db and display mango grape
and apple1 and orange1 its display mango1 grape1  how?
ex if my db is
apple orange mango grape ,
apple1 orange1 mango1 grape1
apple2 orange2 mango2 grape2
i want to compare the input text from the user to db.the input data how to compare DB and display the same row  another values..please help me

A: Try this code. I just give sample code
<script src="<?php echo base_url();?>js/jquery-1.9.1.min.js"></script>
Name1 : <input type="text" class="form-control" id="name" name="name" value="" > </br>
Name2 : <input type="text" class="form-control" id="name2" name="name2" value="" ></br>

<script type="text/javascript">
               $( document ).ready(function() {
                    $('#name').blur(function(){
                     var name=$("#name").val();
                     $.ajax({
                                type: "post",
                                url: "ajax_get_sub",
                                cache: false,
                                data: {name:name},
                                success: function(plan){
                                try{
                                     $("#name2").val(plan);
                                }catch(e) {
                                    alert('Exception while request..');
                                }

                                },
                                error: function(e){
                                    alert('Error while request..');
                                }

                            });
                    });
               });
               </script>

And PHP Function like this. File name:ajax_get_sub
if(isset($_POST['name'])
    {
    $t=$this->input->post('name');
    $result=$this->db->query("select * from table where col1 LIKE '%{$t}%'");
    $result->num_rows();
    foreach($result->result_array() as $row)
    {
        $name = $row['col2'];
    }
    echo $name;
    }


text:
Q: Counts of rows grouped by time frames What do I have:
| id | timestamp  |
| ---| -----------|
| 1  | 1453212172 |
| 2  | 1453512172 |
| 3  | 1453712172 |
...

I want to get the count of entries grouped by time frames. Starting with 2015-11-01 20:00 I need the count for a group lasting 3 days:
| count | from       | to
| ------| -----------|-----------
| 34    | day 0, 8am | day 3, 8am
| 10    | day 3, 8am | day 6, 8am
| 56    | day 6, 8am | day 9, 8am
...

What I found were only for whole days. Is there a nice way to do that on the database layer? The only way I get it running were with multiple queries and calculate it on the application layer, but it's too expensive.

A: Since you're storing the data as timestamps, surely you can do this with a simple calculation, as 3 days is:
24 x 60 * 60 = 86400

In conjunction with a stored procedure which gets the minimum and maximum timestamps for the dataset, converts them to integers and then uses a WHILE loop to iterate through the data until it reaches the end, returning a summary row as you need:
CREATE OR REPLACE FUNCTION get_counts() RETURNS TABLE(row_count integer, from_time integer, to_time integer)
AS $BODY$
  DECLARE
    current_timestamp INTEGER;
    maximum_timestamp INTEGER;
    next_timestamp INTEGER;
  BEGIN
    current_timestamp := (SELECT CAST(EXTRACT(epoch FROM MIN(timestamp)) AS integer) FROM test);
    maximum_timestamp := (SELECT CAST(EXTRACT(epoch FROM MAX(timestamp)) AS integer) FROM test);

    WHILE current_timestamp < maximum_timestamp LOOP
      next_timestamp := current_timestamp + 86400;
      RETURN QUERY EXECUTE (SELECT COUNT(*) AS row_count, current_timestamp AS from_time, next_timestamp AS to_time FROM test WHERE CAST(EXTRACT(epoch FROM(timestamp)) AS integer) >= current_timestamp AND CAST(EXTRACT(epoch FROM(timestamp)) AS integer) < next_timestamp);
      current_timestamp := next_timestamp;
    END LOOP;
  END
$BODY$ LANGUAGE plpgsql;

That procedure is untested and will probably not work out of the box, but gives you an idea of what you can do. You can then convert back from the integer timestamp to a true timestamp on your app side.


text:
Q: DJANGO - How to generate a form for a model not known in advance because of the contentType instance I have the following model and it's form:
class Project(models.Model)

class ProjectForm(forms.ModelForm)
    class Meta:
        Model = Project

So it's easy to create a form by instantiating:
form = ProjectForm()

But in my case, I have several models aside from "Projects", and I don't know in advance for which of these models I will need to create the form.
So I would like to create the form from the ContentType instance of the Project model.
In other words, I'm looking for something that looks like:
myproject = Project()
form = createform(myproject.ContentType)

A: Presumably you have a certain limited selection of models that might be used. The simplest way is just to create form classes for each of them, then choose the one you need from a dictionary:
MODEL_FORMS = {
    MyModel: MyModelForm,
    MyOtherModel: MyOtherModelForm
}

my_form_class = MODEL_FORMS[my_project.content_type]
my_form = my_form_class()

A: Unfortunately, this was the best I could find - but a combination of get_model and form_for_model should do the trick. You'll need to use get_model to load up the model type you want to work on, and then form_for_model to get a form for that model.
Edit: Daniel's solution is a much better one if you know what models you're dealing with.

A: Thank you to both of you, this helps a lot !
I will go with Daniel's solution as I have a limited number of models.
I think maybe I will need to add model_class() to "my_project.content_type.model_class()"  in order to get the model class (to be checked) ?
Just for the record, I had managed to make something work with model formset factories :
from django.forms.models import modelformset_factory
ProjectFormSet = modelformset_factory(my_project.content_type.model_class())
my_form = ProjectFormSet()

but this form would of course not get all the customisations made in my model forms... so that was not a good solution.


text:
Q: Как выровнять иконку в заголовке таблицы QTableWidgets? Есть таблица на Pyqt5, пытаюсь вставить иконку в horizontalHeader, в данный момент нашел только данное решение но никак не могу выровнять иконку по центру:
self.tableWidget.horizontalHeaderItem(2).setIcon(QIcon('IconGraph.png'))

Исходный код приложения:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(320, 120)
        MainWindow.setMaximumSize(QtCore.QSize(320, 120))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(1, 1, 1, 1)
        self.verticalLayout.setSpacing(1)
        self.verticalLayout.setObjectName("verticalLayout")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setRowCount(3)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        self.verticalLayout.addWidget(self.tableWidget)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.tableWidget.verticalHeaderItem(1)
        item.setText(_translate("MainWindow", "2"))
        item = self.tableWidget.verticalHeaderItem(2)
        item.setText(_translate("MainWindow", "3"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "2"))
        self.tableWidget.horizontalHeaderItem(2).setIcon(QIcon('IconGraph.png'))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


text:
Q: Compiling netcat on AIX I have been trying to compile netcat.c on AIX for some time (using the command make aix), but the compiler gives me some weird feedback such as :
"netcat.c", line 117.12: 1506-275 (S) Unexpected text 'int' encountered.
when checked the file netcat.c at line 117, I would find the line (second line in code below):
#ifdef HAVE_BIND
extern int h_errno;
/* stolen almost wholesale from bsd herror.c */

even if I changed the int into char for the same of testing, save the file and re-run the command I get the same error
am I missing something in reading the error code?

A: If you're using xlc (especially older ones), it's normally caused by declarations after statements, something like:
i = i + 1;
int x;

You probably need to give us a little more context, such as 10 or so lines before the error line.
My advice would be to get gcc running on that box if you are using an older xlc. IBM makes some fine compilers now but the earlier ones weren't so crash hot (in my opinion).

A: When innocent-looking code produces bizarre errors, try running the code through the C preprocessor stage, and looking at it then. Sometimes macros do very funny things.
Also note that a problem on an earlier line (missing semicolon, etc.) might produce an error message on a later line.

A: The post maybe already a little outdated, but just in case someone else comes along with the same problem ...
Here (AIX 7.1) h_errno is defined as macro in netdb.h.
/usr/include/netdb.h:#define h_errno   (*(int *)h_errno_which())

Therefore the declaration in netcat.c line 117  does not work.
I just changed the line into
#ifndef h_errno
extern int h_errno;
#endif

and the compilation worked smoothly.

A: @A.Rashad, I moved the HAVE_BIND #ifdef block from line 117 to line 30 which is just under the #include "generic.h" declaration. This permitted the xlc to compile it. The (S)yntax error messages are gone and while there are some (W)arning messages, I do get an nc binary at the end!
hth,
Kevin


text:
Q: Unable To Retrieve Exact Chinese Characters in LOTus Notes IDE 8.5 I am using Eclipse Integrated in Lotus Notes IDE.
I am unable to retrieve exact chineese characters for the Document or attachment name of Embedded Object.i.e., Document.getItemValueString(); or EmbeddedObject.getName() instead of chineese characters i am seeing ???.
Please find below code snippet for more information.And let me know is there is away retrieve exact chineese/Russian/Korean/arbic from the document or from attachment name i.e, from EmbeddedObject.getName also please confirm whether the above mentioned issue(representing  chineese/Russian/Korean/arbic from the document or from attachment name i.e, from EmbeddedObject.getName ) is actually supported by Lotus Notes 8.5.
Session session = getSession();
      AgentContext agentContext = session.getAgentContext();

      Database db = agentContext.getCurrentDatabase();
      Document doc = db.getProfileDocument("TestForm", null);
      String str =doc.getItemValueString("filename");
System.out.println("Doc name sys"+str);

      PrintStream ps = new PrintStream(System.out, true, "UTF-8");

      ps.println("Doc name"+str);

output is
Doc name sys????
Doc nameä½ å¥½ä½ å¥½

What is the solution?


text:
Q: Why is Enum string value inconsistent? I have a enum, with members that are same value, but when I tried to print them as strings, I expected to see it uses the first defined value, that is, for Buy and Bid it prints Buy, and for Sell and Ask it prints Sell, but the test shows it looks they are randomly chosen, as it is neither first nor last for all values. so why is this inconsistence?
Sample code:
using System;

public enum OrderType
{
    Buy,
    Bid = Buy,
    Sell,
    Ask = Sell
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        OrderType o = OrderType.Buy;
        Console.WriteLine("{0}: {1}", (int)o, o);
        OrderType o2 = OrderType.Bid;
        Console.WriteLine("{0}: {1}", (int)o2, o2);
        OrderType o3 = OrderType.Sell;
        Console.WriteLine("{0}: {1}", (int)o3, o3);
        OrderType o4 = OrderType.Ask;
        Console.WriteLine("{0}: {1}", (int)o4, o4);
    }
}

Output:
Buy: 0 - Bid
Bid: 0 - Bid
Sell: 1 - Sell
Ask: 1 - Sell

A: Rather than being inconsistent, you should think of this as being a case of a selection being made arbitrarily.
You have made an enum in which two enum values stand in for the integer 0, and two values stand in for the integer 1. So when you ask "what enum value is associated with 0?" there are two possible answers.
The designers of C# could have answered this question by:

*

*throwing an error

*answering with the enum value that appears first in the declaration

*answering with the enum value that appears last in the declaration

*answering with an arbitrary value

Language designers will sometimes go the "arbitrary" route because it leaves more room for optimization. For example they could put the integer-to-enum mapping in a hash table or something and let the lookup return whatever is most convenient. And this allows them to change their mapping strategy later on and return something else without breaking behaviors relative to the spec.
If they defined the language to produce a value that was sensitive to the declaration order, it might have put a little burden on the implementation and basically ended up with one more rule to keep track of.
I actually would have expected the answer to be "choose an arbitrary value" so I am kind of happy to see C# fits in with my expectations. But we're all different and yes, some people will be surprised. :)


text:
Q: Difference between horizontal and vertical microcode I know what are microcoded instructions in computer architecture and design but was confused between these two terminologies. Went through several articles but was unable to get the clarity.
Some of them said:
Horizontal Microcodes : In this types of code the micro code contains the control signal without any intermediary.
Vertical Microcodes :  In case of vertical micro code every action is encoded in density.
The terminologies are above my understanding and would appreciate a simpler explanation.

A: Well, Wikipedia gives a good introduction.
Assume for the sake of simplicity that we have just two MUXs in the CPU data-path, say A and B.
And that each MUX is controlled by 4 bits.
A horizontal microcoded instruction would contain the select value for both MUXs A and B:
     4-bit   4-bit
     ______ _______
    |  A   |   B   |
     ¯¯¯¯¯¯ ¯¯¯¯¯¯¯
       |       |
       |       |
    ___V_   ___V_
   |MUX A| |MUX B|
    ¯¯¯¯¯   ¯¯¯¯¯

The bits from the instruction are fed directly into the select lines of the two MUXs
A vertical microcoded instruction would instead make use of a DEMUX, a "meta-DEMUX", that is used to select which MUX to drive.
 1

 b
 i
 t  4-bit
 _ _______
|M|  SEL  |
 ¯ ¯¯¯¯¯¯¯
 |    | 4-bit DEMUX input
 |   _V_                          _______
 '->| D |  -- 4-bit output 0 --> | MUX A |
    | M |'                        ¯¯¯¯¯¯¯
    | U |.                        _______
    | X |  -- 4-bit output 1 --> | MUX B |
     ¯¯¯                          ¯¯¯¯¯¯¯

So there is an intermediary combinatoric circuit between the instruction signal bits and the driven components.
You can already see that vertical microcode has shorter instruction but a longer propagation time.


text:
Q: How to sort a column of data frame based on the index of the original data in R? This may be very simple to achieve, but has me stumped.
I have a data frame:
    chip1 chip2
P1  1.57  2.13
P2  2.04  1.92
P3  1.90  2.11
P4  1.48  2.24

The next step for quantile normalization is to sort each column and then generate the row wise mean, like this:
   chip1 chip2     M
P1  1.48  1.92 1.700
P2  1.57  2.11 1.840
P3  1.90  2.13 2.015
P4  2.04  2.24 2.140

Then the final normalized data is:
       chip1  chip2
   P1  1.840  2.015
   P2  2.140  1.700
   P3  2.015  1.840
   P4  1.700  2.140

The normalized data is generated using the M column of the previous data frame which is reordered based on chip1 and chip2 from the first data frame. How can I order the M column using the index from the original columns? I'm little lost?
Thank you.

A: nrm <- rowMeans(sapply(df, sort))
sapply(df, function(x) nrm[rank(x)])

produces:
     chip1 chip2
[1,] 1.840 2.015
[2,] 2.140 1.700
[3,] 2.015 1.840
[4,] 1.700 2.140

A: Based on what you have mentioned, I wish it is what you mean.
> X = cbind(rnorm(5, 1), rnorm(5,0))
> X
          [,1]         [,2]
[1,] 2.2629543 -1.539950042
[2,] 0.6737666 -0.928567035
[3,] 2.3297993 -0.294720447
[4,] 2.2724293 -0.005767173
[5,] 1.4146414  2.404653389
> Y = apply(X,2,sort)
> cbind(Y, rowSums(Y))
          [,1]         [,2]       [,3]
[1,] 0.6737666 -1.539950042 -0.8661834
[2,] 1.4146414 -0.928567035  0.4860744
[3,] 2.2629543 -0.294720447  1.9682338
[4,] 2.2724293 -0.005767173  2.2666621
[5,] 2.3297993  2.404653389  4.7344527
> X[order(rowSums(Y)),]
          [,1]         [,2]
[1,] 2.2629543 -1.539950042
[2,] 0.6737666 -0.928567035
[3,] 2.3297993 -0.294720447
[4,] 2.2724293 -0.005767173
[5,] 1.4146414  2.404653389


text:
Q: Take next parameter as field width in String.Format In C#, I have a width I want to use for some strings, but I won't know that width until runtime.  I'm doing something like this:
string.Format("{0, " + digits + "}", value)  // prints 123 as "  123"

Is there a string formatting directive that lets me specify this without smashing my own format string together like this?
I looked around on MSDN for a little while and I feel like I'm missing a whole chapter on format strings or something.

A: You can use the PadLeft and PadRight methods:
http://msdn.microsoft.com/en-us/library/system.string.padleft%28VS.71%29.aspx

A: you can do something like
string test = valueString.PadLeft(10,' ');

or even sillier
string spaces = String.Concat(Enumerable.Repeat(" ", digits).ToArray());

A: The functions mentioned by others will work, but this MSDN page has a more general solution to formatting that changes at runtime:
Composite Formatting
They give examples much like yours.
Edit: I thought you were trying to solve the general case of composing a format string at runtime. For example, if there were no built in PadLeft(), you could do this:
    int myInt = 123;
    int nColumnWidth = 10;

    string fmt = string.Format("Price = |{{0,{0}}}|", nColumnWidth);

    // now fmt = "Price = |{0,5}|"

    string s = string.Format(fmt, myInt);

You can even do all that in one line, but it's ugly:
    string s = string.Format(
            string.Format("Price = |{{0,{0}}}|", nColumnWidth),
            myInt);

A: Take a look at PadLeft:
s = "123".PadLeft(5);  // Defaults to spaces
s = "123".PadLeft(5, '.');  // Pads with dots

A: Perhaps this will help with your research on formatting:
Formatting Types

Composite Formatting
However, I don't think you're going to do much better than this, as the alignment parameter must be part of the format string and does not seem to be represented by a property.

A: Probably overkill but just to illustrate a way to encapsulate the format specification and use an overload of String.Format that accepts an IFormatProvider.
class Program
{
    public static void Main(string[] args)
    {
        int digits = 7;
        var format = new PaddedNumberFormatInfo(digits);
        Console.WriteLine(String.Format(format, "{0}", 123));
    }
}
class PaddedNumberFormatInfo : IFormatProvider, ICustomFormatter
{
    public PaddedNumberFormatInfo(int digits)
    {
        this.DigitsCount = digits;
    }

    public int DigitsCount { get; set; }

    // IFormatProvider Members
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }
    // ICustomFormatter Members
    public string Format(string format, object arg, IFormatProvider provider)
    {
        return String.Format(
            String.Concat("{0, ", this.DigitsCount, "}"), arg);
    }
}

A: I posted a CodeProject article that may be what you want.
See: A C# way for indirect width and style formatting.
Basically it is a method, FormatEx, that acts like String.Format, except it allows for indirect alignment and formatString specifiers.
FormatEx("{0,{1}:{2}}", value, width, formatString);

Means format the value of varArgs 0, in a field width specified by varArgs 1, using a formattingString code specified by varArgs 2.
Edit: Internally, it does what many others have suggested in their answers.  I've just wrapped the parsing and determination of the final values to use for alignment and formatString.  I also added a "center alignment" modifier.
-Jesse

A: String has a constructor that creates a string with a given character repeated n times.
https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx
// prints 123 as "  123"
string.Format(new string(' ', digits) + "{0}", value)


text:
Q: select a part of the image by putting 4 points on the image to define using JQuery I want to select a part of an image not with the common method like this  but putting 4 points to define the image. These 4 points represent the vertices of the rectangle.
Do you have some idea of how can I proceed ?

A: var x = 0;
$(".yourclass").click(function(event) {x++;
if(x==1){
    X1 = event.clientX;
    Y1 = event.clientY;
}
else{
    X2 = event.clientX;
    Y2 = event.clientY;
}
});

in this way you can get the x,y axis of both points.
Make a div and make its background image this with background positions as these values.. Hope that would help.


text:
Q: Display post list within category list sorted by name I'm trying to display a list of categories sorted by name and all posts of each category inside it. Like this:

*

*Category A
Post B
Post F
Post Z

*Category B
Post A
Post C
Post G

*Category C
Post D
Post E
Post H

I managed to display categories list, but it is only sorted by post names, like this:

*

*Category B
Post A
Post C
Post G

*Category A
Post B
Post F
Post Z

*Category C
Post D
Post E
Post H

This is my code:

$args = array('post_type' => 'projetos');
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <?php foreach((get_the_category()) as $category) {echo $category->cat_name . ' ';} ?>

    <a href="<?php the_permalink() ?>"><?php the_title(); ?>

    <?php
    endwhile;
}

wp_reset_query();

?>

How can i sort it properly?

A: EDIT:
Well, it seems the following approach is a bit DB consuming. Pieter Goosen posted a very interesting alternative. Since this approach has already been accepted as a correct answer I don't know, it it is possible to mark this question still as a duplicate. I flagged my answer so a moderator might have a look. Thanks.

I first collect all data in an multidimensional array. The subarrays are the categories.
So, I first load all categories with get_categories(). They are ordered by title. I load all of them into $post_categories while the array key is the ID of the category. The category information like the name will be stored in $post_categories[ category_id ]['cat'].
After this I run the query, but I make sure, it is ordered by title. Now, I get all the categories the post is attached to and I save the post in $post_categories[ category_id ]['posts'].
Now I have an multidimensional Array, which I just output with two foreach() loops.
$args = array(
        'type' => 'projetos'
    );
    $all_categories = get_categories( $args );
    $post_categories = array();
    foreach( $all_categories as $category )
        $post_categories[ $category->term_id ]['cat'] = $category;
    $args = array(
        'post_type' => 'projetos',
        'orderby' => 'title',
        'order' => 'asc'
    );
    $my_query = new WP_Query( $args );
    if( $my_query->have_posts() ) {
        while ($my_query->have_posts()){
            $my_query->the_post();
            $p = array();
            $p['permalink'] = get_the_permalink();
            $p['title'] = get_the_title();
            foreach( get_the_category() as $category )
                $post_categories[ $category->term_id ]['posts'][] = $p;
        }
    }

    foreach( $post_categories as $cat ){
        if( ! isset( $cat['posts'] ) || count( $cat['posts'] ) == 0 )
            continue;
        ?>
        <?php echo $cat['cat']->name; ?>

        <?php
        foreach( $cat['posts'] as $post ):

        ?>
        <a href="<?php echo $post['permalink']; ?>"><?php echo $post['title']; ?>

        <?php endforeach;
    }

    wp_reset_query();


text:
Q: Calling a JavaScript function, which is inside a string, and concatenating params with a variable? Is there a way to achieve this? My code below doesn't work:
$("#template-1")
    .find("span")
    .html("
<input type='file' onchange='LoadImage(this,"+
        canvas +")' id='t1-1-img-header'/><canvas class='dialogCanvas'"+
        "width='475' height='250' style='border: 1px solid #555; "+
        "margin-top:10px'></canvas>
");

On the code above, I'm trying to pass "this" and a variable, which is filled somewhere else, to the function "LoadImage". Everything is being created dynamically and is inside this long string.
Thanks in advance and sorry if it was a very stupid question.
Edit: The variable "canvas" is a string with an id name
I'm getting somewhere else. And it's the id for a canvas element.
Edit 2:
I'm sorry to be answering to my own post, but I couldn't flag the answer that helped me the most (by @Santiago Rebella), so I'm copying it here.
onchange='LoadImage(this,\""+ canvas +"\")'

Turns out that, by escaping it, the code worked. Thanks!

A: The answer below assumes that canvas is a reference to a HTMLCanvasElement object.
You cannot store an object reference in a string. However you can always store something useful that allows to retrieve the object, like it's id, but there's a better solution.
Your main problem is that you are trying to deal with inline handlers, which should usually be avoided.
You can use jQuery to parse your HTML string, query the created DOM element for the element you are looking for and attach the event handler to it.
E.g.
var $myEl = $('
<input type="text">
')
    .find('input')
    .on('change', function (e) {
        console.log(this); //the input
        console.log(canvas); //use the canvas variable (not declared in this example)

        //if you want to access the canvas next to the input in your example
        //you could do $(this).next('canvas');
    });

$('#content').append($myEl); //append your element rather than setting innerHTML


text:
Q: What is another word for a person who loses admiration/love/respect towards someone or the act of losing said traits? I am looking for a more educated word than "Hater" that describes a person or type of person that at one point admired/respected you, but then for one reason or another, ended up hating/disliking/attacking you. Not necessarily betrayal either. Its more about the part where their emotion/mindset is going from admiration/respect/love to belittling/disrespect/hate towards a person. Adjectives are acceptable too.
A word for each scenario that it could be used in:

*

*You reject their love/admiration so they start hating you/attacking you instead

*You don't live up to their expectations so they don't admire/like you anymore

*Doing something that changed their initial impressions and feelings about you

A: They're disenchanted or disillusioned

Disenchanted: Disappointed by someone or something previously respected or admired; disillusioned.
Example: He became disenchanted with his erstwhile ally. [Lexico]


text:
Q: Extending Navbar with Page Resizing Twitter Bootstrap When I first installed twitter bootstrap and hadn't edited any Bootstrap code (the carousel) the navbar looked normal but it was a bit away from the edge.
And this is what it looked like when it was resized small:

Then when I changed the size of the navbar so it fit the entire page using CSS height and width it started glitching out:
When the browser wasn't resized it looked normal but if you made the browser smaller:

Also if the browser wasn't at the default size but it wasn't really small it would move away from the edge.
This is the code to make the collapsing function:
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

</button>

This is the CSS code for my navbar:
.navbar{position:relative;top:65px;height:75px;width: 100%;margin-bottom:20px;border:1px solid transparent}

How can I keep the collapsing thing and also make sure the navbar is always going from the edge to edge of the web page without it glitching out and the words disappearing and stuff like that?

A: As you use bootstrap you'll only need to remove "container" class from the parents of "navbar" in your html, that'll make the navbar goes full width


text:
Q: Cout prints so many times in the for loop I tried to write a program that gets the roots of a number for example if you entered 3 in the menu it would try to find the third root of your number so if you have entered 8, it would give you 2, but there is a problem. I am using a for loop and if I try to define an else for my condition in the loop it would print the cout as many times the loop is defined too. What should I do to fix this? Can someone please help me? Should I use while instead? And please keep your answers simple and obvious.
Here is my code:
system("cls");
    system("color 78");
    int roots;
    cout << "Which root are you trying to find out?" << endl;
    cin >> roots;
    switch (roots)
    {
    case 1:
    {
        system("cls");
        double po;
        cout << "Please enter the number you wnat to see its first root: " << endl;
        cin >> po;
        cout << "Your number's first root is: " << po << endl;
    Backhome();

    }
    break;
    case 2:
    {
    system("cls");
    double p;
    cout <<"Please enter the number you want to find its second root:"<< endl;
    cin >> p;
    cout <<"Your number's second root is: "<< sqrt(p) << endl;
    cout << "Your number's second root is: " << "-" << sqrt(p) << endl;
    Backhome();
    }
    break;
case 3:
{
    system("cls");
    double th;
    cout << "Please enter the number you want to find its third root: "<< endl;
    cin >> th;
    for (int i= -10000 ; i <= 10000; i++)
    {
        if ((i*i*i) == th)
        {
            cout << "Your number's third root is: " << i << endl;
        }
        else
        {
         cout << "Your number doesn't have a third root." << endl;
         }
    }
    Backhome();
}
break;
case 4:
{
    system("cls");
    double foot;
    cout << "Enter the number you want to see its fourth root: " << endl;
    cin >> foot;
    for (int i = -10000; i <= 10000; i++)
    {
        if ((i*i*i*i) == foot)
        {
            cout << "Your number's fourth root is: " << i << endl;
        }
        else
        {
         cout << "Your number doesn't have a fourth root." << endl;
         }
    }
    Backhome();
}
break;
case 5:
{
    system("cls");
    double pive;
    cout << "Enter the number you want to see its fifth root: " << endl;
    cin >> pive;
    for (int i = -10000; i <= 10000; i++)
    {
        if ((i*i*i*i*i) == pive)
        {
            cout << "Your number's fifth root is: " << i << endl;
        }

        else
        {
         cout << "Your number doesn't have a fifth root." << endl;
         }
}
    Backhome();
}

(Shortly, the problem is that the elses in the loops are printed as many times as the loop is defined and I don't want that to happen. I would appreciate your help.)

A: Your program can be quite shorter, you just need to power the number by 1/roots:
system("cls");
system("color 78");
int roots;
cout << "Which root are you trying to find out?" << endl;
cin >> roots;
system("cls");
double po;
cout << "Please enter the number you wnat to see its " << roots << "th root: " << endl;
cin >> po;
cout << "Your number's " << roots << "th root is: " << pow(po, 1.0/roots) << endl;
Backhome();

You'll probably have numerical errors here, like getting 1.9999 for the third root of 8, you just need to round the number to the nearest integer. I would do:
double result = pow(po, 1.0/roots);
int resultUp = ceil(result);
int resultDown = floor(result);
int nearestInt = resultUp;
if ((result - resultDown) < (resultUp - result))
     nearestInt = resultDown;

if (abs(pow(nearestInt, roots) - po) < 1e-6)
     result = nearestInt;

cout << "Your number's " << roots << "th root is: " << result << endl;
Backhome();


text:
Q: Gain names of the column based on comparision between tables My goal is to retrieve a result of the name of column based on similiar column from table Product_A and Product_B.
It doesn't matter if I gain the result in excel, notepad or table from sql server. The most important is to retrieve the result.
I don't know how to retrieve the result based on calculation with low usage of manual work?
Some criteria you need to take account to:

*

*The column must have the same datatype and name to be similiar

*I'm not interrested in retrieving the data from the column

*The table is created in a basic level. In reality, the table use 200 column.

The table is in SQL server 2008 R2
TABLE Product_A
(
   ProductID INT,
   ProductName VARCHAR(100),
   Rate MONEY,
   Action INT,
   MapINT,
)

TABLE Product_B
(
   ProductID INT,
   Count INT,
   ProductName VARCHAR(100),
   Rate MONEY
)

Requested result

       ProductID INT,
       ProductName VARCHAR(100),
       Rate MONEY,

A: This query will compare two tables and return only same-named columns of same datatype. If you need to find all matches accross database, comment out t1.name = condition.
select
      t1.name TableName,
      c1.name ColumnName,
      types.name,
      c1.max_length,
      c1.precision,
      c1.scale
 from sys.columns c1
inner join sys.columns c2
   -- Condition to join columns - same name, type, length, precision and scale
   on c1.name = c2.name
  and c1.system_type_id = c2.system_type_id
  and c1.max_length = c2.max_length
  and c1.precision = c2.precision
  and c1.scale = c2.scale
   -- Exclude template table
  and c1.object_id <> c2.object_id
inner join sys.tables t1
   on c1.object_id = t1.object_id
inner join sys.types
   on c1.system_type_id = types.system_type_id
inner join sys.tables t2
   on c2.object_id = t2.object_id
where t2.name = 'Product_B'
   -- remove if you want to search for matches in all tables
  and t1.name = 'Product_A'

Check the documentation on sys.columns and sys.tables.

A: Your requirements are not very clear but you might be referring to a UNION so you can get data from both tables which will give you the product information from each table in separate rows:
SELECT ProductId, ProductName, Rate
FROM Product_A
UNION
SELECT ProductId, ProductName, Rate
FROM Product_B

If you could edit your OP and post some sample data and your expected result then the query could be clarified.
If you know which table you want the data from Table A or B, then you could do a JOIN on the ProductName, but you need to decide which Rate and Product Id you want:
SELECT a.ProductId
    , a.ProductName
    , a.Rate
FROM Product_A a
JOIN Product_B b
    ON a.ProductName = b.ProductName


text:
Q: convert multiple list value into string inside multilple dictionary I have data which I have shortened for the understanding.
The actual data has 100k+ dict elements inside the parent list and each individual dictionary element has 50 different key-value pairs. They are unorganized and most of the values for keys are a list. I am trying to convert those internal lists to string in an efficient way possible.

listOfwords = [{"test": ["This" , "is", "a", "new", "program"], "checked": "yes"}, {"checked": "no", "test": ["This" , "was", "an", "old", "program"]}, {"test": ["This", "program"], "checked": "in progress"}, {"checked": "failed", "test": []}]

To convert the list to string, we definitely can use join and I was able to do the same. But as the actual data is too large, in my consideration too much of iteration will make the code look bad. Also with join I am referencing the delimiter as , and that changes the complete data when it comes out
>>> for i in listOfwords:
...     fullStr = ' '.join(i['test'])
...     i['test'] = fullStr
...
>>> print listOfwords
[{'test': 'This is a new program', 'checked': 'yes'}, {'test': 'This was an old program', 'checked': 'no'}, {'test': 'This program', 'checked': 'in progress'}, {'test': '', 'checked': 'failed'}]
>>>

Expected Output
[{"test":"This, is, a, new, program","checked":"yes"},{"checked":"no","test":"That, was, an, old, program"},{"test":"This, program,","checked":"in progress"},{"checked":"failed","test":""}]

A: It looks like you just need to change ' '.join(i['test']) to ', '.join(i['test']) to get what you want.
(Note the difference between ' ' and ', ' in terms of what you call .join() on.)


text:
Q: Why does the loop iterate beyond Integer.MAX_VALUE? Can someone explain why this code is an infinite loop on Java 7,8? The loop should stop when i = Integer.MAX_VALUE + 1 but it seems to deny the limit. Why does this happen?
public static void main(String[] args) {
    for (int i = Integer.MAX_VALUE - 100; i <= Integer.MAX_VALUE; i++);
}

A: *

*The value Integer.MAX_VALUE changes from 2147483647 to
-2147483648 i.e. Integer.MIN_VALUEwhen it overflows.

*Integer overflow occurs when the arithmetic operation tries to create value that is beyond reach of data type value range.

*In java integers have range from -2147483648 to 2147483647.

*In for loop when i becomes 2147483647 then i++ operation will try to increment its value by 1 which is not possible because range is only till 2147483647.

*So instead of having its value as 2147483648 it will go back to starting value i.e. -2147483648

*Hence i <= Integer.MAX_VALUE always becomes true.

*As condition never becomes false, loop will continue till infinity.

You can check value overflow by simply writing your code as below.
for (int i = Integer.MAX_VALUE - 100; i <= Integer.MAX_VALUE; i++){
        System.out.println(i);
}

You will see below output.
2147483645
2147483646
2147483647
-2147483648
-2147483647
-2147483646

A: Look at
 i <= Integer.MAX_VALUE

This is always true. If i = Integer.MAX_VALUE+1 then it will overflow, and become negative.
Do this:
 System.out.println(Integer.MAX_VALUE+1)

A: Because when i reaches being equal to Integer.MAX_VALUE then it becomes Integer.MAX_VALUE + 1 which becomes negative
Better would be
for (long i = Integer.MAX_VALUE - 100; i <= Integer.MAX_VALUE; i++)

A: You expect the loop to run till i <= Integer.MAX_VALUE and stop as soon as it becomes Integer.MAX_VALUE + 1, i.e., 2147483648. However, THAT DOES NOT HAPPEN because whenever you add something to Integer.MAX_VALUE, say x, the calculation takes the form:
Integer.MIN_VALUE + x - 1;

Since int cannot store beyond 2147483647 (and of course beyond -2147483648), this thing is done to make sure that there's no overflow. So, after 2147483647, i becomes -2147483648, which is obviously less than +2147483647 and thus, it is an infinite loop.
If you want the loop to iterate in that range (i.e., you just wanna use the values), you can make use of a type cast between long and int like this:
for(long i = (long)Integer.MAX_VALUE - 100; i<= (long)Integer.MAX_VALUE; i++){
    //to use i as an int, type cast from (long) to (int)
}


text:
Q: Why postgresql planner generates different executions between linux and Windows We use Postgresql locally with very large queries (joins, subrequests and recursion).
On windows, the requests are executed in 4 to 8 seconds depending on the machines tested.
This time is acceptable. But on linux machines, we go to 3minutes 30 minimum for the same queries and the same dataset.
We don't understand why changing OS degrades performance so much.
There is the request,
the explain(analyze, buffer) on linux
and on windows.
The request is generated by our tool, so we are not looking to correct this request. We can install Windows Server for the database, but we hope you can help us figure out why.
We have tested the following leads without success:

*

*hardware differences (all machines have the same RAM, similar SSDs and processors)

*the health of the disks and the RAM of the machines

*all configurations and versions of postgresql instances are the same

*the maintenance operations (vacuums and analyses) have been carried out.

*Datas are the same across instances (export and imported with pgAdmin)

Do you have any idea where this could come from ?
Why postgresql generates plans with totally different execution times depending on the OS ?

A: On Linux, essentially all (204015.385 out of 217006.663 ms) of the time is spent on JIT (just in time compilation) in a vain attempt to make things faster. Just turn off jit, it is rarely useful in my experience.
On Windows, you probably have the fortune of not supporting JIT in the first place.


text:
Q: How can I add New List to my MailChimp Account By programming in PHP? I have mailchimp account, I would like to add new list to my mailchimp account using PHP Library for MailChimp.
I have coded the following for add new Group to the given list.
$mailChimp = new MCAPI($api_key);
$mailChimp->listInterestGroupAdd($mylistId, $group_name);

above code is use for Add new Group into the existing List.
Can I add New List, what is the method available to add new List?
Can I use like this?
$mailchimp->listAdd($listname);

Here is the documentation of Mailchimp API v1.3 and all the List related functions But I have not get any method which will allow us to add new List.

http://apidocs.mailchimp.com/api/1.3/#listrelated

A: It looks like the MailChimp v1.3 API is deprecated. You should use the newer v2.0 version. I checked the API Documentation. I couldn't find the function that you were looking for.

A: I think this can not be done using the API.
You can make list as that you wanted in web-app and also check the group to structure the list data.


text:
Q: Un familiar error in asp.net when an event click..Failed to Load View State Server Error in '/DIY' Application.
Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
Can anyone please advice me w/ this error I'm using asp.net.

A: I've seen this happen when javascript is modifying server-side HTML controls (runat="server") on the page prior to postback.
For example, if you're modifying an asp:DropDownList's items via javascript.
If you post the code of the page having issues, you may get more specific answers.


text:
Q: Kubectl : Could not resolve host I created one node and I'm running microk8s. I created one Pod and 3 replicasets. I can access trought Cluster IP. But I don't know how to access through the name... Please help me. I'm new in Kubenetes.

*

*I create

microk8s kubectl create deployment httpenv --image bretfisher/httpenv

*Scale

microk8s kubectl scale deployment/httpenv --replicas=3

*Expose

microk8s kubectl expose deployment/httpenv --port 8888

*Show Info

microk8s kubectl get all

NAME                          READY   STATUS    RESTARTS   AGE
pod/httpenv-bd844d85f-9xk9l   1/1     Running   0          18m
pod/httpenv-bd844d85f-jf85j   1/1     Running   0          18m
pod/httpenv-bd844d85f-p5kzg   1/1     Running   0          18m

NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
service/httpenv      ClusterIP   10.152.183.91   <none>        8888/TCP   13m
service/kubernetes   ClusterIP   10.152.183.1    <none>        443/TCP    24h

NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/httpenv   3/3     3            3           18m

NAME                                DESIRED   CURRENT   READY   AGE
replicaset.apps/httpenv-bd844d85f   3         3         3       18m

*Try to access

From node :
curl -i 10.152.183.91:8888

   HTTP/1.1 200 OK

curl -i httpenv:8888

   curl: (6) Could not resolve host: httpenv

A: You can access the service in 3 ways, i just ran your example in my own microk8s cluster.

*

*Port forward traffic from 8888 to you localhost on any port(ex: i have forwarded to 8888).

*If you want to access the service from within the cluster, you can access the service from any pod running in your cluster(security issue though, can be handled using policies etc).

*You can conver the service from type: ClusterIP to NodePort

According to the deployment you have given above, which i ran on my local,  below are the pods running. In the port-forward command below, we are routing all the traffic from microk8s cluster on port 8888 to your localhost 8888. You can then use your browser and navigate to http://localhost:8888, you will see the output there.
k get po
httpenv-6fdc8554fb-j9q65   1/1     Running   0          14m
httpenv-6fdc8554fb-4fzr8   1/1     Running   0          14m
httpenv-6fdc8554fb-bsxgw   1/1     Running   0          14m

k port-forward httpenv-6fdc8554fb-j9q65 8888:8888 &

curl localhost:8888
Handling connection for 8888
{"HOME":"/root","HOSTNAME":"httpenv-6fdc8554fb-j9q65","KUBERNETES_PORT":"tcp://10.152.183.1:443","KUBERNETES_PORT_443_TCP":"tcp://10.152.183.1:443","KUBERNETES_PORT_443_TCP_ADDR":"10.152.183.1","KUBERNETES_PORT_443_TCP_PORT":"443","KUBERNETES_PORT_443_TCP_PROTO":"tcp","KUBERNETES_SERVICE_HOST":"10.152.183.1","KUBERNETES_SERVICE_PORT":"443","KUBERNETES_SERVICE_PORT_HTTPS":"443","PATH":"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}%

*

*To access the service within your microk8s cluster, we will run a simple busybox container.

k run -i --tty bb7 --image=busybox -- sh
# curl  http://httpenv:8888
{"HOME":"/root","HOSTNAME":"httpenv-6fdc8554fb-bsxgw","KUBERNETES_PORT":"tcp://10.152.183.1:443","KUBERNETES_PORT_443_TCP":"tcp://10.152.183.1:443","KUBERNETES_PORT_443_TCP_ADDR":"10.152.183.1","KUBERNETES_PORT_443_TCP_PORT":"443","KUBERNETES_PORT_443_TCP_PROTO":"tcp","KUBERNETES_SERVICE_HOST":"10.152.183.1","KUBERNETES_SERVICE_PORT":"443","KUBERNETES_SERVICE_PORT_HTTPS":"443","PATH":"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}#

*

*option 3 is to change the service type from "ClusterIP" to "NodePort" and you can access the service outside of the microk8s cluster. Get your local-ip using ifconfig command and curl the node port.

forex: curl http://local-ip:31223
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2021-11-03T09:55:20Z"
  labels:
    app: httpenv
  name: httpenv
  namespace: default
  resourceVersion: "2013136"
  selfLink: /api/v1/namespaces/default/services/httpenv
  uid: 908f4bbd-fef2-4435-b8c4-a80796e03b13
spec:
  clusterIP: 10.152.183.170
  clusterIPs:
  - 10.152.183.170
  externalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - nodePort: 31223
    port: 8888
    protocol: TCP
    targetPort: 8888
  selector:
    app: httpenv
  sessionAffinity: None
  type: NodePort

 k get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
httpenv      NodePort    10.152.183.170   <none>        8888:31223/TCP   22m

A: You can access the service from any pod running in your cluster so for that you need to create a pod first on it because our cluster is not running on our host same as our docker desktop running on WINDOW/MAC doesn't run on it instead it is running on small Linx VM. So for curl just run a pod:
kubectl run tmp-shell --rm -it --image bretfisher/netshoot -- bash

curl -i httpenv:8888


text:
Q: php slim duplicate response body data I created a PHP API using Slim framework. The issue is when I moved the API to a new server I started getting issue with the response. The data in the response body is getting duplicated!

For example instead of getting this once in the response:

{data: [{ username: 'someone', password: 'something' }] }

 I'm getting this:

{data: [{ username: 'someone', password: 'something' }] }
  {data: [{ username: 'someone', password: 'something' }] }
  {data: [{ username: 'someone', password: 'something' }] }

It's happening on every response to any route.
Even the page not found it display twice.

here's whats in my .htaccess:

RewriteEngine On  RewriteBase /  RewriteCond
  %{REQUEST_FILENAME} !-f  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

A: Turned out I had my index.php file added inside my routes folder as well by mistake.
This might as well occur if you had multiple $app->run();
Slim Framework Rest service getting output twice


text:
Q: Phonegap - Add mp3 files to my app build I have made a custom player that plays mp3 media files from a directory on the phone(sdcard, root and so on).
I want to encapsulate my mp3 files into my application, I've tried copying the files into my project root folder, I've created a new directory and copied them there, but after I build my .zip file on the build.phonegap site and I download the .apk file I have only:
assets/www/ and some .js files/index.html . My .mp3 files are nowhere to be found in the www folder.
If I go one level back I have a startup.zip file and if I open it I can find my files, but there are inexistent in the www folder.
Can someone tell me what structure do I have to respect, or how I have to build my app so that my .mp3 files are included in the www folder, so I can access them in my app.

A: I had a similar problem on android.  I wrote this little function.
function getAudioFileName(audioFileName){
    if(isAndroid()){
        //LOG("It is android so changing fileName");
        return "/android_asset/www/" + audioFileName;
    }
    //LOG("Not android so leaving fileName");
    return audioFileName;
}

all of my sound files are in a sound directory under www.  It is important to set the permissions to read write otherwise it doesn't get copied over.


text:
Q: Coffeescript If works, but Else does not This is the partial that is called by the view:

  <%= link_to "#{key.name} (#{key.description})", key %> (<%= key.id %>)

    Created <%= time_ago_in_words(key.created_at) %> ago.

  <% if key.chords.count > 0 %>
    <%= link_to "show chords", '#', class: "showremovechords" %>
     //
  <% end %>
      <%= link_to "remove", key, method: :delete %>

    <% if key.chords.count > 0 %>

        <%= render key.chords %>

    <% end %>

This is the jQuery (using CoffeeScript) that toggles whether or not to display the div class= 'chordsholder' when the "show chords" button is clicked.
jQuery ->
  toggleChords = (e) ->
    e.preventDefault()
    if $(@).text('show chords')
        $(@).text('hide chords')
    else
        $(@).text('show chords')
    $(@).closest('li').find('.chordsholder').slideToggle()

  $('.showremovechords').click toggleChords

The div starts hidden, and the link starts with the text 'show chords'
The toggle of the div's visibility works, and the text changes to 'hide chords' when it is first clicked, but the ELSE portion of the statement does not work, so the text does not change back to 'show chords' when the div is hidden. Any ideas why this might be happening?
Thanks

A: In your code:
if $(@).text('show chords')

sets the value and the return value of the expression is always truthy.   So your else never executes. jqobject.text(something) is a setter. Instead you may want to compare the value..
So what happens here is, it will set the value to "show cords" due to the setter in your if condition and which inturn returns the jquery object which is truthy so it goes to your if block which then sets it to "hide cords".
Try
if $(@).text() === 'show chords'
        $(@).text('hide chords')
else
    $(@).text('show chords');

You can also do this way using the fn argument syntax of text (Unsure about the coffee syntax though).
$(@).text(function(_, curValue){
   return curValue === 'show chords' ? 'hide chords' : 'show chords';
})


text:
Q: JavaScript fetch to Spotify API returns response body with strange encoding / strange characters I am making a SvelteKit application which uses the Spotify API. Right now I'm trying to create a playlist through the API and grab the playlist ID from the response body. I am making a POST request to https://api.spotify.com/v1/users/myusernamehere/playlists with the following code:
// create playlist
const fetchUrl = PUBLIC_SPOTIFY_API_URI+`/users/${user_id}/playlists`
const headers = {
    'Authorization': authHeader,
    'Content-Type': 'application/json'
}
const createPlaylistResponse = await fetch(fetchUrl, {
    method: 'POST',
    body: JSON.stringify({
        name: 'Playlist Name',
        description: 'A description',
        public: false
    }),
    headers
})
if (!createPlaylistResponse.ok) {
    const err = await createPlaylistResponse.text()
    throw error(createPlaylistResponse.status, JSON.stringify(err))
}
console.log(createPlaylistResponse.status)

I know it works because I see the new playlist on my Spotify account, and I also receive a 201 Created response text every time. But like I said I need the playlist ID so I can actually add tracks to the playlist. The ID is included in the response body in JSON format, as described in the documentation. But createPlaylistResponse.json() fails to parse the response's body. Next I tried createPlaylistResponse.text() and it returns this:
���OO�0���)��i�T�T���mW��u2�c�)mQ�;��GiE�[��������"�K���5
P�2�4=s��j�@�xŘ�tc��-*Ŵ��Zj���@�u$ȍ�:
C!)?o
�D��dx�@���6}\O8����wq�L��.+��ɬ1�BU���YߊEF�t�����p�a=�l�S>��^��#%~���?���K?�`Ri ���P��=>��"�S�5�5���w���蔖2O�͝O,�+�4Ua+�;�g���hr�[�G��AQ������J�g�l�jQ�M�C��`�va�)�A�d�d@��9�:f���<lVq�q�¼�y9MnF�d��%�˸ �xG.�d\Ļ�n~=���ZM�sV��(LV���;�
�v`����XĠ��p0h��>ʻ�2M=lIE� *�����њ��{����z��7���<b}:

I tried making the request through Postman with the exact same parameters and I correctly received the response body in JSON format:
{
  "collaborative" : false,
  "description" : null,
  "external_urls" : {
    "spotify" : "https://open.spotify.com/playlist/JmaQTtPsnZ14Qo8FrcManM"
  },
  "followers" : {
    "href" : null,
    "total" : 0
  },
  "href" : "https://api.spotify.com/v1/playlists/JmaQTtPsnZ14Qo8FrcManM",
  "id" : "JmaQTtPsnZ14Qo8FrcManM",
  ...
}

I have made similar GET requests to Spotify API all throughout my app but now I'm running into this issue with a POST request and I am not sure what to do.
Here are the response headers if that's any help.


text:
Q: Will changing my GitHub username make websites hosted on GitHub Pages inaccessible? For example, will abc.github.io/verbose/ (abc being my current username) be changed to xyz.github.io/verbose/ when I change my username to xyz? Will it be automated through GitHub actions?

A: When you attempt to change your username on GitHub, they explicitly mention that no redirects for GitHub Pages will be set up. Therefore, all links pointing to oldname.github.io/verbose/ will no longer work. It is even possible for someone else to register an account (or organisation) using your old username and then host their website there.
Here is a screenshot of the dialog:


text:
Q: How to add the word Menu to a wordpress 2014 theme when in mobile sized width My wordpress is running a 2014 theme. I am hoping that I can add the word menu next to the lined menu for people who do not know that the lines are a menu. This menu with lines only shows when the site is sized down to the size of a mobile site. The website is dreamgardens.tlchatt.com . I have scoured the web to figure it out. I managed to get my own header image into the theme. Seems like it would be a simple task. I was able to make the area around the button larger in two different ways by changeing style.css .
 It looks like the change to the mobile menu occurs based on this Javascript.
( function( $ ) {
var body    = $( 'body' ),
    _window = $( window );

// Enable menu toggle for small screens.
( function() {
    var nav = $( '#primary-navigation' ), button, menu;
    if ( ! nav ) {
        return;
    }

    button = nav.find( '.menu-toggle' );
    if ( ! button ) {
        return;
    }

I am hoping to make the mobile menu have the text menu to the right of it much like this website http://chattanoogagb.kokofitclub.com/. I do not understand this code well enough to locate where the mobile re sized code is and alter it to include the text Menu.
The above Java Script and PHP refers to this style.css entry
.menu-toggle {
cursor: pointer;
font-size: 0;
height: 48px;
margin: 0;
overflow: hidden;
position: absolute;
top: 0;
right: 0;
text-align: center;
width: 48px;
}

.menu-toggle:before {
color: #fff;
content: "\f419";
margin-top: 16px;
}

The \f419 seems to refer to a style sheet genericons.css which has this code.
.genericon-menu:before {            content: '\f419'; }

I am wondering if there is a simple aditional line of code I can insert somewhere to place the word "Menu" somewhere near the mobile toggled menu button. Some kind of subtext or something would be fine.

A: This is not the most elegant way maybe to do this, but you need to change the following lines 1000-1004
 .menu-toggle:before {
    color: #fff;
    content: "\f419";
    margin-top: 16px;
}

to this
.menu-toggle:before {
    color: #fff;
    content: "MENU";
    font-weight: bold;
    font-size: 12px;
    margin-top: 16px;
}

Remember, this goes in your child themes' style.css. Don't edit the twentyfourteen theme directly.

A: Based on your site it is not responsive - so my assumption you have no media queries?  Any way I would use 'Responsive Select Menu' from the plugins library. Set it to 768px and you should be all good. Let me know how you get on :)


text:
Q: Reflecting text in java I am trying to make  a digital clock in this way:
As shown in the image 1 i want the clock to be reflected.

What i have tried:
I tried using java (Graphics2D)g by rotating the string and the using substring but i got this problem:

My code for this:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Calendar;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

  @SuppressWarnings("serial")
public class DigitalClock extends JPanel {

JLabel label = new JLabel();
int c = 0;
Font font = null;
JFrame frame = new JFrame();

//Constructor
public DigitalClock(){

    frame.setSize(700,500);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(this);
    frame.setVisible(true);

    DigitalThread();

}

//Paint Method
public void paintComponent(Graphics g){
     Graphics2D g2d = (Graphics2D)g;

     //The background
     g2d.setColor(Color.BLACK);
     g2d.fillRect(0,0,500,100);

     //Show Time
     g2d.setColor(Color.WHITE);
     g2d.setFont(new Font(g.getFont().toString(),10,15));
     g2d.drawString(timeNow(),100, 25);

     //Show time Reflected
     g2d.rotate(Math.PI,100,25);
     g2d.drawString(timeNowRot(timeNow()),45, 20);

}

//Change time Value with this Thread
 public void DigitalThread(){

      new Thread(new Runnable(){
          public void run(){

         boolean flag=true;
        while(flag==true){
        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        repaint();
        }

      }}).start();

  }

 //Return time
 public String timeNow(){

   return  zero(Calendar.getInstance().get(Calendar.HOUR_OF_DAY))+":"+
           zero(Calendar.getInstance().get(Calendar.MINUTE))+":"+zero(Calendar.getInstance().get(Calendar.SECOND));
 }

 //Return time reflected
 public String timeNowRot(String time){

     return   time.substring(time.length()-1,time.length())+time.substring(time.length()-2,time.length()-1)+":";
 }

 //Add Zero if value<10
 public String zero(int num){
     if(num<10)  return "0"+num;
     else  return ""+num;
 }

}
I can achieve this by using java 2d? is there a method to rotate a string again vertically so i have not this problem thanks..

A: Use scale(x, y) which multiplies the x and y coordinates.
g2d.scale(1.0, -1.0);
g2.drawString(....);
g2d.scale(1.0, -1.0); // Undo

This does a transformation where the y axis is reversed.
You could also use shear for a paralellogram look.
A g2d.scale(-1.0, 1.0); would draw the string backwards. Can be used in combination with the rotation.
It allt depends on the usage of any rotation and the order, how to scale. Without rotation: scale y by -1:
good
ƃooq

A: Actually i found the answer based n your answers thanks all:
It is and irony but the next day after the question i had a lesson at university about that...
Info about scaling:
 g2d.scale(1,-1);  /*scale  by y axes(Flipping vertical
                                                             |
                                    flip here (scale(-1,1) ) |   here it was
                                                    _ _ _ _ _|_ _ _ _ _
                                                             |
                                   flip here (scale(-1,-1) ) |   fliped here( scale(1,-1) )
                                                             |
                       */
g2d.drawString(timeNow(),10,-27);

I also added some more effect so the clock be more realistic like:
 g2d.setPaint(new GradientPaint(0,-15,color,0,-50,Color.BLACK));

A: Your link shows a clock face AND its reflection. If that's what you want to do then this is the way.
Draw the clock face into an Image, instead of direct to the Component. Then you render the resulting image into the component twice using drawImage - once the normal way, and once transformed so it looks reflected.
This uses slightly more memory, but only temporarily, and it saves you having to do the paint twice.
If you only want to draw the reflected clock face, then set the image transformation properties in the Graphics to get the reflection.
I'll leave the details as an exercise to the reader.


text:
Q: Cannot find the cause of Cycle Exception in simple model( MVC ASP.NET) I got a model where I have Business, Workers and Jobs, also there are WorrkerReports for a business in a specific Job for a Worker.
public class Business
{
    public int BusinessId { get; set; }

    public List<Job> jobs{ get; set; }
    public List<Worker> workers { get; set; }
}

public class Worker
{
    public int WorkerId{ get; set; }
    public string Name{ get; set; }
    public int BusinessId{ get; set; }
}

public class Inspector
{
    public int InspectorId { get; set; }
    public String Name{ get; set; }

}

public class Job
{
    public int JobId { get; set; }
    public string NameOfJob{ get; set; }
    public int BusinessId { get; set; }
}

public class WorkerReport
{
    public int WorkerReportId { get; set; }
    public int InspectorId { get; set; }
    public int JobId { get; set; }
    public int WorkerId { get; set; }

    public Job job{ get; set; }
    public Worker worker{ get; set; }
    public Inspector Inspector { get; set; }
}

But when the model is generating i got this error:
'FK_dbo.WorkerReports_dbo.Workers_WorkerId' on table 'WorkerReports' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I don´t understand why i am getting this error,because  i don´t see where the cycle is being produced. Have anyone some idea? Where is the circle being caused?
Thanks a lot, provide help to a dessesperated programmer.

A: You have two delete cascade path on WorkerReport.

*

*Business -> Worker -> WorkerReport

*Business -> Job -> WorkerReport

By default all the relationship are required and the convention enable all the delete cascade from OneToManyCascadeDeleteConvention. The solution is to remove at least one of the cascade manually from Worker or Job.
modelBuilder.Entity<WorkerReport>()
    .HasRequired(x => x.job) // HasOptional for nullable FK
    .WithMany()
    .WillCascadeOnDelete(false);

// modelBuilder.Entity<WorkerReport>()
//    .HasRequired(x => x.worker) // HasOptional for nullable FK
//    .WithMany()
//    .WillCascadeOnDelete(false);

Or just disable all delete cascade by removing the default delete cascade convention.
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

Put it inside the the DbContext class.
public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // here
    }
}


text:
Q: Split text by sentence but not by special patterns This is my sample text:
text = "First sentence. This is a second sentence. I like pets e.g. cats or birds."

I have a function which splits texts by sentence
library(stringi)
split_by_sentence <- function (text) {

  # split based on periods, exclams or question marks
  result <- unlist(strsplit(text, "\\.\\s|\\?|!") )

  result <- stri_trim_both(result)
  result <- result [nchar (result) > 0]

  if (length (result) == 0)
    result <- ""

  return (result)
}

which actually splits by punctuation characters. This is the output:
> split_by_sentence(text)
[1] "First sentence"            "This is a second sentence" "I like pets e.g"           "cats or birds."

Is there a possibility to exclude special patterns like "e.g."?

A: In your pattern, you can specify that you want to split at any punctuation mark that is followed by a space, if there is at least 2 alphanumeric characters prior to it (using lookaround). Which will result in:
unlist(strsplit(text, "(?<=[[:alnum:]]{3})[?!.]\\s", perl=TRUE))
#[1] "First sentence"                  "This is a second sentence"       "I like pets e.g. cats or birds."

If you want to keep the punctuation marks, then you can add the pattern inside the look-behind and only split on space:
unlist(strsplit(text, "(?<=[[:alnum:]]{3}[[?!.]])\\s", perl=TRUE))
# [1] "First sentence."                 "This is a second sentence."      "I like pets e.g. cats or birds."

text2 <- "I like pets (cats and birds) and horses. I have 1.8 bn. horses."

unlist(strsplit(text2, "(?<=[[:alnum:]]{3}[?!.])\\s", perl=TRUE))
#[1] "I like pets (cats and birds) and horses." "I have 1.8 bn. horses."

N.B.: If you may have more than one space after the punctuation mark, you can put \\s+ instead of \\s in the pattern

A: library(tokenizers)

text = "First sentence. This is a second sentence. I like pets e.g. cats or birds."
tokenize_sentences(text)

Output is:
[[1]]
[1] "First sentence."                 "This is a second sentence."      "I like pets e.g. cats or birds."


text:
Q: Help with a programming challenge I am trying to make the programming challanges from the book written by Steven S. Skiena and Miguel A. Revilla.
But I am already having problems with the first challenge called "The 3n+1 problem".
The challenge can be found here: http://www.programming-challenges.com/english/pdfs/110101.pdf
The solution I though of is.
#include <stdio.h>
#include <iostream>
#include <vector>

using namespace std;

int CalcCycleLenght(int n)
{
    int t = 1;
    while (n != 1)
    {
        if (n % 2)
        {
            n = 3 * n + 1;
        }else{
            n = n / 2;
        }
        t++;
    }
    return t;
}

int main(int argc, char* argv[])
{
    int i;
    int j;
    vector<int> vi;
    vector<int> vj;
    vector<int> vm;

    int p = 0;

    while (scanf("%d %d", &i, &j) != EOF)
    {
        vi.push_back(i);
        vj.push_back(j);
        int max = 0;
        int n;
        for (int t = i; t <= j; t++)
        {
            n = CalcCycleLenght(t);
            if (n > max)
                max = n;
        }
        vm.push_back(max);
    }

    for (int i=0; i < vi.size(); i++)
    {
        printf("%d %d %d \n", vi[i], vj[i], vm[i]);
    }

    return 0;
}

It compiles correctly (although I think I have one extra include) and the answers are correct according to the sample input and output. But the online judge says "wrong answer". I think my problem is the way I input or output the numbers.
[EDIT]
I Solved it. Seems that the problem was that sometimes i was bigger than j. I also removed the vectors and made the code more efficient. Here is the new main function.
int main(int argc, char* argv[])
{
    int i;
    int j;

    int a;
    int b;

    int max;
    int p;

    while (scanf("%d %d", &i, &j) != EOF)
    {
        if (i < j)
        { a = i; b = j; }
        else
        { a = j; b = i; }

        max = 0;
        for (int t = a; t <= b; t++)
        {
            p = CalcCycleLenght(t);
            if (p > max)
                max = p;
        }
        printf("%d %d %d\n",i,j,max);
    }
    return 0;
}

Thanks

A: You output an extra space at the end of each line. Try removing this space, as automated judging often fails on such things. Other than that, your algorithm looks correct to me.
By the way, there's no reason to put the numbers in vectors - you can just output the results for each line as you calculate them.
Edit: It isn't clear from the specifications if it's possible that i>j. Your code will output 0 in that case, so if removing the space doesn't help, you can try swapping i and j in that case so that you have meaningful output (just make sure you output i and j in the same order that you got them).
Edit 2: This is most likely the problem: You use an int in your calculations, which on most platforms can hold values up to 2147483647. But The calculation of the cycle length will require numbers greater than that (for example, for the initial value of 113383). If you use long long (assuming it's supported) you should be OK.

A: I don't think you're supposed to have a space between the third number and the newline.

A: The first mistake I noticed was near the end...
printf("%d %d %d \n", vi[i], vj[i], vm[i]);

should be...
printf("%d %d %d\n", vi[i], vj[i], vm[i]);

I didn't see any other mistakes but I didn't read the whole thing that carefully.
One other thing to note is they may not want a new line character (\n) at the end of the last line.


text:
Q: Lifetime of const references bound to destroyed stack variable I'm wondering if it's by chance a pointer to const reference bound to a destroyed stack variable can be working.
I read const reference lifetime is extended on rvalues, so this is "normal" const reference works but at the end of the ctor of Storage ref should be destroyed, isn't it ?

Does const reference lifetime is also extended because I retrieved it's address in a pointer or is this pure luck ?
Live example
#include <iostream>

class Storage
{
public:
    Storage(const int& ref)
    {
        p = &ref;
    }

    const int* Get() const
    {
        return p;
    }

private:
    const int* p;
};

int main()
{
    Storage* s = nullptr;

    {
        int someValue = 42;
        std::cout << &someValue << std::endl;
        s = new Storage(someValue);
    }

    const int* p = s->Get();
    std::cout << p << std::endl;
    std::cout << *p << std::endl;
}

It's also working with a struct Live example
#include <iostream>

struct Dummy
{
    int value;
};

class Storage
{
public:
    Storage(const Dummy& ref)
    {
        p = &ref; // Get address of const reference
    }

    const Dummy* Get() const
    {
        return p;
    }

private:
    const Dummy* p;
};

int main()
{
    Storage* s = nullptr;

    {
        Dummy dummy;
        dummy.value = 42;
        std::cout << &dummy << std::endl;
        s = new Storage(dummy);
    }

    const Dummy* p = s->Get();
    std::cout << p << std::endl;
    std::cout << p->value << std::endl;
}

A: Your s variable indeed has a dangling pointer as someValue has fallen out of scope. Your code therefore exhibits undefined behavior.
Your comment about "const reference lifetime is extended on rvalues" is true in some circumstances, but someValue is an lvalue.

A: The compiler probably assigns the stack space for all the local variables at the start, so someValue is still in the same place in memory even after it goes out of scope. Of course a different compiler might do something different, and it could get overwritten by a subsequent local variable.
For your second example if you wrote a ~Dummy(){ value=0; }, then it wouldn't work, proving that the lifetime of the dummy object hasn't been extended.


text:
Q: Re-enable load on demand [NativeScript Vue] I have a Radlistview, where the data switches out based on user query. With loadOnDemandMode="Auto" and when the current query is exhausted, I then call notifyLoadOnDemandFinished(true). However, when a new query is made, I cannot re-enable loadOnDemand, and new items are not loaded.
Is there a way to reactivate loadOnDemand, perhaps with a method on the radListView object? I couldn't find anything in the docs.

A: Found the mistake, posting here for anyone else that may have the problem.
I was trying to set
listView.loadOnDemandMode = "Auto"
adding _nativeView fixed it
listView._nativeView.loadOnDemandMode = "Auto"


text:
Q: Loop subfolders with different parent folder I have a folder structure that consists of multiple client names on the root of a drive.  Within each of these client folders I have the same subfolder.  What I'd like to do is loop through each of the client folders and for a specific sub folder within each of the client folders, I'd like to set specific permissions using the Get-Acl command in PowerShell.
I need the script to ignore the client's name (JOHN, PETER) but loop through each to change the permission to the PRIVATE folder or all folders within the Special File folder:

S:\CLIENT FILES\JOHN\Special File\PRIVATE
  S:\CLIENT FILES\PETER\Special File\PRIVATE

A: Get-ChildItem allows the use of wildcards in the -Path parameter.
Get-ChildItem -Path 'S:\CLIENT FILES\*\Special File\PRIVATE' | Get-Acl


text:
Q: Gradle daemon fails to start - Tried all Hi so I'm unable to start the Gradle daemon process. I've tried all that the internet has recommended and still seem to get nowhere.
I've added the line org.gradle.jvmargs=-Xmx1024m to my grade.properties
I've also reinstalled my JDK and android studio.
Heres a preview of the error log that has caused my depression
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized JVM option is used.
Please refer to the user guide chapter on the daemon at
https://docs.gradle.org/4.6/userguide/gradle_daemon.html
Please read the following process output to find out more:
-----------------------

I need it for an assignment and nothing seems to be working for me

EDIT
Here are the logs
https://pastebin.com/7ehbQanJ

A: A temporary solution is to disable the firewall (or adjust some rules, which I don't know right now).
At least that helped me. I am still looking for a permanent solution. However, this is better than nothing for the beginning.


text:
Q: Python3 re.split() via character which is not in special substring I'm trying to parse and validate language. I want to tokenize input to check grammar.
My input string is:
something > 0 AND (something CONTAINS "substr" OR NOT something)

if i did this:
tokens = re.split(r"([\s()])", input)

i got this:
['something', ' ', '>', ' ', '0', ' ', 'AND', ' ', '', '(', 'something', ' ', 'CONTAINS','   ', '"substr"', ' ', 'OR', ' ', 'NOT', ' ', 'something', ')', '']

which is exacly what i want. But, there is allways "something". If i replace "substr" with "substr with whitespace", i got this array, which is not the perfect result:
['"substr', ' ', 'with', ' ', 'whitespace"']

Is there any way how to split to following?
['"substr with whitespace"']

Or how to efficiently repair this "so close split" ?
Or maybe something different which i missed...

A: Just think an split with
re.split(r"\s*(NOT|AND|OR|\(|\)|CONTAINS|<|>|=)\s*", input)

solved my problem


text:
Q: find ones position in 64 bit number I'm trying to find the position of two 1's in a 64 bit number. In this case the ones are at the 0th and 63rd position. The code here returns 0 and 32, which is only half right. Why does this not work?
#include<stdio.h>
void main()
{
unsigned long long number=576460752303423489;
int i;
for (i=0; i<64; i++)
    {
    if ((number & (1 << i))==1)
        {
        printf("%d  ",i);

        }
    }
}

A: Because (1 << i) is a 32-bit int value on the platform you are compiling and running on. This then gets sign-extended to 64 bits for the & operation with the number value, resulting in bit 31 being duplicated into bits 32 through 63.
Also, you are comparing the result of the & to 1, which isn't correct. It will not be 0 if the bit is set, but it won't be 1.
Shifting a 32-bit int by 32 is undefined.
Also, your input number is incorrect. The bits set are at positions 0 and 59 (or 1 and 60 if you prefer to count starting at 1).
The fix is to use (1ull << i), or otherwise to right-shift the original value and & it with 1 (instead of left-shifting 1). And of course if you do left-shift 1 and & it with the original value, the result won't be 1 (except for bit 0), so you need to compare != 0 rather than == 1.

A: #include<stdio.h>
int main()
{
    unsigned long long number = 576460752303423489;
    int i;
    for (i=0; i<64; i++)
    {
        if ((number & (1ULL << i)))   //here
        {
            printf("%d  ",i);
        }
    }
}

First is to use 1ULL to represent unsigned long long constant. Second is in the if statement, what you mean is not to compare with 1, that will only be true for the rightmost bit.
Output: 0 59
It's correct because 576460752303423489 is equal to 0x800000000000001

A: There are two bugs on the line
if ((number & (1 << i))==1)

which should read
if (number & (1ull << i))

Changing 1 to 1ull means that the left shift is done on a value of type unsigned long long rather than int, and therefore the bitmask can actually reach positions 32 through 63.  Removing the comparison to 1 is because the result of number & mask (where mask has only one bit set) is either mask or 0, and mask is only equal to 1 when i is 0.
However, when I make that change, the output for me is 0 59, which still isn't what you expected.  The remaining problem is that 576460752303423489 (decimal) = 0800 0000 0000 0001 (hexadecimal).  0 59 is the correct output for that number.  The number you wanted is 9223372036854775809 (decimal) = 8000 0000 0000 0001 (hex).
Incidentally, main is required to return int, not void, and needs an explicit return 0; as its last action (unless you are doing something more sophisticated with the return code).  Yes, C99 lets you omit that.  Do it anyway.

A: The problem could have been avoided in the first place by adopting the methodology of applying the >> operator to a variable, instead of a literal:
if ((variable >> other_variable) & 1)
   ...

A: I know the question has some time and multiple correct answers while my should be a comment, but is a bit too long for it. I advice you to encapsulate bit checking logic in a macro and don't use 64 number directly, but rather calculate it. Take a look here for quite comprehensive source of bit manipulation hacks.
#include<stdio.h>
#include<limits.h>

#define CHECK_BIT(var,pos) ((var) & (1ULL<<(pos)))

int main(void)
{
    unsigned long long number=576460752303423489;
    int pos=sizeof(unsigned long long)*CHAR_BIT-1;
    while((pos--)>=0) {
        if(CHECK_BIT(number,pos))
            printf("%d ",pos);
    }
    return(0);
}

A: Rather than resorting to bit manipulation, one can use compiler facilities to perform bit analysis tasks in the most efficient manner (using only a single CPU instruction in many cases).
For example, gcc and clang provide those handy routines:
__builtin_popcountll() - number of bits set in the 64b value
__builtin_clzll() - number of leading zeroes in the 64b value
__builtin_ctzll() - number of trailing zeroes in the 64b value
__builtin_ffsll() - bit index of least significant set bit in the 64b value

Other compilers have similar mechanisms.


text:
Q: I suspect this is malware. How do I remove it? Several pop-ups have recently begun appearing on my MacBook screen.  They coincide with my attempting to update Adobe Flash Player.  I suspect I was careless.  I have never seen pop-ups constantly appearing on my Mac before.  They have no name, so I cannot easily search for where the program is residing and get rid of it. Does anyone recognize these who would be able to instruct me on how to locate and eradicate?

A: Turn off the Mac, then power it up holding down the shift key. depending on what has infected you that may either disable it or reduce its effect on the system.
Download Malwarebytes (or another) virus scanning app for the mac and run it. Hopefully it will be found and removed. If not perhaps someone here recognizes it and knows how to remove it manually.
Alternatively if you have another Mac and the right cables to connect them together you could boot the affected Mac into target disk mode, and plug it into your other Mac that you have installed AV software on and scan the infected drive from there.
Note that these are preliminary steps. other people may have more and/or better suggestions. Proceed with caution and, if possible, turn off the network on the infected Mac.