text:
Q: Str_compare -- from Irvine's assembly book     Str_compare PROC USES eax edx esi edi,
        string1: PTR BYTE,
        string2: PTR BYTE
    ;
    ; Compare two strings.
    ; Returns nothing, but the Zero and Carry flags are affected
    ; exactly as they would be by the CMP instruction.
    ;-----------------------------------------------------------
        mov  esi, string1
        mov  edi, string2
    L1: mov  al, [esi]
        mov  dl, [edi]
        cmp  al, 0
        jne  L2
        cmp  dl, 0
        jne  L2
        jmp  L3

    L2: inc  esi
        inc  edi
        cmp  al, dl
        je   L1

    L3: ret
    Str_compare ENDP

Against the code above, what if string1 is just byte 0 and string2 is some common string whose length is not 0?
I suppose, when cpu enter L1 at the first time, IP will jump to L2 after cmp dl, 0. inc esi will make esi point to an content-unknown byte right after the 0 byte of string1, so this program break down, right?

A:
inc esi will make esi point to an content-unknown byte right after the 0 byte of string1, so this program break down, right?

Pointing to X simply means holding the address of X. It's perfectly ok to hold a value which could be interpreted as an invalid address, as long as you don't try to dereference the pointer (i.e. read from the address).
Even if you did try to read from [esi] when esi points one byte beyond string1 there would probably not be any crash. It's fairly likely that you've got other data located after string1 which also belongs to your program, and which your program therefore has access to. So reading beyond string1 will just read whatever happens to be there, up until some point where you go beyond the end of your program's data section or stack or wherever string1 happens to be located.
What happens in the Str_compare function if one string is empty (contains only a NUL-terminator) and the other is non-empty is that cmp  al, dl will compare a NUL-terminator against something that is not a NUL-terminator. The conditional je L1 will therefore not jump back to L1, and instead the ret at L3 will be executed, causing the function to return. The incremented addresses in esi and edi will therefore not be dereferenced.


text:
Q: postgres/sqlalchemy/python: group-by/max in union query? I'm using sqlalchemy in python with a postgres database.
I want to perform a union query from two tables, upon which I want to select the rows with the maximum of a column with a common key. I have not been able to figure out how to make this work in sqlalchemy.
Suppose I have a table object for table users and another table object for table orders.
I know how to define this union query:
union_query = union(
  select([users.c.email,  users.c.timestamp]),
  select([orders.c.email, orders.c.timestamp])
)

However, in some cases, there might be common email columns with differing timestamp values. In this case, I want the result to show the largest timestamp for any given email.
For example, suppose the users table contains this data:
email   | timestamp
--------| ---------
a@b.com | 00:00:00
c@d.com | 02:03:04
e@f.com | 10:10:10

... and suppose the orders table contains this data:
email   | timestamp
--------| ---------
a@b.com | 12:12:12
c@d.com | 01:01:01
q@r.com | 09:09:09

I want the results of my union-based query to be as follows ...
email   | timestamp
--------| ---------
a@b.com | 12:12:12
c@d.com | 02:03:04
e@f.com | 10:10:10
q@r.com | 09:09:09

I haven't been able to come up with the proper combinations of group_by(), func.max(), and other sqlalchemy functions to use with my union_query in order to generate this query.
Thank you for any help you can offer.

A: I think I came up with the answer. An alias is needed, and union_query needs to be used as a subquery.
Do any of you see anything wrong with this, or perhaps a more efficient way to do it?
union_query = union(
  select([users.c.email,  users.c.timestamp]),
  select([orders.c.email, orders.c.timestamp])
).alias('uq_alias')

query = select(
          [union_query.c.email, func.max(union_query.c.timestamp)]
        ).group_by(union_query.c.email)

... and then simply execute query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matching ranges of lines in python (like sed ranges) Sometimes the good old tools still work best. In sed, I could write things like this:
sed '/^Page 5:/,/^Page 6:/p'
sed '110,/^Page 10:/+3p'
sed '/^Page 5:/,/^Page 6:/s/this/that/g'

The first applies a substitution to all lines between the ones matching /^Page 5:/ and /^Page 6:/. The second starts printing at line 110 and stops 3 lines after the one matching /^Page 10:/. The third example applies a substitution to each line in the specified range.
I don't mind using re.search to search line by line, but for line ranges, line numbers or relative offsets, I end up having to write a whole parser. Is there a python idiom or module that can simplify this kind of operations?
I don't want to call sed from python: I'm doing python-type things with text, and just want to be able to operate on line ranges in a straightforward way.
Edit: It's fine if the solution works on a python list of strings. I'm not looking to process gigabytes of text. But I do need to specify several operations, not just one, and interleave them with single-line regexp substitutions. I've looked at iterators (in fact I would welcome a solution using iterators), but the results always got out of hand for anything more than single operation.
Here's a simple example: A snippet of code with java-style comments, to be changed to python comments. (Don't worry I am NOT trying to write a cross-compiler using regexps :-)
/*
 This is a multi-line comment.
 It does not obligingly start lines with " * "
 */

x++;  // a single-line comment

It's trivial to write regexps that change "//" comments to "#" (and also to drop semicolons, change "++" to "+= 1", etc.) But how do we insert "#" at the start of each line of a multi-line java comment? I can do it with a regexp on the entire file as a single string, which is a pain because the rest of the transformations are line-oriented. I've also been unable to (usefully) integrate iterators with line-oriented regexps. I'd appreciate suggestions.

