text:
Q: Verify unique data from either/or and join. Using R to make a booklist I am trying to modify an R function which currently makes sure ISBNs are unique in Zotero data to check for ISBNs or DOI's.
I found this great package for creating a booklist in Google sheets from a Zotero group and I want to use it to build a simple sheet to track my dissertation reading (see: https://github.com/joelnitta/booklist). I have been able to successfully modify it to suit the data I want to retrieve however much of my material uses DOIs rather than ISBNs. I can get a DOI function working, similar to the existing ISBN but I can't figure out how to get it to look for either an ISBN or DOI, check for uniqueness, return the appropriate error messages, and later during the update phase join on unique ISBNs or DOIs. Any help is appreciated!
I am using RStudio v1.2.1335 on a Macbook Pro OSv10.14.6 (Mojave). I have been searching for an answer and have tried several versions of syntax but have yet to be successful. I can only get either unique DOI or unique ISBN, but not both.
#' Verify that all ISBN numbers are unique
#'
#' @param data Dataframe including at least one column called "isbn"
#' @param data_source Either "Google" or "Zotero"
#'
#' @return TRUE if there are no duplicate ISBN numbers or an error stating
#' which ISBN numbers are duplicates.
check_isbn <- function(data, data_source = c("Google", "Zotero")) {

  assertthat::assert_that(!any(is.na(data$isbn)),
                          msg = "One or more ISBNs are missing")

  assertthat::assert_that(!any(data$isbn == ""),
                          msg = "One or more ISBNs are missing")

  dup_isbn <-
    data %>%
    dplyr::count(isbn) %>%
    dplyr::filter(n > 1) %>%
    dplyr::pull(isbn) %>%
    paste(collapse = ", ")

  assertthat::assert_that(
    dup_isbn == "",
    msg = glue::glue("Duplicate ISBNs detected in {data_source} data: {dup_isbn}.
                     Please remove these before updating.")
    )
}

#' Update Sheet: Synchronize a Zotero bibliography and a Google Sheet
#'
#' It is assumed that the Google Sheet is located in the root folder of the
#' user's Google Drive.
#'
#' @param groupID ID number of Zotero group with bibliography
#' @param api_key API key needed to access Zotero group
#' @param sheet_name Name of the Google Sheet
#'
#' @return A \code{\link[googlesheets]{googlesheets}} object;
#' the Google Sheet should be updated with new book entries from Zotero, if any.
#' @export
update_booklistannotated <- function (groupID, api_key, sheet_name) {

  # Read in current bibliographic data from Zotero
  zotero_data <- get_zotero(groupID = groupID,
                            api_key = api_key)

  # Make sure ISBNs are unique in Zotero data
  check_isbn(zotero_data, "Zotero")

  # Get book status data (whether purchased or checked out) from Google Sheets
  book_status <- load_gs_data(sheet_name) %>%
    dplyr::select(isbn, contains("purchased"), contains("checked_out"))

  # Make sure ISBNs are unique in Google data
  check_isbn(book_status, "Google")

  # Merge Zotero data with book status and update Google Sheet
  book_update <-
    dplyr::full_join(zotero_data, book_status) %>%
    dplyr::mutate_all(~ifelse(is.na(.), "", .))

  # Update Google Sheet with new data
  googlesheets::gs_title(sheet_name) %>%
    googlesheets::gs_edit_cells(input = book_update)

}


text:
Q: Access Windows VPN DNS from Ubuntu I am using Ubuntu 10.04 to access a Windows VPN. I connect to the VPN from Ubuntu, and when I open a Windows 7 virtual machine (VirtualBox), everything works great ... I can access local network drives, ping local servers, remote into local machines, etc.
However, I can do none of this from Ubuntu. With the VPN connected, I cannot even ping anything within the VPN local network. I'm guessing it's a DNS issue that Windows is handling automatically but Ubuntu needs a setting somewhere to tell it to use the DNS servers of the VPN network?
Any ideas? I'm a relative novice to Ubuntu, esp. VPN in Ubuntu.
[EDIT] Actually, I'm almost positive it is DNS, because if I get the IP address from the Windows VM I can use Terminal Server Client to remote into a machine.

A: I had the same problem, and it was a routing issue. When you connect to the Windows VPN, the routes are not automatically added.
Here's what I did in 10.10 under the "IPv4 Settings" tab of the Network Manager's VPN config dialog. Hopefully, it will apply equally to 10.04.

*

*Selected Method "Automatic (VPN) addresses only"

*Specified DNS server IP's separated by comma

*Added our office's standard parent domain under "Search domains". (I'm not sure this matters because all my DNS lookups use the servers specified in #3 while connected to the VPN.)

*Clicked the "Routes..." button to open the routes dialog.

*Added a route for VPN addresses through the "Routes..." dialog.

*Example route: Address=192.168.0.0, Netmask=255.255.0.0, Gateway=192.168.2.53

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is the FOR loop in my program producing empty matrices? I am having a problem running a spiking-neuron simulator. I keep getting the error message, "operation +: Warning adding a matrix with the empty matrix will give an empty matrix result." Now I'm writing this program in "Scilab," but I'm hoping the problem I am having will be clear for the educated eye regardess. What I am doing is converting an existing MATLAB program to Scilab. The original MATLAB program and an explanation can be found here: https://www.izhikevich.org/publications/spikes.pdf
What happens in my Scilab version is that the first pass through the loop produces all the expected values. I Know this becuase I hit pause at the end of the first run, right before "end," and check all the values and matrix elements. However, if I run the program proper, which includes a loop of 20 iterations, I get the error message above, and all of the matrix values are empty! I cannot figure out what the problem is. I am fairly new to programming so the answer may be very simple as far as I know. Here is the Scilab version of the program:
Ne=8; Ni=2;
re=rand(Ne,1); ri=rand(Ni,1);

a=[0.02*ones(Ne,1); 0.02+0.08*ri];
b=[0.2*ones(Ne,1); 0.25-0.05*ri];
c=[-65+15*re.^2; -65*ones(Ni,1)];
d=[8-6*re.^2; 2*ones(Ni,1)];
S=[0.5*rand(Ne+Ni,Ne), -rand(Ne+Ni,Ni)];

v=60*rand(10,1)
v2=v
u=b.*v;
firings=[];

for t=1:20

    I=[5*rand(Ne,1,"normal");2*rand(Ni,1,"normal")];
    fired=find(v>=30);

    j = length(fired);
    h = t*ones(j,1);
    k=[h,fired'];

    firings=[firings;k];

    v(fired)=c(fired);
    u(fired)=u(fired)+d(fired);

    I=I+sum(S(:,fired),"c");

    v=v+0.5*(0.04*v.^2+5*v+140-u+I);
    v=v+0.5*(0.04*v.^2+5*v+140-u+I);

    u=u+a.*(b.*v-u);

end
plot(firings(:,1), firings(:,2),".");

I tried everything to no avail.  The program should run through 20 iterations and produce a "raster plot" of dots representing the fired neurons at each of the 20 time steps.

A: You can add the following line
oldEmptyBehaviour("on")

at the beginning of your script in order to prevent the default Scilab rule (any algebraic operation with an empty matrix yields an empty matrix). However you will still have some warnings (despite the result will be OK). As a definitive fix I recommend testing the emptyness of fired in your code, like this:
Ne=8; Ni=2;
re=rand(Ne,1); ri=rand(Ni,1);

a=[0.02*ones(Ne,1); 0.02+0.08*ri];
b=[0.2*ones(Ne,1); 0.25-0.05*ri];
c=[-65+15*re.^2; -65*ones(Ni,1)];
d=[8-6*re.^2; 2*ones(Ni,1)];
S=[0.5*rand(Ne+Ni,Ne), -rand(Ne+Ni,Ni)];

v=60*rand(10,1)
v2=v
u=b.*v;
firings=[];

for t=1:20

    I=[5*rand(Ne,1,"normal");2*rand(Ni,1,"normal")];
    fired=find(v>=30);

    if ~isempty(fired)
        j = length(fired);
        h = t*ones(j,1);
        k=[h,fired'];

        firings=[firings;k];

        v(fired)=c(fired);
        u(fired)=u(fired)+d(fired);

        I=I+sum(S(:,fired),"c");
    end

    v=v+0.5*(0.04*v.^2+5*v+140-u+I);
    v=v+0.5*(0.04*v.^2+5*v+140-u+I);

    u=u+a.*(b.*v-u);

end
plot(firings(:,1), firings(:,2),".");

A: The [] + 1 is not really defined in a mathematical sense. The operation might fail or produce different results depending on the software you use. For example:

*

*Scilab 5 [] + 1 produces 1

*Scilab 6 [] + 1 produces [] and a warning

*Julia 1.8 [] .+ 1 produces [] but [] + 1 an error.

*Python+Numpy 1.23 np.zeros((0,0)) + 1 produces [].

I suggest checking with size() or a comparison to the empty matrix to avoid such strange behaviour.


text:
Q: OS X: Deleted files still accessible through Terminal session? This is something neat that I've discovered today- I was modifying gcov files in a terminal.  I had one window open with old gcov files from 11 AM.  At 11:15, I ran my program again, and recreated the gcov files (overwriting the old ones).  I looked at them in a second terminal window.  However, I discovered I could still view the 11 AM gcov files in the first window!
Is this because of how the OS X file system works, that deleted files are still somewhat accessible?  It seems to be connected to how one can rename or move files that are already open, unlike in Windows.

A: A directory entry points to an inode, the inode contains metainfo and points to the file data. You can remove the directory entry (this reduces the reference count of the inode), or close the open file (also reduces the reference count of the inode). When the inode reference count is 0, then the actual file is deleted.
On e.g. FAT filesystems, the "inode" and the directory entry are the same entity - so removing a directory entry also removes the file.


text:
Q: Task start/stop handling using abstract classes I have this code logic to handle my tasks:
public abstract class BaseJob{

    public bool Running { get; private set; }

    public CancellationToken Token => _tokenSource.Token;

    private CancellationTokenSource _tokenSource;

    public virtual void Start()
    {
        _tokenSource = new CancellationTokenSource();
        Running = true;
    }
}

now when I inherit BaseJob I will have this situation:
public class CustomJob: BaseJob{

public MyEnum Status {get; private set;}

public StopRequested { get; set;}

public override async void Start(){

    base.Start();
    while(!StopRequested){
        await MyLongRunningMethod();
    }

    //base.Running = true but I can't access it here!
}

public async Task<bool> MyLongRunningMethod(){
            await Task.Run(()=>{
                //more work
            },this.Token);
            //someWork

    return false;
}
}

As you can see I can't access Running to set it to false as soon as myJob finishes, and I want BaseJob to handle that.
What code logic changes must I bring to the base class in order to automatically detect when myJob finishes, and then finalize the task with Running = false without accessing the least from the inherited classes?

A: Make Running set protected instead of private. This way it cant be accessed from outside but it can accessed by entities who inherit from BotTask

A: You could rewrite your abstract class to have an internal start method that can know when your job completes. Assuming your job is synchronous and takes no parameters:
public abstract class BotTask
{

    private bool Running { get; set; }

    public CancellationToken Token => _tokenSource.Token;

    private CancellationTokenSource _tokenSource;

    public abstract void Start();

    protected void InternalStart(Action job)
    {
        _tokenSource = new CancellationTokenSource();
        Running = true;
        job();
        Running = false;
    }
}

public class CustomTask : BotTask
{
    public override void Start()
    {
        InternalStart(MyJob);
    }
}


text:
Q: Generating number sequence in verilog (automat) I was given a task to create verilog code that generates number sequence 323135343355.
It should be generated like automat so it has states and next number in sequence is generated according to its previous output.
Task should be done in two ways.
First one is that sequence is generated in eternity (solved that one, but still wonder can my code be reduced.)
Second one is when sequence is generated once output should be only one number that repeats (for example 32313534335511111111111111....) I tried this one by settinf if statment but default case always outputs 4 if all demands are not met.
//implementation
module prvi(
output reg [3:0] out,
input clk, restart
    );

reg [3:0] state;

    always@(posedge clk)
    begin
        if(restart)
        begin
            out<=3;
            state<=5;//state is set to 5 because previos number is 5
        end

        else
        begin
            case(out)
                3:begin
                    if(state==5)
                        begin
                            out<=2;
                            state<=2;//state is set to 2 because it is our output
                        end
                    else if(state==2)
                        begin
                            out<=1;
                            state<=1;//output is 1 so state is 1
                        end
                    else if(state==1)
                        begin
                            out<=5;
                            state<=0;//state is 0 because 5 already in use 0=STATE WHEN 3534
                        end
                    else if(state==0)
                        begin
                            out<=4;
                            state<=4;//output is 4 so state is 4
                        end
                    else if(state==4)
                        begin
                            out<=3;
                            state<=3;//output is 3 so state is 3 BUT STATE AT 4335
                        end
                    else if(state==3)
                        begin
                            out<=5;
                            state<=6;//5 ALREADY IN USE SO STATE=6 IS FOR 355
                        end
                    end
                2:begin
                    out<=3;
                    state<=2;
                end
                1:begin
                    out<=3;
                    state<=1;
                end
                5:begin
                    if(state==6)
                        begin
                            out<=5;
                            state<=3;
                        end
                    else if(state==3)
                        begin
                            out<=3;
                            state<=5;
                        end
                        else if(state==0)
                            begin
                                out<=3;
                                state<=0;
                            end
                    end
                4:begin
                    out<=3;
                    state<=4;
                end
                default:begin
                    out<=4;
                    state<=4;
                end
            endcase
        end
    end
endmodule

//test module
module test_prvi;

    // Inputs
    reg clk;
    reg restart;

    // Outputs
    wire [3:0] out;

    // Instantiate the Unit Under Test (UUT)
    prvi uut (
        .out(out),
        .clk(clk),
        .restart(restart)
    );

    initial begin
        // Initialize Inputs
        clk = 0;
        restart = 0;

        #60 restart=1;
        #9 restart=0;

        // Wait 100 ns for global reset to finish
        #200 $stop;

        // Add stimulus here

    end
    always begin
        #3 clk=~clk;
    end

endmodule

A:
but still wonder can my code be reduced

Here is a possible solution which reduces your code size: store the sequence in a variable and just retrieve what is needed every cycle, without creating a classic state machine:
module prvi(
            output reg [3:0] out,
            input            clk, restart
            );

   reg [48-1:0]              state;
   reg [3:0]                 count;

   always@(posedge clk)
     begin
        if(restart)
          begin
             count <= 0;
             state <= 48'h553343531323; // reverce of 323135343355
          end
        else if (count == 12)
          begin
             out <= 4'h1;
          end
        else
          begin
             count <= count + 1;
             out <= state & 4'hf;
             state <= state >> 4;
          end
     end
endmodule

To simplify code and demonstrate the concept I used right shift >> and for that reason reversed your sequence of numbers. When count reaches 12 (length of the sequence), the result will always be '1'. The signal width you need is 12 * 4 = 48, 4 bits per hex digit. Decimal digits are a subset of hex.
You can use direct sequences or two-dimensional arrays to achieve it.


text:
Q: Database with Image display Ok, this one is annoying me. The company network is restricted to the max, we can't run exe's only set programs via AD.
I cant use powerapps as the folders I need to access are internal. Can't use php/mysql or asp/sql as admins will not allow me space or even look at setting up a dev site.
I looked at Excel, but have a few GB's of images, that'll almost kill any excel file.
What options if any are out there that will allow me to create a db of all my images and make a searchable user interface that can be shared out to users?
Thnaks in advance


text:
Q: O que significa a instrução "retn" com um argumento? É possível ver instruções de returno com um argumento, como isso é feito e como o valor de retorno é tratado? É para retornar um argumento na pilha?

A: Quando o código vai retornar de um rotina ele deve especificar quantos bytes ele deve voltar na pilha mudando o registrador Stack Pointer (SP). Esse é o número que consta ali.
Note que os números são sempre múltiplos de 4 bytes que é o tamanho de uma palavra na arquitetura então ele está voltando a quantidade de palavras determinada por esse número dividido por 4. Não esqueça que está em hexadecimal.
O N indica que deve fazer isso dentro do próprio segmento de código. No passado códigos em 16 buts só conseguiam endereçar 64KB e para conseguir mais memória era obrigado usar vários segmentos através de um endereçamento chamado distante (far) e aí usava-se a instrução RETF, a não ser que fosse só no mesmo segmento que usa o RETN (near). EM códigos modernos só há um segmento, mas mesmo no passado era mais raro sair do segmento para esse tipo de fim.
O RET na verdade é o RETN (ou RETF se for mesmo necessários), mas o montador infere quantos bytes deve voltar no ponteiro da pilha.
Isso é Assembly do x86, não vele para outros sabores.

A: Pode-se notar:

*

*É comum ter essa instrução no fim do Epílogo da função.

*Quando ela usada, sempre altera o ESP e o EIP.

*As vezes é utilizada para sair do "current segment".

Em breve retorno com mais informações.
Para referencia: https://www.felixcloutier.com/x86/ret


text:
Q: What is the idiomatic way to persist the data in this simple data-based application? I'm looking at developing a simple application in Java for a game which allows a user to keep track of which items they own and how much experience they have obtained while using the item. All of this data is input by the user.
What is the idiomatic/standard way to persist the data that is being manipulated (the model)? The immediate possibilities seem to be saving it to a file, serialization, databases, etc, but many of these seem to be overkill for simple text fields that don't seem to necessitate objects. What is the idiomatic/traditional way to handle something like this?

A: SQLite is a nice, lightweight database application. Some of the NoSql databases are easy to download and get running quickly, with low learning curve. I've heard Redis is pretty easy for saving simple data. MongoDB is very accessible as well, if you just use the basic features and don't worry about the complicated bits.
Managing everything in flat files on disk would work, too, but my guess is that the time it would take to define file formats, serialization, random access, and all the tricky parts -- with all the unit tests because you don't want a bug to corrupt your data -- then it would take more time and effort than just launching and learning something easy like SQLite or Redis.


text:
Q: Nodejs for loop callback issues I wrote this function that should run this for loop and then the callback at the end but it keeps running the callback before it finishes the loop. The only solutions I've read said using a callback would fix this issue but it doesn't seem to be making much of a difference.
function run(callback){
  for(var i = 0; i < urls.length; i++){
    request(url, function(error, resp, body){
      //uses cheerio to iterate through some elements on the page
      //then saves to an object for a future response
    });
    callback();
  }
}

A: I would add a variable called totaltasks and another one called tasksfinished. Then when a request is finished increment tasksfinished, and call your callback whenever tasksfinished equals totaltasks:
function run(callback){
  var totaltasks = urls.length;
  var tasksfinished = 0;

  // helper function
  var check = function() {
    if(totaltasks == tasksfinished) {
       callback();
    }
  }

  for(var i = 0; i < totaltasks; i++){
    try {
      request(url, function(error, resp, body) {

        tasksfinished++;
        check();
     });
    } catch(e) {
      tasksfinished++;
      check();
    }
  }
};

A: You need to move your callback function inside of the request callback:
function run(callback){
  for(var i = 0; i < urls.length; i++){
     request(url, function(error, resp, body){
        //uses cheerio to iterate through some elements on the page
        //then saves to an object for a future response
         callback();
     });

}

A: First of all your code example is missing some brackets. request is likely an asynchronous library. So at it's function call it's registering with the event loop and returns immediately. Meaning you actually call the callback immediately, probably without request having finished. So synchronously looping with async functions won't work.
Either use something like Promises, Continuation Passing, or register a variable, which tracks whether all calls have returned already.


text:
Q: match 2 files using awk when first file as key has multiple values I have 2 files A & B.
And I'm using this command for matching:
awk -F"\t" 'NR==FNR {a[$1]=$3","$2; next}; $1 in a {print $0a[$1]}' A B

Problem is file A has repeated entries in column 1. Now there'll be many values for a single key in array 'a'. Will this command print all the values or first value only present in array a?


text:
Q: Image resize optimization causes memory usage to sky rocket I made a function that takes an original image and resizes it to 3 different zoom scales -> 16x, 10x, and 4x.  For a better understanding, continue reading this paragraph.  Let's say the original image is 1000x1000.  I declare that at 1x zoom it's dimensions will be 50x50.  That means 4x zoom will be 200x200, 10x zoom will be 500x500 and 16x zoom will be 800x800.  So my function needs to resize the original 1000x1000 down to 800x800, then down to 500x500, then down to 200x200.  Please note I have done this successfully and my question is regarding memory usage.
Below I have two methods of doing so.  Both methods work, but one causes a HUGE memory usage bloat using approximately 3x/4x more memory than the other...  I like the 2nd method better, because it loads significantly faster than the first method because it's not resizing each of the 3 images from the original image, instead it's resizing them from the previously resized image.
Notes:  I'm using Xcode Instruments to measure memory usage.  The ImageResizer Class contains a function called "Resize" which resizes the Image.
Method 1.)
    public List<UIImage> InitImageList_BFObjects ( UIImage image, SizeF frameSize )
    {
        List<UIImage> listOfImages = new List<UIImage>();

        for ( int i = 0; i < 3; i++ )
        {
            if ( i == 0 )
                zoomScale = 16f;
            else if ( i == 1 )
                zoomScale = 10f;
            else// if ( i == 2 )
                zoomScale = 4f;

            Resizer = new ImageResizer(image);
            Resizer.Resize(frameSize.Width * zoomScale, frameSize.Height * zoomScale);
            UIImage resizedImage = Resizer.ModifiedImage;
            listOfImages.Insert(0, resizedImage);

        }

        return listOfImages;
    }

Method 1 works and uses very little memory usage.  I ran this with a group of about 20 images.  My app had about 14mb of memory usage after this loaded (using Xcodes Instruments to examine memory usage)
Method 2.)
    public List<UIImage> InitImageList_BFObjects ( UIImage image, SizeF frameSize )
    {
        List<UIImage> listOfImages = new List<UIImage>();

        for ( int i = 0; i < 3; i++ )
        {
            if ( i == 0 )
                zoomScale = 16f;
            else if ( i == 1 )
                zoomScale = 10f;
            else// if ( i == 2 )
                zoomScale = 4f;

            if ( listOfImages.Count == 0 )
            {
                Resizer = new ImageResizer(image);
                Resizer.Resize(frameSize.Width * zoomScale, frameSize.Height * zoomScale);
                UIImage resizedImage = Resizer.ModifiedImage;
                listOfImages.Insert(0, resizedImage);
            }
            else
            {
                // THIS LINE CONTAINS THE MAIN DIFFERENCE BETWEEN METHOD 1 AND METHOD 2
                // Notice how it resizes from the most recent image from listOfImages rather than the original image
                Resizer = new ImageResizer(listOfImages[0]);
                Resizer.Resize(frameSize.Width * zoomScale, frameSize.Height * zoomScale);
                UIImage resizedImage = Resizer.ModifiedImage;
                listOfImages.Insert(0, resizedImage);
            }
        }

        return listOfImages;
    }

Method 2 works but the memory usage sky rockets!  I ran this with the same group of about 20 images.  My app had over 60mb of memory usage after this loaded (using Xcodes Instruments to examine memory usage)  Why is the memory usage so high?  What is it about Method 2 that causes the memory to sky rocket?  It's almost as if a variable is not getting cleaned up properly
* Additional Information, ImageResizer Class **
I cut out the non-needed functions from my ImageResizer Class and renamed it "ImageResizer_Abridged".  I even switched over to using this class to make sure I didn't accidentally cut out anything needed.
public class ImageResizer_Abridged
{
    UIImage originalImage  = null;
    UIImage modifiedImage = null;

    public ImageResizer_Abridged ( UIImage image )
    {
        this.originalImage = image;
        this.modifiedImage = image;
    }

    /// <summary>
    /// strech resize
    /// </summary>
    public void Resize( float width, float height )
    {
        UIGraphics.BeginImageContext( new SizeF( width, height ) );
        //
        modifiedImage.Draw( new RectangleF( 0,0, width, height ) );
        modifiedImage = UIGraphics.GetImageFromCurrentImageContext();
        //
        UIGraphics.EndImageContext();
    }

    public UIImage OriginalImage
    {
        get
        {
            return this.originalImage;
        }
    }

    public UIImage ModifiedImage
    {
        get
        {
            return this.modifiedImage;
        }
    }
}

 I created a simplified test project showing this problem *
Here is a dropbox link to the project:  https://www.dropbox.com/s/4w7d87nn0aafph9/TestMemory.zip
Here is Method 1's Xcode Instruments screen shot as evidence (9 mb memory usage):
http://i88.photobucket.com/albums/k194/lampshade9909/AllImagesResizedFromOriginalImage_zps585228c6.jpg
Here is Method 2's Xcode Instruments screens hot as evidence (55 mb memory usage):
http://i88.photobucket.com/albums/k194/lampshade9909/SignificantIncreaseInMemoryUsage_zps19034bad.jpg
Below is the code block needed to run the test project
        // Initialize My List of Images
        ListOfImages = new List<UIImage>();

        for ( int i = 0; i < 30; i++ )
        {
            // Create a UIImage Containing my original Image
            UIImage originalImage = UIImage.FromFile ("b2Bomber.png");
            float newWidth = 100f;
            float newHeight = 40f;
            float zoomScale;
            float resizedWidth, resizedHeight;

            UIImage resizedImage1;
            UIImage resizedImage2;

            // Basically, I want to take the originalImage Image and resize it twice.
            // Method 1.) Resize the originalImage and save it as ResizedImage1.  Resize the originalImage and save it as ResizedImage2.  We're finished!
            // Method 2.) Resize the originalImage and save it as ResizedImage1.  Resize ResizedImage1 and save it as ResizedImage2.  We're finished!

            // The pro to Method 1 is that we get the best possible quaility on all resized images.  The con is, this takes a long time if we're doing dozens of very large images
            // The pro to Method 2 is that it's faster than Method 1.  This is why I want to use Method 2, it's speed.  But it has a HUGE con, it's memory usage.
            // Please run this project on an iPad connected to XCodes Instruments to monitor memory usage and see what I mean

            zoomScale = 10f;
            resizedWidth = newWidth*zoomScale;
            resizedHeight = newHeight*zoomScale;
            UIGraphics.BeginImageContext( new SizeF( resizedWidth, resizedHeight ) );
            originalImage.Draw( new RectangleF( 0, 0, resizedWidth, resizedHeight ) );
            resizedImage1 = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            zoomScale = 4f;
            resizedWidth = newWidth*zoomScale;
            resizedHeight = newHeight*zoomScale;
            UIGraphics.BeginImageContext( new SizeF( resizedWidth, resizedHeight ) );

            // Run this project on an iPad and examine the memory usage in XCode's Instruments.
            // The Real Memory Usage will be aroud 9 MB.
            // Uncomment this "originalImage.Draw" line to see this happening, make sure to comment out the "resizedImage1.Draw" line

            // originalImage.Draw( new RectangleF( 0, 0, resizedWidth, resizedHeight ) );

            // Run this project on an iPad and examine the memory usage in XCode's Instruments.
            // The Real Memory Usage will be aroud 55 MB!!
            // My question is, why does the memory sky rocket when doing this, and how can I prevent the memory from sky rocketing??
            // My App requires me to resize around a hundred images and I want to be able to resize an already resized image (like in this example) without the memory usage sky rocketing like this...
            // Uncomment this "resizedImage1.Draw" line to see this happening, make sure to comment out the "originalImage.Draw" line

            resizedImage1.Draw( new RectangleF( 0, 0, resizedWidth, resizedHeight ) );
            resizedImage2 = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            // Add my resized images to the list of Images
            ListOfImages.Add (resizedImage1);
            ListOfImages.Add (resizedImage2);
        }

A: I'm not sure about your Resize code but I have seen Scale do strange thing. It's not really strange, once you dig into it, but it's definitively not obvious.
Creating an UIImage can be very cheap, memory wise, as long as its backing CGImage is not created. IOW iOS might not immediately allocate a new CGImage backing image that match the new size. That allocation will be differed until the CGImage is needed.
In such case it's possible for some code (like your method 1) to require almost no additional memory when scaling up. However your 2nd method is using a scaled-up image (and will need to allocate the backing CGImage to do so) so it end up requiring the memory earlier.
How can you check for this ?
Compare your resizedImage.Size with the resizedImage.CGImage.Size. If they don't match then you're likely hitting caching.
Notes

*

*I say might because the caching logic is unknown (undocumented). I know that this can differ from running on the simulator and devices - and it also vary between iOS versions;

*Caching is a good thing - but it can be surprising :-) I just wish this was documented.

A: Have you checked whether Resizer implements the Dispose() method? I don't see you disposing it anywhere.
I believe your new code line is implementing the Zoom on the entire image, hence the increased memory usage.
Resizer is zooming the ENTIRE image at the new zoomed in scale, so that an incoming 4MB image is zoomed to 8MB, 16MB and 32MB, consuming your memory.

A: UIImage implements IDisposable, so something will have to Dispose of it eventually. The Resize method appears to "lose" the reference to modifiedImage, so I'm going to Dispose() it. Hopefully the caller is doing the same to all images in the list returned by InitImageList_BFObjects when it's done with them. Or that class implements IDisposable and it's kicked up the line of who has to deal with it. But rest assured, these images being created need to be Dispose()d somewhere sometime.
public class ImageResizer_Abridged
{
    private readonly UIImage originalImage;

    private UIImage modifiedImage;

    public ImageResizer_Abridged(UIImage image)
    {
        this.originalImage = image;
        this.modifiedImage = image;
    }

    /// <summary>
    /// stretch resize
    /// </summary>
    public void Resize(float width, float height)
    {
        UIGraphics.BeginImageContext(new SizeF(width, height));
        //
        var oldImage = this.modifiedImage;
        this.modifiedImage.Draw(new RectangleF(0, 0, width, height));
        this.modifiedImage = UIGraphics.GetImageFromCurrentImageContext();
        oldImage.Dispose();
        //
        UIGraphics.EndImageContext();
    }

    public UIImage OriginalImage
    {
        get
        {
            return this.originalImage;
        }
    }

    public UIImage ModifiedImage
    {
        get
        {
            return this.modifiedImage;
        }
    }
}


text:
Q: Programmatically distinguishing multi-stores in magento? How do I distinguish in core_config_data the web/unsecure/base_url and web/secure/base_url to the correct domain if value is set incorrectly?
For example:

*

*row
config_id: 2
scope: default
scope_id: 0
 path: web/unsecure/base_url
value: http://www.com/

*row
config_id: 3
scope: default
scope_id: 0
 path: web/secure/base_url
value: https://www.com/

*row
config_id: 837
scope: stores
scope_id: 7
 path: web/unsecure/base_url
value: http://www.com/

*row
config_id: 838
scope: stores
scope_id: 7
 path: web/secure/base_url
value: https://www.com/

*row
config_id: 883
scope: stores
scope_id: 9
 path: web/unsecure/base_url
value: http://www.com/

*row
config_id: 884
scope: stores
scope_id: 9
 path: web/secure/base_url
value: https://www.com/

*row
config_id: 951
scope: websites
scope_id: 6
 path: web/unsecure/base_url
value: http://www.com/

*row
config_id: 952
scope: websites
scope_id: 6
 path: web/secure/base_url
value: https://www.com/

A: Here is an idea:
Look in the table 'core_website' in the database, over here you will find all the "website id's" for your installation as well as what you named each store.
Next match the 'website_id' to the 'scope_id' in the core_config_data table (where the path is web/unseucre/base_url etc).
Let us know if you need further assistance


text:
Q: Uncaught SyntaxError: Unexpected token < JS В блок форума IPB добавил небольшой JS следующего содержания:

var Events = {};

Events.text = [
 ['Начнётся через', 'Открыт, до начала'],
 ['Появится через', 'Торопись, осталось']
];

Events.sked = [
  ['Информация 1',          0,      '08:40', '02:30', '04:30', '06:30', '08:30', '10:30', '12:30', '14:30', '16:30', '18:30', '20:30', '22:30', ],
  ['Информация 2',          0,      '01:00', '05:00', '09:00', '13:00', '17:00', '21:00'],
  ['Информация ',          0,      '01:30', '03:30', '05:30', '07:30', '09:30', '11:30', '13:30', '15:30', '17:30', '19:30', '21:30', '23:30'],
  ['Информация 3',        0,      '02:00', '06:00', '10:00', '14:00', '18:00', '22:00'],
  ['Информация 4',         0,      '02:30', '08:30', '14:30', '20:30'],
  ['Информация ',             0,      '20:00'],
  ['Информация 5',     1,      '02:15', '06:15', '10:15', '14:15', '18:15', '22:15'],
  ['Информация 6',    1,      '02:30', '08:30', '14:30', '20:30'],
  ['Информация 7',    1,      '02:40', '06:40', '10:40', '14:40', '18:40', '22:40'],
  ['Информация 8',               1,      '04:30', '12:30', '23:59'],
];

Events.init = function (e) {

        if (typeof e == "string")
        var g = new Date(new Date().toString().replace(/\date('H')+:\date('i')+:\date('s')+/g, e));
        var f = (typeof e == "number" ? e : (g.getHours() * 60 + g.getMinutes()) * 60 + g.getSeconds()), q = Events.sked, j = [];

        for (var a = 0; a < q.length; a++) {
                var n = q[a];
                for (var k = 2; k < q[a].length; k++) {
                        var b = 0, p = q[a][k].split(":"), o = (p[0] * 60 + p[1] * 1) * 60, c = q[a][2].split(":");
                        if (q[a].length - 1 == k && (o - f) < 0) b = 1;
                        var r = b ? (1440 * 60 - f) + ((c[0] * 60 + c[1] * 1) * 60) : o - f;
                        if (f <= o || b) {
                                var l = Math.floor((r / 60) / 60), l = l < 10 ? "0" + l : l, d = Math.floor((r / 60) % 60), d = d < 10 ? "0" + d : d, u = r % 60, u = u < 10 ? "0" + u : u;
                                j.push('
' + '' + q[a][b ? 2 : k] + "" + n[0] + '

' + (l + ":" + d + ":" + u) + '' + (Events.text[q[a][1]][+(l == 0 && d < (q[a][1] ? 1 : 5))]) + "
");
        break;
                        };
                };
        };
        document.getElementById("events").innerHTML = j.join("");
        setTimeout(function () {
                Events.init(f == 86400 ? 1 : ++f);
        }, 1000);
};

Сам код из блока вызывается следующим путём:

Всё работает как нужно, но как только перехожу в какую-либо тему на форуме - получаю в консоли ошибку "Uncaught SyntaxError: Unexpected token <", ну и само собой JS отказывается работать.

Люди добрые, помогите пожалуйста разобраться, ибо я от JS очень далёк.


text:
Q: Retrieve prestashop orders 1.6.1 Do you know what code I should use to (automaticaly) retrieve the last prestashop orders? My goal is to use these informations to stock them in xml files and send them on a ftp server.
Thanks for your answers.

A: You can use Prestashop webservice
Please see below
for 1.6
http://doc.prestashop.com/display/PS16/Web+service+tutorial
for 1.7
http://doc.prestashop.com/display/PS17/Webservice


text:
Q: Web application made "Native" with Phonegap I have a mobile web application that is published in a designated URL.
If I want users to access the web-app by installing an application (besides just browsing to the URL from their mobile) can I use Phonegap for this? This app should only be used when the user is online.
One of the solutions I had in mind is to create a Phonegap app that holds an <iframe> to the relevant URL. Is there a different way? Are there any disadvantages in my solution?

A: If you are using cordova aka phonegap just to load the website, I would not recommend to use it as it will make you application bit heavy.
The Simple technique would be to include a webview component in your screen/page and load the url using the following code your activity class
    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    public class Main extends Activity {
    private WebView mWebview;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            mWebview = new WebView(this);
            mWebview.loadUrl("http://www.google.com");
            setContentView(mWebview);
        }
 }


text:
Q: Create href to subpage in Blazor My page has this directive @page "/sales/reports" so it loads at https://localhost/sales/reports route.
I want to create link Report 1 that will lead to a sub-page /sales/reports/{id} - for example https://localhost/sales/reports/8c5b8c1c-12b5-43ee-92c9-8d3bcb8644a4 but not sure what do I put in href of my anchor. When I simply put Report 1 link has a form of https://localhost/8c5b8c1c-12b5-43ee-92c9-8d3bcb8644a4. Do I need to hard-code Report 1 or there is a smarter way?

A: The term 'subpage' does not really exist.
There are just 'pages' and they have 'routes'.  Sometimes the route appears nested, as in your example, but this does not make it a 'subpage'.
The answer to your question is that, yes, you need to include the route to the 'page' you want to go to.
Report 1

That doesn't necessarily mean hardcoding in the page itself.  You might create a helper class that does that for you.  For example:
class ReportPathCreator
{
    public static string ReportRouteFor(Guid reportGuid) => $"sales/reports/{reportGuid}";
}

Then use:
Report 1

Then, if you choose to change the route where reports are hosted, you only need to change it in the helper class and all anchor elements in your site will automatically pick up that new route.
UPDATE
You can also use the static class to generate a template for you to use instead of @page directive:
class ReportPathCreator
{
    public static string ReportRouteFor(Guid reportGuid) => $"sales/reports/{reportGuid}";

    public static string ReportTemplate = "sales/reports/{reportGuid:guid}";
}

And then, instead of @page directive, use:
@attribute [Route(ReportPathCreator.ReportTemplate)]


text:
Q: Euclidean algorithm pseudocode conversion to Swift? I have been working on a function for reducing fractions in Swift, and came across the Euclidean algorithm for finding the greatest common factor (http://en.wikipedia.org/wiki/Euclidean_algorithm)
I converted the pseudo code into swift, but yet I am confused how this is going to give me the greatest common factor if it is returning a which I thought was supposed to be the numerator of the fraction. Any help on this would be greatly appreciated. Thanks!
Pseudocode:
function gcd(a, b)
    while b ≠ 0
       t := b
       b := a mod b
       a := t
     return a

Swift:
var a = 2
var b = 4

func gcd(a: Int, b: Int) -> Int {
    var t = 0
    while b != 0 {
        t = b
        let b = a % b
        let a = t
    }
    return a
}

println("\(a)/\(b)")

Console output:  2/4

A: When you do this
let b = a % b

you are creating another readonly variable b, which has nothing to do with the variable b from the outside scope. You need to remove both lets inside the loop, and make parameters modifiable by declaring them with var, like this:
func gcd(var a: Int, var b: Int) -> Int {
    var t = 0
    while b != 0 {
        t = b
        b = a % b
        a = t
    }
    return a
}

You can call your function like this:
let a = 111
let b = 259
println("a=\(a), b=\(b), gcd=\(gcd(a,b))")

This prints a=111, b=259, gcd=37

A: Taking @dasblinkenlight's answer and getting rid of t by using tuples for parallel assignment yields:
Swift 2.1:
func gcd(var a: Int, var _ b: Int) -> Int {
    while b != 0 {
        (a, b) = (b, a % b)
    }
    return a
}

gcd(1001, 39)  // 13

var parameters are deprecated in Swift 2.2 and will be removed in Swift 3.  So now it becomes necessary to declare a and b as var within the function:
func gcd(a: Int, _ b: Int) -> Int {
    var (a, b) = (a, b)
    while b != 0 {
        (a, b) = (b, a % b)
    }
    return a
}

A: Swift 3 version of answer given by Christopher Larsen
func gcd(a: Int, b: Int) -> Int {
  if b == 0 { return a }
  return gcd(a: b, b: a % b)
}

A: Can use a recursive method that just keeps calling itself until the GCD is found.
func gcd(a: Int, b: Int) -> Int {
    if b == 0 {
        return a
    }

    let remainder: Int = a % b

    return gcd(b, b: remainder)
}

and use like so
let gcdOfSomeNums = gcd(28851538, b: 1183019)
//gcdOfSomeNums is 17657


text:
Q: Unobtrusive Oracle Deployment on Windows Server 2008 I have a .NET 4.0 Web Forms app that I am running with the beta Oracle EF-aware data provider, and I want to perform "unobtrusive" Oracle deployment to a Win2K8 box, as shown in many SO solutions.
There is an existing Oracle Instant Client installation on the Win2K8 box, which I can neither work with nor remove, and it has an entry in the PATH environment variable on the Win2K8 box. According to this SO answer, I do not need to set PATH for my Oracle DLLs, since I have DllPath set in the web.config.
I am following the procedure from here, yet I still get the provider is not compatible with the version of Oracle client error.
Here's my (unsuccessful) setup, as of now:
Oracle DLLs are in my web app's bin directory, and set to Copy Always Do Not Copy.
Platform and Platform Target settings are set to x86 in my local Build Configuration.
32-bit applications are enabled in the app pool (.NET 4.0) on the Win2K8 box.
Oracle DLLs are not present in the GAC, not are they present in the GAC_32 and GAC_64 directories on the Win2K8 box.
My web.config (but not my Win2K8 machine.config) contains this:
<configuration>

    <configSections>
        <section name="oracle.dataaccess.client" type="System.Data.Common.DbProviderConfigurationHandler, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>

    <oracle.dataaccess.client>
        <settings>
            <add name="DllPath" value="C:\inetpub\wwwroot\myapp\bin"></add>
            <add name="FetchSize" value="65536"></add>
            <add name="StatementCacheSize" value="10"></add>
            <add name="TraceFileName" value="c:\temp\odpnet2.log"></add>
            <add name="TraceLevel" value="0"></add>
            <add name="TraceOption" value="0"></add>
        </settings>
    </oracle.dataaccess.client>

    <system.data>
        <!-- Version=4.112.2.50 -->
        <DbProviderFactories>
            <add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.2.50, Culture=neutral, PublicKeyToken=89b483f429c47342" />
        </DbProviderFactories>
    </system.data>

    <connectionStrings>
        <add name="MyEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=**<using EZCONNECT format here>**" providerName="System.Data.EntityClient" />
    </connectionStrings>

<configuration>

The app itself deploys successfully, and I can run pages that do not reference my Oracle DLLs. But, for those that do reference Oracle, I still get the provider compatibility error.
What am I missing?
Thanks again for the help.
UPDATE: The web app runs on the Win2K8 target with .NET 4.0, EF4.1, and the Oracle EF Provider, completely separate from the other active ODAC install. No PATH variable, no installation from Universal Installer, no Oracle DLLs in GAC.

A: Case closed. I was missing an Oracle DLL.


text:
Q: How can i view the MVC Object Model graphically This page explains MVC result types, in part, by showing a graphic tree of that part of the object model. What tool was used to render that graphic?

A: Add a Class Diagram item to your Visual Studio 2010 project in and drop your classes onto it.

A: It looks like a Class Diagram from the Visual Studio Class Designer:
http://msdn.microsoft.com/en-us/library/33864ckt.aspx


text:
Q: s expects argument of type char c but argument 2 has type 'int' warning and bad return Yes ,I know that this question was already asked for many times ,but none of these helped me to discover the problem (duplicate...yeah). I want to read from input a series of strings into an array and then search from 'First Name'. If the name exist ,I want to display all the data stored in that element of array (I attached the code to undestand easily). When I run it ,I read from keyboard all the data ,but it returns me absolutely nothing.
#include<stdio.h>

typedef struct record {
    char name[10],lname[10],phone[10],bday[10];
};
void main() {
 struct record rec;
 char search;
 int i,nr;

printf("\nInput number of records: ");
scanf("%d",&nr);

for (i=0 ; i<nr ;i++) {
    printf("First name: ");
    scanf("%s",&rec.name[i]);
    printf("Last name: ");
    scanf("%s",&rec.lname[i]);
    printf("Phone: ");
    scanf("%s",&rec.phone[i]);
    printf("Bday: ");
    scanf("%s",&rec.bday[i]);
}

printf("Input the first name for searching: ");
scanf("%s",&search);

for (i=0 ;i<nr;i++) {
    if (search == rec.name[i]) {
        printf("First name: %s\nLast name: %s\nPhone: %s\nB-day: %s",rec.name[i],rec.lname[i],rec.phone[i],rec.bday[i]);
    }
}

}

NOTE: I already replaced
scanf("%s",&rec.name[i]);

with
scanf("%s",rec.name[i]);

but no effect.

A: I believe there are a lot of problems with your code.
Firstly in this line:
scanf("%s",&search);

You have declared search as only a char, when really you want an array of chars. You also don't need & with search, as an array decays to a pointer to the first element.
It instead should be like this:
char search[10];
scanf("%9s", search); /* %9s to avoid buffer overflow */

You need to make this change to all your other scanf() calls, as this seems to be everywhere in this code.
It also seems that you want to create an array of records(structures), So you might need to make this after getting the value of nr. You can create it like this:
struct record rec[nr]; /* array of nr structures */

This also means calls like this:
rec.name[i]

Don't make sense, as you are iterating over the characters within a name, not over all the records in struct records.
This needs to be instead:
rec[i].name

Secondly, Your using == to compare strings, when you should be using strcmp instead. Using == will only compare the base address of the strings, not the actual contents of strings.
Your line should be this instead:
if (strcmp(search, rec[i].name) == 0) {

If you read the manual page for strcmp(), checking for a return value of 0 means that both strings are equal in comparison.
Lastly, in your first scanf() call:
scanf("%d",&nr);

You should really check the return value of this:
if (scanf("%d", &nr) != 1) {
    /* exit program */
}

Note: For reading strings, you should really be using fgets instead. You can try upgrading to this later, but I think it is better to understand these basics first.
Here is working example of what your program should do:
#include <stdio.h>
#include <string.h>

#define STRSIZE 10

typedef struct {
    char name[STRSIZE+1]; /* +1 to account for null-btye at the end */
    char lname[STRSIZE+1];
    char phone[STRSIZE+1];
    char bday[STRSIZE+1];
} record;

int main() {
    char search[STRSIZE+1];
    int i,nr;

    printf("\nInput number of records: ");
    if (scanf("%d", &nr) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    record rec[nr]; /* array of records */

    for (i = 0; i < nr ; i++) {
        printf("First name: ");
        scanf("%10s", rec[i].name);

        printf("Last name: ");
        scanf("%10s", rec[i].lname);

        printf("Phone: ");
        scanf("%10s", rec[i].phone);

        printf("Bday: ");
        scanf("%10s", rec[i].bday);
    }

    printf("Input the first name for searching: ");
    scanf("%10s", search);

    for (i = 0; i < nr; i++) {
        if (strcmp(search, rec[i].name) == 0) {
            printf("First name: %s\nLast name: %s\nPhone: %s\nB-day: %s\n",rec[i].name,rec[i].lname,rec[i].phone,rec[i].bday);
        } else {
            printf("Record not found.\n");
        }
    }

    return 0;

}

A: The numeric input leaves a new line character in the input buffer, which is then picked up by the character input. when numeric input with scanf() skips leading white space, character input does not skip this leading white space.
Use a space before %c and it will help you cause if  space is not used then a buffer added with value .so that use space before %c
scanf(" %c",&rec.name[i]);


text:
Q: google Custom Search api in a js file First I found the demo in google doc:

    <title>JSON/Atom Custom Search API Example</title>

And it works fine.
But know I want to trigger the "search process" inside a js file say mySearch.js, so how can I get this done ?
example:
var XXXLayer = cc.Layer.extend({
    init:function () {
        this._super();
        var theUrl = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr';

        // what to do here ???????

        return true;
    },
    hndlr:function(response) {
          // handle result
    }
});

Any suggestion would be appreciated thanks :)

A: You could add a script element, when you trigger the search process.
function triggersearch(){
     var query=document.getElementById("query").value;
     var JSElement = document.createElement('script');
     JSElement.src = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=KEY&q='+query+'&callback=hndlr';
     document.getElementsByTagName('head')[0].appendChild(JSElement);
}

A: using the code from @RamK, do the following:
index.html:

    <title>Example</title>

cs.js:
var key = "your api key";                // API KEY
var id = "your custom search engine id"; // CSE ID
var q = "cats";                          // QUERY

function hndlr(response) {
  console.log(response);                 // a way to see your results
}

function triggersearch(){
  var query=document.getElementById("query").value;
  var JSElement = document.createElement('script');
  JSElement.src = `https://www.googleapis.com/customsearch/v1?key=${key}&cx=${id}&q=${q}`+query+'&callback=hndlr';
  document.getElementsByTagName('head')[0].appendChild(JSElement);
}

triggersearch();


text:
Q: Apache 2 Test Page displays on the website after I overwrite the .htaccess Website: http://www.trbi.com.ph/
I edited the .htaccess and inputted a code to allow Google Bot and block the spam bots:
SetEnvIfNoCase User-Agent .*google.* search_robot
SetEnvIfNoCase User-Agent .*yahoo.* search_robot
SetEnvIfNoCase User-Agent .*bot.* search_robot
SetEnvIfNoCase User-Agent .*ask.* search_robot

Order Deny,Allow
Deny from All
Allow from env=search_robot

Then uploaded the .htaccess using FTP. I refreshed the website and it now displays the Apache 2 Test Page.
What should I do? HELP PLS!


text:
Q: iPhone: What is Springboard? Do I need to care? When creating iPhone apps in simulator, I sometimes see messages like "Springboard failed to  launch application", etc.
What is Springboard? Are there things I should know about it as a developer?

A: Springboard is just the iPhone home screen application.
This related question may help.

A: Springboard is the launcher application -- i.e. the one you see on the home screen with all the tiled app icons.
I don't think there's anything more you really need to know about it.

A: Springboard is the iPhone emulator that your app runs within.  If Springboard only periodically fails to launch your app, something's probably wrong with Springboard, but if your app won't launch at all, there's probably something wrong with your app (and if it was deployed on a real phone, wouldn't launch there, either).


text:
Q: Refresh one component after another component is closed I have a first component, that display a list of records.
In that component I have another component, displaying a modal with a form, and a validate button.
The purpose of this form i to add a record to the list.
So when I lauch the app, the first component is displyed, the other is display=none, and when I click on a button to add a record the second component is displayed (with display=block).
When I click on the save button on the second component, the component is again display=none and the first component only is displayed. But Here the list is not refreshed with the newly added record. How can I refresh the first component when the second is closed ?
Here is what I want :

A: There are similar things going on in my app.  For example, a user could click a "close" icon on one component, which causes it to destroy itself, and also causes another component to move a toggle switch to an off position.
I elected to use events to handle these.  I considered using bound attributes or methods, but decided to try and make the components more standalone and not need a bunch of variable bindings or method calls.  The event mechanism allows me to send an event when a component does something (such as "I'm being closed") and have other components listen for that and take action.  That way, the component that initiates the event doesn't have to worry about communication channels with recipients (such as attributes or method calls), it just fires an event, and it's up to other components to listen for those if they're interested.  I happen to use application events instead of component events, only because I didn't want to concern myself with bubbling order.  To me, application events were easier to work with, so that's what I stuck with.
If you wanted to go with an event approach, your Component 2 could fire some kind of "Validation complete" event at the end of the validation logic.  The event could also contain attribute values, if those are needed for recipients to do their processing.  Component 1 could listen for those events and based on the event, attributes, and/or target, take appropriate action, such as refreshing itself.
Hope this info helps!

A: At the end of your last method called in the component 2 controller (or helper), you'll want to call something like:
component.set("v.newItem",newItem);

where "newItem" is an attribute that's been declared in component 1. You may also need to set an attribute for "v.items" if the "newItem" has been added to a list of items using a method called in your form. In which case, "items" would also be an attribute you'd declare in component 1.
See the Lightning Components Basics Module for an example that demonstrates this in practice.


text:
Q: Function Expression Parameter is not assigned a value, but has a value I'm hoping someone can explain how the the below function expression works.  The parameter 'p' has not been assigned a value, however it is used in the body of the function for calculations (defining the "angle" and "tail" variables) and as an argument object when draw() is called.  When you step through the code, you can see that parameter 'p' does, indeed, have a value (see attached image)- but I don't understand where that value comes from. Please note that 'p' is not noted anywhere else upon review of the full code.
When you log 'p' to the console you see the following values, which continue to increase as the application runs:
Image of console.log(p);
Here is the full function expression and the function call:
var draw = function(p) {
  $.fillStyle = "hsla(38,5%,12%,.90)";
  $.fillRect(0, 0, w, h);
  $.fillStyle = "hsla(38, 25%, 90%, 1)";
  $.strokeStyle = "hsla(38, 25%, 90%, 1)";
  for (var i = 0; i < numh; i++)
    for (var j = 0; j < numw; j++) {
      var diagnalW = j * spacing +
        (i % 2 ? 0 : spacing / 2);
      var diagnalH = i * spacing;
      var arr = [position[0] - diagnalW,
          position[1] - diagnalH
        ],
        wave = Math.sqrt(arr[0] * arr[0] +
          arr[1] * arr[1]),
        arr = [arr[0] / wave, arr[1] / wave],
        angle = 50 * (Math.cos(p / 360 - wave / 105) - 1);
      $.beginPath();
      $.arc(diagnalW + arr[0] * angle, diagnalH +
        arr[1] * angle, 2.8, 0, 2 * Math.PI, false);
      $.closePath();
      $.fill();
      for (var n = 0; n < 5; n++) {
        var tail = 50 * (Math.cos((p - 50 * n) /
          360 - wave / 105) - 1);
        $.beginPath();
        $.moveTo(diagnalW + arr[0] * angle, diagnalH +
          arr[1] * angle);
        $.lineWidth = 5 - n;
        $.lineTo(diagnalW + arr[0] * tail, diagnalH + arr[1] * tail);
        $.stroke()
      }
    }
};

var anim = function(p) {
  window.requestAnimationFrame(anim);
  draw(p);
};
anim();

I understand everything about this code with the exception of how 'p' obtains the values shown in the console. Also - in case it wasn't clear, this is an html5 canvas application.
(Side note: No, $ in the above isn't jQuery. It's just what the original author uses for her canvas context object.)

A: In the first call to draw, p will have the value undefined because anim() doesn't pass a value for p, and anim then uses p when calling draw.
After that, though, draw is called by the browser, not by that code, because it's being used as the callback for requestAnimationFrame. The browser will call it with a high-resolution timer value, which is what you're seeing in p.

A: p is a parameter of a callback for window.requestAnimationFrame

A parameter specifying a function to call when it's time to update your animation for the next repaint. The callback has one single argument, a DOMHighResTimeStamp, which indicates the current time (the time returned from performance.now()) for when requestAnimationFrame starts to fire callbacks.


text:
Q: Why is my Python script is telling me that 6*2=222222? class timeDifference:
    def __init__(self, sal=0):

        self.sal = sal
        if self.sal == 0:
            pass
        elif self.sal == 1:
            salory = input("Salory (per hour): ")

        #imports
        import datetime

        #defining the Start and End times
        while True:
             timeStart = input("Start time: ")
             timeEnd = input("End time: ")
             if len(timeStart) & len(timeEnd) == 4:
                break
             else:
                print("Error 001: only 4 integers allowed! (hh/mm)")

        #defining the hours
        timeStartH = timeStart[0:2]
        timeEndH = timeEnd[0:2]
        #defining the minutes
        timeStartM = timeStart[2:4]
        timeEndM = timeEnd[2:4]

        #converting strings to ints for math
        v = int(timeStartH)
        v1 = int(timeEndH)
        v2 = abs(v - v1)

        z = int(timeStartM)
        z1 = int(timeEndM)
        z2 = abs(z - z1)

        #calculating money earned
        money = v2*salory
        print("~$", money)

        #printing the difference between times
        print(datetime.time(v2, z2))

Everything works fine until the money variable decides to say that 6*2 is 6 2s...
The script is supposed to let me input a work shift and have it tell me how long it is and how much I will make from it.
However, it obviously screws up on the money part
I feel like this is a simple problem with a simple solution, but I can't find it :/


text:
Q: Unable to configure CI build for Dot Net core 3.1 from deployment center. Is there any way to setup CI Azure DevOps Unable to configure CI build for Dot Net core 3.1 from deployment center.
Is there any way to setup CI Azure DevOps.
Please let us know is there any way to configure?.

A:
Is there any way to setup CI Azure DevOps

For this issue ,you can achieve this through the following tasks. The build pipeline performs various tasks such as fetching sources from the Git repository, restoring dependencies, compile the application, run tests and publishing outputs used for deployments.

Then selecting Triggers. The Azure DevOps project automatically created a CI trigger, and every commit to the repository initiates a new build. You can optionally choose to include or exclude branches from the CI process.

You can refer to this lab for details. If you want to use yaml to set CI build, you can refer to this official document and guide.


text:
Q: Mongodb condition on foreign collection with lookup I have three collections in MongoDB 4.0 (pymongo)
users: [
{_id: "aaa", name: "John", user_type: "writer", department: {value: "1", label:"press"}},
{_id: "bbb", name: "Charles", user_type: "writer", department: {value: "1", label:"press"}},
{_id: "ccc", name: "Jessy", user_type: "admin_writer", department: {value: "1", label:"press"}},
{_id: "ddd", name: "Tim", user_type: "writer", department: {value: "2", label:"news"}},
{_id: "eee", name: "Max", user_type: "admin_writer", department: {value: "2", label:"news"}},
{_id: "fff", name: "Julia", user_type: "admin", department: {value: "2", label:"news"}},
{_id: "ggg", name: "Arnold", user_type: "writer", department: {value: "3", label:"infos"}}
]

departments: [
{_id: 1, name: "press", group: "times"},
{_id: 2, name: "news", group: "times"},
{_id: 3, name: "infos", group: "herald"}
]

docs: [
{_id: 1, name: "monday", user_id: "aaa"},
{_id: 2, name: "tuesday", user_id: "bbb"},
{_id: 3, name: "wednesday", user_id: "ddd"},
{_id: 4, name: "thursday", user_id: "ddd"},
{_id: 5, name: "friday", user_id: "ggg"}
]

In my example, user can write a doc and work in a department. A department is defined by is group (society). A writer can see only his docs, an admin_writer can see all docs from his department include a doc he writes and admin can see all docs in the group evenif he works on a specific department.
I need to have the list of all docs in dashboard when a user logs in the application
For example, the result will be :
John (writer) : [{name: "monday"}]
Jessy (admin_writer) : [{name: "monday"}, {name: "tuesday"}]
Max (admin_writer) : [{name: "wednesday"}, {name: "thursday"}]
Julia (admin) : [{name: "monday"}, {name: "tuesday"},{name: "wednesday"}, {name: "thursday"}]
Arnold (writer) : [{name: "friday"}]

For that, I manage queries for each specific user_type. For a writer, I use a $match because user_id is directly in docs collections, but for the two others user_type, I need to use $lookup to add condition in foreign collection. I tried two ways (I use Pymongo) :
user_department = 1

db.docs.aggregate([{
            '$lookup': {
                'from': "users",
                'localField': "user_id",
                'foreignField': "_id",
                'as': "user"
            }
        },{
                "$addFields": {
                    "user": {
                        "$arrayElemAt": [
                            {
                                "$filter": {
                                    "input": "$user",
                                    "as": "userId",
                                    "cond": {
                                        "$eq": ["$$userId.department.value", user_department]
                                    }
                                }
                            }, 0
                        ]
                    }
                }
            }, {'$project: {'name': 1}]);

or
db.docs.aggregate([{
                "$lookup": {
                    "from": "users",
                    "let": {
                        'id': "$user_id"
                    },
                    "pipeline": [
                        {
                            '$match': {
                                '$expr': {
                                    '$eq': [
                                        "$_id",
                                        "$$id"
                                    ]},
                                "_id": user_department
                            }
                        }
                    ],
                    "as": "user"
                }
            }]);

In my two tries, I don't have expected result. When I connect with an admin_writer (Jessy), I also have the "friday" doc from an other department and group. If you have an idea on why it's happen or another solution, Thanks

A: You can divide your looked up docs into 3 cases:

*

*the docs that the user can view by himself/herself

*the docs that the user can view by department if he/she is admin_writer

*the docs that the user can view if he/she is admin(i.e. all the docs)
The final list of viewable docs will be a union of the above 3 cases.

the docs that the user can view by himself/herself
A trivial $lookup will suffice
{
    "$lookup": {
      "from": "docs",
      "localField": "_id",
      "foreignField": "user_id",
      "as": "selfDocs"
    }
}

the docs that the user can view by department if he/she is admin_writer
You will need first to get a full list of users in same department first. Add a $and condition and the lookup in sub-pipeline to check for the user_type and the docs by all the department users
{
    "$lookup": {
      "from": "users",
      "localField": "department.value",
      "foreignField": "department.value",
      "as": "deptUsers"
    }
},
{
    "$lookup": {
      "from": "docs",
      "let": {
        userType: "$user_type",
        deptUsers: "$deptUsers"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$$userType",
                    "admin_writer"
                  ]
                },
                {
                  $in: [
                    "$user_id",
                    "$$deptUsers._id"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "deptDocs"
    }
}

the docs that the user can view if he/she is admin(i.e. all the docs)
$lookup departments to find out the group of the user. Then used the user's group to lookup all the users within the group. Do a conditional check for user_type: "admin" and the doc belongs to user in the same group.
{
    "$lookup": {
      "from": "departments",
      let: {
        dept: "$department.value"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$$dept",
                {
                  $toString: "$_id"
                }
              ]
            }
          }
        }
      ],
      "as": "group"
    }
  },
  {
    "$unwind": "$group"
  },
  {
    "$set": {
      "group": "$group.group"
    }
  },
  {
    "$lookup": {
      "from": "users",
      "let": {
        group: "$group"
      },
      "pipeline": [
        {
          "$lookup": {
            "from": "departments",
            let: {
              d: "$department.value"
            },
            pipeline: [
              {
                $match: {
                  $expr: {
                    $eq: [
                      "$$d",
                      {
                        $toString: "$_id"
                      }
                    ]
                  }
                }
              }
            ],
            "as": "gp"
          }
        },
        {
          "$unwind": "$gp"
        },
        {
          $match: {
            $expr: {
              $eq: [
                "$gp.group",
                "$$group"
              ]
            }
          }
        },
        {
          "$project": {
            "_id": 1
          }
        }
      ],
      "as": "groupUsers"
    }
  },
  {
    "$lookup": {
      "from": "docs",
      "let": {
        userType: "$user_type",
        groupUsers: "$groupUsers"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$$userType",
                    "admin"
                  ]
                },
                {
                  $in: [
                    "$user_id",
                    "$$groupUsers._id"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "adminDocs"
    }
  }

Use $setUnion to chain them up
allDocs: {
  "$setUnion": [
    "$selfDocs",
    "$deptDocs",
    "$adminDocs"
  ]
}

Here is the Mongo playground for your reference.


text:
Q: Dynamic Web scraping - Chromedriver security I am trying to web-scrap a dynamic page, simple urllib request gets me results from fist page only, instead of returning the whole set.
from urllib import request
from bs4 import BeautifulSoup

URL = "https://www.olx.pl/d/nieruchomosci/mieszkania/warszawa/"
get_url = request.urlopen(URL)
get_page = get_url.read()
get_url.close()
print(get_page)

I was about to implement selenium and chromedriver for the dynamic webscraping, but then I read about security of this solution. Chromedriver should never be run on account with privileges, best option would be virtual machine.
As I read forum posts, almost all solutions to dynamic web scrapping involve chromedriver / selenium/ scrapy. It makes me wonder if all users set up firewall or VM to download data.
Is there any other, safer solution you would recommend for dynamic web scrapping?


text:
Q: Not Resolving/Importing Any Class Android Studio Okay its weird error though, but I will explain it, actually I did remove "emulator" folder from my android SDK folder because it's causing android studio to slows down on ita knees, and when I did it, it throws a Gradle related error like "Can not read from some file", well for that i did reinstall Gradle 4.1 and error gone, but the weirdest problem occurred, now i can not import any class except appcompatactivity and constraint layout which I implemented in build.gradle , for those who wonder what I have messed up with the Android SDK folder, I want to tell you guys I just downloaded everything from scratch except having JDK 1.8.0_171. I mean I can not even import core java classes or anything, studio is pointing out for "please specify android SDK" or something, but hey I have already fresh SDK, what will be the issue, help me guys, and I swear I will never mess with SDK, am running out of time, already wasted too much time with this, Thank You !

A: Okay so finally i deleted C:/users/username/.AndroidStudio3 folder with all files in it! Works like charm ! An stupid solution for a stupid problem, btw problem solved ! Thanks everyone !!

A: You need specify the SDK in Modules section in Project Settings.
Right Click your Project Name in Android Studio and Select Settings..

or
Perform these three steps

*

*Open gradle.buld in your app module

*Change minSdkVersion and sync gradle

*Revert back your minSdkVersion and sync gradle again

A: Close the current project and go to project location directory and delete
.idea folder

You can open your project again. This worked for me and problem comes most often when you are working with VCS. And this problem is not associated with android component classes but also to the libraries, both shows the same error.


text:
Q: Duplicate Sent messages is showing in Sent Folder We recently upgraded iOS to 9.2.1. Both our iPads now show the sent messages twice in the Sent Folder although only one message has been sent.
How do I solve this annoying problem?


text:
Q: Insert Element within specific tags I'm trying to insert an element at a specific point within my file, then save that file out. However, I can't seem to get it right. My XML layout is like this:
<?xml version="1.0" encoding="utf-8"?>
<Settings>
   <Items />
   <Users />
</Settings>

This is my current code:
            XDocument xd = XDocument.Load(@"C:\test.xml");

            var newPosition =  xdoc.Root.Elements("Users");
            //I've tried messing around with newPosition methods

            XElement newItem = new XElement("User",
                new XAttribute("Name", "Test Name"),
                new XAttribute("Age", "34"),

                );

            //how can I insert 'newItem' into the "Users" element tag in the XML file?

            xd.Save(new StreamWriter(@"C:\test.xml"));

I'd like to use Linq to XML to insert 'newItem' into the  tag. Thanks for any help on this.

A: Just find the Users element, and append it:
// Note that it's singular - you only want to find one
XElement newPosition = xdoc.Root.Element("User");
XElement newItem = new XElement("User",
     new XAttribute("Name", "Test Name"),
     new XAttribute("Age", "34"));

// Add the new item to the collection of children
newPosition.Add(newItem);

Your use of var here was leading you astray - because the type of newPosition in your code was really IEnumerable<XElement>... you were finding all the User elements. (Okay, there would only have actually been one element, but that's irrelevant... it was still conceptually a sequence.)


text:
Q: how to search sqlite database using regular expression in android? I am trying to search a database using regular expression in sqlite. Here is my code:
cursor = db.rawQuery("SELECT _id, employee FROM employees WHERE employee REGEXP ?",
                    new String[]{"%" + prepareSearchText()  + "%"});
    adapter = new SimpleCursorAdapter(
            this,
            R.layout.search_row,
            cursor,
            new String[] {"_id", "employee "},
            new int[] {R.id.idField, R.id.nameField});
    setListAdapter(adapter);

However I am getting this error:
Caused by: android.database.sqlite.SQLiteException: no such function: REGEXP.

I used the function REGEXP in MySQL before so I assumed it exists in sqlite, but apparently it is not.
What is the best way to perform regular expression when querying sqlite database in android?

A: In sqllite the "REGEXP" function is not included by default and you need to "roll your own".
However the "LIKE" operator should do what you want as long as your searches are reasonably simple.
the docs

A: As James suggested, use the LIKE operator, and then do a java search on the results using regular expressions


text:
Q: How to solve this pair of differential equations? The equations are
$$y' = y + 3z$$$$z' = -3y + z$$I vaguely remember I need to differentiate one to get the form of the other, but by differentiating the first and subbing in the second I get$$y'' = y' + 3z'=> y''- y' + 9y = 3z$$ I don't know what to do from here.
Edit:
From here I got to $y''-2y'+10y = 0$, so from $m^2-2m+10=0$ we get$$y=e^x(Acos(3x) + Bsin(3x))$$Where would I go from here?

A: From the first equation, $z = \frac{1}{3}(y'-y)$ and $y'' = y' + 3z'$. From the second eqution, $z' = -3y+z = -3y+\frac{1}{3}(y'-y)$. So, $$y'' = y'+ 3(-3y+\frac{1}{3}(y'-y)) \\ \Rightarrow y'' - 2y' + 10y = 0 \\ \Rightarrow y = (A\cos(3x)+B\sin(3x))\exp(x) $$
Recalling that $z = \frac{1}{3}(y'-y)$, we first calculate $$y' = y + (B\cos(3x)-A\sin(3x))\exp(x) $$
and so
$$ z = \left(\frac{B}{3}\cos(3x)-\frac{A}{3}\sin(3x)\right)\exp(x) $$

A: $(y,z)'=A\cdot(y,z)$ where $A=\begin{pmatrix}1&3\\-3&1\end{pmatrix}$. Hence
$$
(y,z)(t) = \exp(tA)\cdot(y,z)(0)
$$

A: Your equation is
$$x'(t)=Mx(t)$$
Where
$$M=\begin{bmatrix}1&3\\-3&1 \end{bmatrix}$$
$$x(t)=\begin{bmatrix}y(t)\\z(t)\end{bmatrix}$$
Which has the solution
$$x(t)=e^{Mt}x(0)$$


text:
Q: SQL Server 2016 replication between Windows 10 and Windows Server 2012 I've been asked to set up SQL Server 2016 replication between a development PC running Windows 10 Home and Windows Server 2012 R2. Both run developer versions of SQL Server 2016.
I have found this tutorial: Replication Tutorials SQL Server 2016 and later
This is when I realised that the Windows 10  Home edition does not allow you to create extra users and groups, and in order to do so I would need to spend another £120 to upgrade to Windows 10 Pro.
I've never set up server replication at all, my question is:

*

*Is it possible to setup replication between those operating systems and SQL Servers Dev Editions?

I thought I ask before spending the money just in case it is not possible or I will hit ridiculous amount of problems doing it.
I tried finding anything on that online, to no avail. The Editions and Supported Features for SQL Server 2016 do not mention SQL Server 2016 Developer Edition and the only version from that list that supports Windows 10 is SQL Server 2016 Standard.

A: https://msdn.microsoft.com/en-GB/library/ms143506.aspx shows SQL 2016 Dev as supported on Win10 Home, and I don't know of any explicit feature limitations--though you are right in general that you're limited to what the OS supports.
Have you tried to set up replication using the built-in service logins? I believe the instructions around adding Windows logins are for security best practice, which may not be an issue for a dev environment.


text:
Q: Stretch a row with data overflow while having multiple rows in a single band My requirements bind me to have multiple rows in a single "Details" band.
Right now I am having a static text field (which is highlighted in color) in the leftmost column and three text data fields next to it.
What I want in my report is, the static text band along with the three bands should stretch in height when data in either of the three bands overflows, with the next row "properly" displayed below the stretched row. By "properly" I mean the next row elements should have their "top" values the same and be displayed in the same "row".
I tried setting "Stretch with overflow" flag to "true" and "Position" to "float" but the problem is that the next row data is not properly positioned.

A: In case someone comes up to this problem and above answers don't work. I suggest checking your xml's root element. If it has the following attribute then remove it:
printOrder="Horizontal"

Then above answers should work.
Hope I'll save someone a day of googling the same stuff.

A: I have found the answer. The key to the solution is grouping the elements inside a row together.

*

*Remove all the static text labels. Use text fields instead, with the text in quotes. They can be grouped with other text fields and data fields.

*Put all the data fields after the quoted text field in the same group as the quoted text field.

*Now, do the same with all the rows that you want to display. Separate group for individual row.

Select all the elements in a group, or, all the elements in all the gorups and do this:

*

*Set "Position" to "Float"

*Set "Stretch Type" to "Relative to the tallest object"

*Check "Print when detail overflows" checkbox.

*Check the "Stretch with overflow" checkbox.

That's all we can do to make things "stretch" together.
Now, the band would have to stretch dynamically with these stretched details. Just go to the band properties, set Split type to "Default" and split allowed to true. This did the trick for me.

A: In my case doing as you advised didn't work. I had to modify your solution a little bit - I made a "frame" instead of grouping objects, and put previuosly grouped elements in that frame. I set positionType="Float" and stretchType="No stretch" in that frame, and set stretchType="RelativeToTallestObject" to its child items - then it all works.


text:
Q: Convert a 100-277V dimmer to 1-10V I'm trying to use the following dimmer:
https://www.smarthome.com/switchlinc-dimmer-insteon-2477dh-remote-control-dimmer-dual-band-high-wattage-white.html
with these lights
https://www.eledlights.com/led-lights/eled-indoor-lights/led-drop-ceiling-panel-lights.html
is there any product I can buy to fix the voltage issue and eliminate buzzing/flickering?
thanks!

A: From the manufacturer website.
0 -10V LED dimmer is required.
Recommendation: Lutron DVSTV


text:
Q: How to combine multi excel workbook into single workbook with multiple worksheets I have 3 workboooks with single sheets.I need to combine all workbooks into single workbook with 3 sheets.
I tried the below code :
from pandas import ExcelWriter

writer = ExcelWriter("Sample.xlsx")

for filename in glob.glob("*.xlsx"):
    df_excel = pd.read_excel(filename,engine='openpyxl')

    (_, f_name) = os.path.split(filename)
    (f_short_name, _) = os.path.splitext(f_name)

    df_excel.to_excel(writer, f_short_name, index=False)

writer.save()

i got an error like "File is not zip File"

A: "Sample.xlsx" is created in the same directory as the input workbooks and before you look for all files with glob.glob("*.xlsx"). Therefore you try to read "Sample.xlsx" which is your writer. This isn't working.
Make sure to only iterate over the real input workbooks e.g. like that:
import pandas as pd
from pandas import ExcelWriter
import glob
import os

writer = ExcelWriter("Sample.xlsx")
input_workbooks = glob.glob("*.xlsx")
input_workbooks.remove("Sample.xlsx")

for filename in input_workbooks:
    df_excel = pd.read_excel(filename,engine='openpyxl')

    (_, f_name) = os.path.split(filename)
    (f_short_name, _) = os.path.splitext(f_name)

    df_excel.to_excel(writer, f_short_name, index=False)

writer.save()

Better would be to save the output workbook ("Sample.xlsx") to another directory to avoid confusion. Obviously, when you do that, you do can not remove it from the list any longer, so just delete the line: input_workbooks.remove("Sample.xlsx")


text:
Q: Calling static method from another java class I've recently switched from working in PHP to Java and have a query.  Want to emphasise I'm a beginner in Java.
Essentially I am working in File A (with class A) and want to refer to a static method saved in File B (class B).  Do I need to make any reference to File B when working with class A?  (I'm thinking along the lines of require_once in PHP) My code in Class A is as follows:
Public class A{
String[] lists = B.staticMethod();
}

Eclipse is not recognising B as a class. Do I need to create an instance of B in order to access the static method.  Feel like I'm really overlooking something and would appreciate any input.

A: You don't need to create an instance of the class to call a static method, but you do need to import the class.
package foo;

//assuming B is in same package
import foo.B;

Public class A{
  String[] lists = B.staticMethod();
}

A: Ensure you have proper access to B.staticMethod. Perhaps declare it as
public static String[] staticMethod() {
    //code
}

Also, you need to import class B
import foo.bar.B; // use fully qualified path foo.bar.B

public class A {
    String[] lists = B.staticMethod();
}

A: Java has classloader mechanism that is kind of similar to PHP's autoloader. This means that you don't need anything like a include or require function: as long as the classes that you use are on the "classpath" they will be found.
Some people will say that you have to use the import statement. That's not true; import does nothing but give you a way to refer to classes with their short names, so that you don't have to repeat the package name every time.
For example, code in a program that works with the ArrayList and Date classes could be written like this:
java.util.ArrayList<java.util.Date> list = new java.util.ArrayList<>();
list.add(new java.util.Date());

Repeating the package name gets tiring after a while so we can use import to tell the compiler we want to refer to these classes by their short name:
import java.util.*;
....
ArrayList<Date> list = new ArrayList<>();
list.add(new Date());


text:
Q: Moving stack to specific place How to move my stack to specific virtual address? For example I would like for my stack to be 40960 big, and beginning in the address 0x355480. I tried playing with setcontext, but I'd like to know whether there is a 'standard' way to do that:
ucontext_t cont;
bool flag = false;
getcontext (&cont);
if(!flag){
  void* a = mmap((void*)0x34B000, 81920, PROT_EXEC | PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
  cont.uc_mcontext.gregs[REG_ESP] = 0x355000;
  flag = true;
  setcontext(&cont);
}

A: Code below sets the stack pointer around the mmap we did before and allows us to work on it in main2 function:
bool flag = false;
int argc2;
char ** argv2;
int main2(){
    ...
}
int main(int argc, char ** argv){
    argc2 = argc;
    argv2 = argv;
    ucontext_t cont;
    getcontext (&cont);
    if(!flag){
      void* a = mmap((void*)0x34B000, 81920, PROT_EXEC | PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
      if(a == MAP_FAILED){
        printf("mmapfail");
        return 1;
      }
      cont.uc_mcontext.gregs[REG_ESP] = 0x355000;
      flag = true;
      setcontext(&cont);
    } else{
      exit(main2());
    }
}


text:
Q: Is there an automated way to generate a sequence diagram from an applications Javascript code? I'm trying to find out if there's a way to generate a sequence diagram from our Javascript code.
Either something like that does not exist (yet), or I can't seem to find the good Google query. I always end up with js-sequence-diagram, which is a tool to generate sequence diagrams using Javascript, but not from Javascript code.
Firebugs profiling tool is able to tell you which Javascript methods were called how many times in 1 profiling session. It can also tell you the file in which the Javascript method resides. This kind of tells me it should be possible..

A: I was thinking that profiling with with the Developer Tools (Chrome or whatever) might be the only way but then I saw the answers to this question: How can I reverse engineer my JavaScript files with js/uml?
"code2flow generates callgraphs"
I'll have to give it a try.


text:
Q: $z=x=y$ in $\Bbb R^3$ It is a simply question. But I want to make sure. The surface $$z=x=y$$ represents  a line in $\Bbb R^3$ that passes  through the origin. Is that correct?

A: Consider the your surface $S=\lbrace(x,y,z)\in \mathbb{R}^3 \mid x=y=z \rbrace$ subspace of $\mathbb{R}^3$ a basis for $S$ is $\beta=\lbrace (1,1,1)\rbrace$ therefore your $S$ is a line that pass throught of $(1,1,1)$. As @JMoravitz say.


text:
Q: How do I find the Millman theorem in this op-amp circuit? So I have this circuit and I want to find the millman theorem of it. I started with it and I got here.
I have E2 connected to the ground and E1 connected to a voltage source V1. So V+ = V1; and V- is where i got confused a little bit. So when I want to find V-, I have on the numerator ((0/R + Vs/R0 + Vs/R1 + Vs/R2) / (1/R + 1/R0 + 1/R1 + 1/R2))
Is that right? Is that what I should do or not?

A: Well, we are trying to analyze the following circuit (assuming an ideal opamp):

simulate this circuit – Schematic created using CircuitLab
When we use and apply KCL, we can write the following set of equations:
$$
\begin{cases}
\text{I}_1=\text{I}_2\\
\\
\text{I}_4=\text{I}_2+\text{I}_3\\
\\
\text{I}_4=\text{I}_1+\text{I}_3
\end{cases}\tag1
$$
When we use and apply Ohm's law, we can write the following set of equations:
$$
\begin{cases}
\text{I}_1=\frac{\text{V}_\text{b}-\text{V}_1}{\text{R}_1}\\
\\
\text{I}_2=\frac{\text{V}_1-\text{V}_3}{\text{R}_2}\\
\\
\text{I}_3=\frac{\text{V}_2-\text{V}_3}{\text{R}_3}\\
\\
\text{I}_4=\frac{\text{V}_3}{\text{R}_4}
\end{cases}\tag2
$$
Substitute \$(2)\$ into \$(1)\$, in order to get:
$$
\begin{cases}
\frac{\text{V}_\text{b}-\text{V}_1}{\text{R}_1}=\frac{\text{V}_1-\text{V}_3}{\text{R}_2}\\
\\
\frac{\text{V}_3}{\text{R}_4}=\frac{\text{V}_1-\text{V}_3}{\text{R}_2}+\frac{\text{V}_2-\text{V}_3}{\text{R}_3}\\
\\
\frac{\text{V}_3}{\text{R}_4}=\frac{\text{V}_\text{b}-\text{V}_1}{\text{R}_1}+\frac{\text{V}_2-\text{V}_3}{\text{R}_3}
\end{cases}\tag3
$$
Now, using an ideal opamp, we know that:
$$\text{V}_+=\text{V}_-=\text{V}_\text{a}=\text{V}_1$$
So we can rewrite equation \$(3)\$ as follows:
$$
\begin{cases}
\frac{\text{V}_\text{b}-\text{V}_\text{a}}{\text{R}_1}=\frac{\text{V}_\text{a}-\text{V}_3}{\text{R}_2}\\
\\
\frac{\text{V}_3}{\text{R}_4}=\frac{\text{V}_\text{a}-\text{V}_3}{\text{R}_2}+\frac{\text{V}_2-\text{V}_3}{\text{R}_3}\\
\\
\frac{\text{V}_3}{\text{R}_4}=\frac{\text{V}_\text{b}-\text{V}_\text{a}}{\text{R}_1}+\frac{\text{V}_2-\text{V}_3}{\text{R}_3}
\end{cases}\tag4
$$
Now, we can solve for \$\text{V}_2\$:
$$\text{V}_2=\text{V}_\text{a}\cdot\left(1+\frac{\text{R}_3}{\text{R}_4}\right)+\left(\text{V}_\text{a}-\text{V}_\text{b}\right)\cdot\frac{\text{R}_4\left(\text{R}_2+\text{R}_3\right)+\text{R}_2\text{R}_3}{\text{R}_1}\tag5$$
Where I used the following Mathematica-code:
In[1]:=V1 = Va; FullSimplify[
 Solve[{I1 == I2, I4 == I2 + I3, I4 == I1 + I3, I1 == (Vb - V1)/R1,
   I2 == (V1 - V3)/R2, I3 == (V2 - V3)/R3, I4 == V3/R4}, {V2, V3, I1,
   I2, I3, I4}]]

Out[1]={{V2 -> ((R3 + R4) Va)/R4 + ((R2 + R3 + (R2 R3)/R4) (Va - Vb))/R1,
  V3 -> ((R1 + R2) Va - R2 Vb)/R1, I1 -> (-Va + Vb)/R1,
  I2 -> (-Va + Vb)/R1, I3 -> (R1 Va + (R2 + R4) (Va - Vb))/(R1 R4),
  I4 -> ((R1 + R2) Va - R2 Vb)/(R1 R4)}}


text:
Q: Tag cell value based on text and symbol I have will have following values in Column A;
A1: 11/5, A2: 11/5R,A3:11/6, A4:11/7, A5:11/5$, A6: 11/5
I want to mark these cells as duplicates in Column 10 if the numbers are same without considering the end symbol: Ex: A1, A2, A5, A6 are duplicates and should mark in Col J1, J2, J5, and J6.
Following code is working only for numbers. it is not accounting the end symbols of the cell value. Any suggestions to modify the code to get the desired output are appreciated.
Sub FindDuplicates()

Dim LastRow As Long, matchFoundIndex As Long, iCntr As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row

For iCntr = 1 To LastRow             ' 1 set the start of the dup looks
    If Cells(iCntr, 1) <> "" Then
        matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" &    LastRow), 0)
        If iCntr <> matchFoundIndex Then
             Cells(iCntr, 10) = "Duplicate"
        Else
             Cells(iCntr, 10) = "E"
        End If
    End If
Next

End Sub

Thank you

A: Assuming that the last character in the cell should be ignored if it is not a number:
Sub FindDuplicates()
    Dim v As Variant
    Dim LastRow As Long, x As Long
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    For x = 1 To LastRow                          ' 1 set the start of the dup looks
        If Cells(x, 1) <> "" Then

            v = IIf(IsNumeric(Right(Cells(x, 1), 1)), Cells(x, 1), Left(Cells(x, 1), Len(Cells(x, 1)) - 1))
            Cells(x, "J") = IIf(Application.Match(v, Range("A1:A" & LastRow), 0) > 1, "E", "Duplicate")

        End If
    Next

End Sub


text:
Q: Poisson variable situation; same probability for two different outcomes Suppose a customer service rep gets on average exactly 2 calls per minute. What are the odds of getting 1 call in the next minute?
This problem calls (no pun intended) for the Possion distribution : $$ P\{X = k\} =  e^{-2} \frac{2^k}{k!}$$
Here's where I'm stuck wondering. The probability of there being
one call $$P\{X = 1\} = e^{-2} \frac{2^1}{1!} \approx .2707  $$ is the same as the probability of getting two calls: $$P\{X = 2\} = e^{-2} \frac{2^2}{2!} \approx .2707  $$
I understand that the calculations show they are the same (obviously), but conceptually, I don't see how they can be the same. And also, why should one have the same probability as the average, but not three (which has a probability of $.1804$).
Unless, am I calculating it incorrectly?

A: The distribution can't be symmetric, since the probability for arbitrarily high numbers of calls is non-zero, whereas the probability for negative numbers of calls is zero; thus the probabilities for $3$ and $4$ must be less than the probabilities for $1$ and $0$.
There's no contradiction in the fact that $1$ has the same probability as $2$, and in fact it's true for any integer average number of calls $n$ that $n$ calls and $n-1$ calls have the same probability, since $\mathrm e^{-n}n^n/n!=\mathrm e^{-n}n^{n-1}/(n-1)!$. In general the average and maximum of an asymmetric distribution don't coincide, so there's no reason to expect the maximum to be exactly at $n$.


text:
Q: TensorFlow example for text classification - how to evaluate your own text? Does any one have full steps  and example for TensorFlow example for passing in your own text files and getting them evaluated against the existing model that comes with examples - using train.py as documented?
Also, if I wanted to train on different input set of say 1000 text files of my own samples, and then use that model for new text files? I know there is documentation but is terse for someone who is not familiar with text classification process.
I was able to run image example against my own images as that was only requiring to swap out one image .jpg file name for myh new image file, but for text it seems to be more involved.
Thanks

A: Here is an example: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification.py
You can set the flag test_with_fake_data to use the fake data in text_train.csv (training samples) and text_test.csv (testing samples) here. Next, you can modify these two files to include whatever data you'd like to have. You will need to do some preprocessing if your existing text files are in a different format.

A: You need to load the vocabulary file saved during training and process your new text with that. See the eval.py file here
Change the data parameters with your input text and proceed.