text:
Q: root directory permission issue cocoa app to run scripts in mac os 10.7 Team,
I'm new to MAC OS Cocoa application developement.
I'm developing a cocoa application, kind of utility application.
In my application I'm executing few commands like "mkdir", "cp", "rm"
Im executing the above commands from objective c using system command. As example shown below.
system("mkdir tempDir");

While running this application from xcode it is running fine and created all folders.
when i run by double clicking on the .app file in Mac OS X 10.7, the directory is not created and exited with error code 256. I noticed that while launch the application from .app file directly it is running from root directory i.e. macintosh drive.
Then I have changed the Macintosh's permission, allowing read&write permission for everyone. I did this in "GetInfo" section. By doing this allowed the application to create directories while running from .app.
Kindly help me to solve this permission problem from my application itself.

A: If permissions are ok, then its sounds like you may not be getting a proper shell environment.  There are Cocoa equivalents for many simple commands like mkdir, but if you prefer the command line, I'd suggest using the NSTask object model which I've had very good luck with.  Here is my own adaptation of a fairly common pattern for you to try.
-(NSString *) runThisCmd:(NSString *) runString withArgs:(NSArray *)runArgs  {

//this method of calling NSTask is designed for small quick commands that return
//a small amount of data to the command line

NSTask *task = [NSTask new];
[task setLaunchPath:runString];
[task setArguments:runArgs];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput: [NSPipe pipe]];
[task setStandardError: [task standardOutput]];
[task launch];

NSData *stdOuput = [[[task standardOutput] fileHandleForReading] readDataToEndOfFile];

[task waitUntilExit];

if ([task terminationStatus] == 0) {

    //scriptSuccess = YES;
}
else {

    //scriptSuccess = NO;
}

NSString *outputString = [[NSString alloc] initWithData:stdOuput encoding:NSUTF8StringEncoding];
return outputString;

}

call it like this:
NSString *runCmd = [[NSString alloc] initWithString:@"/bin/bash"];
NSArray *runArgs = [[NSArray alloc] initWithObjects:@"-c",@"mkdir",@"/tmp/newdir",nil];

//update proper label
NSString *output;
output =  [self runThisCmd:runCmd withArgs:runArgs];

Note: you can adapt this approach to act just like the system() command if you use the [task termination] logic and drop the return strings.  Even if you don't need it, the output can be helpful in troubleshooting errors.

A: I was having the exact same problem as you, and thought I might as well share the solution. You are writing data to the wrong directory. See this page:

On the Mac, the correct location to store persistent user-related files for your application is in a directory with the same name as your application in the Application Support directory for the current user.

The page I linked above shows you how to create a directory for your data in Application Support and find it in your code. Doing this solved all my permissions problems.


text:
Q: How does MATLAB treat operations on subarrays in terms of speed and memory I have large arrays which I am doing fairly simple linear algebra on. I have achieved good speed ups by vectorising the operations but i want to know how MATLAB treats the subarrays.
I pre-allocate arrays because they are used in various operations, and my formulae are long and require many different arrays and subarrays so readability counts while I am still coding.
For example, a simple case:
Array = someBig2DArray;
soln = Array;
[len_x len_y] = size(Array);
A1 = Array(2:len_x-1, 2:len_y-1);
A2 = Array(1:len_x-2, 2:len_y-1);
A3 = Array(3:len_x, 2:len_y-1);

soln(2:len_x-1, 2:len_y-1) = (A1 - 2*A2 + A3)/2

The down side of using this method is that I have 3 extra arrays of basically the same size taking up memory.
Alternatively:
soln(2:len_x-1, 2:len_y-1) = (Array(3:len_x, 2:leny-1) - 2*Array(2:len_x-1, 2:len_y-1) + Array(1:len_x-2, 2:len_y-1))/2

Does this second method use less memory, while sacrificing readability? Or does it actually create 'temporary' arrays and actually end up using roughly the same amount of memory, but only briefly? (I am nearing the limit of my system...)
Are these methods the same speed internally, talking about bigO and number of operations?
Are there any ways of reducing the memory requirements of the first method while keeping readability?
Here is a snippit from my code (actually 1D in this case). My initial thinking was that vectorising the for loop and using matlab's usually very good matrix functions would speed things up. As it turns out the first method is significantly faster. Why?
for i = 3:len-1
    dSdx = sigma(i) - sigma(i-1) + ...
        0.25*(sigma(i+1) - sigma(i) - sigma(i-1) + sigma(i-2));
    ddSdx2 = sigma(i+1) - 2*sigma(i) + sigma(i-1);
    sigma_new(i) = sigma(i) + dT*(kappa*ddSdx2/h^2 - U*dSdx/h);
end

%This section replaces the for loop above
dSdx = sigma(3:len-1) - sigma(2:len-2) + 0.25*(sigma(4:len) ...
    - sigma(3:len-1) - sigma(2:len-2) + sigma(1:len-3));
ddSdx2 = sigma(4:len) - 2*sigma(3:len-1) + sigma(2:len-2);
sigma_new(3:len-1) = sigma(3:len-1) + dT*(kappa*ddSdx2/h^2 - U*dSdx/h);

A: you can use tic and toc to time your methods. trying out your two approaches (there are some typos and assignment mismatches that needed to be fixed), shows that the second approach is ~3.5 times slower than the first.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the properties of this linear operator? Suppose $f(x)$ is a function which satisfies the following condition:
$$f(x)=\sum_{k=0}^\infty G(2k)\frac{x^{2k}}{(2k)!}$$
Where the generating function $G(x)$ is a "natural" or "discrete-analytic" function in the sense it is equal to its Newton series expansion:
$$G(x) = \sum_{k=0}^\infty \binom{x}k \Delta^k G\left (0\right)$$
The function $f(x)$ is evidently even.
Now the operator $U$ on $f(x)$ is defined as follows:
$$Uf(x)=\sum_{k=0}^\infty G(2k+1)\frac{x^{2k+1}}{(2k+1)!}$$
It is evident that this operator is linear. It transforms an even function to a similarly-looking odd one. Yet it is not defined for polynomials because they do not satisfy the first condition.
Given that the basis vectors of the standard Hilbert space of analytic functions are polynomials, so $U$ cannot be applied to the basis vectors, and I cannot construct the infinite matrix corresponding to this operator.
My questions are the following:

*

*Is it possible still find the matrix corresponding to the operator in the basis $e_n=x^n/n!$?

*At what conditions the operator transforms elementary functions to elementary ones?


text:
Q: JQuery drag/drop: Only the first dropped item can be deleted I have a table of draggable rows, which can be drug into the droppable area and then disabled so the same row cannot be dropped again unless deleted from the droppable area.
This works fine for one item but does not work for deleting additional items from the dropped area. Only the first dragged item is deleted from the dropped area, when clicking delete on the other items, nothing happens. Also the dropped area keeps a position/placeholder for the dragged items, so when I drag a new item in the drop area, it is placed below where the last item was.

            Source
            Title
            Publish Date
            Share

        <?php
        if(is_array($bookmarks))
        {
                echo '
';
                echo '	';
                echo ''.$bookmark['name'].'	';
                echo ''.$bookmark['title'].'	';
                echo ''.$formatted_date.'	';
                echo '

	';
                echo '
';
            }
        }
        ?>

Drag Bookmarks Here