A: I would try to use the regex flags re.DOTALL or re.MULTILINE.
The first treats newlines as regular characters, so if you use .* it might count newlines inside the pattern.
The second is almost the same, but you can still use linestarts (^) and endlines ($) to match these. This can be useful to count lines.
I could, for now, come up with this, which prints ONE MORE LINE after the ocurrence of "six" (a whole line is captured by the final ^.*?$, but I'm pretty sure there should be a much better way):
import re

source = """one
two
three
four
five
six
seven
eight
nine
ten"""

print re.search('^three.*six.*?^.*?$', source, re.DOTALL|re.MULTILINE).group(0)

A: For the comments at least, just use a real parser.
#!/usr/bin/python

from pyparsing import javaStyleComment
import re

text = """

/*
 * foo
 * bar
 * blah
 */

/***********************
 it never ends
***********************/

/* foo

   bar blah
*/

/*
* ugly
* comment
*/

// Yet another

int a = 100;

char* foo;

"""

commentTokenStripper = re.compile(r'\s*[/\\\*]')

for match in javaStyleComment.scanString(text):
    start,end = match[-2:]
    print '# comment block %d-%d ##############' % (start,end)
    lines = ['#' + re.sub(commentTokenStripper, '', l) for l in match[0][0].splitlines()]
    print '\n'.join(lines)
    print

Yields
# comment block 2-30 ##############
#
# foo
# bar
# blah
#

# comment block 32-96 ##############
#
# it never ends
#

# comment block 98-121 ##############
# foo
#
#   bar blah
#

# comment block 123-145 ##############
#
# ugly
# comment
#

# comment block 147-161 ##############
# Yet another

A: You could try something like this:
import re

def firstline(rx, lst):
    for n, s in enumerate(lst):
        if re.search(rx, s):
            return n
    return 0

and then:
text = ["How", "razorback", "jumping", "frogs", "can", "level", "six", "piqued", "gymnasts"]

# prints all lines between the one matching `^r` and the one matching `^s`
print text[firstline('^r', text)+1:firstline('^s', text)]

This looks overly verbose, but the verbosity can be reduced, for example:
import functools
L = functools.partial(firstline, lst=text)

print text[L('^r')+1:L('^s')]

The latter is almost as concise  as its sed counterpart.

A: I don't think there's a straightforward way to do that in Python.
But there are different approaches you could follow:

*

*Read the file line by line and activate your search only when you need.
This has the advantage of read the file only one time, but it works on one line at the time.

*Slice the file with itertools.islice() and do the search of your pattern there.
You'll have to read the file again for each patterns, but it's very easy to implement.

*Use mmap.
If your file is not too big and you have more than one pattern to look for, I'd go with this one.
Edit: If you're interested in iterator tools, itertools.takewhile() with a smart lambda might do the work.
Disclaimer: I don't know nothing about sed.

A: Something like this.
from __future__ import print_function

def get_lines( some_file, start_rule, end_rule, process=print ):
    line_iter= enumerate( source )
    for n, text in line_iter:
        if start_rule( n, text ):
            process( text )
            break
    for n, text in line_iter:
        process( text )
        if end_rule( n, text ): break

Then you can define a lot of smaller functions:
def match_page_5( n, text ):
    return re.match( '^Page 5:', text )
def match_line( n, text ):
    return line == n

Or stateful, callable objects
class Match_Pattern( collections.Callable ):
    def __init__( self, pattern ):
        self.pat= re.compile( pattern )
    def __call__( self, n, text ):
        return self.pat.match( text )

class Match_Lines_Post_Pattern( collections.Callable ):
    def __init__( self, pattern, lines ):
        self.pat= re.compile( pattern )
        self.lines= lines
        self.saw_it= None
    def __call__( self, n, text ):
        if self.saw_it:
            if n == self.saw_it + self.lines
                return True
            if self.pat.match( text ):
                self.saw_it = n

You can create syntactic sugar via functions like this.
def sed_by_pattern( filename, pattern1, pattern2 ):
    with open(filename,'r') as source:
        get_lines( source, lambda n,tx: re.match(pattern1,tx), lambda n,tx: re.match(pattern2,tx) )

This gets you to a function like the following
This usage is  as simple as the SED command with extra punctuation.
sed_by_pattern( some_file, '^Page 5:', '^Page 6:' )

Or this bit of sugar...
def sed_by_matcher( filename, matcher1, matcher2 )
    with open(filename, 'r') as source:
        get_lines( source, matcher1, matcher2 )

This usage is  as simple as the SED command with extra punctuation.
see_by_matcher( some_file, match_line(100), Match_Lines_Post_Pattern( '^Page 10:', 3 ) )


text:
Q: Generic class value check c# I have been working in c# to create a generic class (which is a class that takes a given type, then behaves off of that type) e.g. the List class, which lets you create a list of a certain post-defined type. The reason why I want to do this is less important, and more difficult to explain than just presenting my question. I want to be able to check a value from another class constantly, without having to write any excess code other than instantiating the class. Here is my code for the class:
using UnityEngine;
using System.Collections;

public class ValueWatch<T> : MonoBehaviour {
    public delegate void OnValueChanged();
    private OnValueChanged onValueChanged;

    T lastValue;

    public ValueWatch(T value, OnValueChanged onValueChanged) {
        this.lastValue = value;
        this.onValueChanged = onValueChanged;
    }

    public void checkValue(T value) {
        if(!lastValue.Equals(value)) {
            onValueChanged();
            lastValue = value;
        }
    }

    void Update() {
        checkValue (
            //this is where I want the value from the original class.
            );
    }
}

I want to be able to write
new ValueWatch<bool>(exampleBool, exampleCallBackMethod);

Without calling the
ValueWatch.checkValue(exampleBool);

Outside of the valueWatch class, but I am struggling to find a way to do this. I don't want to have to assign the ValueWatch to a variable, I want it to be a one line thing. I want to retrieve the exampleBool and compare it to the last one, is this possible? If my question is unclear I will fix it. I am using unity, update is called once per frame.


text:
Q: How to redeploy nodejs server in modulus without facing downtime? I have a node js server running at modulus.io. How can I redeploy the latest version of the server without facing downtime ?

A: Modulus builds your app using a new container every time you deploy, so the switching can be as quick as a few milliseconds.
From their docs:

Since the bundle is already built, making the switchover from the old
  version of your application to the new is very quick. The process is:

*

*Send graceful shutdown request to old application.

*Stop the old application instance.

*Remove the old application instance.

*Extract new application instance.

*Start the new application instance.

  Under normal conditions, the actual switchover takes a few
  milliseconds. The amount of time it takes the application to start
  serving requests then depends on how long it takes your application to
  startup.

A: You can't, Modulus currently deploys to all servos simultaneously so the server will inevitably go down for a few seconds while it starts.


text:
Q: PHP- Carbon Datetime DiffInSeconds and How to Group By Hour I'm calculating difference between 2 datetimes in seconds but I want to group them by hours. It should be like that.
This is how I'm getting difference between 2 dates.
$date_diff = $first->created_at->diffInSeconds($second->created_at);

And For example first time is 09:47:20 and next one is 11:47:50 I need the group them by hour like this.
In 09:00 =  12.40 Minutes
In 10:00 =  60.00 Minutes
In 11:00 =  47.50 Minutes

How can I do that ? And what you'll suggest for this ?
Thanks

A: You can check out the code below.
Keep in mind that it works as expected if the start time <= the end time.
Also, there's room for improvement, like extracting logic to separate functions or adding trailing/leading zeros where you'd need them, but it should get you started.
    $start = '09:47:20';
    $end = '11:47:50';

    $startTime = Carbon::createFromFormat('H:i:s', $start);
    $endTime = Carbon::createFromFormat('H:i:s', $end);

    $startHour = $startTime->hour; // 9
    $endHour = $endTime->hour; // 11

    $hourRange = range($startHour, $endHour); // array(9, 10, 11)

    if (count($hourRange) === 1) {
        // start and end time share the same hour
        $hourRange = array($startHour, $endHour);
    }

    $lastIndex = count($hourRange) - 1;
    $diffGrouped = array();

    foreach ($hourRange as $index => $hour) {

        if ($index === 0) {

            // start hour has the next full hour - calculate the difference
            $nextFullHour = $startHour + 1;
            $nextFullHourTime = Carbon::createFromFormat('H', $nextFullHour);

            $minutes = $startTime->diff($nextFullHourTime)->format('%i.%s');

        } else if ($index === $lastIndex) {

            // end hour is its own "previous full hour"
            $previousFullHourTime = Carbon::createFromFormat('H', $endHour);

            $minutes = $endTime->diff($previousFullHourTime)->format('%i.%s');

        } else {

            // everything between the start and the end hour
            $minutes = '60.00';

        }

        $diffGrouped[] = array(
            'hour' => $hour,
            'minutes' => $minutes
        );

    }

    dd($diffGrouped);

    /*
     array:3 [
          0 => array:2 [
            "hour" => 9
            "minutes" => "12.40"
          ]
          1 => array:2 [
            "hour" => 10
            "minutes" => "60.00"
          ]
          2 => array:2 [
            "hour" => 11
            "minutes" => "47.50"
          ]
        ]
    */


text:
Q: Need help in understanding an argument. Suppose $u: A\times B\to (0,\infty)$ be a function such that
$$
\int_{x\in A}\int_{y\in B}u^2(x,t)\,dx dt\leq \int_{x\in A}\int_{y\in B}f(u(x,t))\,dx dt.
$$
Now let us fix $\hat{t}\in B$, and define $v(x,\hat{t})=u(x,\hat{t})$, then is it possible to get
$$
\int_{x\in A}\int_{B}v^2(x,\hat{t})\,dx dt\leq \int_{x\in A}\int_{B}f(v(x,\hat{t}))\,dx dt.
$$
Note that is this holds then we get
$$
\int_{x\in A}u^2(x,\hat{t})\,dx\leq\int_{x\in A}f(u(x,\hat{t}))\,dx.
$$
You can take any function $f$. Basically, my question is if one can get the second one from the fist when one fixes the variable $t$ and get the same estimate for the one variable function $v(x,\hat{t})$?
Can somebody kindly help me?
Thanking you.


text:
Q: How to export references from a bbl file to csv? I have a .bib file, but not all references are cited.
I want to list all cited (only) references in a .csv file.
But, the .bib file contains references that are not cited as well.
What I understood is, the .bbl file contains the cited references only.
So, how do I export the cited references to a .CSV file?

A: Depending on whether you are using biblatex or BibTeX, the .bbl file might not really lend itself to being read back by a machine if you want to recover all data. If you only want to recover which entries were cited and no additional data, that is less relevant.
The .bbl file produced for BibTeX bibliographies contains typesettable text and thus requires quite intricate parsing if you want to get back the entry data.
\begin{thebibliography}{1}
\bibitem[Elk(1972)]{elk}
Anne Elk.
\newblock \emph{A Theory on Brontosauruses}.
\newblock Monthy \& Co., 1972.

\end{thebibliography}

Since the style decides what gets written to the .bbl file, some data might be missing.
The .bbl file produced for biblatex contains entry data in a structured, LaTeX-readable format that could in theory be parsed to get back all entry data.
\refsection{0}
  \datalist[entry]{nyt/global//global/global}
    \entry{elk}{book}{}
      \name{author}{1}{}{%
        {{un=0,uniquepart=base,hash=6a9b0705c275273262103333472cc656}{%
           family={Elk},
           familyi={E\bibinitperiod},
           given={Anne},
           giveni={A\bibinitperiod},
           givenun=0}}%
      }
      \list{location}{1}{%
        {London}%
      }
      \list{publisher}{1}{%
        {Monthy \& Co.}%
      }
      \strng{namehash}{6a9b0705c275273262103333472cc656}
      \strng{fullhash}{6a9b0705c275273262103333472cc656}
      \strng{bibnamehash}{6a9b0705c275273262103333472cc656}
      \strng{authorbibnamehash}{6a9b0705c275273262103333472cc656}
      \strng{authornamehash}{6a9b0705c275273262103333472cc656}
      \strng{authorfullhash}{6a9b0705c275273262103333472cc656}
      \field{sortinit}{E}
      \field{sortinithash}{8da8a182d344d5b9047633dfc0cc9131}
      \field{extradatescope}{labelyear}
      \field{labeldatesource}{year}
      \field{labelnamesource}{author}
      \field{labeltitlesource}{title}
      \field{title}{A Theory on Brontosauruses}
      \field{year}{1972}
    \endentry
  \enddatalist
\endrefsection
\endinput

The .bbl file generated for biblatex will contain context-specific data that is only relevant within the current document context. This may or may not be wanted when you want to export the data to .csv.
But I would go down a different route. I would use one of the methods from Creating .bib file containing only the cited references of a bigger .bib file to generate a .bib file of only the cited references and would then use a library to read in the .bib file directly.

A: You can get a complete list of citations in your document from the .aux file. Each \cite command will cause an entry to be written in the .aux file in the format
\citation{REFNAME}

where REFNAME is the name you used in the \cite command. It will create a separate \citation command for each reference in a multi-reference \cite command, so if you, for example, typed \cite{foo,bar} in your document you will see
\citation{foo}
\citation{bar}

From here, you can do what you want to generate your CSV file, so if you're on a Unixish system (including MacOS and Linux), you can write
grep '\\citation` my.aux | sort | uniq

that will give you a list of all the reference names cited in your document with duplicates removed.


text:
Q: Why is my Spring Batch job not exiting after completion My batch job is configured as follows
@Bean("MyJob")
    public Job umpInpatientCensusRptBatchJob(...) throws IOException {
        return jobBuilderFactory.get( "MyJob" )
                .incrementer( new RunIdIncrementer() )
                .start( Step0 ).on( COMPLETE ).end()
                .from( Step0 ).on( CONTINUE )
                .to( Step1 )
                .next( Step2 )
                .next( Step3 )
                .end()
                .build();
    }

where Steps 0, 1, and 3 are tasklets. My Job is completing with the message Job: [FlowJob: [name=MyJob]] completed with the following parameters. However, it doesn't exit - it hangs there. When I run it locally on IntelliJ, I have to manually quit the job.
I haven't implemented any asynchronicity. Each tasklet is also explicitly returning a FINISHED status upon completion.

A: An apparent problem is the word "COMPLETE" inside the first on().
The method on(String pattern) is given "COMPLETE" as a parameter instead of, for example, "COMPLETED", the job completes with a FAILED state, if an appropriate custom exit status hasn't been created. However, I don't know why it hangs and doesn't just fail in your case.
The following version of your job configuration seems to run fine, as long as all the tasklets return a FINISHED RepeatStatus:
@Bean("MyJob")
public Job umpInpatientCensusRptBatchJob(...) throws IOException {
    return jobBuilderFactory.get( "MyJob" )
            .incrementer( new RunIdIncrementer() )
            .start( Step0 ).on( "COMPLETED" ).end()
            .from( Step0 ).on( "CONTINUE" )
            .to( Step1 )
            .next( Step2 )
            .next( Step3 )
            .end()
            .build();
}

If the tasklet of Step0 returns RepeatStatus.CONTINUABLE though, Step0 repeats forever, since that is the purpose of that RepeatStatus. So, it's impossible to reach Step1 with this configuration.
In order to decide if you should run the next steps, instead of using the tasklet repeat status (which I don't know if is possible) you could either use a StepExecutionListener on Step0 or add a decider to the flow, after Step0:
Spring-Batch: how do I return a custom Job exit STATUS from a StepListener to decide next step


text:
Q: Having an issue with my div alignments Hi all I seem to be having serious trouble getting my div to go exactly where I need it to. Here is a link to the website.
As you can see my slideshow is supposed to be in the frame, but in now way shape or form am I able to make it do so.
here is the link to the style sheet that Im working with.
Some help would be much appreciated, I've googled page upon page and can't seem to find any solution so I can to the place that I've found help from before.

A: #slideshow {
position: relative;
left: auto;
right: auto;
top: 119px;}

This CSS looks horrible (width of #content, left:auto; margin-top: auto...)
My suggestion is to make a fresh start and get rid of all those autos.

A: This'll fix what ails you:
#contentbox {
    position: relative;
}
#content {
    position: absolute;
    left: 100px;
    top: 100px;
}

Personal preference:
#wowslider-container1 {
    border: none;
}

A: Have you tried removing the "margin-top: auto;"?
#content {
height: 374px;
width: 524;
margin-right: auto;
margin-left: auto;
margin-top: auto;

}

A: A quick fix would be to add
.ws_images{
    margin-top: 122px;
}


text:
Q: combining GO GIN-GONIC GORM and VALIDATOR.V2 I am quite new to Go and I would like to startup by setting a GIN-GONIC API. I found this tutorial and I am very happy with that skeleton. But now I am stuck with the validating process which I added: "gopkg.in/validator.v2" and
type Todo struct {
    gorm.Model
    Title     string `json:"title"`
    Completed int `json:"completed"`
}

became
type Todo struct {
    gorm.Model
    Title     string `json:"title" **validate:"size:2"**`
    Completed int `json:"completed"`
}

and then in the CreateTodo function which I added :
if errs := validator.Validate(todo); errs!=nil {
    c.JSON(500, gin.H{"Error": errs.Error()})
}

but then a POST call send :

"Error": "Type: unknown tag"

after some research I found that :

Using a non-existing validation func in a field tag will always return false and with error validate.ErrUnknownTag.

so the **validate:"size:2"** must be wrong ...
I don't get how to set the validation and also how to display the correct error within the "catch":
c.JSON(500, gin.H{"Error": errs.Error()})

A: Looks like you haven't defined size validation function. Also you can do it.
Custom validation functions:
func size(v interface{}, param int) error {
    st := reflect.ValueOf(v)
    if st.Kind() != reflect.String {
        return validate.ErrUnsupported
    }

    if utf8.RuneCountInString(st.String()) != param {
        return errors.New("Wrong size")
    }
    return nil
}

validate.SetValidationFunc("size", size)


text:
Q: Flow to update fields of same records when there is record update Not working I have custom object parcel__c there are 8 fields over this object. I have written a flow so that whenever user enter parcelnumber__c values it will get updated same in systemParcelNumber__c. User can enter below values.
parcelnumber__c-->systemParcelNumber__c
parcelDate__C--->systemParcelDate__c

Issue is flow will copy value correctly but in scenarios where lets suppose parcelnumber__c=100 & parcelDate__C= blank or Null..flow is copying null values also to systemParcelDate__c which is not required. we  want values to be copied only when non null values are there. Is there any we can acheive this.
Thanks

A: You can either use multiple Decision elements, or you can use Formulas. For example, using formulas, you could write these two formulas:
// NewParcelNumber (Text)

{!BLANKVALUE($Record.ParcelNumber__c, $Record.SystemParcelNumber__c)}

And
// NewParcelDate (Date)

{!BLANKVALUE($Record.ParcelDate__c, $Record.SystemParcelDate__c)}

Then, create an Assignment element that assigns those values:
$Record.SystemParcelNumber__c equals {!NewParcelNumber}
$Record.SystemParcelDate__c equals {!NewParcelDate}


text:
Q: Why does calling TreeViewer.refresh() not call the contentProvider's getChildren(Object) method? Amongst other places, I've looked here and here, but I've not found an answer to my question.
A little background:

*

*I'm implementing a view that represents a subset of the resources in an eclipse project.

*The project nodes in the tree will check whether the project is open to see if they should contain children. Effectively, the Project node's hasChildren() method returns IProject.isOpen().

*The eclipse view subscribes to resourceChangeEvents, and in the case that any change occurs, it calls refresh() on the TreeViewer.

Based on information from this question:

If you have added or removed objects in the tree use
TreeViewer.refresh();

refresh() (with no arguments) should then go through and update the entire tree with fresh information from the model.

By setting breakpoints in the code, I've discovered that during the refresh process, the framework calls hasChildren() several times on a node, but never calls getChildren().
Let us say that Project is currently open, and the node representing it in the tree is expanded with some children. I close the project and resource change event is fired. This causes a refresh(). When asked, the project now returns false from hasChildren(), and yet the children are still present in the tree.
Conversely, if the project is closed and the node has no children (there is no expansion arrow), opening the project will fire a resource change event, which refresh()es the tree, the project node returns true from hasChildren() and yet getChildren() is never called to find out what these children are. The node still has no children and no expansion arrow.
Currently the model fires events when new nodes are added and old ones removed, and the tree listens for these and calls add(Object, Object) and remove(Object) on the TreeViewer as appropriate, but the model only checks to see whether its children need to be changed when it is asked for them via the content provider's getChildren() method.
The problem can be partially alleviated by calling getChildren() from hasChildren(), but this seems messy, and from my understanding of how refresh() works, shouldn't be necessary.

Why does the TreeViewer's refresh() method not re-query a node to see what its children are? Given that is doesn't do this, how is it meant to handle adding and removing objects?

A: It turns out the problem was that the Implementation of the IElementComparer passed to TreeViewer.setComparer looked like this:
@Override
public boolean equals( final Object one, final Object two ) {
    if (one.getClass().equals( two.getClass() ) ) { <-- This is not always true...
        if ( one instanceof MyCustomNodeBaseClass) {
            return ((MyCustomNodeBaseClass) one).isEquivalentTo( (MyCustomNodeBaseClass) two);
        }
    }
    return false; <-- ...therefore this is the problem, as it wasn't expected to be reached
}

The IElementComparer.equals(Object, Object) method can be called with arguments of class org.eclipse.ui.internal.ViewSite, and should handle those too.
It was a questionable move to quietly return false in cases where the class of the parameters was unrecognised, and the problematic line could be replaced with:
return ( one.equals( two ) ); <-- this will quietly handle unexpected classes better.

I eventually found this by following the debugger into the updatePlus() method of the AbstractTreeViewer


text:
Q: keras's model.fit() is not consistent with model.evaluate() I have a set of 32 chairs and 32 lamps which form one training set. I ran them through a simple CNN in Keras whose goal was to discriminate chairs from lamps.
When calling model.fit(), I achieve accuracy close to 1.0 according to the printout. After training, however, model.evaluate() on the training data results in an accuracy of ~0.5.
Here's my code:
# train_tensors, train_labels contain training data
model = keras.models.Sequential()
model.add(Conv2D(filters=5,
                 kernel_size=[4, 4],
                 strides=2,
                 padding='same',
                 input_shape=[225, 225, 3]))
model.add(LeakyReLU(0.2))

model.add(Conv2D(filters=10,
                 kernel_size=[4, 4],
                 strides=2,
                 padding='same'))
model.add(BatchNorm(axis=3))  # imported BatchNormalization as BatchNorm
model.add(LeakyReLU(0.2))

model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(train_tensors, train_labels, batch_size=8, epochs=5, shuffle=True)

metrics = model.evaluate(train_tensors, train_labels)
print('')
print(np.ravel(model.predict(train_tensors)))
print('training data results: ')
for i in range(len(model.metrics_names)):
    print(str(model.metrics_names[i]) + ": " + str(metrics[i]))

train_tensors was used for both model.fit() and model.evaluate(). The printout was:
Epoch 1/5
 8/64 [==>...........................] - ETA: 0s - loss: 0.6927 - acc: 0.5000
16/64 [======>.......................] - ETA: 0s - loss: 1.1480 - acc: 0.5000
24/64 [==========>...................] - ETA: 0s - loss: 0.8194 - acc: 0.6667
40/64 [=================>............] - ETA: 0s - loss: 0.5205 - acc: 0.8000
56/64 [=========================>....] - ETA: 0s - loss: 0.4896 - acc: 0.8036
64/64 [==============================] - 0s - loss: 0.4504 - acc: 0.8125
Epoch 2/5
 8/64 [==>...........................] - ETA: 0s - loss: 0.0082 - acc: 1.0000
24/64 [==========>...................] - ETA: 0s - loss: 0.0391 - acc: 1.0000
40/64 [=================>............] - ETA: 0s - loss: 0.0444 - acc: 0.9750
56/64 [=========================>....] - ETA: 0s - loss: 0.0392 - acc: 0.9821
64/64 [==============================] - 0s - loss: 0.0382 - acc: 0.9844
Epoch 3/5
 8/64 [==>...........................] - ETA: 0s - loss: 4.8843e-04 - acc: 1.0000
24/64 [==========>...................] - ETA: 0s - loss: 7.5668e-04 - acc: 1.0000
40/64 [=================>............] - ETA: 0s - loss: 6.1193e-04 - acc: 1.0000
56/64 [=========================>....] - ETA: 0s - loss: 0.0096 - acc: 1.0000
64/64 [==============================] - 0s - loss: 0.0128 - acc: 1.0000
Epoch 4/5
 8/64 [==>...........................] - ETA: 0s - loss: 9.2490e-04 - acc: 1.0000
24/64 [==========>...................] - ETA: 0s - loss: 9.6854e-04 - acc: 1.0000
40/64 [=================>............] - ETA: 0s - loss: 9.6813e-04 - acc: 1.0000
56/64 [=========================>....] - ETA: 0s - loss: 7.5456e-04 - acc: 1.0000
64/64 [==============================] - 0s - loss: 8.3200e-04 - acc: 1.0000
Epoch 5/5
 8/64 [==>...........................] - ETA: 0s - loss: 4.2928e-04 - acc: 1.0000
24/64 [==========>...................] - ETA: 0s - loss: 0.0044 - acc: 1.0000
40/64 [=================>............] - ETA: 0s - loss: 0.0027 - acc: 1.0000
56/64 [=========================>....] - ETA: 0s - loss: 0.0026 - acc: 1.0000
64/64 [==============================] - 0s - loss: 0.0024 - acc: 1.0000
32/64 [==============>...............] - ETA: 0s
64/64 [==============================] - 0s

[  2.20039312e-21   3.70743738e-15   7.76885543e-08   3.38629164e-20
   1.26636347e-14   8.46270983e-23   4.83105518e-24   1.63172146e-07
   3.59334761e-28   7.74249325e-20   6.30969798e-28   2.79597981e-12
   1.17927814e-21   3.84340554e-01   3.83124183e-23   4.88756598e-07
   8.28199488e-27   3.89127730e-16   7.77586222e-32   2.96250031e-21
   1.51558620e-22   3.26927439e-12   1.96537564e-20   2.68915438e-16
   2.90332289e-17   1.78180949e-03   6.45235020e-23   2.82894642e-25
   9.87989724e-01   5.52072190e-02   6.61221920e-31   6.48611497e-29
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   2.91474397e-38
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   1.56358186e-38   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00]
training data results:
loss: 7.17852215999
acc: 0.515625