$(document).ready(function() {

$(".bmkitem").draggable({
    helper: "clone",
    containment: "document",
    cursor: 'move',
    revert: 'true',
    start: function(event, ui) {
        source = $(this).find('#article_source').text()
        contents = $(this).find('#bookmark-link').text();
    }
});

$('#bkm-dropbox').droppable({
    hoverClass: 'hover',
    acceptable: '.bmkitem',
    containment: 'document',

    drop: function(event, ui) {
        $(this).find(".temp-text").remove();

        $(this).append('' + source + ' - ' + contents + '
');

        ui.draggable.draggable("disable");
        selected_row = ui.draggable.find("i").hide();

        $('#drop_delete').on('click', function () {
            $(this).parent('span').remove();
            ui.draggable.draggable("enable");
            selected_row.show();
        });
    }
});
});

A: You create the dropped items with the same id again and again. The id of the element must be unique in html.
A common mistake with draggable/droppable that the cloned dropped part keeps the original ids. You need to remove or alter the dropped ids to not break dom selectors.
You may modify your code to create a "unique" id each time when you drop the item:
$(document).ready(function() {

$(".bmkitem").draggable({
    helper: "clone",
    containment: "document",
    cursor: 'move',
    revert: 'true',
    start: function(event, ui) {
        source = $(this).find('#article_source').text()
        contents = $(this).find('#bookmark-link').text();
    }
});

var id = 0;
$('#bkm-dropbox').droppable({
    hoverClass: 'hover',
    acceptable: '.bmkitem',
    containment: 'document',

    drop: function(event, ui) {
        $(this).find(".temp-text").remove();

        id++;
        $(this).append('' + source + ' - ' + contents + '
');

        ui.draggable.draggable("disable");
        selected_row = ui.draggable.find("i").hide();

        $('#drop_delete' + id ).on('click', function () {
            $(this).parent('span').remove();
            ui.draggable.draggable("enable");
            selected_row.show();
        });
    }
});
});


text:
Q: Infinite address nesting How to move through .htaccess from such addresses:
/one/two/thre/four/five/.../.../.../
There can be any characters and nesting after /.
And it turns out this crap flies out:

Not Found
The requested URL /sdfsdf/sdfsdf/sdfsdf/sdf/ was not foundon this server.

And you need to transfer to the main page, if not found.

A: The issue is resolved!
Who needs it, I leave it here:
<If "%{HTTPS} == 'on'">
    ErrorDocument 404 https://%{HTTP_HOST}
</If>
<Else>
    ErrorDocument 404 http://%{HTTP_HOST}
</Else>


text:
Q: Doubts regarding irrational functions irrational function
So, as you can see in the photo above, I solved this equation and I got 2 results as an answer. Both of which seem correct to me. But my teacher stated that the -2 solution is incorrect, and that 1 is the only correct answer. I graphed the function, in a software, and I saw that the function really does only cut the x axis at 1 and that the function is only defined at x greater or equal to 2. With all of that being stated, what I don't understand is: why -2 isn't a solution and why the function is only defined at x greater or equal to 2.
P.S. In case that you are wondering, Solución means solution in Spanish.

A: I think the key idea here is to be careful when squaring both sides of an equation.
Any solution for an equation $L(x) = R(x)$ is surely also a solution for $(L(x))^2$ = $(R(x))^2$, but the reverse is not necessarily true.
If $x$ satisfies $(L(x))^2 = (R(x))^2$ then we can only deduce that $|L(x)| = |R(x)|$, but after taking away the absolute value signs around each side, the equality might not hold (the signs of either side may not match).
You found 2 candidate solutions from the squared equation but you need to check them in the original equation to make sure they still work on the "un-squared expressions".

A: Put $-2$ in the original equation. You can see the result is not $0$. That one extra root came because you squared the equation.


text:
Q: Max operating temp of IC's Why do so many IC's have a max temp range of 125C? Is it due to packaging material tolerances, ie the black plastic enclosures and/or the bonding epoxy that holds the die to the package and/or something else?

A: All semi-conductor characteristics are affected by Boltzman statistics relating charge carrier densities with respect to temperature.  The hotter it is the more intrinsic carriers are present, at some point the intrinsic carrier concentration gets so high that any doping (n-type vs. p-type) gets wiped out.  That is at high temperatures.
A conductor has the characteristic that as you heat it, the carriers are more mobile and collide more and resistance goes up.  A Semi-conductor has the characteristic that as you heat it up, more carriers are present and the resistance goes down.
So it's natural to see that there are limits.  Why particularly those temperatures, I don't know, I'm sure some one will come up with the historical answer.  However, it's very celar that some temperature must be selected, because if you design for a very broad temperature range then some other performance metric will be compromised, like speed or margins.
Designs are specified over what are called PVT corners, as in Process, Temperature and Voltage corner cases.

A: The military temperature range for operation of silicon integrated circuits (ICs or chips) is -55C to +125C, which is meant to ensure operation in virtually any field situation, with plenty of margin (125C is 25% hotter than the boiling point of water).
Other standard ranges for ICs are -40C to +125C for Automotive, -40C to +85C for Industrial, and 0C to +70C for Commercial (e.g. chips in TV sets). There are variations in these standards, for example some automotive devices may extend to +130C or higher, and high performance CPU chips in home computers may be limited to +55C.
A chip's packaging is chosen according to the chip's rated temperature range and is generally either plastic for lower temperature devices and ceramic for higher temperature. Ceramic packages also have superior sealing and may have provision for mating with an external heat sink to cool the package.
The silicon from which ICs are made has a limit beyond which heat generated by the chip's circuitry can't flow through the silicon and out of the chip fast enough to prevent permanent damage, regardless of external heat dissipation methods (heat sinks). The faster the clock signal for a digital chip such as a CPU, the more heat it generates because the clock signal spends more time in the transition region between high and low logic states. Clock transitions are the only time a typical digital circuit generates significant heat, so more heat is generated as the clock speed is increased. A typical upper limit for clock speed in silicon ICs is around 4 GHz (4,000 MHz) but some specialized devices can be clocked much faster.


text:
Q: Unable to install I am a beginner in Android who has got miserably stuck up with the following message in Android Studio:
'Launching 'app' on Xiaomi Redmi Y2.
Installation did not succeed.
The application could not be installed.
Installation failed due to: 'null''
I had already tried: adding -r-t in install flag in run configuration, clean, rebuild, invalidate caches etc.   all of no avail. Finally I uninstalled the studio and reinstalled the same..But when I added a device, again the error message repeats! Experts, please rescue me!

A: Silly of me,  I had forgotten to reboot the phone!  Once I did that the problem is solved.


text:
Q: Rank of a degenerate conic This question comes from projective geometry. A degenerate conic $C$ is defined as $$C=lm^T+ml^T,$$
where $l$ and $m$ are different lines. It can be easily shown, that all points on $l$ and m lie on the $C$. Because, for example, if $x\in l$, then by definition $l^Tx=0$ and plugging it into conic equation makes it true.
Question: Find the rank of $C$.
(We can limit ourself to 3-dimensional projective space.)
P.S. I'm reading a book, where it is guessed and checked, but I would like to have a proof without guessing. I do not provide the guess, since it can distract you, but if you really need it just leave a note.

A: The rank of $lm^T$ is one. The same goes for $ml^T$. In most cases, the rank of the symmetric matrix $C$ as you define it will be 2. This corresponds to a conic degenerating into two distinct lines. If the lines $l$ and $m$ should coincide, though, the rank of $C$ will be 1.
If you need a proof, you can show this assumption for specific cases without loss of generality. Of you can have a look at the corresponding dual conics and how that relates to adjoint matrices.


text:
Q: Replace values in Excel At work, we have a spreadsheet that the data is copied from another uploaded spreadsheet. We need to convert:
Yes --> 1
No --> 0
NA --> 9
Is there any way to create a formula that will automatically do that?

A: =if(Cell="Yes",1,if(Cell="No",0,9))

Replace "Cell" with the cell you are referencing. You can drag this formula down and apply it to all cells in the given column. This assumes that your column or row can only take on the three listed values: "Yes", "No", and "NA". You'll need to nest more "if" functions to account for the addition of new values.


text:
Q: What can we say about this excerpt from "Utilitarianism" from a grammatical aspect?
"If, then, it is asserted that there is a comprehensive formula, including all things which are in themselves good, and that whatever else is good, is not so as an end, but as a mean, the formula may be accepted or rejected, but is not a subject of what is commonly understood by proof."

Excerpt From: "Utilitarianism." iBooks.
First of all, is this sentence grammatically correct? If so, what is the subject of "is not so?"
Secondly, regardless of the correctness of the sentence, what does it mean?
Context:

"On the present occasion, I shall, without further discussion of the
  other theories, attempt to contribute something towards the
  understanding and appreciation of the Utilitarian or Happiness theory,
  and towards such proof as it is susceptible of. It is evident that
  this cannot be proof in the ordinary and popular meaning of the term.
  Questions of ultimate ends are not amenable to direct proof. Whatever
  can be proved to be good, must be so by being shown to be a means to
  something admitted to be good without proof. The medical art is proved
  to be good by its conducing to health; but how is it possible to prove
  that health is good? The art of music is good, for the reason, among
  others, that it produces pleasure; but what proof is it possible to
  give that pleasure is good? If, then, it is asserted that there is a
  comprehensive formula, including all things which are in themselves
  good, and that whatever else is good, is not so as an end, but as a
  mean, the formula may be accepted or rejected, but is not a subject of
  what is commonly understood by proof. We are not, however, to infer
  that its acceptance or rejection must depend on blind impulse, or
  arbitrary choice. There is a larger meaning of the word proof, in
  which this question is as amenable to it as any other of the disputed
  questions of philosophy. The subject is within the cognisance of the
  rational faculty; and neither does that faculty deal with it solely in
  the way of intuition. Considerations may be presented capable of
  determining the intellect either to give or withhold its assent to the
  doctrine; and this is equivalent to proof."

Thank you all in advance.

A: This quote is from John Stuart Mill's Utilitarianism.  JSM in this quote is going to ask you to agree with two assumptions, written as relative clauses with "that" and introduced by

If, then, it is asserted

*

*that there is a comprehensive formula, including all things which are in
themselves good

That is, assume we can come up with a list of those things that are intrinsically good.  He'll call those kind of things "ends."  And

*that whatever else is good, is not so as an end, but as a mean

Assume that there may be other good things outside the list, but these don't belong on the list because they're not ends, but rather means, i.e., the agency or way to obtain an end that is on the list.  (The OED notes that "mean" in the singular denoting agency is archaic, but then Mill published Utilitarianism in 1863.  Today we use "means" in contrast to "end," even in the singular:  "a means to an end.")
These two assumptions form the compound protasis, the subordinate "if" clause conditions from which Mill will derive the apodosis, the "then" clause conclusion, which is

[then] the formula may be accepted or rejected, but is not a subject of what
  is commonly understood by proof.

That is, we may argue about what things should be on the "good" list, but we won't be able to agree based on common notions of "proof," e.g, by manipulating logical propositions.  The statement sets up a discussion of utilitarianism, which sets out the ethics of action (the means) regardless of what can be agreed upon as the results (the ends).
Finally, to answer your syntax question, the subject of "is not good" is the noun clause "whatever else is good"

A: I'd put it like this to explain:
"...whatever else is good, is not [good] as an end, but as a mean..."
It is perfectly correct, if not a bit chunky (but de gustibus non est disputandum).
As to the meaning, it seems to be presenting the age-old "how can we call something truly good?" question. The passage (put basically) seems to be pointing out a debate of the good being contained in that which something causes (its "end") or the methods it takes to get there (its "mean[s]"). There's more philosophy than language there, though, and more than I could get at in a short answer.
Hope this helps!


text:
Q: splitting words for full name in only one variable I want to separate a full name from each other. It only works for first name.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
     string FullName;
     int i = 0;
     cout <<"Enter your full name "<<endl;
     getline(cin,FullName);

     while (FullName[i] != ' ')
     {
         cout<<FullName.substr(i,FullName.find(' '))<<endl;;
         i++;
     }

     cout <<endl;
     }
return 0
}

I want to separate each name in a separate line like this: If I enter this:
     Max Michael Max

the output should be with each name in a separate new line:
     Max
     Michael
     Max

How can I split names each one in separate line ?

A: The simplest approach is to use std::istringstream after the name is read in.
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
     string FullName;
     cout <<"Enter your full name "<<endl;
     getline(cin, FullName);
     string namepart;
     istringstream strm(FullName);
     while ( strm >> namepart )
        cout << namepart << '\n';
}

Live Example


text:
Q: How can I serve the same route with fastify/static and a custom route based on header? Say for example I have a route along the lines of /object/:id, and I want to use fastify/static to serve STATIC_FOLDER/object/<supplied id>/index.html by default.
This is really easy, I just register fastify/static with STATIC_FOLDER as the root.
I also want to have the same route (i.e. /object/:id), if the "Content-Type" header is set to "application/json", with custom logic to retrieve the relevant data and return json. This is also simple enough to achieve.
But how to I achieve both simultaneously?
If I set up just fastify/static, the static file is served perfectly fine. If I also set up a custom route like so:
fastify.get('/object/:id', async function (request, reply) {
  // ... custom logic to get obj by id
  reply.type('application/json').code(200).send(obj)
}

Then it only calls that route and returns the json.
Is there any way I can add a filter or something on the route based on Content-Type header?
I tried looking into the route options documentation but couldn't find anything relevant.

A: With fastify, you can do everything
You need to configure route constraints.
They are not a bit verbose, so in this example I used the header-constraint-strategy plugin that eases a lot the implementation
const path = require('path');
const Fastify = require('fastify')
const fastifyStatic = require('@fastify/static')
const headerConstraintStrategy = require('header-constraint-strategy')

const app = Fastify({
  logger: true,
  constraints: {
    ct: headerConstraintStrategy({ name:'ct', header: 'content-type' }),
  }
})

app.register(fastifyStatic, {
  root: path.join(__dirname, 'public'),
})

app.get('/object/:id', {
  handler: (request) => {
    return { hello: request.params.id }
  },
  constraints: {
    ct: 'application/json'
  }
})

app.listen({port:8080})

// curl http://localhost:8080/object/my-id -H 'content-type:application/json'
// print: {"hello":"my-id"}%

// curl http://localhost:8080/object/my-id
// print: hello%


text:
Q: Rewrite URLs without file extension (including across sub-directories) I have the following .htaccess file on my server (It's a tweak of code I found on-line somewhere, for the life of me I cannot remember where) and I'm not quite sure how to amend it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

It basically grabs the URL, removes any trailing /, adds .php to the end of it, goes to that page, but then displays the link with a / instead of the extension in the URL bar (from what I can tell).
It works really well, bar two annoying niggles:

*

*I can then only have .php files within that directory. Any others break.

*The .htaccess file needs to be copied to EVERY subdirectory to function.

Can this script be improved upon at all, to do the following:

*

*Put it in my root (/) directory and have it work in to all sub-folders?

*Allow multiple file extensions within each directory? (e.g. some .php, some .html)

A: This code should work from your DocumentRoot and will add all the extensions:
Options +MultiViews

RewriteEngine On
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^(.+)$ /$1/ [R=301,L]


text:
Q: How can I exit my lookup table routine with the desired value? How can I get my code to work correctly when I include ADC conversion in it?
I have a working code that displays two digits on 2 LED displays using a p16f1829. However, a problem arises when I try to include a code block that collects the results of an ADC conversion to display on the LED display (see below).
A2D:
; Start the ADC
        NOP                         ; Requried ADC delay of 8uS => (1/(Fosc/4)) = (1/(500KHz/4)) = 8uS
        BANKSEL     ADCON0          ; Selects memory bank containing ADCON0 register
        BSF         ADCON0, GO      ; Start the ADC
        BTFSC       ADCON0, GO      ; This bit will be cleared when the conversion is complete
        GOTO        $-1             ; Keep checking the above line until GO bit is clear

; Grab Results and write to the LEDs
        SWAPF       ADRESH, w       ; Get the top 4 MSbs (remember that the ADC result is LEFT justified!)
        MOVWF       L0
        RETURN

To be more precise, it seems to occur at the very point where I am trying to grab the corresponding value from the lookup table (see below):

The result in W-reg after that instruction should be 0x7D. However, it exits the Lookup table without returning the expected value.

The original working code without the ADC block is below:
    LIST        p=16f1829   ;list directive to define processor
    #INCLUDE    <p16f1829.inc>  ;processor specific variable definitions

    __CONFIG _CONFIG1, (_FOSC_INTOSC & _WDTE_OFF & _PWRTE_OFF & _MCLRE_OFF & _CP_OFF & _CPD_OFF & _BOREN_ON & _CLKOUTEN_OFF & _IESO_OFF & _FCMEN_OFF);
    __CONFIG _CONFIG2, (_WRT_OFF & _PLLEN_OFF & _STVREN_OFF & _LVP_OFF);

;-------------------------------------------------------------------------

; UDATA_SHR declares a section of shared (all across the banks) uninitialised data
INT_VAR     UDATA_SHR   ; INT_VAR is the section name in ACCESS RAM
TempC       RES     1   ;
L0          RES     1   ;
w_temp      RES     1   ; variable used for context saving
pclath_temp     RES 1   ; variable used for context saving
status_temp RES     1   ; variable used for context saving

;-------------------------------------------------------------------------

LEDtrisA    EQU     TRISA
LEDtrisC    EQU     TRISC
LEDlatA     EQU     LATA
LEDlatC     EQU     LATC

;-------------------------------------------------------------------------

RESET_VECTOR    CODE    0x0000
        GOTO    START   ; When using debug header, ICD2 may not stop
                        ; on instruction 0 during reset.

;-------------------------------------------------------------------------

INT_VECTOR      CODE    0x0004  ; Interrupt vector location

ISR             ; Relocatable Interrupt Service Routine
;   Context saving for ISR
    MOVWF   w_temp      ; save off current W register contents
    MOVF    STATUS, w   ; move status register into W register
    MOVWF   status_temp ; save off contents of STATUS register
    MOVF    PCLATH, w   ; Saves value in register PCLATH
    MOVWF   pclath_temp

;-------------------------------------------------------------------------

;   If the interrupt came from the timer, execute the TMR0 interrupt
;   service routine.

    BANKSEL     TMR0
    MOVLW       .96
    MOVWF       TMR0
    BTFSC       INTCON, TMR0IF
    CALL        Service_TMR0
    BRA         UpdateDisplay   ; Refresh the display

UpdateDisplay
    BANKSEL     LATA        ; Selects memory bank containing LATA register
    MOVF        LEDlatA, w  ; display status -> w register
    ANDLW       0x0f        ; Separate the lower half byte
    MOVWF       TempC       ; Save display status in TempC
    BSF         TempC, 4    ; Beginning status of LSD display
    RRF         TempC, F    ; Set the status of the next display
    BTFSS       STATUS, C   ; C = 1?
    BCF         TempC, 3    ; If not, turn off the LSD display
    BTFSC       TempC, 0

    BRA         UpdateMsd   ; If it is turned on, display the MSD
                            ; digit of the number
UpdateLsd
    BCF         TempC, 3
    BSF         TempC, 1
    BTFSS       STATUS, Z   ; If it is, skip
    MOVF        L0, w       ; Third LSD digit -> w
    ANDLW       0x0f        ;   /
    BRA         DisplayOut  ; Show it on the display

UpdateMsd
    SWAPF   L0, w       ; MSD figure - >
    ANDLW   0x0f        ;   /
    BTFSC   STATUS, Z   ; MSD = 0?
    MOVLW   0x0a        ; If it is, skip

DisplayOut
    CALL    LedTable    ; Take the mask for a digit
    MOVWF   LEDlatC     ; Set the mask on port B
    MOVF    TempC, W    ; Turn on displays
    MOVWF   LEDlatA
    BRA ISR_END

LedTable
    ADDWF   PCL, F
    RETLW   B'00111111' ; mask for digit 0
    RETLW   B'00000110' ; mask for digit 1
    RETLW   B'01011011' ; mask for digit 2
    RETLW   B'01001111' ; mask for digit 3
    RETLW   B'01100110' ; mask for digit 4
    RETLW   B'01101101' ; mask for digit 5
    RETLW   B'01111101' ; mask for digit 6
    RETLW   B'00000111' ; mask for digit 7
    RETLW   B'01111111' ; mask for digit 8
    RETLW   B'01101111' ; mask for digit 9
    RETLW   B'00000000' ; no digit ......

;-------------------------------------------------------------------------

ISR_END
;   Restore contents before returning from interrupt
    MOVF    pclath_temp,w   ; PCLATH is given its original content
    MOVWF   PCLATH
    MOVF    status_temp,w   ; STATUS is given its original content
    MOVWF   STATUS
    SWAPF   w_temp,f        ; W is given its original content
    SWAPF   w_temp,w

    BSF     INTCON,GIE  ; Global interrupt enabled
    RETFIE              ; Return from interrupt routine

;-------------------------------------------------------------------------

MAIN_PROG   CODE

START

;-------------------------------------------------------------------------

    ERRORLEVEL -302     ; Disable warning accessing register not in bank 0
    BANKSEL OSCTUNE     ; Configure OPTION_REG and TMR0
    MOVLW   0x00        ; Set oscillator to factory calibrated frequency
    MOVWF   OSCTUNE     ;
    BANKSEL STATUS
    ERRORLEVEL +302     ; Enable warning accessing register not in bank 0

CLEAR_RAM                   ; code sequence initialises all GPR's to 0x00
    MOVLW       0x70        ; initialise pointer
    MOVWF       FSR0        ; to RAM
    CLRF        FSR0H

NEXT
    CLRF        INDF0       ; Clear INDF0 register
    INCF        FSR0L, F    ; Inc pointer
    BTFSS       FSR0L, 7    ; All done?
    GOTO        NEXT        ; No, clear NEXT

CONTINUE                    ; Yes, CONTINUE
    NOP

;-------------------------------------------------------------------------
; MAIN BODY OF PROGRAM
;-------------------------------------------------------------------------

; Setup main init
        BANKSEL     OSCCON      ; Selects memory bank containing OSCCON register
        MOVLW       b'01011000'     ; Set CPU clock speed of 500KHz -> correlates to (1/(500K/4)) for each instruction
        MOVWF       OSCCON          ; OSCCON <- 0x38

; Setup pins as digital I/O
    BANKSEL     ANSELA      ; Selects memory bank containing ANSELA register
    CLRF        ANSELA      ; All pins are digital
    CLRF        ANSELC

; Configure the input & output pins
    BANKSEL     TRISA           ; Selects memory bank containing TRISA register
    MOVLW       b'11111100'     ; RA0 and RA1 are configured as outputs and
                                ; used for 7-segment display multiplexing
                                ; RA2 is input push-button for initialization
    MOVWF       TRISA
    CLRF        LEDtrisC    ; Port C is output

    BANKSEL     LATA        ; Selects memory bank containing LATA register
    CLRF        LEDlatA     ; Set all outputs to "0"
    CLRF        LEDlatC ;
    BSF         LEDlatA, 1  ; Turn on MSD display

; Setup Timer0 as the delay
    BANKSEL OPTION_REG
    MOVLW   b'10000100'     ; TMR0 is incremented each 32us (Fclk=8MHz)
    MOVWF   OPTION_REG  ; ps = 32

    BANKSEL     TMR0        ; Selects memory bank containing TMR0 register
    BSF         INTCON, GIE     ; Global interrupt enabled
    BSF         INTCON, TMR0IE  ; Timer TMR0 interrupt enabled

    MOVLW       0x79
    MOVWF       L0

MAINLOOP
    BRA         MAINLOOP    ; Continue forever

; TIMER 0 Interrupt routine clears the TMR0 interrupt flag.
Service_TMR0:
    BANKSEL     INTCON
    BCF         INTCON, TMR0IF  ; MUST ALWAYS clear this in software or else stuck in the ISR forever
    RETURN

;-------------------------------------------------------------------------
; END OF PROGRAM
;-------------------------------------------------------------------------

    END         ; End of program

I have tried all sorts and have currently a mental block on how to proceed. Any insights that anyone can provide will be very much appreciated.


text:
Q: I've impregnated a cow. How long until it gives birth? My cow is pregnant, but the game doesn't include any instructions for pregnancy, so I'm not sure how long it takes for the cow to give birth. Furthermore, how long after birth does it take the baby cow to produce milk?

A: When you impregnate a cow, there is a 50/50 chance that it will be either a bull or a cow.
I believe it's the same when you breed 2 different kinds of cattle (E.g., Star Bull + Normal Cow = Star Bull/Cow or Normal Bull/Cow)
It takes 21 days for a cow to give birth. I recommend impregnating your cow(s) to give birth at least 3 times to unlock Jersey Cows (buy from Neil). (10 hatched eggs for Silkie chickens)
It takes 20 days (of feeding) before the calf become adult. Chicks takes are 8 days to become an adult.
If you choose to buy the "Miracle Potion" to impregnate your cow, the calf that was born will be an exact copy of it's mother. It was always a female and always be the same kind of cow it's mother was.
I believe the baby calf will have half the hearts of the mother.
Your animals cannot conceive if they are dirty or sick.
For chickens, if more than two are scheduled the hatch only the first two will hatch on the schedule day, any other will have to wait till the next day. Chickens that lay Golden Eggs don't pass this onto their children.


text:
Q: How do I get dynamic content (numbers) in xpath I have few posts with dynamic numbers in the end of the DIV, how can I get the content inside the div with xPath?
The example codes:

It's pattern of 5 numbers each time.
I tries this code but don't works,
//div[starts-with(@class,"OpenMediaElement_Video video-player video-item-")]

Regards.


text:
Q: SQL IS NOT NULL for CASE WHEN My current database is in the follow format,
| question_id |Tag  | Question  |
|      -      |-   --|--        -|
|1            | EN   | DOG       |
|1            | DE   | HUND      |

and i'm trying to create a result such as;
| question_id |English  | German    |
|      -      |-      --|--        -|
|1            | DOG     | HUND       |

I currently have a case when set up;
select  question_id
  , CASE WHEN tag = 'en'
               THEN text
          END AS "ENGLISH",
   CASE WHEN tag = 'de'
              THEN text
          END AS "GERMAN"
from table

The problem is because I have two case when(s), it end up returning duplicate rows
  | question_id |English  | German    |
|      -      |-      --|--        -|
|1            | NULL     | HUND       |
|1            | DOG     | NULL       |

My attempt to fix this, was to add a WHERE "ENGLISH" IS NOT NULL to the end of the statement to delete these rows, but SQL doesn't seem to recognise that case when columns are real columns.

A: You could use aggregation:
SELECT question_id,
       max(text) FILTER (WHERE tag = 'en') AS english,
       max(text) FILTER (WHERE tag = 'de') AS german
FROM atable
GROUP BY question_id;

A: you could use aggregation with case when as well
select  question_id
  , max(CASE WHEN tag = 'en'
               THEN text
          END )AS ENGLISH,
   max (CASE WHEN tag = 'de'
              THEN text
          END) AS GERMAN
from table group by question_id

A: CREATE TABLE test_table(question_id NUMBER,
tag VARCHAR2(10),
question VARCHAR2(10));

INSERT INTO test_table VALUES(1,'EN','DOG');
INSERT INTO test_table VALUES(1,'DE','HUND');

COMMIT;

SELECT QUESTION_ID,
MAX(CASE WHEN TAG='EN' THEN QUESTION END) AS ENGLISH,
MAX(CASE WHEN TAG='DE' THEN QUESTION END) AS GERMAN
FROM test_table
GROUP BY QUESTION_ID;

I tried the expected result for the above sample set of data.


text:
Q: Unity - wait until animation finished I try to start a co-routine after my animation finished playing.
I tried it like this:
...

while (animCamera.isPlaying) {
    new WaitForSeconds(1);
}

StartCoroutine(LoadAsync(sceneName, sliderLoadbar, sliderLoadbarText));

But this crashes my unity and even my browser after a while and my unity stucks as soon as the while loop is entered.
How can I solve this?

A: in the animation tab of your animated gameobject create an event at the last frame of the animation, attach the above script to this gameobject, and choose the method you want to run at the end of it

Remove The coroutine and just make a simple method
public void LoadScene()
{
   LoadAsync(sceneName, sliderLoadbar, sliderLoadbarText)
}


text:
Q: js accessing return value of then() statement I am building a function that returns an array of links that are present on a webpage. Later on, this function will be used to further scrape information on the website. The function (cf. infra) works fine, but I have no clue how to access the final hrefArray. I have tried adding multiple return statements (within the for loop and the different then()'s but without success.

const {Builder, By, Key, WebDriver, elementLocated, Browser, tagName} = require('selenium-webdriver');

var driver = new Builder().forBrowser('chrome').build()

function findURLS(webpage){
    console.log('Starting to look for URLS on webpage: ' + webpage)
    var result =
    driver.get(webpage)
    .then(res => {
        if(driver.getCurrentUrl() === webpage){
            return true;
        }
    }).then(res => {
        console.log('Webpage opened')
    }).then(res => {
        var links = driver.findElements(By.tagName('a'))
        return links;

    }).then(links => {
        var hrefArray = []

        function findhref(array, input){
            var href = driver.wait(array[input].getAttribute('href'))
            return href;
        }

        for(i=0; i<links.length; i++){
            findhref(links, i)
            .then(href => {
                hrefArray.push(href)
                if(hrefArray.includes(href)){
                    console.log("Href " + href + " succesfully pushed to hrefArray")
                    return hrefArray;
                }
                else{
                    console.log("something went wrong while pushing the link to the hrefArray")
                }
            })
            .then(hrefArray => {
                if(hrefArray.length == links.length){
                    console.log("hrefArray constructed successfully: " + hrefArray)
                    return hrefArray //this is the final hrefArray that need to be returned after calling the findURLS(webpage) function
                }
            })
        } //end of for statement
    })
    .catch(error => {
        console.log(error)
    })
}

function testexample(){
    findURLS('https://dbrc.be/rechtspraak');
}

testexample()

``


text:
Q: Adding an element to the beginning of the array php Is there a built-in php function or an easy way to insert an element to the beginning of an array?
Something Like:
$matches = Array("apples", "oranges");
insert_to_beginning($matches, "peach");

Contents:
$matches[0] = peach
$matches[1] = apples
$matches[2] = oranges

A: array_unshift is the function you're looking for.
array_unshift($matches, "peach");

A: array_unshift($matches, 'peach');

http://nz.php.net/array_unshift


text:
Q: Running plugins in a sandbox I am designing a system in C/C++ which is extendible with all sort of plugins. There is a well defined C public API which mostly works with (const) char* and other pointer types. The plugins are compiled into .so or .dll files, and the main application loads them upon startup, and later unloads or reloads them upon request.
The plugins might come in from various sources, trustable or not so :)
Now, I would like to make sure, that if one plugin does something stupid (such as tries to free a memory which he was not supposed to free), this action does not bring down the entire system, but merely notices the main system about the misbehaving plugin for it in order to remove it from the queue.
The code calls are being done in the following manner:
const char* data = get_my_data();
for(int i = 0; i<plugins; i++)
{
   plugins[i]->execute(data);
}

but if plugin[0] frees "by accident" the data string or overwrites it or by mistake jumps to address 0x0 this would bring down the entire system, and I don't want this. How can I avoid this kind of catastrophe. (I know, I can duplicate the data string ... this does not solve my problem :) )

A: Make a wrapper process for plugin and communicate with that wrapper through IPC.
In case of plugin failure your main process would be untouched

A: Simply put, you can't do that in the same process. If your plugins are written in C or C++, they can contain numerous sources of undefined behavior, meaning sources for undetectable unavoidable crashes. So you should either launch the plugins in their own processes like kassak suggested and let them crash if they want to, or use another language for your plugins, e.g. some intepreted scripting language like lua.

A: Have a look at http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.90).aspx
I use /EHa in one of my projects to help me catch exceptions from libraries that do stupid things. If you compile your code with this setting a normal try catch block will catch exceptions like devide by zero, etc.
Not sure if there is some equivalent for this on Linux -- please let me know if there is..


text:
Q: Get Selected value from Spinner inside ListView Android I have a ListView of Spinners I'm trying to get the selected values out of. Some of the Spinners have the first selection automatically selected if there is only 1 item in the list, so I feel

setOnItemSelectedListener

won't necessarily work? Either way, I'm unsure how to code this scenario. Even if I had the listener coded correctly, How do I use it in my class to work with the adapter?
CustomAdapter
public class CustomPLNViewAdapter extends BaseAdapter{

private static ArrayList<ArrayList<String>> partLotNumbersArrayList;
private static ArrayList<String> partNames;

private LayoutInflater mInflater;

private Context myContext;

public CustomPLNViewAdapter(Context context, ArrayList<ArrayList<String>> results, ArrayList<String> parts){
    partLotNumbersArrayList = results;
    partNames = parts;
    mInflater = LayoutInflater.from(context);
    myContext = context;
}
@Override
public int getCount() {
    return partLotNumbersArrayList.size();
}

@Override
public Object getItem(int position) {
    return partLotNumbersArrayList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.view_assembly_parts, null);
        holder = new ViewHolder();
        holder.txtName = (TextView) convertView.findViewById(R.id.partName);
        holder.spinner = (Spinner) convertView.findViewById(R.id.LotNumbers);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtName.setText(partNames.get(position));

    ArrayAdapter<String> adp1=new ArrayAdapter<String>(myContext, android.R.layout.simple_list_item_1, partLotNumbersArrayList.get(position));
    adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //set the adapter to the spinnner
    holder.spinner.setAdapter(adp1);

    //if there is only one other part besides "" then set that as default part
    if(partLotNumbersArrayList.get(position).size() == 2){
        holder.spinner.setSelection(1);
    }

    return convertView;
}

static class ViewHolder {
    TextView txtName;
    Spinner spinner;
}
}