There's a huge discrepancy between the accuracy during model.fit() and the accuracy from model.evaluate(), which is 0.515625. Why might this be?

A: The problem is with the BatchNormalization layer. As you've noted in your comment, removing the layer makes the model work. The issue here is that batchnorm works differently when training vs when testing. At train time, it uses statistics computed on a per batch basis. As testing time, it uses statistics (mean/stdev) computed over the whole run of the training, as a running mean of the whole training set. Since your training is so short, the statistics have not been accurately completed in all likelihood.
You could either (a) remove the batchnorm layer, as I mentioned in a comment which seems to work. Or (b) increase the rate at which the moving mean/std is computed, by adjusting the parameter momentum in the batchnorm layer to a lower value. Try momentum in the range [0.5-0.95]


text:
Q: Fetch 2 URLRequests at the same time on one tableView I'm new to Swift, in the last 72 hours I searched everywhere to find an answer for my problem but with no luck.
I created my first app using Xcode 10, Swift 4.2 My app successfully fetches news data from newsapi.org but I need to fetch data from 2 different sources on the same tableView at the same time. Please take a look at my code: Your help is extremely appreciated!
func fetchArticles(){
    if let articlesFromJson = jsodTemp!["articles"] as? [[String : AnyObject]] {
                    for articleFromJson in articlesFromJson {
                        let article = Article()
                        if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String, let pubDate = articleFromJson["publishedAt"] as? String {

                            article.author = author
                            article.desc = desc
                            article.headline = title
                            article.url = url
                            article.imageUrl = urlToImage
                            article.pubDate = pubDate

                        }
                        self.articles?.append(article)
}
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
            return;
        }
        print("Call API")

        let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=396c2db56f7541cd93fb8b5cec9f447b")!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

            if error != nil {
                print(error as Any)
                return
            }

            self.articles = [Article]()
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
                // Save data for offline mode
                UserDefaults.standard.set(json, forKey: "offlineUse");
                UserDefaults.standard.synchronize()

                if let articlesFromJson = json["articles"] as? [[String : AnyObject]] {
                    for articleFromJson in articlesFromJson {
                        let article = Article()
                        if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String, let pubDate = articleFromJson["publishedAt"] as? String {

                            article.author = author
                            article.desc = desc
                            article.headline = title
                            article.url = url
                            article.imageUrl = urlToImage
                            article.pubDate = pubDate

                        }
                        self.articles?.append(article)
                    }
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            } catch let error {
                print(error)
            }

        }
        task.resume()
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as! ArticleCell

        cell.title.text = self.articles?[indexPath.item].headline
        cell.desc.text = self.articles?[indexPath.item].desc
        cell.author.text = self.articles?[indexPath.item].author
        cell.pubDate.text = self.articles?[indexPath.item].pubDate
        cell.imgView.downloadImage(from: ((self.articles?[indexPath.item].imageUrl)!)!)
        return cell
    }

A: Set a temp Variable called ready. Add one if it has successfully loaded one data source. If it's two then reload tableView.
 var ready : Int = 0{
    didSet{
        if ready == 2 {
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        }
    }
}

func fetchArticles(){
    ready = 0;
    self.articles = [Article]()

    if let articlesFromJson = jsodTemp!["articles"] as? [[String : AnyObject]] {
        for articleFromJson in articlesFromJson {
            let article = Article()
            if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String, let pubDate = articleFromJson["publishedAt"] as? String {

                article.author = author
                article.desc = desc
                article.headline = title
                article.url = url
                article.imageUrl = urlToImage
                article.pubDate = pubDate

            }
            self.articles?.append(article)
        }
        ready += 1;
    }

let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=396c2db56f7541cd93fb8b5cec9f447b")!)

let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error)   in

if error != nil {
    print(error as Any)
    return
}

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
    // Save data for offline mode
    UserDefaults.standard.set(json, forKey: "offlineUse");
    UserDefaults.standard.synchronize()

    if let articlesFromJson = json["articles"] as? [[String : AnyObject]] {
        for articleFromJson in articlesFromJson {
            let article = Article()
            if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String, let pubDate = articleFromJson["publishedAt"] as? String {

                article.author = author
                article.desc = desc
                article.headline = title
                article.url = url
                article.imageUrl = urlToImage
                article.pubDate = pubDate

            }
            self.articles?.append(article)
        }
    }
   self.ready += 1

} catch let error {
    print(error)
}

}
task.resume()
}

As suggested, you may use DispatchGroup() if you have multiple asynchronous data loading.
 func fetchArticles (){
      ready = 0;
self.articles = [Article]()

       let dispatchGroup = DispatchGroup()
        dispatchGroup.enter()
        if let articlesFromJson = jsodTemp!["articles"] as? [[String : AnyObject]] {
    for articleFromJson in articlesFromJson {
        let article = Article()
        if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String, let pubDate = articleFromJson["publishedAt"] as? String {

            article.author = author
            article.desc = desc
            article.headline = title
            article.url = url
            article.imageUrl = urlToImage
            article.pubDate = pubDate

        }
        self.articles?.append(article)
    }

}

        dispatchGroup.leave()  //  self.ready += 1

        dispatchGroup.enter()

 let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=396c2db56f7541cd93fb8b5cec9f447b")!)

 let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error)   in

if error != nil {
print(error as Any)
return
}

 do {
   let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
// Save data for offline mode
UserDefaults.standard.set(json, forKey: "offlineUse");
UserDefaults.standard.synchronize()

if let articlesFromJson = json["articles"] as? [[String : AnyObject]] {
    for articleFromJson in articlesFromJson {
        let article = Article()
        if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String, let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String, let pubDate = articleFromJson["publishedAt"] as? String {

            article.author = author
            article.desc = desc
            article.headline = title
            article.url = url
            article.imageUrl = urlToImage
            article.pubDate = pubDate

        }
        self.articles?.append(article)
    }
}
dispatchGroup.leave() //  self.ready += 1

} catch let error {
print(error)
 }

 }
task.resume()

 _ = dispatchGroup.wait(timeout: DispatchTime.distantFuture)
   DispatchQueue.main.async {
                self.tableView.reloadData()
            }

 }


text:
Q: Как отловить событие перехода на другой роутер в vue.js? Есть роутер
router.map({
    '/': {
        component: Index
    },
    '/user/:id': {
        component: UserInfo,
        name: 'UserInfo.show'
    },
...
});

Мне нужно, что если переходишь по ссылке '/' -сработала функция 1, если по ссыдке- '/user/:id', то функция- 2 . И при обновлении страницы, если роут на ссылке '/user/:id', что б так же сработала функция 2.
Как такое сделать?
(Читал про router.beforeEach(function(transition) ,но это срабатывает, при каждом переходе и не пойму, как разобраться.В ангуляре просто контроллер срабатывал, а здесь нигде не нашёл.)

A: Сейчас столкнулся с точно такой же задачей, в интернете нет информации об этом. У меня есть меню для мобильных устройств и его нужно закрывать при переходе по <router-link>. Отследить переход по ссылке можно:

*

*С помощью события click. Это не очень удобно, нужно вешать событие на каждую ссылку. Кроме того переход может быть совершён без нажатия на ссылку

*Следить за $route.path

watch: {
    '$route.path'() {
        console.log('Совершён переход по ссылке')
    }
}

A: Каждому конкретному можно задать метод beforeEnter, но мне кажется, что в представленном кейсе лучше выполнять весь код, который должен срабатывать при переходе в самом компоненте с помощью этих хуков.


text:
Q: Ngx-translate not translating anything I am in the process of internationalizing my current Angular 12 prototype application. Prototype means there is only the skeleton and a bunch of administrative features, and the developer(s) are in the process of coding vertical features in their working branch.
I have done the following, mostly following this tutorial

*

*Added the required dependencies in package.json
"@ngx-translate/core": "^13.0.0",
"@ngx-translate/http-loader": "^6.0.0",

and devDependencies:
"@biesbjerg/ngx-translate-extract": "^7.0.4",

*Set up AppModule (that's SharedModule in my case).
The module is imported by AppModule anyway:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {HTTP_INTERCEPTORS, HttpClient} from "@angular/common/http";
import {DelayInterceptor} from "./interceptors/delay.interceptor";
import {ConfirmationDialogComponent} from './dialogs/confirmation-dialog/confirmation-dialog.component';
import {MaterialModule} from "./material.module";
import {GenericErrorDisplayComponent} from './error/generic-error-display/generic-error-display.component';
import {TranslateLoader, TranslateModule} from "@ngx-translate/core";
import {TranslateHttpLoader} from "@ngx-translate/http-loader";

@NgModule({
  declarations: [
    ConfirmationDialogComponent,
    GenericErrorDisplayComponent
  ],
  imports: [
    CommonModule,
    MaterialModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: DelayInterceptor,
      multi: true
    },
  ],
  exports: [
    MaterialModule,
  ]
})
export class SharedModule {
}

// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
  return new TranslateHttpLoader(http);
}

*Set up some translation strings.
In some of my HTML files, I added translate directive, e.g.
<button (click)=add() class="btn btn-success" id="btn-add" mat-button translate>Aggiungi Ruoli</button>

*Ran ngx-translate-extract
"i18n:init": "ngx-translate-extract --input ./src --output ./src/assets/i18n/template.json --key-as-default-value --replace --format json",
"i18n:extract": "ngx-translate-extract --input ./src --output ./src/assets/i18n/it.json --output ./src/assets/i18n/en.json --clean --format json",

ngx-translate-extract populated some JSON files I had to amend
en.json
{
    "Permission": "Permission",
    "LegalEntity": "Legal Entity",
    "AML Type": "AML Type",
    "Indietro": "Back",
    "Salva": "Save",
    "Aggiungi Ruoli": "Add Roles",
    "ID": "ID",
    "Nome": "Name",
    "Data Creazione": "Created Date",
    "Data Modifica": "Modified Date",
    "Azioni": "Actions",
    "Aggiorna": "Refresh",
    "Nessun risultato trovato": "No result found",
    "Necessario eseguire login all'applicazione": "Application login is required"
}

Yes, that's a bunch of strings for now

*Set default language.
Now I have set en as default language. In the AppComponent:
  constructor(
    private router: Router,
    private injector: Injector,
    private translate: TranslateService,
  ) {
     translate.setDefaultLang(environment.language); //this is equal to 'en'
  }

Running the application, I expected text to appear in English, but was still localized. I have checked the Network tab and, indeed, the English JSON file is loaded
But none of the stings is localized in English

The console shows no error.
What is wrong in this setup and what should I do next to display English text?
By using ngx-translate-extract, I am now using the third approach provided by the tutorial:

*