Where I am calling the code. Obviously I get an error here because an ArrayList cannot be cast to Spinner, but I'm unsure how to get the View of the Adapter and then the subsequent spinner?
// save button click event
    saveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Log.d("lv count", Integer.toString(lv.getCount()));

            //iterate through listview,
            for(int i = 0; i < lv.getCount(); i++){
                Spinner temp = (Spinner) lv.getItemAtPosition(i);
                Log.d("lv isItemCheck", temp.getSelectedItem().toString());

            }
            //check to make sure all items have been selected
            if(!checkAllParts()){
                Toast.makeText(getApplicationContext(), "Please Select All List Items", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getApplicationContext(), "All items have been selected", Toast.LENGTH_SHORT).show();
            }
            //go back to previous intent, return 100 that saving succeeded

            //close intent
        }
    });


text:
Q: I want to use dates in ui picker view for first component I am trying to use dates in picker view for first component. I want to use another component with another array.
Please help me out...Thanks

A: You will be needing 2 arrays right? Then Declare and populate two arrays to be used in two components as follows:
NSArray *firstComponentArray = // populate the first array here
NSArray *secondComponetArray = // populate the second array here

.
.
.

- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
   // return the number of components do you need
}

// return the right number of items in picker view delegate: numberOfRowsInComponent
- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent(NSInteger)component
{
   // first component
   if ( component == 0 )
     // return the count of the first array

   // second component
   else
     //return the count of the second array
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row   forComponent:(NSInteger)component
{
   // first component
   if ( component == 0 )
     // return the content of the first array at index using row

   // second component
   else
     // return the content of the second array at index using row
}


text:
Q: Why Selenium HtmlUnit or PhamtonJs have some trouble to execute Js code I'm trying to run my selenium test in a headless browser (htmlUnit Webdriver, and phamtomJs). But whatever i use, some exception is thrown by the execution of javascript code, or error when i try to use an event which will use javascript in the html page i'm testing.
I'm unable to understand why it could not work.
here is the script I am trying with:
public class Test {
static WebDriver driver;
static Wait<WebDriver> wait;
public static void main(String[] args) {
//      File file = new File("C:/phantomjs-2.1.1-windows/bin/phantomjs.exe");
//      System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
//      DesiredCapabilities caps = new DesiredCapabilities();
//      caps.setJavascriptEnabled(true);
//      driver = new PhantomJSDriver(caps);
    driver = new HtmlUnitDriver(true);//true to enable the JS
    wait = new WebDriverWait(driver, 3000);
    final String url = "https://localhost:8444/myApp/";

    JavascriptExecutor js = (JavascriptExecutor) driver;

    try {
        driver.navigate().to(url);
        js.executeScript("document.getElementsByName('formLogin')[0].checked = true;");
        By usernameInput = By.xpath("//input");
        By passwordInput = By.xpath("//div[2]/div/div/input");
        By submitButton = By.xpath("//a[contains(@href, '#')]");

        wait.until(ExpectedConditions.visibilityOfElementLocated(usernameInput));
        wait.until(ExpectedConditions.visibilityOfElementLocated(passwordInput));
        wait.until(ExpectedConditions.visibilityOfElementLocated(submitButton));

        WebElement log = driver.findElement(usernameInput);
        WebElement pass = driver.findElement(passwordInput);
        WebElement click = driver.findElement(submitButton);

        log.sendKeys("root");
        pass.sendKeys("pass");
        click.click();

        By headerId = By.className("header");

        wait.until(ExpectedConditions.visibilityOfElementLocated(headerId));

        System.out.println("Page title is: " + driver.getTitle());
        String var = (String) js.executeScript("var truc = 'bonjour'; return truc;");
        System.out.println(var);
    } finally  {
        driver.close();
    }

}

Fot this one i have multiple :

ReferenceError: "xxx" is not defined. (urlOfmyAPp/jsp/ihm.js?ts=0.1975212200823856#1451)

where the xxx to an javascript element.
I have another version of this script but with the firefox WebDriver, it's working well. But i don't understand why it"s not working with the htmlUnitDriver.
Could someone explain why it's failing? Thanks.


text:
Q: Como puedo manipular los datos un Json que me manda mi back end para pintar distintos datos de varios colores? Estoy recibiendo un servicio de un JSON, en el cual hay un atributo que se llama PalClav, este contiene Idioma y coincidencias con ese idioma, lo que necesito es que el atributo Idioma lo pueda pintar de color azul.
Estoy usando angular para imprimir los datos y este es el codigo donde mando llamar ese atributo  <p [innerHTML]='articulo.palClave'>{{articulo.palClave}}  y al final se imprime de esta manera en html, estoy usando el InnerHTML por que ya trae codigo html en el json. Sin embargo no me pueden enviar el idioma de color azul como yo lo quiero.


text:
Q: Vertically center el-row in div (ElementUI) I am using ElementUI for the grid system of an application. I need to vertically center a  on a Div. When using flexbox in the parent container of the  the el-row style breaks.
This is how the div that I want to center vertically looks like:

<template>

    <el-row type="flex" class="row-bg" justify="center">
      <el-col :span="12">

          1

      </el-col>
      <el-col :span="12">

          2

      </el-col>
    </el-row>

</template>

I greatly appreciate your help.


text:
Q: Replacing Variables with Microsoft C# Can't get "z" to be replaced by the code below. Any help would be awesome. Thanks
//Generate Nut Part Number
textBox7.Text = "MLA028Z-CAN-" + comboBox2.Text + "R" + "-" + comboBox3.Text + "z" + "0";

//Replaces z Variable in Lead Screw Assembly Part Number
if (comboBox1.Text == "0")
    textBox6.Text.Replace("z", "B");
else if (comboBox1.Text == "1")
    textBox7.Text.Replace("z", "D");
else if (comboBox1.Text == "2")
    textBox7.Text.Replace("z", "D");
else if (comboBox1.Text == "3")
    textBox7.Text.Replace("z", "D");
else if (comboBox1.Text == "4")
    textBox7.Text.Replace("z", "D");
else if (comboBox1.Text == "5")
    textBox7.Text.Replace("z", "D");
else if (comboBox1.Text == "6")
    textBox7.Text.Replace("z", "D");
else if (comboBox1.Text == "7")
    textBox7.Text.Replace("z", "B");

A: The problem is Replace() returns a new string with the replacement made. It does not update the string on which it operates, and so you have to do that yourself:
if (comboBox1.Text == "0") textBox6.Text = textBox6.Text.Replace("z", "B");

Making that change (i.e. assigning the result back to textBox6.Text/textBox7.Text) will make your code work as expected.

A: Modify each of your
textBox7.Text.Replace("z", "D");

with
textBox7.Text = textBox7.Text.Replace("z", "D");

A: Strings are immutable in .NET, hence textBox7.Text = textBox7.Text.Replace("z", "D").

A: Since you're not really using the value assign to the textbox in the first place and only have two different scenarios in your if's I've rearranged the code a bit. The main problem however as stated elsewhere is that you weren't assigning the result of the replace back to the text property
 //Replaces z Variable in Lead Screw Assembly Part Number
 var replace = "z";
 int combo;
 if(int.TryParse(comboBox1.Text, out combo)){
    if (combo == 0) textBox6.Text = textBox6.Text.Replace("z", "B");
    else if (combo >0 && combo < 7) replace = "D";
    else if (combo == 7) replace = "B";
 }
//Generate Nut Part Number
 textBox7.Text = "MLA028Z-CAN-" + comboBox2.Text + "R" + "-" + comboBox3.Text + replace + "0";

A: Others have answered the main question but i would also recomend replacing all those else if with the following.
var oneToSix = Enumerable.Range(1, 7).Select(x => x.ToString());
if (comboBox1.Text == "0") textBox6.Text = textBox6.Text.Replace("z", "B");
if (comboBox1.Text == "7") textBox7.Text = textBox7.Text.Replace("z", "B");
else if (oneToSix.Contains(comboBox1.Text)) textBox7.Text = textBox7.Text.Replace("z", "D");

A: as an aside, this should be a switch statement:
switch(comboBox1.Text){
    case "0":
        textBox6.Text = textBox6.Text.Replace("z", "B");
        break;
    case "7":
        textBox7.Text = textBox7.Text.Replace("z", "B");
        break;
    case "1":
    case "2":
    case "3":
    case "4":
    case "5":
    case "6":
         textBox7.Text = textBox7.Text.Replace("z", "D");
         break;
}


text:
Q: First row of SELECT DISTINCT I am having a little trouble with a SQL query. I have a table to stores results against a date. I'd like to select all distinct results with the maximum (most recent) date. I can make this work with:
select distinct(r.data), max(c.committed_at) as timestamp
from results r
     inner join commits c on (r.commit_id=c.id)
where r.repository_id=65 AND data_type='data_model'
group by data
order by timestamp DESC

This is good and all works.
However, I want to be able to select a third column, which is a hash. This hash is unique to every result row.
But when I add it in to the SELECT clause, I of course have to add it to my GROUP BY too.
select distinct(r.data), max(c.committed_at) as timestamp, c.hash
from results r
     inner join commits c on (r.commit_id=c.id)
where r.repository_id=65 AND data_type='data_model'
group by data, c.hash
order by timestamp DESC

And this throws the query out. I no longer get distinct results (of course).
I tried an aggregate function on hash:
select distinct(r.data), max(c.long_hash), max(c.committed_at) as timestamp
from results r
    inner join commits c on (r.commit_id=c.id)
where r.repository_id=65 AND data_type='data_model'
group by data
order by timestamp DESC

But then I don't get the maximum time, I get the maximum hash.
I feel like I just want to be able to say "find the distinct results with the maximum timestamp and then just include the hash in the result", but I can't figure out how...
Cheers,
Ben
Edit: my attempt at this with DISTINCT ON is:
select distinct on (data) data, c.committed_at as committed_at, c.long_hash
from results r
    inner join commits c on (r.commit_id=c.id)
where r.repository_id=65 AND data_type='complexity'
order by data, c.committed_at DESC

But this requires an ORDER BY on data, which again, throws out the ordering of my results...
Edit 2:
Executing this query gives the following result:
'{"status":"supported","per_method":"10.2","total":"815.2","data"<snip>...}','2017-01-04 13:25:51','4a44bccca804c28c6a5e61b36b5ebcb716d4c11f'
'{"status":"supported","per_method":"8.8","total":"649.3","data":<snip>...}','2017-01-02 23:35:11','d747e657a81c5c6da4262a5298c3071082b2af41'
'{"status":"supported","per_method":"10.7","total":"944.3","data":<snip>...}','2017-01-08 17:28:57','ff4be5fa6dc88237e7855ed1b534baee69aa8800'

As you can see, the data column is in order (according the JSONB column rules), whereas the timestamp column is not (it goes from Jan 4th, to Jan 2nd, to Jan 8th).

A: You don't need group by with select distinct on.  You just adjust the order by.  So:
select distinct on (r.data) r.*, c.*
from results r inner join
     commits c
     on r.commit_id = c.id
where r.repository_id = 65 and
      data_type = 'data_model'
order by r.data, c.committed_at desc;

distinct on does all the work you want to do.  It returns one row for each combination of values in the distinct on list.  The row is the first one specified by the order by.
I think this is what you intend with distinct(r.data), because distinct itself is not a function and you would not use parentheses with it.

A: Try this:
with cte as
(
select r.data,c.committed_at, c.hash,timestamp,
ROW_NUMBER() over (Partition by r.data order by c.committed_at DESC) as ranking
from results r
     inner join commits c on (r.commit_id=c.id)
where r.repository_id=65 AND data_type='data_model'
)
Select data,committed_at, hash
from cte where ranking=1 order by timestamp DESC


text:
Q: Why dp is looking different on 2 devices with same screen density? As far as I know, dp is used to calculate how many pixels are needed to occupy the same space in different screen densities. The following image describes this:

According to the above information, for example if I have a ConstraintLayout and I am using Top and Bottom margin in an element of the ConstraintLayout (Imagine that Top and Bottom margin is 10dp). If now I test the app in two devices with the same screen density, why the margin is looking different in both devices although the screen density is the same? Shouldn't they have exactly the same px margin according to the definition of dp? Why the margin is looking different in 2 devices that have the same screen density?
Edit of the example:
I am using app:autoSizeTextType="uniform" in an AppCompatTextView to resize it according to its space (the AppCompatTextView has width and height = 0dp to fill completely respecting its constraints). So to resize it I am using Top and Bottom margin so that if the margin is higher the text is smaller as it will have less space to fill. As you can see in the following images, I am using 2 devices with same screen density but the text is looking different although the same margin should be applied:
1st device:

2nd device:


text:
Q: Why UWP app can not use PCL that references classic .Net dll? We have a huge collection of classic .Net libraries written in anything from .Net 3.5 to 4.6. This includes our core business logic and data model classes we use across various .Net solutions using WCF, Web API, Asp.Net, WPF and Windows Forms. It is only natural therefore that when looking into creating a UWP app, we'd need to reuse some of these .Net dlls.
I've create a portable class library (PCL) in which I reference one of our .Net 4.5 dlls. I then created a class in the PCL that implements one of the 4.5 classes:
using DODServiceLib.Models;

namespace PortableClassLibrary
{
    public class UtilityStats : ProcessorStats
    {
    }
}

ProcessorStats is from the 4.5 dll, DODServiceLib.Models.
In my UWP app, I've added a project reference to the PCL, PortableClassLibrary and added a using statement in my code behind, this is where I need to use the implementation of my .Net class:
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Net.Http;
using System.Threading.Tasks;
using PortableClassLibrary;

namespace HelloWorld
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var utilityStats = new UtilityStats();
        }
    }
}

When building the solution, I get these errors against the UWP HelloWorld app:
Type universe cannot resolve assembly: DODServiceLib, Version=20.17.7.28, Culture=neutral, PublicKeyToken=null.
Cannot resolve Assembly or Windows Metadata file 'DODServiceLib.dll'

Why is the UWP app looking for a reference to the .Net DLL (DODServiceLib) when it only uses the PCL?
Can I not use a PCL like this as a "wrapper" for a classic .Net library?

A:
Why is the UWP app looking for a reference to the .Net DLL (DODServiceLib) when it only uses the PCL?

It's normal. Your PCL add added reference to that .NET DLL, so it certainly will look for this dll. But this dll is not support in UWP. That's reason why you will get the exception. UWP project can reference Universal Windows Class Library, Portable Library or Windows Runtime Component.It doesn't mean that you could use PCL to wrap the classic .NET library.That's entirely different thing. I think what you need to do is copy all the code from your .NET library into PCL and then start to eliminate/replace all code which doesn't fit.


text:
Q: Merge Videos in Node.js? I wrote a web app that gives the ability to merge several videos into a single (split-screen) video. I am using video.js and the video-stream-merger to merge the different videos together. I merge the media streams while playing the videos and capture them by using a MediaRecorder. The user can configure the size and position of each video. This works fine on my Notebook.
Unfortunately, this doesn't work for older clients and slower phones, so I decided to do the merging server-side using firebase functions. Is it possible to capture and merge the media streams in a firebase function? I know that is not the purpose of media streams, but I thought I could make it work somehow. Is there any better way to merge the videos using node.js? At the time I call the merge function, the single video files are already stored at the firestore.
What is the best approach to merge those videos?
Thank you & best regards,