*translation directive — id as a child <element translate>id</element>

so everything should work fine.
Following the GitHub tutorial, I moved the TranslationModule.forRoot import from the SharedModule to the AppModule. Same result as before.

A: I fell into this trap, too, but finally figured it out.
A lot of angular elements create wrapper elements, so for example a:
<button translate>My message</button>

actually turns into
<button>My message</button>

in which case the translation attribute lands on the wrong element.
I ended up having to do:
<button>My message</button>

to work around it.


text:
Q: Python "calculator" cant get it right, invalid syntax First time i've come here, and i would appreciate som help.
version = str(input("Select version: A B C D"))
number = int(input("Enter your first number"))
number2 = int(input("Enter you second number"))
if version == A:
    print(number * number2)

So i dont know what im doing wrong, have been trying float(input(select version: A B C D")  (im actually not rly finished with my script yet)
I want that if you press A, that it will register that to the version and print the numbers you wished for.

A: In your code A it's undefied variable. Change it to string 'A'
version = str(input("Select version: A B C D"))
number = int(input("Enter your first number"))
number2 = int(input("Enter you second number"))
if version == 'A':
    print(number * number2)

A: I get the following error:
NameError: name 'A' is not defined

It means that the variable named A is not defined. You probably want to compare to the string 'A', since the version variable contains a string.


text:
Q: Reference for a type of "multi-hamiltonian" system Let $H_1,H_2\in\mathcal{C}^1(\mathbb{R}^3;\mathbb{R})$ be two scalar fields. Consider a trajectory $\vec{x}(t)\in\mathbb{R}^3$ such that, for all observable $f\in\mathcal{C}^1(\mathbb{R}^3;\mathbb{R})$,
$$\frac{\mathrm{d}}{\mathrm{d}t}f(x)=\det\big(\nabla f,\nabla H_1, \nabla H_2\big)=\frac{\partial(f,H_1,H_2)}{\partial\vec{x}}.$$
This dynamical system recalls a Hamiltonian system with hamiltonian $H$ on the phase space $\lbrace(x,p)\in\mathbb{R}^2\rbrace$ such that for all observable $f\in\mathcal{C}^1(\mathbb{R}^2;\mathbb{R})$:
$$\frac{\mathrm{d}}{\mathrm{d}t}f(x)=\det\big(\nabla f,\nabla H\big)=\frac{\partial(f,H)}{\partial(x,p)}=\frac{\partial f}{\partial x}\frac{\partial H}{\partial p}-\frac{\partial f}{\partial p}\frac{\partial H}{\partial x}=\big\lbrace f,H\big\rbrace,$$
the Poisson bracket. Hence I would like to say that my dynamical system is a kind of "multi-hamiltonian" system. Is there any reference in which this kind of generalisation is studied?
Edit: it can be generalised to a system with $d-1$ scalar fields $(H_i)$ on $\mathbb{R}^d$ satisfying:
$$\frac{\mathrm{d}}{\mathrm{d}t}f(x)=\det\big(\nabla f,\nabla H_1,... \nabla H_{d-1}\big)=\frac{\partial(f,H_1,...,H_{d-1})}{\partial\vec{x}}.$$

A: Answered in PhysicsOverflow; reposting here for convenience:

Intriguingly enough, a quick search for "multi Hamiltonian physics" does not give any meaningful result; the mechanics described by the OP is Nambu mechanics, and is linked to nonassociative algebras appearing in e.g. M-theory.
In contrast to the construction by the OP, Nambu generalizes the Poisson bracket (rather than using a higher-dimensional matrix determinant) and writes the equations of motion
$$\frac{df}{dt}=\{f,H_1,H_2,…,H_n\}$$
See
https://arxiv.org/abs/hep-th/0212267 |    https://arxiv.org/abs/1903.05673


text:
Q: Convert byte slice "[]uint8" to float64 in GoLang I'm trying to convert a []uint8 byte slice into a float64 in GoLang.  I can't find a solution for this issue online.  I've seen suggestions of converting to a string first and then to a float64 but this doesn't seem to work, it loses it's value and I end up with zeroes.
Example:
metric.Value, _ = strconv.ParseFloat(string(column.Value), 64)

And it doesn't work...

A: For example,
package main

import (
    "encoding/binary"
    "fmt"
    "math"
)

func Float64frombytes(bytes []byte) float64 {
    bits := binary.LittleEndian.Uint64(bytes)
    float := math.Float64frombits(bits)
    return float
}

func Float64bytes(float float64) []byte {
    bits := math.Float64bits(float)
    bytes := make([]byte, 8)
    binary.LittleEndian.PutUint64(bytes, bits)
    return bytes
}

func main() {
    bytes := Float64bytes(math.Pi)
    fmt.Println(bytes)
    float := Float64frombytes(bytes)
    fmt.Println(float)
}

Output:
[24 45 68 84 251 33 9 64]
3.141592653589793

A: I think this example from Go documentation is what you are looking for:
http://golang.org/pkg/encoding/binary/#example_Read
var pi float64
b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.LittleEndian, &pi)
if err != nil {
  fmt.Println("binary.Read failed:", err)
}
fmt.Print(pi)

Prints 3.141592653589793

A: As the comments read, it all depends on what kind of data you have in your []uint8 slice.
If it is bytes representing an IEEE 754 floating-point value in Little Endian order, then use Kluyg's or peterSo's (better performance without use of reflection) answer.
If it is a textual representation in Latin-1/UTF-8 encoding, then you should be able to do what you just did:
package main

import (
    "fmt"
    "strconv"
)

func main() {
    var f float64
    text := []uint8("1.23") // A decimal value represented as Latin-1 text

    f, err := strconv.ParseFloat(string(text), 64)
    if err != nil {
        panic(err)
    }

    fmt.Println(f)
}

Result:

1.23

Playground: http://play.golang.org/p/-7iKRDG_ZM

A: I hope this hack helps. The purpose of it is to convert the long stream of binary numbers to float.
For example:
0110111100010010100000111100000011001010001000010000100111000000 -> -3.1415
func binFloat(bin string) float64 {

    var s1 []byte
    var result float64

    if len(bin) % 8 == 0 {

            for i := 0; i < len(bin) / 8; i++ {

                    //Chop the strings into a segment with a length of 8.
                    //Convert the string to Integer and to byte

                    num, _ := strconv.ParseInt(bin[8*i: 8*(i + 1)], 2, 64)
                    //Store the byte into a slice s1
                    s1 = append(s1, byte(num))
            }

    }

    //convert the byte slice to a float64.
    //The algorithm below are copied from golang binary examples.

    buf := bytes.NewReader(s1)

    //You can also change binary.LittleEndian to binary.BigEndian
    //For the details of Endianness, please google Endianness

    err := binary.Read(buf, binary.LittleEndian, &result)

    if err != nil {

            panic(err)
            fmt.Println("Length of the binary is not in the length of 8")
    }

    return result
}


text:
Q: Using aliased bond interface on host by an lxc container As the title says, how do I edit the lxc container's configuration to use the aliased bond0 interface on the host? This is what I have in the /etc/network/interfaces file now:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
#allow-hotplug eth0
#iface eth0 inet static
#   address 192.168.100.90/22
#   gateway 192.168.101.1

auto bond0
iface bond0 inet static
    address 192.168.100.90/22
    gateway 192.168.101.1
    bond-slaves eth0 eth1
    bond-mode active-backup
    bond-miimon 100
    bond-primary eth0 eth1

Can I add this to at the end:
auto bond0:101
iface bond0:101 inet static
    address 192.168.100.101
    netmask 255.255.252.0

and make the lxc container use this address? I don't want bridging, I just want the host and lxc cont. on the same network. I don't know what configuration options go into /var/lib/lxc/lxc_cont/config file. I tried this
lxc.network.type = phys
lxc.network.flags = up
lxc.network.link = bond0:101
lxc.network.hwaddr = 00:00:00:fe:fe:01
lxc.network.ipv4 = 192.168.100.101/22
lxc.network.ipv4.gateway = 192.168.101.1

but get this error:
lxc-start 20160912185144.642 ERROR    lxc_conf - conf.c:lxc_assign_network:3044 - failed to move 'bond0:101' to the container : Invalid argument
      lxc-start 20160912185144.642 ERROR    lxc_start - start.c:lxc_spawn:1197 - failed to create the configured network

In the future I would be adding other containers on the bond0 interface such as:
auto bond0:102
iface bond0:102 inet static
    address 192.168.100.102
    netmask 255.255.252.0

auto bond0:102

etc.

I've setup containers using bridged interface before, but I'm stuck whith regards to this bonding thing.
Any help or pointers are much appreciated!
Thanks for your time!
P.S. seems to me that my question is similar to this one
https://serverfault.com/questions/744443/is-there-a-way-to-get-the-kvm-guest-using-alias-interfaces-to-communicate-with-o

A: Had some help from a colleague admin at work. This is the working configuration:
# interfaces file

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
#allow-hotplug eth0
#iface eth0 inet static
#   address 192.168.100.90/22
#   gateway 192.168.101.1

auto bond0
iface bond0 inet manual
    bond-slaves eth0 eth1
    bond-mode active-backup
    bond-miimon 100
    bond-primary eth0 eth1

auto br0
iface br0 inet static
    address 192.168.100.90
    netmask 255.255.252.0
    gateway 192.168.101.1
    bridge-ports bond0
    bridge-fd 0
    bridge-stp off
    bridge-maxwait 5

So you need to move the ip address to the bridge. lxc-config looks like this:
...
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = br0
lxc.network.name = eth0
lxc.network.mtu = 1500
lxc.network.hwaddr = 00:00:00:fe:fe:01
lxc.network.ipv4 = 192.168.100.91/22
lxc.network.ipv4.gateway = 192.168.101.1
...

I usually edit the interfaces file for the guest also, although this shouldn't be needed as the config above controls the ip assignment:
# guest interfaces file
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
    address 192.168.100.91
    netmask 255.255.252.0

So now the host machine and future guest lxc containters will reside on the same network. For the other lxc containter you simply assign the next ip in the subnet. I guess you don't need macvlans, I tried using those but couldn't get it to work.
Hope someone will find this usefull, if they do I'll mark this as accepted answer.
If I missed some information please let me know.


text:
Q: The field must be a date - DatePicker validation fails in Chrome - mvc I have strange problem. My date validation doesn't work in Chrome. I've tried this answer but it didn't work for me.
I have this in my model:
[Display(Name = "Date")]
[DataType(DataType.Date)]
public DateTime Date { get; set; }

My View:

@Html.TextBoxFor(model => model.Item.Date, new { @class = "picker" })
@Html.ValidationMessageFor(model => model.Item.Date)

$(document).ready(function () {
    $('.picker').datepicker({
        dateFormat: 'dd.mm.yy',
        changeMonth: true,
        changeYear: true,
        selectOtherMonths: true
    });
});

Everything works in Opera and Firefox but Chrome doesn't like this type of date. I'm constantly getting the following error The field 'Date' must be a date.
Any ideas?
UPDATE
It seems there is a problem when the code is inside a partial view. When I copy that code to a main page, validation works fine.
I'm inserting partial view inside my main View simply like this:
@Html.Partial("_CreateOrEdit", Model)

And that code above is inside a partial view:
@model Pro.Web.Models.Model

@Html.TextBoxFor(model => model.Item.Date, new { @class = "picker" })
@Html.ValidationMessageFor(model => model.Item.Date)

$(document).ready(function () {
$('.picker').datepicker({
    dateFormat: 'dd.mm.yy',
    changeMonth: true,
    changeYear: true,
    selectOtherMonths: true
});

</script>
});

UPDATE2
It doesn't work after all. Sometimes it works, sometimes not. I clicked a couple of times on dates and sometimes validation passes. For the same date there could be good and wrong validation.
This is output html for date field:

<input class="picker" data-val="true" data-val-date="The field Date must be a date." data-val-required="The Date field is required." id="date" name="Item.Date" type="text" value="1.1.0001. 0:00:00" />

A: I solved it by removing the validation attribute
@model Pro.Web.Models.Model

@{ Html.EnableClientValidation(false); }
@Html.TextBoxFor(model => model.Item.Date, new { @class = "picker" })
@Html.ValidationMessageFor(model => model.Item.Date)
@{ Html.EnableClientValidation(true); }

A: It is kind of late to crash to the party after a year, but I've tried every solution I could find regarding this error, and none of them helped. So for anyone struggling like myself here is what solved this issue.
Add to the end of jquery.validate.globalize.js and its minified version(depends on what you are using) this little snippet of code.
...
   $.validator.methods.range = function (value, element, param) {
        var val = Globalize.parseFloat(value);
        return originalMethods.range.call(this, val, element, param);
    };

}(jQuery, Globalize));