text:
Q: Prevent dismissal of UIAlertController when pressing button Is it a way not to dismiss UIAlertController right after pressing button, UIAlertAction?
I do not want validate textfield. But wait until. quick webservice call responds.


text:
Q: Python - How to add new column and add value to each file and then club to one Adding new column to all the file that are there in the folders
Example : Folder EU -> Folder LOH --> File - DB_LOH_2019_20.csv , DB_ABC_2019_20.csv
      folder AP -> Folder SGH--> File - DB_SGH_2019_20.csv ,DB_EDF_2019_20
      Folder US -> Folder NYK --> File - DB_NYK_2019_20.csv,DB_KEH_2019_20
Code should pick the file from moving to the folder and pick one file DB_LOH_2019_20.csv
add new column as SITE =LOH and
DB_ABC_2019_20.csv add new column as SITE= ABC
same for folder B file as SITE= SGH and Folder C , SITE= NYK , once this is done then club all file into one dataframe.


text:
Q: Gulp/NodeJS: Require('fs') fails on Ubuntu, but works on Windows I've inherited a project that does its build using NodeJS. Everything's been working fine for us for months. We've built a number of production releases with no problem.
Enter xlsx.js.
Since adding this package as a dependency, we've found that our Gulp build works on Windows but not on Ubuntu (which is our build machine). When we do the build on Ubuntu, RequireJS barfs on require('fs'):
johnny@ubun-16:~/dev/eVGM-JavaScript-Client$ node --version
v4.6.1
johnny@ubun-16:~/dev/eVGM-JavaScript-Client$ gulp test
[15:19:35] Using gulpfile ~/dev/eVGM-JavaScript-Client/gulpfile.js
[15:19:35] Starting 'test'...
[15:19:35] Starting 'run-tests'...
07 11 2016 15:19:40.236:WARN [karma]: No captured browser, open http://localhost:9876/
07 11 2016 15:19:40.298:INFO [karma]: Karma v0.13.22 server started at http://localhost:9876/
07 11 2016 15:19:40.308:INFO [launcher]: Starting browser PhantomJS
07 11 2016 15:19:41.421:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket Hq69p1CiIhcsCDOGAAAA with id 72071968
07 11 2016 15:19:41.596:WARN [web-server]: 404: /base/jspm_packages/system-polyfills.js
07 11 2016 15:19:43.457:WARN [web-server]: 404: /base/fs.js
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  Error: (SystemJS) XHR error (404 Not Found) loading /home/johnny/dev/eVGM-JavaScript-Client/fs.js
Error loading /home/johnny/dev/eVGM-JavaScript-Client/fs.js as "fs" from /home/johnny/dev/eVGM-JavaScript-Client/jspm_packages/github/sheetjs/js-xlsx@0.8.0/xlsx.js

PhantomJS 2.1.1 (Linux 0.0.0): Executed 0 of 0 ERROR (2.27 secs / 0 secs)

From what I can tell, 'fs' is a built-in package for NodeJS. (right?)  And it should be there. Yet it's not according to Gulp.
To make matters even weirder, if I type Node and at the Node prompt, type "require('fs')", I get the flood of text that tells me that Node is finding the package A-OK.
Maybe it's a Gulp issue. Maybe it's a Ubuntu issue. Maybe it's a Jeff's-an-idiot issue. For whatever reason, I can not get our build to find fs from Gulp, and only on Ubuntu.
Any help very, very gratefully received ...
Thanks,
      Jeff

A: Ok, i figured it out, digging through some related StackOverflow answers.
require('fs') is only intended to be used on a server application. After all, what is the file system of a browser? It makes no sense in that context. If I'd been using my brain I would have realized that.
So I looked at where the library was using fs, and it was only in a single place:
var fs;
function readFileSync(filename, options) {
  if(fs === undefined) fs = require('fs');
  return parse(fs.readFileSync(filename), options);
}

I stuck an alert in there and ran the code we needed; the alert was not called.
That means that even though fs.js is loaded it is not actually used when executing in the browser for our application.
So the next step is probably to make a custom version of the library (a fork) and remove that single function. We don't need it and it breaks our build, so we can get rid of it.
Does this make sense?
Jeff

A: Do not fork, the library is made for both client and server side, it's normal to find this.

I've inherited a project that does its build using NodeJS.
  Everything's been working fine for us for months. We've built a number
  of production releases with no problem.

Inheritance these days :)
So correct me if I'm wrong, it's a javascript client side project build with gulp (using node).
You added xslx and your test works fine on windows but not on ubuntu.
My first suspect is phantomJS. Check your version. It may be related to https://github.com/SheetJS/js-xlsx/issues/184


text:
Q: US Voting precinct data I am looking for a source for data to determine voting precinct boundaries in the United States. My thought is that they might be on the Census website but under a name that doesn't make it obvious.
Does anyone have a working link (or set of instructions) that will allow me to find that information?

A: You may want to take a look at the Harvard Election Data Archive, which is for the 2008 elections. Curiously the shape files don't come with a .prj file, but that can be fixed. Also, boundary files are not available for all the states, unfortunately.

A: There is a github repository that seeks to maintain up-to-date precinct shapefiles by github user aaron-strauss.
From the README:

Voting Precinct Shapefiles in the United States
This project aims to catalog as many shapefiles of precincts (in some
  states "voting tabulation districts", or "election districts") across
  the United States. The priority is to obtain current shapefiles,
  namely more recent than 2010.

Note that the repo organizes data by state, and for some states it provides an external link to a shapefile rather than the shapefile itself.

A: The Election Geodata git repository seems like a promising source.


text:
Q: What is the theoretical basis behind counting dispersion as an implicit additional free parameter in R's logLik() function? Recently I was attempting to calculate the Akaike Information Criterion (AIC) for a set of fitted models in R, using standard packages available on CRAN.  A package that I was using seemed to be exhibiting unexpected behavior, adding "+1" to the number of free parameters in each model.  While trying to understand the reason for this result, I ran across this stackoverflow question about the same issue.  I wrote my own question seeking further clarification, and confirmed that the extra parameter is intended to count the dispersion of the observed data about the fit model, even though the dispersion does not appear to be a parameter that could be independently adjusted in order to further improve the goodness of a fit.  The result of this "+1" behavior is that if one performs a linear regression against, for example, a simple line, using maximum likelihood techniques to estimate a slope and intercept parameter, then logLik() will report the number of model parameters as 3, rather than 2. A respondent to my question pointed me to this additional answer further confirming that this is indeed the intended behavior, in fact a commit to the source code from 19 years ago even references switching back and forth between the two alternative return values, as if there had been some significant disagreement within the developer community about which option was the correct output.
I looked up Hirotugu Akaike's original article from 1974, and the abstract references the "number of parameters" in a model as meaning "the number of independently adjusted parameters within the model".  Furthermore in the text of the paper (paywalled), in section IV, he additionally clarifies that "$k$ is the [...] number of parameters independently adjusted for the maximization of the likelihood"  It seems clear from context that because the dispersion of a fitted model is not used or referenced in maximizing the likelihood, but only emerges after the fitting procedure is already completed, Akaike would argue that for purposes of calculating AIC, he did not intend for the dispersion to be counted as one of the model's free parameters.  Thus, the practice of adding "+1" to the number of free parameters as the R stats module does, and using that value as input to an AIC calculation, seems counter to how the AIC was originally conceived by Akaike himself.
I am aware that in mathematics, sometimes we define certain concepts in order to enforce consistency within a larger theoretical framework.  So, for example, we define that $\sqrt{-1} = i$, or $0! = 1$, even though the reasons for those definitions wouldn't make much sense if considered only in isolation, without an appreciation of the larger context.  I'm curious whether there's also some broader context here that I'm not yet understanding, which developed within the field only after Akaike published his paper in 1974.
My question: what is the theoretical justification behind adding "+1" in order to count the dispersion among the number of free parameters in R's logLik() function, when the dispersion is not actually an independently adjustable parameter that could be tuned to further increase the maximum likelihood, and earlier thinkers such as even Akaike himself did not seem to have viewed it as such?

A: The loglikelihood returned for a linear regression model in R is the full Gaussian loglikelihood, which does depend on maximisation over $\sigma^2$; it isn't just the RSS.
The code (in stats:::logLik.lm) has
0.5 * (sum(log(w)) - N * (log(2 * pi) + 1 - log(N) +
        log(sum(w * res^2))))

which is maximised over both $\beta$ and $\sigma^2$ and so genuinely has $|\beta|+1$ parameters.  It is not $-\mathrm{RSS}/2$ or $-\mathrm{RSS}/2\sigma^2$
Because only differences in AIC have any meaning, the parameter count will only be affected if comparing a model with and a model without a dispersion parameter -- eg comparing a model with a prespecified error variance to one with an estimated error variance. In that setting, you would want to count $\sigma^2$ as a parameter.


text:
Q: Invalid DB Instance class: db.t2.micro Why can I not create a database of size db.t2.micro in CloudFormation?
Here is my template:
Resources:
  Database:
    Type: AWS::RDS::DBInstance
    Properties:
      AllocatedStorage: 20
      AllowMajorVersionUpgrade: No
      BackupRetentionPeriod: 7
      DBInstanceClass: db.t2.micro
      DBName: myDB
      DeletionProtection: no
      Engine: mysql
      MasterUsername: admin
      MasterUserPassword: superSecret
      MultiAZ: no
      PubliclyAccessible: yes
      VPCSecurityGroups:
        - !Ref SG

And the error that I am getting is:
Invalid DB Instance class: db.t2.micro (Service: AmazonRDS; Status Code: 400; Error Code: InvalidParameterValue; Request ID: ????; Proxy: null)

Any suggestions are appreciated.

A: You can use the following AWS CLI command to check whether a DB instance class is orderable in a particular AWS region:
aws rds describe-orderable-db-instance-options --engine mysql --db-instance-class db.t2.micro --region eu-north-1

In this case, it returns
{
    "OrderableDBInstanceOptions": []
}

This means that the db.t2.micro is not orderable in eu-north-1.


text:
Q: C# Object null check I read my database using DataReader.
and some row does not have fdate value.
so when I Convert the null date to DateTime then Error occurs.
How can I check the field empty or not?
AdsCommand cmd = conn.CreateCommand();
cmd.CommandText = "select name,fdate from abc";

AdsDataReader reader = cmd.ExecuteReader();

DateTime flsdate = (reader["fdate"].Equals(null))? Convert.ToDateTime(reader["fdate"]) : DateTime.Today;

I tried with Equals, but it does not work.
anybody know how to check the null object to avoid convert error?
Thank you!

A: Use DbNull:
http://forums.asp.net/t/1383849.aspx/1

A: In a situation such as this I like to represent nullable database columns with either a reference type (string for varchar) or a Nullable wrapped value type (DateTime?).  This way you're more accurately representing the database schema in your program.
This also allows you to more cleanly write the conversion logic using the format:
DateTime? fdate = datareader["fdate"] as DateTime?;

This cast will fail in the event the datareader result is a DbNull and fdate will be set to default(DateTime?), which is null.  At that point you can obtain your real desired value by checking whether the nullable type has a value or not (fdate.HasValue), and if not, using your default - DateTime.Today.

A: DateTime flsdate = reader["fdate"].Equals(DBNull.Value)
    ? Convert.ToDateTime(reader["fdate"])
    : DateTime.Today;

But it seems dangerous to default the date to Today.  I'd do this instead:
DateTime? flsdate = reader["fdate"].Equals(DBNull.Value)
    ? Convert.ToDateTime(reader["fdate"])
    : (DateTime?)null;

Furthermore, if the underlying tpe of the fdate column is already DateTime, don't use System.Convert:
DateTime? flsdate = reader["fdate"].Equals(DBNull.Value)
    ? (DateTime?)reader["fdate"])
    : null;

A: As everyone pointed you how to solve the issue, I am trying to give you the info regarding what is the difference between NULL and DBNull.

*

*null and DBNull are different.

*null is not an instance of any type. DBNull is a singleton class with one instance: DBNull.Value.

*null represents an invalid reference where as DBNull.Value represents a nonexistent value in DB.

*DBNull.Value is what db providers provide for a nonexistant value in a table.
With that background (reader["fdate"].Equals(null)) is not correct to use here. You have to check it with DBNull.Value. If it is of type DBNull, or if it is equal to DBNull.Value, then assign what ever value you like.

A: Try the following:
DateTime flsdate = reader["fdate"] != null && reader["fdate"] != System.DbNull.Value
    ? DateTime.ParseExact(reader["fdate"])
    : DateTime.Today;

A: DateTime flsdate = DateTime.Today;
if(reader["fdate"] != null)
    flsdate = Convert.ToDateTime(reader["fdate"])


text:
Q: SSIS: Mismatched quotes error I am trying to get this DTEXEC statement to work:
DTExec /REP E /f Congrat.dtsx
/CONNECTION AcadProfDW;"\"Data Source=###########;User ID=######;
Password=##########;Initial Catalog=AcadProfDW;Provider=SQLNCLI11.1;
Persist Security Info=True;Auto Translate=False;\""
/Set \Package.Variables[Project::CsvInputFilePath].Properties[Value];
"d:\directory\"

I get this error:
The argument "\Package.Variables[Project::CsvInputFilePath].Properties[Value];d:\directory " has mismatched quotes.

I've tried placing a quote before '\Package', adding an extra quote at the end, around the semicolon, and myriad other variations and I keep getting that error.  What am I missing?

A: You should write your /Set param as follows:
/Set \Package.Variables[Project::CsvInputFilePath].Properties[Value];
"d:\directory\\"

or
"/Set \Package.Variables[Project::CsvInputFilePath].Properties[Value];
d:\directory\\"

There is an SO question on this, here is the answer - https://stackoverflow.com/a/3348557


text:
Q: binary search tree updating I am developing an application which needs to store the values in a binary search tree. It is some what similar to the application which implements textpad by storing each line as a value with some key. If a line is deleted, keys for lines after that are updated in O(n). I am able to achieve O(n) time in my application by considering a parameter similar to line number(in the example) as the key.
Is there a way to achieve O(log n) time by choosing some other key?

A: If you need guaranteed O(logN) peformance from a binary tree you should use a self-balanced version e.g. Splay Tree or Red black tree

A: If your requirements are to Insert/Update, Delete and Search, then try Hash Table with good hash function.  Many languages provides hash table implementations unordered_map in C++, dict in python, {} in javascript... Oh btw, You can write one yourself.
Also you can try some balanced bst for O(log(n)) like Red-Black trees, avl trees, 2-3 trees.


text:
Q: Is there any possible way to programmatically load all images from a local workspace directory to a vite-react component? I am trying to figure out a way for me to add some jpgs to my cats gallery. My layout includes images from one of three categories. I am using vite-react scaffold. I thought I could find a way to create one folder for each category, add all the jpgs in that folder, and then drum up some JSX to handle rendering. This is what I have so far. PS - the console is logging nothing - no errors or my attempt to confirm all the values were logging

// import { useState } from 'react'
import * as allFloofs from './assets/floofs/floofs'

function App() {
  // const [images, setImages] = useState(false)
  for (var i = 0; i < allFloofs.length; i++) {
    let src = `${allFloofs[i]}`;
    console.log(allFloofs[i])
    let floof = new Image();
    floof.src = src;
    querySelector.image - container.appendChild(floof);
  }

  return (

 {
      /*  <Floofs/>
          <Sleps/>
          <Snyks/>  */
    }

  )
}

export default App
.App {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

h2 {
  text-align: center;
}

.image-container {
  width: 80%;
  margin-left: 10%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 5px;
}

.image-container div:first-child {
  grid-column-start: 1;
  grid-column-end: 3;
}

.image-container div:last-child {
  grid-row-start: 2;
  grid-row-end: 5;
}

.image {
  width: 100%;
  height: 30px;
}

.image img {
  width: 40%;
  height: 40%;
}

:root {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;
  color-scheme: light dark;
  color: rgba(255, 255, 255, 0.87);
  background-color: #242424;
  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
}

a {
  font-weight: 500;
  color: #646cff;
  text-decoration: inherit;
}

a:hover {
  color: #535bf2;
}

body {
  margin: 0;
  display: flex;
  place-items: center;
  min-width: 320px;
  min-height: 100vh;
}

h1 {
  font-size: 3.2em;
  line-height: 1.1;
}

button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  background-color: #1a1a1a;
  cursor: pointer;
  transition: border-color 0.25s;
}

button:hover {
  border-color: #646cff;
}

button:focus,
button:focus-visible {
  outline: 4px auto -webkit-focus-ring-color;
}

@media (prefers-color-scheme: light) {
   :root {
    color: #213547;
    background-color: #ffffff;
  }
  a:hover {
    color: #747bff;
  }
  button {
    background-color: #f9f9f9;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <link rel="stylesheet" href="/src/index.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>  F.I.R  </title>

dir layout


text:
Q: MongoDB/Mongoose Query for multiple objects I got an MongoDB database that consists from 3 collections.

*

*Categories

*Subcategories

*Products

Each product has the following model:
const ProductSchema = new Schema({
    category: String,
    subcategory: String,
    name: String,
    description: String,
    price: String,
    Image: [{
        url: String,
        filename: String
    }],
    deleteImages: []

});

What I want is to query a category then get the subcategories that belong to the category and (here is the question:) from the found subcategories query the products that belong to them.
app.get("/api/front/show/:category", asyncHandler(async(req,res)=>{
  const category = req.params.category;
  const subcategories = await SubCategoryMd.find({'category' : category});
  const products = await ProductMd.find({/* Pass here the found subcategories */});
  res.json({subcategories, products});
}));

How do I query multiple objects with find?

A: app.get("/api/front/show/:category", asyncHandler(async(req,res)=>{
  let products = []
  const category = req.params.category;
  const subcategories = await SubCategoryMd.find({'category' : category});
  const productsBulk = await ProductMd.find({}).collation({ locale: 'el' }).sort('name');
  productsBulk.forEach(product => {
    subcategories.forEach(subcategory => {
      if(subcategory.name === product.subcategory){
        products.push(product)
      }
    });
  });
  res.json({subcategories, products});
}));

This is a simple solution but it already pulls all the products and on top of that it is a very expensive function to run in my opinion.


text:
Q: Summernote, set editor width and height I can't seem to be able to set the editor to have a fixed width and height.
My code is
$('#myEditor').summernote({
    height: 20,
    width: 320,
    disableResizeEditor: true,
    airMode: true,
    popover: {
        air: [
            // [groupName, [list of button]]
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['strikethrough', 'superscript', 'subscript']],
            ['insert', ['link']]
        ],
        link: [
            ['link', ['linkDialogShow', 'unlink']]
        ]
    },
    callbacks: {
        onEnter: function (e) {
            e.preventDefault();
        },
        onPaste: function (e) {
            var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
            e.preventDefault();
            document.execCommand('insertText', false, bufferText.replace(/\n/g, ''));
        }
    }
});

The editor width is not set using the config above.
Note that I am also using Bootstrap, if that makes a difference (I saw some issues about this). As soon as I type more text the editor grows. Basically I would like the field to behave like an input text field.
Is there a way to set the width and height in the config?
Do I have to try to set the DOM properties myself?

A: You can insert  inside them
<textarea id="summernote">
    Place some text here

</textarea>


text:
Q: Vagrant with docker provisioning I am new to docker and vagrant. I installed vmbox and vagrant in my ubuntu 14.04 machine.
I did "git clone https://github.com/dotcloud/docker.git" to get the docker repository. I have also added precise64 from vagrant successfully.
From docker directory i tried "vagrant up". But it told me to do "vagrant init" first. So I did "vagrant init precise64". After doing "vagrant ssh" there is no docker inside the precise64 vm. How can I make sure that docker is installed already in precise64 on startup?
PS: vagrantfile is not allowing " config.vm.provision "docker" "

A: The following Vagrantfile will get you a VM with docker ready to go:
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.box = "phusion/ubuntu-14.04-amd64"
  config.vm.hostname = "dockerhost"

  config.vm.provision "shell", inline: <<-SCRIPT
    curl -sL https://get.docker.io/ | sh
    curl -sL https://raw.githubusercontent.com/dotcloud/docker/master/contrib/completion/bash/docker > /etc/bash_completion.d/docker
    adduser vagrant docker
  SCRIPT

end

EDIT :
Even easier, you can now use Docker Toolbox to get up and running.

A: You might be using old version of vagrant.
config.vm.provision "docker" work only with vagrant 1.6.5 .
Try upgrading your vagrant to 1.6.5. It will resolve the issue.

A: Upgrading the Vagrant to 1.6.5 resolves the issue.


text:
Q: Why does this while-loop run infinitely? How come this code runs an infinite loop?
Everything i type in the prompt returns null and I dont know why.

var userChoice = prompt("Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka." + "\n\n" + "Vad vill du göra? Skriv in ditt val:" + "\n" +
  "1. Stäng av TVn" + "\n" + "2. Gå utomhus" + "\n" + "3. Fyll glaset med vodka" + "\n" + "\n" + "4. Avsluta");

while (userChoice != "stäng av tvn" || "gå utomhus" || "fyll glaset med vodka" || "avsluta") {
  alert("Skriv in ditt val som det är skrivet i menyn!")
  userChoice = prompt("Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka." + "\n\n" + "Vad vill du göra? Skriv in ditt val:" + "\n" +
    "1. Stäng av TVn" + "\n" + "2. Gå utomhus" + "\n" + "3. Fyll glaset med vodka" + "\n" + "\n" + "4. Avsluta");

  console.log(userChoice);
}

A: A non-empty string is a truthy value so the OR conditions will be true. That's why you got a infinite loop. You need to set userChoice != before every string.
Moreover, you should use AND operators to check that the userChoice is none of the expected values.
while (userChoice != "stäng av tvn" && userChoice != "gå utomhus" && "fyll glaset med vodka" && userChoice != "avsluta")


text:
Q: get the backtrace before unwinding the stack My process is not running on a debugger, instead it generates a core file when crash happened.
UPDATE: The crash happens due to an exception. From a throw() and it was not handled even in main() scope.
When I attach it and run it inside a debugger it does generate backtrace correctly but in the corefile it does not.
The issue may be operating system unwinds the stack before passing control to terminate so when terminate generates the SIGABT it does not have such information about the previous stack.
I'm getting this crash for a stress memory testing, so there's no way I could ru n this under gdb.
What to do ? Any walkaround

A:
The issue may be operating system unwinds the stack before passing control to terminate

The Linux OS does no such thing.
You didn't supply relevant details, but the two most common causes for "bad" stack trace from a core dump are:

*

*running out of ulimit -c and getting a truncated core dump, or

*trying to analyse core using different system libraries from the ones used to produce it. This could happen if you produce and analyse core on different machines, or if you've upgraded system libraries in between.


text:
Q: Javascript Nesting Quotes not clear What will be the Nesting Quotes for this
"javascript:window.open('http://localhost:9000/index.html#/mypage/detailspage\',
'details-page','width=300,height=250');"