Globalize.culture("en-GB");
Of course, use your own culture settings inside quotation marks.
Hope it helps!

A: Exact the same situation here (partial view)
I solved it by removing the validation attribute and perform validation at server side:
$('#date').removeAttr("data-val-date");

A: In my opinion problems is that MVC is generating for date HTML5 input with [type=date]. This causes that in chrome valid date format is same same as system date format.
You can probably set date format in MVC to be common with JqueryUI using following attribute:
[DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd.MM.yy}", ApplyFormatInEditMode=true )]

The second idea is to use code from article: Creating a Native HTML 5 Datepicker with a Fallback to jQuery UI
One more thing. There is a good topic about date in html input: Is there any way to change input type="date" format?

A: The problem seems to be with <input type="date" /> (HTML5) as specification says that valid value is defined as RFC3339.
So I changed my View to something like this:

    @Html.LabelFor(model => model.ValidFrom)

    <input id="validfrom" type="text" name="validfrom" />
    @Html.HiddenFor(model => model.ValidFrom)
    @Html.ValidationMessageFor(model => model.ValidFrom)

Hope it helps.

A: I had the same error. Solved it by applying datetime as the type,
 @Html.EditorFor(model => model.LineResetAllowStartDate, new { htmlAttributes = new { @class = "form-control" ,  @type = "datetime" } })

similarly use time for only time
 @Html.EditorFor(model => model.LineResetAllowStartDate, new { htmlAttributes = new { @class = "form-control" ,  @type = "time" } })


text:
Q: Fragments reuse Is it somehow possible to reuse fragments?
In an example like this
def unpublished_by_title(title) do
  from p in Post,
    where: is_nil(p.published_at) and
           fragment("downcase(?)", p.title) == ^title
end

It seems like it would be very convenient to be able to extract fragment-part into a separate function so that it can be reused in other places, e.g.:
def unpublished_by_title(title) do
  from p in Post,
    where: is_nil(p.published_at) and
           downcase(p.title) == ^title
end

def downcase(title) do
  fragment("downcase(?)", ^title)
end

however, after trying many different variations it seems like this wouldn't work because of macro expansions or something like that. Any ideas?

A: You are right, queries are composed at compile time. Because of this, if you want to extend query syntax, you need to define macros instead of regular functions.
Something like the following should do the trick:
defmacro downcase(field) do
  quote do
    fragment("downcase(?)", unquote(field))
  end
end

Remember you need to define macro before you use it.


text:
Q: Is it possible to completely dispose of a usercontrol in winrt? I have an app where I dynamically create user controls depending on the situation.  When I'm done with them I remove them from the container, but they are still taking up memory.
I've implemented a "dispose" method in the code to clear the controls inside of the user control, but I still feel like there is a better way to do it.
I'm not sure what code I can post as no code is really relevant.
All I really have is what I'm doing now with the dispose method
  public void Dispose()
        {

            ContentWebView.NavigateToString("about:blank");
            YoutubeMediaPlayer.Stop();
        }

A: The Dispose method is used for releasing unmanaged resources.
When all references to an object are removed, the garbage collector will eventually "Collect" it (freeing the memory). You can't actually control when this happens, even calling GC.Collect is technically just a suggestion. You can, however, invoke dispose on an object directly (note that this may cause odd behavior or exceptions if it is still in use!)
If you suspect a control has unmanaged resources that need to be cleaned up, you should call Dispose on it directly when you are finished with it (GDI Bitmap objects need to be cleaned up like this). From your comments, it sounds like you just need the garbage collector to actually free the memory, which is something thats hard to control (you can try calling GC.Collect though).
MSDN for Dispose: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx


text:
Q: centering all Imgs on Responsive Design I'm wondering if there's a good, generic, simple way, to code/ state all images to be centered horizontally within a responsive design below a certain viewport.
Eg, below 480px width viewport, all images display as block and are centered on the screen.

A: You'll need to use a combination of CSS Media Queries and the actual CSS...
e.g. You can have 2 separate CSS files and call the relevant one based on device features
<link href="small.css" media="only screen and (max-width:480px)" />
<link href="big.css" media="only screen and (min-width:480px)" />

Then define the actual CSS inside small.css/big.css
e.g. in small.css, define the following style
img {margin:o auto;text-align:center}

and no need to define anything in big.css (default gets applied)

A: I'm not sure if it works, but try
img { margin:o auto; text-align:center}

but some part will work, but I'm not totally sure if will work all way around due some DIVs might have not inherit the width and will not align all images to center.


text:
Q: Listbox doesn't detect selected item I have the following listbox:
<ListBox ItemsSource="{Binding AvailableTemplates}" Style="{DynamicResource SearchListBoxStyle}" SelectedItem="{Binding SelectedTemplate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <RadioButton Content="{Binding}" GroupName="group" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

this doesn't detect as selected item changed if i select on the radiobutton. It only detects if i click under the radio button on the listbox row. Any ideeas how to amend to detect as selected item changed when clicking on the radio button?

A: If you only want to synchronize the RadioButton.IsChecked with ListBoxItem.IsSelected, you can use a binding
<RadioButton Content="{Binding}" GroupName="group"
             IsChecked="{Binding Path=IsSelected, RelativeSource={
                 RelativeSource AncestorType={x:Type ListBoxItem}},Mode=TwoWay}"/>

If you don't want your items synchronized, you can use a Trigger that sets IsSelected whenever the item gets keyboard focus, although this will only keep an item selected as long as it has keyboard focus
<Style TargetType="ListBoxItem">
  <Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="True">
      <Setter Property="IsSelected" Value="True" />
    </Trigger>
  </Style.Triggers>
</Style>

And if you want it selected regardless of if the element still has keyboard focus or not, you have to use a little code behind
<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>

protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

A: You can not mistake: listBox.SelectedItem and radioButton.IsChecked
They are totally different things,
SelectedItem is called the ListBoxItem, your radiobutton is within a listboxitem.
You must make a binding for property IsChecked (RadioButton).

A: Try setting ListBoxItem.IsHitTestVisible to false (you may do this in xaml). It solved my selection problem elementary. My problem was that selection only worked when I clicked on white space in ListBox line but not a custom content.


text:
Q: Access to iTunes Ratings Data We want to write a Windows/OS X app that sends podcast ratings info from an iPod and iTunes back to a server. Two questions:

*

*Is there documentation for how ratings data are stored in iTunes,

*if a user has iTunes set to auto-delete programs he has heard, is there a way to capture the ratings data before it's gone?

A: I doubt there is an official spec on the data file format, but you can find rating info in the "iTunes Music Library.xml" file in the iTunes directory.  Look for a key called "Rating" with an integer value from 0 to 100.  It won't be there if the user hasn't rated the item.  For example, a 4-star rating will have a value of 80.

A: itunes stores its Music Library data and Ratings in an XML file on the user's machine. In windows its located in the "Music" or "My Music" folder.
You can open the "iTunes Music Library.xml" file and look for the Rating element to see what the user rated each song. Since its XML, it's pretty self-explanatory. That should be pretty easy to open and parse from the program you're writing.
I think iTunes doesn't remove the podcasts from its xml file until the program is closed. You should be able to grab that rating data as long as itunes is still open.

A: In addition to the xml file, there is also a COM interface that will give you access to all of the library info, including the rating for each song. The SDK is documented.
I don't know what language you want to use, but I have used the C# to interface with iTunes and it was very smooth.
You can download the SDK at http://developer.apple.com/sdk/


text:
Q: A weighted score in addition to total points per user There are two observations on Stackoverflow:

*

*Some topics naturally receive more activity than others - for example a question about PHP/Javascript would get much more activity (in terms of views, votes, answers etc) than a question on Scala/Erlang.

*Esp within the high activity areas, voting on some answers becomes a popularity contest rather than a vote on the quality of the answer. For example, a question on which Javascript library can be used to perform a certain task becomes a popularity vote on JQuery vs Dojo etc, so answers supporting any get more up-votes depending on the respective popularity rather than answer quality.
Here is a fundamental question:
If a  Scala/Erlang expert has provided 100 good quality answers, do they roughly accumulate the same points as a PHP/Javascript expert who has provided the same number of good quality answers?
In the current system the answer I think is no. This kind of skewed reward system might result over the long run in a winner-takes-all situation, where few popular areas would get lots of users and interest while most unpopular areas get very few users.
Here is a proposed solution:
A weighted score can be used, and the factors that affect this score would be:

*

*the relative total activity in the tag/tags area of the question.

*the relative activity for the given question.

Based on these two factors a relative scoring factor can be generated that would be used to weight the the points generated for activity in the given question. This weighted points score is then used to accumulate the total weighted score per user which better reflects the quality of the user activities. So basically, the total points figure is like your net worth, and the weighted score is like your worth value relative to your demographic group etc.
Not all details are sorted out here of course - like whether the popularity measure is a snapshot or changing over time.
Such weighted score can then be displayed next to the user name as a mark of credentials, and can even be used in the permissions system.
Update:
Some clarifications:

*

*The popularity contest above refers to the popularity of the languages/platforms/apps/libs etc not the popularity of the poster. There is no issue w.r.t poster popularity.

*The proposed weighting system does not give higher weight to less popular topics, rather it tries to achieve fairness by giving equal relative weight. For example if  Javascript or an aspect within it is decided to be 5 folds more popular than Scala, then 5 up-votes in Javascript would be equivalent to one up-vote for Scala. Or maybe a factor of that like 60%, or an effect that comes into play after certain threshold - say after 4 up-votes. All these are details on how this balance can be achieved.
Another devilish detail is how to decide the popularity factor - I proposed factors based on the popularity of the tags on the question and the activity in the question. Others might suggest other factors or a different take on these.

A: I disagree that it's a popularity contest, I don't see where you got that from. I rarely ever see answers getting upvoted just because someone has more reputation. In fact, I quite often see people point out things that higher-rep users do wrong. I think it's more the opposite of a popularity contest. "They have a lot of reputation, gotta find everything they do wrong and point it out."

If a Scala/Erlang expert has provided 100 good quality answers, do they roughly accumulate the same points as a PHP/Javascript expert who has provided the same number of good quality answers?

Well you're being a bit hypocritical in a way. Just because an answer is posted in a less popular topic doesn't mean it's any better than an answer posted in a more popular topic. So why should it get more weight? Honestly, if a certain language or feature, whatever, is a lot less popular around the world, it doesn't make much sense to credit users more just for using it. If you tags are appropriate, all the users who find it relevant to them will look at it. That's the point, to get people who can help you to look at your question. The reputation system may be a game for a lot of people, trying to get as high as they can, but really that's not the focus of the site. Not to say I don't love getting reputation, but I spend a lot more time commenting and helping others improve their questions/answers, and more recently, a heck of a lot of time in the review panel.
This particular line bothers me: the relative activity for the given question. The activity of a question completely depends on the wording in the title and the tags that it is given, and maybe a mix of upvotes that it's received so far. If it's poorly worded and tagged, a lot less people are going to look at it.
This would be like giving students who take Japanese in high school extra credit because the subject is less popular than say Spanish or German, even though all the students put in an equal amount of effort and time into their work.
Update:

For example if Javascript or an aspect within it is decided to be 5 folds more popular than Scala, then 5 up-votes in Javascript would be equivalent to one up-vote for Scala.

That still seems entirely unfair. A vote is a vote is a vote. We're just giving specific users more attention for their equally helpful answer, merely because they're posting in a less popular topic. A post in JavaScript will receive more upvotes because it's more useful to the majority of people than a post in Scala. You're trying to say that Scala is equivalent to JavaScript, and other languages, when it's not.
The base of the problem is you're shifting the "fairness" from one side to the other, not really creating an equal medium. Reputation is a rough measurement of how much the community trusts you. The community, not the peers within the specific tags you work with. If the greater majority of the community works with JavaScript, then it would stand true that a greater majority of the community trusts a user posting in JavaScript than a user posting in Scala. Note as well how it says "rough measurement."


text:
Q: Graphic image rendering corrupted I'm using lubuntu 18.04 and I keep it up to date to avoid problems.
However, latelly I wanted to enable the Radeon graphic card to off-load the CPU, but enabling it results in a corrupted image as shown below.

Link to corrupted screen image
I tried several parameters and settings of the radeon driver to avoid this corruption without any luck. One of the effects is that if I over the pointer onto the defects, they disappear for a few seconds and then they reappear again in other positions.
agpmode  4
...
disp_priority  0 , 1 , 2
..
dynclks  -1 , 0 , 1
fastfb  0 , 1
...
modeset  1
...
no_wb  0 , 1
...

The only way I observed the corruption disappear is when I remove memory below 1GB of total size. By the way, I did swap around the modules to check if one is defective, but no, all of them seam to be fine as long as the total memory remains below the 1GB.
Here is some characteristics of the laptop I'm using:
user@bcn-lap:~$ sudo lspci
00:00.0 Host bridge: Intel Corporation 82855PM Processor to I/O Controller (rev 03)
00:01.0 PCI bridge: Intel Corporation 82855PM Processor to AGP Controller (rev 03)
...
00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev 81)
...
00:1f.3 SMBus: Intel Corporation 82801DB/DBL/DBM (ICH4/ICH4-L/ICH4-M) SMBus Controller (rev 01)
...
01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] RV250/M9 GL [Mobility FireGL 9000/Radeon 9000] (rev 01)
...

Any pointer of how to avoid this rendering problem is much appreciated.


text:
Q: PHP + MYSQL Seating Reservation System. Counting free seats I have a table like this:
    $sql = "CREATE TABLE dramaStudio
   (
   rowId varchar(1) not null,
   columnId int not null,
   status int,
   firstName varchar(15) not null,
   lastName varchar(15) not null,
   updatedby varchar(10),
   PRIMARY KEY (rowId, columnId)
   )";

On the homepage of my website I would like the user to be able to see if there are any free seats without going on to the seating plan. Pretty much just a bit saying 'free seats:'followed by a number.
My logic in pseudo code would be:
$j=0
select * from dramaStudio
for every status == 0
    $j+1
echo $j

Any help will be greatly appreciated.

A: just do a COUNT on all the fields who have a status of 0?
SELECT COUNT(*) FROM dramaStudio WHERE status = '0'

A: Assuming that status=0 if the free seat:
SELECT COUNT(*) AS freeseats FROM dramaStudio WHERE status=0

Full example, from php manual:
<?php
  $link = mysqli_connect("localhost", "my_user", "my_password", "world");

  /* check connection */
  if (mysqli_connect_errno()) {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
  }

  $query = "SELECT COUNT(*) AS freeseats FROM dramaStudio WHERE status=0";
  $result = mysqli_query($link, $query);

  /* associative array */
  $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
  echo $row['freeseats']; // this is an integer

  /* free result set */
  mysqli_free_result($result);

  /* close connection */
  mysqli_close($link);
?>

A: See sample code
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("test_db",$con);

$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);

while ($property = mysql_fetch_field($result))
  {
  echo "Field name: " . $property->name . "
";
  echo "Table name: " . $property->table . "
";
  echo "Default value: " . $property->def . "
";
  echo "Max length: " . $property->max_length . "
";
  echo "Not NULL: " . $property->not_null . "
";
  echo "Primary Key: " . $property->primary_key . "
";
  echo "Unique Key: " . $property->unique_key . "
";
  echo "Mutliple Key: " . $property->multiple_key . "
";
  echo "Numeric Field: " . $property->numeric . "
";
  echo "BLOB: " . $property->blob . "
";
  echo "Field Type: " . $property->type . "
";
  echo "Unsigned: " . $property->unsigned . "
";
  echo "Zero-filled: " . $property->zerofill . "

";
  }

mysql_close($con);

A: you are storing the filled seat? to find out empty you have to specify number of colomn and rows.
and if the filled and empty seat is distinguishable on status in table.
you can do like this,
    $query = "select * from dramaStudio where status = 0";
    $result_Set = mysql_query($query);
    while($row = mysql_fetch_object($result_set)){
        echo $row->rowId .',', $row->columnId;
        echo '
';
    }


text:
Q: String ASCII value to Integer Array i want to convert a string to a integer array.
but i want the ASCII Value in the integer array
for example "A"  -> 65
for example "2"  -> 50

Dim myString as string = "ABC"
'....
Dim integerArray(3) as integer

plz without any work around like loops ;)

A: If you want ASCII encoding, you can do this:
Dim test As String = "Hello"
Dim bytes As Byte() = Encoding.ASCII.GetBytes(test)

The array 'bytes' will contain the ASCII representation of the string.  As @user1937198 pointed out, though, is ASCII encoding what you really want?
To get the byte array to an array of integers, you can do this:
Dim ints As Integer() = bytes.Select(Function(b) Convert.ToInt32(b)).ToArray()

A: Without any "cheating" like for loops:
Dim asciiValues = "The string to convert".ToCharArray().Select(Function(c) Asc(c)).ToArray()

(Note: loops are not cheating either... ;))


text:
Q: Automatically number paragraphs The report format I am working with requires each paragraph to be numbered. Is there a way to implement automatic paragraph numbering in R markdown? Thanks.

A: One option to solve your question is to create a counter manually and inlcude this before every paragraph and make it print with the brakets like this:
---
title: "Sample Document"
output:
  html_document
---

```{r setup, include=FALSE}
x <- 0
```

# title 1
`r (x <- x+1)` bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1 bla1

`r (x <- x+1)` bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2 bla2

# title 2
`r (x <- x+1)` bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3 bla3

The result will be this:


text:
Q: Почему приложение вылетает Подскажите почему мое приложение не работает.Сам пытался  разобраться к сожалению не смог.
Майн акстивити.
public class MainActivity extends AppCompatActivity {
List<ModelClass> model = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setData();
    RecyclerView recyclerView =(RecyclerView) findViewById(R.id.recyclerView);
    // создаем адаптер
    Adapter_class adapter = new Adapter_class(this, model);
    // устанавливаем для списка адаптер
    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(adapter);
}

private void setData(){

    model.add(new ModelClass (R.color.colorAccent));
    model.add(new ModelClass (R.color.colorAccent));
    model.add(new ModelClass (R.color.colorAccent));
    model.add(new ModelClass (R.color.colorAccent));
}
public void Intent_1(int ButtonPosition){
    Intent intent=new Intent(MainActivity.this,for_trenirovryClick.class);
   intent.putExtra("OnClickRecyclerView",ButtonPosition);
    startActivity(intent);
}

}
public class Adapter_class extends RecyclerView.Adapter<Adapter_class.ViewHolder> {
private LayoutInflater inflater;
private List<ModelClass> modelClass;
Context context1;
MainActivity mainActivity=new MainActivity();
int positionIndex;

Adapter_class(Context context, List<ModelClass> modelClass) {
    this.modelClass = modelClass;
    this.inflater = LayoutInflater.from(context);
    this.context1=context;
}
@Override
public Adapter_class.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.item_layout, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(Adapter_class.ViewHolder holder, final int position) {
    ModelClass model_class = modelClass.get(position);
    holder.button.setBackgroundResource(model_class.getBackground());

    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           switch (position){
               case 0:mainActivity.Intent_1(0);
               case 2:mainActivity.Intent_1(1);
               case 3:mainActivity.Intent_1(2);
               case 1:mainActivity.Intent_1(3);
           }

        }
    });

}