I tried this not working
"javascript:window.open(\'http://localhost:9000/index.html#/mypage/detailspage\',
 \'details-page\',\'width=300,height=250\');"

A:

var y="javascript:window.open('http://localhost:9000/index.html#/mypage/detailspage\' ,\'details-page\',\'width=300,height=250\'')";
alert(y);

This works fine in browser i guess.

A: Thanks guys for the reply but it is now working for me. Actually my requirement is that from my app I am passing the value as a  post request to another app in that app I am not able to see my code as I am sending it. Below is the example
<input type="hidden" name="value11" id="value11" ng-model="indexedArray[34]" value="javascript:window.open('http://localhost:9000/index.html#/abc/details-page\' ,\'details-page\',\'width=300,height=250\'');" autocomplete="off" class="ng-pristine ng-untouched ng-valid ng-empty">
In response I am getting this


text:
Q: Display a dialogbox with a text input in C#
Possible Duplicate:
Which control to use for quick text input (inputbox)?

I need to display a dialog box which contains an input text to let the user type something and press ok, so I can read the typed text and do other things.
Is there anyone who knows the name of it ?

A: There is no such a thing in C#. You have to create dialogbox with input on your own. Take a look here, there is a good example how to do that.

A: You can use Interaction.InputBox() method, which comes within Microsoft.VisualBasic namespace. You can use it in C# project by simply adding Microsoft.VisualBasic.dll assembly reference.

A: You can use the InputBox from VB6 by referencing the DLL.  Here is a link on how to do this in C#:
http://www.codeproject.com/KB/edit/InputBox.aspx


text:
Q: React.findDOMNode comes as undefined I have

A: In React v0.13 use React.findDOMNode().
In earlier versions e.g. v0.12 you can use component.getDOMNode()
this.refs.myRef.getDOMNode();

To support ES6 based patterns going forward, the React team added React.findDOMNode(component) to be used in place of component.getDOMNode().

A: Not sure when it happened, but it seems to live in ReactDOM now ReactDOM.findDOMNode.
See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode.

A:
React.findDOMNode

has been deprecated, use

ReactDOM.findDOMNode

in React 15.1 and up

A: React.findDOMNode was introduced in React v0.13, so make sure you are using at least v0.13.

A: This might not be very relevant for the code mentioned with the question above, however a couple of other checks from react's docs are:

*

*"When render returns null or false, findDOMNode returns null."

*"findDOMNode cannot be used on functional components."
Hope this helps someone in need.


text:
Q: AngularJS select seems to need to match on the same object to set the selected option I have asked a question very recently in this post about why my angular select is not setting my select using saved answers.
This is my select:
        <select ng-model="question.answer" ng-options="opt as opt.Value for opt in question.options" />

The answer by pkozlowski.opensource tothis stackoverflow post  got me thinking that the value that is being set in the ng-model of my select can't be matching any of the values that are being passed as options in the ng-options of my select.
I created this jsfiddle that should highlight the issue. Whenever the answer is changed the answer object is logged to the console. (Note that for some reason it is being logged twice in jsfiddle, but it's only being logged once when I run the same code locally on my machine)
You can see that when the button is pressed, the answer logged out is the same object structure as the third option, but the picklist is set to a blank option.
Output logged to console after setting the picklist to the third option:
answer is: picklistTest.js:25
Object {id: 3, Value: "Three"}

Output logged to console after clicking the "setToThirdAnswer" button:
answer is: picklistTest.js:25
Object {id: 3, Value: "Three"}

It is the same structure, but not the same object. So I wondered if the object in the model has to be exactly the same object as one of the options.
This second jsfiddle shows that that is the case. The button is setting the answer to be a reference to one of the option objects.
So, I'm happy that I have found out why my selects weren't setting the selected value after a page refresh, but now I would really like to know (and this must be a very common use case):
If my options are objects and I am setting the whole object to the ng-model, how can I use saved json to re-render the form without first doing some processing on the client side?
var json = question = {
    options: [
       {
           id: 1,
           Value: "One"
       },
       {
           id: 2,
           Value: "Two"
       },
       {
           id: 3,
           Value: "Three"
       }
   ],
   answer: {
               id: 3,
               Value: "Three"
           }
};

because the answer object and the third value of the options array aren't the same object, but you can't represent a reference in json (can you?).

A: The ng-options attribute has a track by expression to do just what you're talking about:
ng-options="opt as opt.Value for opt in question.options track by opt.id"

See the updated fiddle: http://jsfiddle.net/CkLEu/6/

A: Yes, you need to have the same reference. You can do this like so:
question.answer = question.options[2]

Directly after you create it.


text:
Q: How can I sum values if two fields are the same using JSON COUNT - SUM this is my JSON file.
{"result":[
{"beer":"23","store":"1","table":"1"},
{"beer":"12","store":"1","table":"1"},
{"beer":"5","store":"1","table":"2"}]}

I want to sum beer if the store and table fields are the same.
The result should be be 2 records:
beer 35, store 1 table 1
beer 5, store 1 table 2

This is the MYSQL Query I use:
$sql = "SELECT * FROM data  ORDER BY beer DESC";
        $res = mysql_query($sql);
        $result = array();

        while( $row = mysql_fetch_array($res) )
            array_push($result, array('beer' => $row[1],
                                      'store'  => $row[2],
                                      'table' => $row[3]));

        echo json_encode(array("result" => $result));

A: Hope you need group by
$sql = "
    SELECT sum(beer) as beer, store, table
    FROM data
    GROUP BY store, table
    ORDER BY beer DESC
";

A: To do this directly from the sql:
$query = "SELECT sum(beer) as beer, store, table
    FROM data
    GROUP BY store, table " ;
to sum it from the json:
$json_result = json_decode($json_var) ;

$result = array() ;

foreach($json_result->result as $key=>$value){
    if(!isset($result[$value->store])){
        $result[$value->store] = array() ;
        $result[$value->store][$value->table] = $value->beer ;
    }
    else if(!isset($result[$value->store][$value->table])){
        $result[$value->store][$value->table] = $value->beer ;
    }
    else{
        $result[$value->store][$value->table] += $value->beer ;
    }
}

$result will contain the json sum


text:
Q: return value from observable to view problem I am working on image upload with nativescript, but I couldn't return the image base64 to my view for the preview, the problem here is my function does not read my global variable.
here is the code
myImg:any;
pickFiles() {
let options = {
  title: "Importer",
  cancelButtonText: "Annuler",
  actions: ["Image(s)", "Video(s)", "Audio(s)", "Fichier(s)"]
};
dialogs.action(options).then(async (result) => {
  if (result == 'Image(s)') {...}
  if (result == 'Video(s)') {...}
  if (result == 'Audio(s)') {...}
  if (result == 'Fichier(s)') {...}
  this.mdf.on("getFiles", async function (res: any) {
    let results = res.object.get('results');
    let img1 = await imageSourceModule.fromFile(results[0].file).toBase64String('jpg');
    // let img2 = await imageSourceModule.fromBase64(img1)
   this.myImg;
  });
  this.mdf.on("error", function (res) {
    let msg = res.object.get('msg');
    console.log(msg);
  });
});

I expect that the variable myImg gets the new value of the img, but when I bind it to view it becomes null.

A: myImg1 which you are referring from an anonymous function will not be referenced and you must be getting an error on console. The reason is anonymous function will have it;s own this and will not refer to the this of component. So you need to have an arrow function:
You need to modify you code like this:
pickFiles() {
let options = {
  title: "Importer",
  cancelButtonText: "Annuler",
  actions: ["Image(s)", "Video(s)", "Audio(s)", "Fichier(s)"]
};
dialogs.action(options).then(async (result) => {
  if (result == 'Image(s)') {...}
  if (result == 'Video(s)') {...}
  if (result == 'Audio(s)') {...}
  if (result == 'Fichier(s)') {...}
  this.mdf.on("getFiles", async (res: any) => {
    let results = res.object.get('results');
    let img1 = await imageSourceModule.fromFile(results[0].file).toBase64String('jpg');
    // let img2 = await imageSourceModule.fromBase64(img1)
    this.myImg = img1;
  });
  this.mdf.on("error", function (res) {
    let msg = res.object.get('msg');
    console.log(msg);
  });
});