@Override
public int getItemCount() {
    return modelClass.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    final Button button;
    ViewHolder(View view) {
        super(view);
        button =  (Button) view.findViewById(R.id.button4);
    }

}

}
public class ModelClass {
private int image;

public ModelClass(int image){ this.image = image;}

public int getBackground() {return this.image; }

}
public class for_trenirovryClick extends AppCompatActivity {
List<ModelClass2> model = new ArrayList<>();

RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_for_trenirovry_click);
    Intent intent1=getIntent();
    int i= intent1.getIntExtra("OnClickRecyclerView",1);
    setData();
    recyclerView=findViewById(R.id.recyclerView2);

    // создаем адаптер
    Adapter_class2 adapter = new Adapter_class2(this, model);
    // устанавливаем для списка адаптер
    recyclerView.setAdapter(adapter);

}
private void setData(){

    model.add(new ModelClass2 (R.color.colorAccent,"приседания","x 16"));
    model.add(new ModelClass2(R.color.colorAccent,"jkhjjhgjhhjhjgjkhkjkkjkj","x 21"));
    model.add(new ModelClass2 (R.color.colorAccent,"jdjkgjkdfjgkfdfkhdk","x 10"));
    model.add(new ModelClass2 (R.color.colorAccent,"kjhjklkijdhkhdfdsaaa","x 9"));
}

}
public class ModelClass2 {

private int image_resourse;
private String text_for_ex;
private String text_for_times;

public ModelClass2(int image_resourse, String text_for_ex, String text_for_times) {
    this.image_resourse = image_resourse;
    this.text_for_ex = text_for_ex;
    this.text_for_times = text_for_times;
}

public int getImage_resourse() {
    return this.image_resourse;
}

public String getText_for_ex() {
    return this.text_for_ex;
}

public String getText_for_times() {
    return this.text_for_times;
}

}
public  class Adapter_class2 extends RecyclerView.Adapter<Adapter_class2.ViewHolder> {
private LayoutInflater inflater1;
private List<ModelClass2> modelClass2;

Adapter_class2(Context context, List<ModelClass2> modelClass) {
    this.modelClass2 = modelClass;
    this.inflater1 = LayoutInflater.from(context);

}
@Override
public Adapter_class2.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater1.inflate(R.layout.item_layout2, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull Adapter_class2.ViewHolder viewHolder, int i) {
    ModelClass2 model_class = modelClass2.get(i);
    viewHolder.imageView_ex.setImageResource(model_class.getImage_resourse());
  viewHolder.kol_times.setText(model_class.getText_for_times());
  viewHolder.name_exercise.setText(model_class.getText_for_ex());

}

@Override
public int getItemCount() {
    return modelClass2.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    final TextView name_exercise;
    final TextView kol_times;
    final ImageView imageView_ex;
    final CheckBox checkBox;
    ViewHolder(View view) {
        super(view);
        name_exercise=view.findViewById(R.id.textView11);
        kol_times=view.findViewById(R.id.textView12);
        imageView_ex=view.findViewById(R.id.imageView5);
        checkBox =view.findViewById(R.id.checkBox5);

    }

}

}
При клике на кнопку у меня приложение вылетает

A: Вы создаёте вручную экземпляр активити и вызываете на нём методы. Это не будет работать, т.к. все работоспособные экземпляры активити создаются системой.
У вас в коде много проблем, в т.ч. неправильное именование переменных, классов, методов, засим не буду описывать сложное и правильное решение, а покажу простое решение:
Измените ваш адаптер так, чтобы он принимал созданный системой экземпляр активити:
public class Adapter_class extends RecyclerView.Adapter<Adapter_class.ViewHolder> {

    private LayoutInflater inflater;
    private List<ModelClass> modelClass;
    Context context1;
    MainActivity mainActivity;
    int positionIndex;

    Adapter_class(MainActivity context, List<ModelClass> modelClass) {
        this.modelClass = modelClass;
        this.inflater = LayoutInflater.from(context);
        this.context1=context;
        this.mainActivity = context;
    }

тут изменена одна строка и одна строка добавлена. После этого ваш код должен заработать.


text:
Q: How to get date from month as input in oracle? My query is , I need to give input a month ,i.e ex :input will be 'MAR' then i need to get 1st date and last date for the March month .
select to_char(trunc(trunc(sysdate, 'MM'), 'MM'),'DD-MON-YYYY') "First Day of Last Month"
       , to_char(trunc(sysdate, 'MM') ,'DD-MON-YYYY') "Last Day of Last Month"
 from dual ;

Any one please help..

A: month_start := to_date('MAR', 'MON');
month_end := last_day(month_start);

*

*Month names depend on specifics of the NLS language/territory so may need to tweak them. (alter session set nls_language/nls_territory = AMERICAN/AMERICA).

*You haven't mentioned what would be the year, so the assumption is that you need current one.

If the year is also a variable input:
month_start := to_date('2015-MAR', 'yyyy-MON');


text:
Q: Moving objects in PyGame and taking a single input I'm creating a game in PyGame where I need to pick up a plate and move it around the kitchen. so far I have managed to have the player collide and interact with the object but have not been able to pick up and move the object around the screen. I've been stuck on this issue for weeks and any help would be massively appreciated.
def new(self):
  self.plate = pg.sprite.Group()
  for tile_object in self.map.tmxdata.objects:
    if tile_object.name == 'plate':
            self.plate.x = tile_object.x
            self.plate.y = tile_object.y
            Plate(self, self.plate.x, self.plate.y)

      touch=False
      if (tx-32)<= x and (tx+32) >= x and (ty-64)<= y and (ty+64) >= y:
          touch = True
      elif (ty-32)<= y and (ty+32) >= y and (tx-64)<= x and (tx+64) >= x:
          touch = True
      return(touch)

def update(self):
      self.all_sprites.update()
      x = self.player.pos[0]
      y = self.player.pos[1]
      holding = 0
      keys_pressed = self.get_pg_events()```

      touch = self.grid_location(self.player.pos[0] ,self.player.pos[1] ,self.plate.x, self.plate.y)
      if touch == True:
          self.space_bar_plate.reposition(self.player.pos[0], self.player.pos[1]+64)
          keys = pg.key.get_pressed()
          if keys[pg.K_SPACE]:
              now = pg.time.get_ticks()
              if now - self.player.last_action > ACTION_RATE:
                  self.player.last_action = now
                  self.plate.x = math.cos(self.player.rot*math.pi/180)*80+self.player.pos[0]
                  self.plate.y = math.sin(self.player.rot*math.pi/180)*80+self.player.pos[1]
                  self.plate = Plate(self, self.plate.x , self.plate.y)
     else:
         self.space_bar_plate.reposition(-32, 0)```

in my sprites file

class Plate(pg.sprite.Sprite):
  def __init__(self, game, x, y):
      self.groups = game.all_sprites, game.plate
      pg.sprite.Sprite.__init__(self, self.groups)
      self.game = game
      self.image = game.plate_img
      self.rect = self.image.get_rect()
      self.pos = (x, y)
      self.rect.center = self.pos

  def reposition(self, x, y):
      self.pos = (x, y)
      self.rect.center = self.pos

A: Here's a simple example of how to do something like that. Use W,A,S,D to move and SPACE to pick up and drop the black box.
import pygame

RESOLUTION = 800, 600
TILESIZE = 32
PLAYER_SPEED = 200
FPS = 60

class Player(pygame.sprite.Sprite):
    def __init__(self, pos, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((TILESIZE, TILESIZE))
        self.image.fill('dodgerblue')
        self.rect = self.image.get_rect(center=pos)
        self.pos = pygame.Vector2(pos)
        self.movement = pygame.Vector2()
        self.item = None

    def update(self, dt, events):
        pressed = pygame.key.get_pressed()
        self.movement.x, self.movement.y = 0, 0
        if pressed[pygame.K_w]: self.movement.y = -1
        if pressed[pygame.K_a]: self.movement.x = -1
        if pressed[pygame.K_s]: self.movement.y =  1
        if pressed[pygame.K_d]: self.movement.x =  1
        if self.movement.length() > 0:
            self.movement.normalize_ip()
        self.pos += self.movement * dt * PLAYER_SPEED
        self.rect.center = self.pos

        if self.item:
            self.item.pos += self.movement * dt * PLAYER_SPEED
            self.item.rect.center = self.item.pos

        for e in events:
            if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE:
                self.pick_up() if not self.item else self.drop()

    def pick_up(self):
        collisions = pygame.sprite.spritecollide(self, self.groups()[0], False)
        items = list(s for s in collisions if hasattr(s, 'can_be_picked_up') and s.can_be_picked_up)
        if items:
            self.item = items[0]

    def drop(self):
        self.item = None

class Plate(pygame.sprite.Sprite):
    def __init__(self, pos, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((TILESIZE, TILESIZE))
        self.image.fill('black')
        self.rect = self.image.get_rect(center=pos)
        self.pos = pygame.Vector2(pos)
        self.can_be_picked_up = True

def main():
    pygame.init()
    screen = pygame.display.set_mode(RESOLUTION)
    dt, clock = 0, pygame.time.Clock()
    sprites = pygame.sprite.Group()
    Player((400, 300), sprites)
    Plate((200, 200), sprites)
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return
        screen.fill('grey')
        sprites.update(dt, events)
        sprites.draw(screen)
        pygame.display.flip()
        dt = clock.tick(FPS) / 1000

if __name__ == "__main__":
    main()

As you can see, in the update function of the Player we check if space was pressed. Then we check if we're already holding an item.
If yes, we drop it.
If not, we check all sprites that we currently collide with and take that first that has can_be_picked_up set to True (you don't have to do this this way but why not) and pick it up.
Picking it up just means setting it to self.item and then update its position in the player's update method, too.
Of course, there are multiple ways to do something like this; but I think this quite similar to what you tried to do in your code.

A: First you track if a click is made and change a variable to True:
if event.type == pygame.MOUSEBUTTONDOWN:
    clicked = True

If you release the mouse you reset this variable:
elif event.type == pygame.MOUSEBUTTONUP:
    clicked = False

Then again in your pygame loop you track the mouse position by:
elif event.type == pygame.MOUSEMOTION:
    if clicked:
        x, y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]

Then when you blit the image you do it with these x and y values.


text:
Q: Why does Stack Overflow get a F in the Add Expires Headers category from YSlow? Stack Overflow's main page gets good grades in YSlow except for an F for Add Expires Headers. I know that SE team members are obsessed with performance. Why don't they put far expiration dates in the headers by configuring IIS?

A: YSlow gives me grade D for Expires headers,

As you can see there, all of those sites are outside stackoverflow network.
And also those are ads, and site stats sites, so expires headers are no much meaningful for such sites.