text:
Q: What's an easy way to set up object communication in Obj-C? I am trying to send a slider value from a controller object to a method of a model object. The later is implemented in the separate file and I have appropriate headers. I think the problem is that I am not sure how to instantiate the receiver in order to produce a working method for the controller.
Here is the controller's method.
-(IBAction)setValue:(id)slider {[Model setValue:[slider floatValue]];}
@implementation Model
-(void)setValue:(float)n{
    printf("%f",n);
}
@end

What I get is 'Model' may not respond to '+setValue' warning and no output in my console.
Any insight is appreciated.

A: you should allocate the modal first because the method is an instance method and cannot be used as an class(static) method.
Use Model *modelObject = [[Model alloc] init];
[modelObject setValue:2];

A: Another way to do this, if this makes sense for your project, is to 1) in your nib file add an object controller 2) set the class of that object controller to your model class 3) in your model class create an instance variable for the slider: float sliderFloatValue 4) create accessors for the float :@property (readwrite, assign) float sliderFloatValue; @synthesize sliderFloatValue; 5) bind the slider value to the sliderFloatValue of your model class


text:
Q: How to run a macro that is stored in a module in a workbook after the Workbook.Close method? I have a data connection from my Excel file to an Access file. The issue is that, you cannot establish a data connection to an Access file if it's being used. So the workaround is to actually copy the Access file that is being used and store it in a different location, then the Excel file will connect to that copy.
However, the duplicated Access file will need to be updated eventually, but it cannot be updated when the Excel file that is connecting to it is open. So the only way to actually update the duplicated Access file is to close the Excel file then overwrite it. I plan to achieve this by using 2 steps:
1.) Close the Excel file
Workbooks("Excel-file.xlsm").Close

2.) Run a batch file that will update the Access file:
Sub TryShell()

  Dim PathCrnt As String

  PathCrnt = ActiveWorkbook.Path
  Call Shell(PathCrnt & "\TryShell.bat " & PathCrnt)

End Sub

The issue is that the lines after closing the excel file won't run anymore (for example):
Workbooks("Excel-file.xlsm").Close
MsgBox "Hello"

Hello will not display anymore.
For those interested in seeing my connection string to MS Access:
Provider=Microsoft.ACE.OLEDB.12.0;
User ID=Admin;
Data Source=C:\Users\ACER\Desktop\Test.MDB;
Mode=Share Deny Write;
Extended Properties="";
Jet OLEDB:System database="";
Jet OLEDB:Registry Path="";
Jet OLEDB:Engine Type=5;
Jet OLEDB:Database Locking Mode=0; (changing to a value of 1 still results to an error to connect)
Jet OLEDB:Global Partial Bulk Ops=2;
Jet OLEDB:Global Bulk Transactions=1;
Jet OLEDB:New Database Password="";
Jet OLEDB:Create System Database=False;
Jet OLEDB:Encrypt Database=False;
Jet OLEDB:Don't Copy Locale on Compact=False;
Jet OLEDB:Compact Without Replica Repair=False;
Jet OLEDB:SFP=False;
Jet OLEDB:Support Complex Data=False

A: If you don't need data from Excel-file.xlsm anymore, you can put the macro in your Personal Macro Workbook.

A: I tried to reproduce your situation, and indeed, I couldn't refresh the table once the db was open.  So I went to the Connection Properties, Definition tab, Connection String, and I changed:
Jet OLEDB:Database Locking Mode=0

to
Jet OLEDB:Database Locking Mode=1

Now I can refresh the table in Excel even if it is open in Access.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't start PHP on Win via HTA with setx PATH and php -S commands I've created HTA file to install and start PHP on Windows. If there is already the my_app_folder/php folder with some version of PHP, via HTA file we only have 1) to set the Win PATH variable with path to the PHP folder, 2) go to the /my_app_folder where is index.php and 3) to run the php -S CMD-command.
So here is the code of my testing HTA file:
<script>
var objUserInfo = new ActiveXObject('WScript.network');
var pathToUserFolder = 'C:\\Users\\'+objUserInfo.UserName+'\\';

var WShell = new ActiveXObject('WScript.Shell');

WShell.Run('cmd /c setx PATH '+pathToUserFolder+'my_app_folder\\php',0,true);

WShell.CurrentDirectory = pathToUserFolder+'my_app_folder';
WShell.Run('cmd /c php -S localhost:80',0,false);

setTimeout(function() {
    WShell.Run('chrome -url http://localhost:80', 0, false);
}, 17000);
</script>

If I open this HTA file, the PATH variable is being added successfully, but the php.exe process is not being runned. However if the PATH variable already exists and I open the file, the php.exe process is being runned.
ps. I noticed that the PHP server is ready at least 17 seconds after we runned the php -S command, so as you see I use setTimeout() before opening the browser and following by the localhost address.

A: Ok, it's enough to use full path to php.exe in the CMD-command if we have some troubles with the PATH variable:
WShell.Run('cmd /c C:\\my_app_folder\\php\\php.exe -S localhost:80',0,false);


text:
Q: How to config and open Edge browser in headless mode how to set up codeception headless mode for EDGE
config is set like this (just like headless mode for Chrome, where headless mode works), but tests still run in nonHeadless mode in EDGE
modules:
   enabled:
        - WebDriver:
      config:
        WebDriver:
          browser: MicrosoftEdge
          window_size: 1920x1080
          capabilities:
                  EdgeOptions:
                    args: [ "--headless", "--disable-gpu", "--no-sandbox" ]
                    binary: ""


text:
Q: Simplifying a big O expression O(k + (n-k)Logk + kLogk) = O(n + klogk)? On an exercise to find the k smallest or largest elements in an array A, there's a solution that produces a O(k + (n-k)Logk + kLogk) runtime. However, my friend told me this expression equals O(n + klogk). I'm not sure if he's right or not, can anybody help me with the math on this?

A: If everything is exactly as you describe it, then your friend was careless with his arithmetic. Quite obviously k + (n-k)Logk + kLogk = k + nLogk, and not n + kLogk. If n is larger than k then the first one can be arbitrarily large compared to the second one.


text:
Q: Rails: Form isn't saving properly I'm building a basic application for practice, you input a movie and when it was rented on. The move form works fine, the title of the movie links to the rental date. But the rentals form doesn't seem to work. I don't get an error or anything, it just doesn't save. I'm assuming the issue is with my create method but I can't figure it out.
movies_controller.rb
class MoviesController < ApplicationController
  def new
    @movie = Movie.new
    @movies = Movie.all
  end

  def create
    @movie = Movie.new(comment_params)
    if @movie.save
      redirect_to new_movie_path
    end
  end

  def comment_params
    params.require(:movie).permit(:title, :year)
  end

end

rentals_controller.rb
class RentalsController < ApplicationController
  def new
    @movie = Movie.find(params[:id])
    @rental = @movie.rentals.build
  end

  def create
    @movie = Movie.find(params[:id])
    @rental = @movie.rentals.build(rental_params[:rental_id])
    if @rental.save
      redirect_to new_rental_path(:id => @movie.id)
    end
  end

  def rental_params
    params.require(:rental).permit(:borrowed_on, :returned_on, :movie_id)
  end

end

new.html.erb (rentals)
Movie: <%= @movie.title %> <%= link_to "back", new_movie_path %>

<%= form_for @rental, :url => { :action => :create, :id => @movie.id } do |f| %>
  Borrowed on: <%= f.text_field :borrowed_on %>

  Returned on: <%= f.text_field :returned_on %>

  <%= f.submit %>
<% end %>

Rentals:
<% if !@movie.rentals.blank? %>
  <% for item in @movie.rentals %>
    <%= item.borrowed_on %>, <%= item.returned_on %>

  <% end %>
<% else %>
  No rentals yet
<% end %>

new.html.erb (movies)
Enter new movie information

<%= form_for @movie do |f| %>
  Title: <%= f.text_field :title %>

  Year: <%= f.text_field :year %>

  <%= f.submit %>
<% end %>

List of all movies:

<% if !@movies.blank? %>

       Title
       Year

  <% for item in @movies %>

       <%= link_to item.title, :controller => :rentals, :action => :new, :id => item.id %>
       <%= item.year %>

  <% end %>
  </table

<% end %>

Routes:
Rails.application.routes.draw do

  resources :movies do
    resources :rentals
  end

  root 'movies#new'
end

rake routes:
 Prefix Verb   URI Pattern                                  Controller#Action
        movie_rentals GET    /movies/:movie_id/rentals(.:format)          rentals#index
                      POST   /movies/:movie_id/rentals(.:format)          rentals#create
     new_movie_rental GET    /movies/:movie_id/rentals/new(.:format)      rentals#new
    edit_movie_rental GET    /movies/:movie_id/rentals/:id/edit(.:format) rentals#edit
         movie_rental GET    /movies/:movie_id/rentals/:id(.:format)      rentals#show
                      PATCH  /movies/:movie_id/rentals/:id(.:format)      rentals#update
                      PUT    /movies/:movie_id/rentals/:id(.:format)      rentals#update
                      DELETE /movies/:movie_id/rentals/:id(.:format)      rentals#destroy
               movies GET    /movies(.:format)                            movies#index
                      POST   /movies(.:format)                            movies#create
            new_movie GET    /movies/new(.:format)                        movies#new
           edit_movie GET    /movies/:id/edit(.:format)                   movies#edit
                movie GET    /movies/:id(.:format)                        movies#show
                      PATCH  /movies/:id(.:format)                        movies#update
                      PUT    /movies/:id(.:format)                        movies#update
                      DELETE /movies/:id(.:format)                        movies#destroy
                 root GET    /                                            movies#new

A: Your controller should look like this,
class RentalsController < ApplicationController
  def new
    @movie = Movie.find(params[:movie_id])
    @rental = @movie.rentals.build
  end

  def create
    @movie = Movie.find(params[:movie_id])
    @rental = @movie.rentals.build(rental_params)
    if @rental.save
      redirect_to new_rental_path(@movie)
    end
  end

  def rental_params
    params.require(:rental).permit(:id, :borrowed_on, :returned_on, :movie_id)
  end

end

And your form should look like this
<%= form_for [@movie, @rental] do |f| %>
  Borrowed on: <%= f.text_field :borrowed_on %>

  Returned on: <%= f.text_field :returned_on %>

  <%= f.submit %>
<% end %>

A: The root of the problem (as you mentioned in the comments) is coming from the @movie = Movie.find(params[:movie_id]) so I would say that you have the problem in your routes.rb, which should look something like this:
resources :movies do
  resources :rentals
end

now the link for creating a new rental would be /movies/:movie_id/rentals/new and the path would be new_movie_rental. You can write something like this to link to the new rentals page:
<%= link_to new_movie_rental_path(@movie) %>


text:
Q: Как прочитать этот код в C? Что это? Как прочитать этот код?
sfc_ecode(*load_rom)(void*, sfc_rom_info_t*);

A: Переменная load_rom объявлена как указатель на функцию, которая принимает 2 аргумента (указатель на void и указатель на sfc_rom_info_t) и возвращает sfc_ecode.


text:
Q: Star Rating in php with mysql I am working on 5 star rating which is working fine. Now I want to optimize the database.
CREATE TABLE IF NOT EXISTS `rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `article_id` int(11) NOT NULL,
  `vote` float NOT NULL,
  'user_id' int(11) NOT NULL

  PRIMARY KEY (`id`)
)

This is my current database. Now if 10,000 user rate the same article, I got 10000 records in a single table.
Can anybody helps me to understand and optimize the database?

A: This depends on what your rating algorithm and requirements are. You can just record the number of stars received using five fields instead of one:
star1    integer not null default 0,
star2    integer not null default 0,
...
star5    integer not null default 0,

but if you do, you lose the possibility of "cooling off" ratings and changing idea on the user's part.
On the other hand, this accepted answer algorithm requires only to store the mean, so you can store
stars    integer not null default 0,
voters   integer not null default 0,

...but now the user cannot retract his vote, and indeed not even know whether he has voted or not.
(You can compromise by storing daily or weekly votes into one table, with datetime and voter id and whatever, and then "distilling" older results in the average table. Now the voter can see and undo what he did in the last week).
So what you need to do is to clearly state your requirements - what can the user do? What must the system be able to do? etc. - and work out what information needs to be known; then you derive the table(s) structure from there. If the data is too much (10,000,000 records isn't much) you either try throwing more hardware at it, or see if you can scale somehow - for example if you don't (often) need cross-article information (such as "the most starred articles"), nothing stops you from partitioning the rating table across different servers based on article id until each partition is small enough for your taste.


text:
Q: I may have used Disk Utility to erase my drive - is there hope? I have an external NTFS drive from which I was trying to copy some files to my macbook pro 10.6.6.
I was getting error 36 so with disk utility I clicked on Repair Disk. Now all my data is gone!
What gives and how can I fix it?
By the way I was using Paragon NTFS as well.
Part of the log:
2011-02-12 16:32:56 +0100: $UpCase file is formatted for use in Windows NT/2K/XP
2011-02-12 16:32:56 +0100: Verifying 95756 folders ...
2011-02-12 16:32:57 +0100: Deleting entry "._501" from index 0x1b ".Trashes"
2011-02-12 16:33:30 +0100: Correcting error in index 0x30 ($I30) for file 0x1746d.
2011-02-12 16:36:57 +0100: Creating root directory
2011-02-12 16:36:59 +0100: Inserting empty data to files.
2011-02-12 16:37:00 +0100: Verifying files security...
2011-02-12 16:38:50 +0100: Correcting $MFT bitmap data.
2011-02-12 16:38:51 +0100: Correcting $Bitmap data attribute.
2011-02-12 16:38:53 +0100:      94.88 Gb in 569134 files
2011-02-12 16:38:53 +0100:     111716 Kb in 95758 directories
2011-02-12 16:38:53 +0100:          0 Kb in bad blocks in 0 fragments
2011-02-12 16:38:53 +0100:     125388 Kb in use by the system
2011-02-12 16:38:53 +0100:       4096 Kb occupied by the log file
2011-02-12 16:38:53 +0100:       4096 bytes in each allocation unit
2011-02-12 16:38:53 +0100:   61049000 total allocation units on volume
2011-02-12 16:38:53 +0100:   31304981 allocation units available on volume
2011-02-12 16:38:53 +0100: The volume /dev/disk1s1 has been repaired successfully.
2011-02-12 16:38:53 +0100:
2011-02-12 16:38:57 +0100: Volume repair complete.2011-02-12 16:38:57 +0100: Updating boot support partitions for the volume as required.2011-02-12 16:38:57 +0100: Repair tool completed:
2011-02-12 16:38:57 +0100:
2011-02-12 16:38:57 +0100:

A: Try plugging your drive into different computers (Mac and PC). If you don't see anything, you will probably have to send it to a data recovery service if you don't have a backup.
You can also try software to recover data, like DiskWarrior.
As for why DU erased this when you clicked Repair, I have no idea. Are you sure you didn't click Erase, Reformat, or Repartition?

A: I had the same problem, and I resolved it with the chkdsk.exe on Windows. The drive mounted and I was able to recover my files.

A: Highly recommend Get Data's Recover My Files program.  You can scan for lost files for free but must pay to save them.  However, it's a LOT cheaper than paying for professional recovery service.

A: Get the hard-drive into an external enclosure.  Preferably something with a fast interface, like FW800.  Image the drive.
Then get yourself some data rescue software (I like Data Rescue 3 -- but there are many out there), and run your recovery software on the image.
Worst case scenario is you send the hard-drive (that you've manipulated very little since you've been operating from a disk image) to a recovery centre.


text:
Q: How do I do a "combined" subscription model in iOS app? We have a print magazine and we're going to release an app with subscription model, sort of kiosk app but with extended functionality.
Well, what we want is to solve the following cases:
Case 1 (complex)

*

*User buys a print issue and discovers a promo code in it. This code should allow user to download free digital copy of this issue from our app.

*User launches the app, opens a dialog box where he can enter the promo code.

*Voila! User gets his free digital copy of purchased print issue.

*Digital issue always remains in his list of purchased issues and is a valid purchased issue with all App Store options available for them (restore, etc.)

Case 2 (simple)

*

*User does not have a print issue. He launches the app and buys the same digital issue using IAP.

So, both issues  are the same (i.e. "blablabla magazine", November, 2014) but 1st was downloaded using a promo code, and 2nd was purchased with IAP, and they both should have the same properties and "weight" for App Store.
Problem is I don't know if this model will be approved by Apple. Or, if they do, how do I develop this? AFAIK, list of purchased and non-purchased items is provided by App Store and there's no way to intervene this process.
I didn't find any samples of using 3d party promo codes in iOS apps. Can anyone provide a solution for this, please?
Thanks

A: To keep a record of the promo code usage, I think the simpliest way to do it is to require an account. Once the user is logged with his account, you can tell a server that the promo code have been used with that account. If the user delete/reinstall your app, you will be able to restore all his promo codes from his account.
For your issue with IAP and promo codes, here is the App Store Review Guidelines
See the 11.16 section:

Apps may enable additional approved features or functionality when
  used in combination with specific approved physical products (such as
  a toy) as long as the additional features and functionality are either
  completely dependent on such hardware (for example an App that is used
  to control a telescope) or also available through the App without the
  physical products, such as by way of reward for achievement or by use
  of IAP

So basically, what you want to do shouldn't be rejected.
But by experience when you do something that borderline with Apple's money (possibility to "undercut" IAP), you should expect a review failure, whatever the guidelines review says.
Keep in mind that the guidelines can be interpreted in your advantage, or in you disadvantage.


text:
Q: Remove meta box from taxonomy editing screen I've been adding/removing meta boxes with code similar to:
function mw_remove_postboxes() {

    // Remove metaboxes from WooCommerce screens
    remove_meta_box( 'wp-display-header', 'product', 'normal' );
    remove_meta_box( 'wp-display-header', 'shop_order', 'normal' );
    remove_meta_box( 'wp-display-header', 'shop_coupon', 'normal' );
    remove_meta_box( 'wp-display-header', 'acf', 'normal' );

    // Remove metaboxes from Banners post type management
    remove_meta_box( 'wp-display-header', 'banners', 'normal' );
    remove_meta_box( 'wpseo_meta', 'banners', 'normal' );

}
add_action( 'do_meta_boxes' , 'mw_remove_postboxes' );

Now I have a slightly different need, where I need to remove a meta box from the edit-tags.php screen /edit-tags.php?action=edit&taxonomy=featured&tag_ID=22&post_type=page
This is the page for editing a taxonomy. I've found ways to remove a taxonomy meta box from custom post types, but none for this case.
Could you help?

A: Can be done with jQuery:
$('h3').each(function() {
    if( $(this).text() === 'Header' ) {
        // Text after element: http://stackoverflow.com/a/6925135/1287812
        var a = $(this).parent().first().contents().filter(function() {
            return this.nodeType == 3;
        });
        a.remove();
        $(this).hide();
        $(this).next().hide();
    }
});

Or using this master lesson on removing hooks registered by anonymous objects. Pull the function remove_anonymous_object_filter() from WPSE and call it like:
add_action( 'admin_init', 'kill_anonymous_example', 0 );

function kill_anonymous_example()
{
    foreach ( get_taxonomies( array( 'show_ui' => true ) ) as $_tax )
        remove_anonymous_object_filter(
            "{$_tax}_edit_form",
            'Obenland_Wp_Display_Header', // plugin instantiation on Obenland_wpdh_instantiate(new Obenland_Wp_Display_Header)
            'edit_form'
        );
}


text:
Q: How to set error in conda list command in Jupyter Can you help me with the following: I'm doing conda list in Jupyter, but the following message appears:
Note: you may need to restart the kernel to use updated packages.

I already restarted the computer, I went to Kernel in Jupyter then I pressed Restart, but even so, this message does not come out, when I do conda list. How to fix this?


text:
Q: Google Data Studio (BigQuery) - Create filter to select by latest hour I have a columns DATE, TIME (only hour number) and GROSSVALUE
DATE          TIME     GROSSVALUE
2018-09-12    13       734564
2018-09-12    12       234324

How to use Scorecard to display GROSSVALUE for the current and previous hour?
IF currently is 2018-09-12 (and any time between 13:00 to 13:59)
EXAMPLE:
--------------

CURRENT
________________
|              |
|   734564     |
|______________|

PREVIOUS
________________
|              |
|   234324     |
|______________|

A: Does the BigQuery LAG() function get what you're after?
Something like:
SELECT GROSSVALUE
   , LAG()GROSSVALUE AS GROSSVALUE_last_hour
FROM DATASOURCE
ORDER BY DATE
   , TIME


text:
Q: Usage of Callipygian / Callipygous I am not at all familiar with this word. Oxford dictionary defines Callipygian as

adjective (rare) having well-shaped buttocks.
DERIVATIVES callipygous | ˌkalɪˈpɪdʒəs, ˌkalɪˈpʌɪdʒəs | adjective

I came across it in the following context:

Search on YouTube for "female long jumpers"...notice anything
consistent about the thumbnails? Why do the cameramen at these sports
events seem so adroit at focusing on the most callipygian of the
ladies?

The usage of the word callipygian in the above sentence somehow doesn't feel correct. Is it because callipygian is used rather than callipygous, or is the sentence grammatically incorrect in either case?

A: Callipygian and callipygous have virtually the same definition and are interchangeable.

callipygian, adj.
Designating a person who has well-shaped or finely developed buttocks;
of or relating to such a person. Also: of or relating to the buttocks.
callipygous, adj. Compare earlier CALLIPYGIAN adj.
Designating a person who has well-shaped or finely developed buttocks;
of or relating to such a person; = CALLIPYGIAN adj.
Source: Oxford English Dictionary (login
required)

Here's an example usage offered by the OED:

2011   New Yorker 28 Mar. 60/3   The famously
callipygian television personality Kim Kardashian makes frequent
requests for free Spanx.

You can swap in — for the sake of adjectival illustration — fine-butted wherever you see either to see that the usage is correct. For example:

The famously fine-butted television personality Kim Kardashian makes frequent requests for free Spanx.
Why do the cameramen at these sports events seem so adroit at focusing on the most fine-butted of the ladies?

To know before you go . . .
Google Books Ngram Viewer indicates that callipygian is more common.
If you need an adverb, the OED lists the derivative adverb callipygously. Callipygianously is not in use.
Callipygous is pronounced cal-uh-PIE-gus (ˌkæləˈpaɪɡəs), with a hard g and a long-i y. Callipygian has a soft g and a short-i y (ˌkæləˈpɪdʒiən). (Hear the pronunciations.)


text:
Q: POI Set foreground color not working in if statement I am doing some code that compares two sheets and outputs a file with the matching cells in green and the others in red.
Problematic section (see full code at the end)
CellStyle style = cellOutputFile.getCellStyle();

if (isCellContentEqual(cellComparisonFile1, cellComparisonFile2) == true)
{
    style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
}
else
{
    style.setFillForegroundColor(IndexedColors.RED.getIndex());
}

style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellOutputFile.setCellStyle(style);

Problem
This code always displays ALL cells as green, even if, when debugging, the else statement is triggered and the style is set to have a red background.
Thanks in advance for any help!
Full Code
    for (int i = 0; i < workbookComparisonFile1.getNumberOfSheets(); i++)
    {
        sheetComparisonFile1 = workbookComparisonFile1.getSheetAt(i);
        sheetComparisonFile2 = workbookComparisonFile2.getSheet(sheetComparisonFile1.getSheetName());
        sheetOutputFile = workbookOutputFile.getSheet(sheetComparisonFile1.getSheetName());

        System.out.println(sheetComparisonFile1.getLastRowNum());

        if (sheetComparisonFile2 != null)
        {
            for (int j = 0; j < sheetComparisonFile1.getLastRowNum(); j++)
            {
                Row rowComparisonFile1 = sheetComparisonFile1.getRow(j);
                Row rowComparisonFile2 = sheetComparisonFile2.getRow(j);
                Row rowOutputFile = sheetOutputFile.getRow(j);

                if ((rowComparisonFile1 != null && rowComparisonFile2 != null)
                        && (rowComparisonFile1.getLastCellNum() == rowComparisonFile2.getLastCellNum()))
                {
                    for (int k = 0; k < rowComparisonFile1.getLastCellNum(); k++)
                    {
                        Cell cellComparisonFile1 = rowComparisonFile1.getCell(k);
                        Cell cellComparisonFile2 = rowComparisonFile2.getCell(k);
                        Cell cellOutputFile = rowOutputFile.getCell(k);

                        if (cellComparisonFile1 != null && cellComparisonFile2 != null)
                        {
                            CellStyle style = cellOutputFile.getCellStyle();

                            if (isCellContentEqual(cellComparisonFile1, cellComparisonFile2) == true)
                            {
                                style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
                            }
                            else
                            {
                                style.setFillForegroundColor(IndexedColors.RED.getIndex());
                            }

                            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                            cellOutputFile.setCellStyle(style);
                        }
                    }
                }
            }
        }
    }

public boolean isCellContentEqual(Cell cell1, Cell cell2)
{
    if (getCellContents(cell1).equals(getCellContents(cell2)) == false)
    {
        System.out.println("Sheet: " + cell1.getRow().getSheet().getSheetName() +
                " Cell1: " + cell1.getRow().getRowNum() + "-" + cell1.getColumnIndex() + " "
                + getCellContents(cell1).equals(getCellContents(cell2)));
    }
    return getCellContents(cell1).equals(getCellContents(cell2));
}

public String getCellContents(Cell cell)
{
    DataFormatter df = new DataFormatter();

    return df.formatCellValue(cell);
}

A: Styles are created at the workbook level, not the cell level.  Try the following code but this may fail if the workbook style table is full.  Modify the if/else logic of your inner loop as such:
if (isCellContentEqual(cellComparisonFile1, cellComparisonFile2) == true)
{
    CellStyle style = workbook.createCellStyle();
    style.cloneStyleFrom(cellOutputFile.getCellStyle());
    style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    cellOutputFile.setCellStyle(style);
}
else
{
    CellStyle style = workbook.createCellStyle();
    style.cloneStyleFrom(cellOutputFile.getCellStyle());
    style.setFillForegroundColor(IndexedColors.RED.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    cellOutputFile.setCellStyle(style);
}

edit code sample updated to copy preexisting style before changing the fill foreground color and fill pattern


text:
Q: iOS Push Notifications - Developing from multiple computers So I set up Push Notifications for my app and I'm using Parse.com to facilitate their operation.  Everything works well: I download the app onto my phone, send a push from Parse, and I get a notification.  Great.  Now I want another developer to get his device ready for action.  He plugs his phone into my computer, downloads the app, I send a notification, works great.  The provisioning profile contains his device so no problems.
However, when he downloads a copy of our app from the git repo onto his computer (+ downloads the provisioning profile and sets that up), downloads the app on his phone and then registers, push notifications don't work.  To be clear, it creates an installation entry in the Parse table with his newly created user but the deviceToken field is empty:

To put it simply, Parse creates an installation field with the deviceToken filled in if I download the app from my computer, but not anyone else's computer.  Might seem like a minor issue, but we often work in completely different locations so it could end up being a major one.

A: If you're working on a single developer account (and not a company account), as you mentioned in the comment, you can simply send your certificates to the other developer's computer so that he'll sign the app with the same credentials, which should resolve your issue.

*

*Goto to Keychain Access.

*Find the relevant certificates (development/distribution certificates and possibly also the matching push development/distribution certificates) and press the small arrow to the left of the certificate name.

*Select both the certificate and its matching key and right click to select the Export option.

*Give the file some password that will be known to the other developer and send him these files.

When these files are opened by the other developer on his computer and added to his keychain access (simply by opening them and entering the right password), he should be able to use these files to sign the apps when installing them on his device, making it identical to the process performed from your computer. This should resolve the push issues. Good luck!


text:
Q: Concatinate integer arrays iteratively I have a methode in2.getImagesOneDim() which gives me an array of integers, to be more precise the pixel values of an image. Now i want to create one big array with all the pixel values of all the images. Therefore I have to call this method several times. Now I would like to concatenate the previous output to the current output until all images are read.
In some kind of pseudo code, where the + is a concatination ... :
 for (int i = 1; i < 25; i++) {
  ConArray = ConArray + in2.getImagesOneDim("../images/"+i);
 }

How would I do this in java ?

A: Split big problem into many smaller and You find the way:

*

*Read each image into separate array

*Compute total size

*Join sub arrays

See example
import java.util.Arrays;

public class ImageProgram {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new ImageReader().readImages()));
    }
}

class ImageReader {

    public int[] readImages() {
        int[][] images = readImagesInto2DArray();
        return makeOneDimensionArray(images);
    }

    private int[] makeOneDimensionArray(int[][] arrays) {
        int totalLength = computeTotalLength(arrays);
        int[] array = new int[totalLength];
        int destPos = 0;
        for (int[] subArray : arrays) {
            System.arraycopy(subArray, 0, array, destPos, subArray.length);
            destPos += subArray.length;
        }
        return array;
    }

    private int computeTotalLength(int[][] arrays) {
        int length = 0;
        for (int[] subArray : arrays) {
            length += subArray.length;
        }
        return length;
    }

    private int[][] readImagesInto2DArray() {
        int size = 24;
        int[][] result = new int[size][];
        for (int i = 0; i < size; i++) {
            result[i] = readArray(i + 1);
        }
        return result;
    }

    private int[] readArray(int index) {
        // read from file
        int[] result = new int[index];
        Arrays.fill(result, index);
        return result;
    }
}

A: List<int[]> pixels = new ArrayList<int[]>();
for (int i = 1; i < 25; i++) {
    pixels.add(in2.getImagesOneDim("../images/"+i));
}
return pixels;

Now you have a list of all the data, you can get the data with pixels.get(index);

A: You could use the Collections#addAll method.
List<Integer> allIntegers = new ArrayList<Integer>();

for (int i = 1; i < 25; i++) {
    Integer[] imageIntegers = in2.getImagesOneDim("../images/"+i);
    allIntegers.addAll(Arrays.asList(imageIntegers));
}

return allIntegers.toArray();


text:
Q: What's the harm with this epsilon-delta definition of continuity? Normally continuity of a map between normed spaces is defined as :

A map $f : X \rightarrow Y$ is continuous at $x_0$, if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x \in X$ satisfying $||x - x_0\|| < \delta $, we have $||f(x) - f(x_0)|| < \epsilon$.

I am wondering that if the following is equivalent:

A map $f : X \rightarrow Y$ is continuous at $x_0$, if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x \in X$ satisfying $||x - x_0\|| \leq \delta $, we have $||f(x) - f(x_0)|| \leq \epsilon$.

Perhaps I am being overly analytic, but I would still like to know if there is any harm is using the latter definition.


text:
Q: How to remove active class in AngularJS After adding the active class to an element.
 ng-class="{active: $index == selected}"

How can remove it by some button click in another function scope.

A: add another variable for tracking click buttonClicked
ng-class="{active: (($index == selected) && !buttonClicked)}"

<button ng-click="buttonClicked=true">Disable class</button>

as per the comment of Satpal you can achieve the same result by setting $scope.selected = -1
ng-class="{active: $index == selected}"
<button ng-click="selected=-1">Disable class</button>


text:
Q: Error on PS script that installs app to Hololens using device portal APIs I'm trying to develop a PS script that install app package to Hololens via the device portal APIs. Looking for some troubleshooting tips on the 400 BAD REQUEST response.
Here are the references I used :
https://learn.microsoft.com/en-us/windows/mixed-reality/device-portal-api-reference
END POINT /api/app/packagemanager/package (POST)
$user = 'snarain'
$pass = 'snarain'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

$FilePath = 'C:\Users\snarain\Downloads\My HololensApp.appxbundle'

Invoke-RestMethod -Uri 'http://127.0.0.1:10080/api/app/packagemanager/package?package=My%20HololensApp.appxbundle' -Headers $Headers -Method Post -InFile $FilePath -ContentType 'multipart/form-data'

The output is Invoke-RestMethod : The remote server returned an error: (400) Bad Request. However, I am able to use Postman to hit the end point and upload the app successfully. I saved the request from POSTMAN to its curl equivalent here it is, for the experts to quickly debug it.
  --url 'http://127.0.0.1:10080/api/app/packagemanager/package?package=My%20HololensApp.appxbundle' \
  --header 'Authorization: Basic c25hcmFpbjpzbmFyYWlu' \
  --header 'Postman-Token: c6613653-3ff0-43c1-896c-63d62b125277' \
  --header 'cache-control: no-cache' \
  --header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  --form '=@C:\Users\snarain\Downloads\My HololensApp.appxbundle'```

A: The answer from jklemmack on this post helped solve this problem. Also I should be using ISO-8859-1 encoding instead of UTF-8 to make the appxbundle read successful.
powershell invoke-restmethod multipart/form-data
Solved !


text:
Q: Display text based on multiple checkbox selection I'm currently trying to figure out how to display predefined texts based on checkbox selections (multiple) in Google Sheets.
Example:
Checkbox 1 True
Checkbox 2
Checkbox 3 True

Predefined answers:
Answer 1
Answer 2
Answer 3

Result:

*

*Displaying the strings of Answer 1 + Answer 3 in a textbox.

*If Checkbox 2+3 are checked, text of answer 2+3 should be shown inside a textbox.

Any idea how to make that happen?
Another exmaple in the picture:
Example

A: You can do the same thing with onedit trigger
function onEdit(e) {
  //e.source.toast("onEdit");
  const sh = e.range.getSheet();
  if(sh.getName() == 'Sheet0' && e.range.columnStart == 1) {
    sh.getRange('D1').setValue(sh.getRange(1,1,sh.getLastRow(),2).getValues().filter(r => r[0]).map(r => r[1]).join(','));
  }
}

The ouput is the string in col2 where col1 is truthy

A: Try
=textjoin(char(10),,arrayformula(vlookup(filter( C1:C6, A1:A6=true, left(C1:C6,1)=A15),A8:B13,2,0)))


text:
Q: having a dictionary of matrices, how to return a dictionary containing the matrix with the smallest number of zeros? I have a dictionary containing matrices, I want for each matrix count the number of zero and return a dictionary containing the element with the minimum of zero
To do this I have already the method to count the number of zero, and how to have the matrix with the minimum of zero, but I did not know how to return the pair.

Dictionary<string, int[,]> c
        foreach ( int[,] entry in c.Values)
        {
            //array to contain the number of zeros
              int[] max_couverture = new int[c.Count];
                for (int i = 0; i < max_couverture.Length; i++)
                {
             //calcul_zero the method that calculate the number of zero of a matrix
                    max_couverture[i] = calcul_zero(entry);
                }
                int min = max_couverture[0];
                for (int i = 0; i < max_couverture.Length; i++)
                {
                    if (max_couverture[i] < min) min = max_couverture[i];

                    i++;
                }

        }
//calculate the number of zero of a matrix
 public static  int calcul_zero(int[,] m)
    {
        int colIdx = 0; // column index to check
        int num = Enumerable.Range(0, m.GetLength(0)).Count(i => m[i, colIdx] == 0);
        return num;
    }

A: The problem can be solved by using facilities which are already there by decomposing the problem. First, unfortunately, int[,] does not implement IEnumerable<int>, which can be addressd with the following extension method.
public static IEnumerable<T> ToEnumerable<T>(this T[,] target)
{
    foreach (var item in target)
    {
        yield return item;
    }
}

Next, we can use Linq to define a function which counts the number of zeros in a two-dimensional array as follows.
public static int CountZeros(int[,] iMat)
{
    return iMat.ToEnumerable<int>().Count(iInt => 0 == iInt);
}

Surprisinlgy, Linq also does not provide an extension method to determine an element of a sequence which is maximal or minimal if a certain function is applied to it. This can be done with the following two extension methods.
public static T ArgMin<T, R>(T t1, T t2, Func<T, R> f)
where R : IComparable<R>
{
    return f(t1).CompareTo(f(t2)) > 0 ? t2 : t1;if equal
}

public static T ArgMin<T, R>(this IEnumerable<T> Sequence, Func<T, R> f)
where R : IComparable<R>
{
    return Sequence.Aggregate((t1, t2) => ArgMin<T, R>(t1, t2, f));
}

Finally, we can define a method returning a dictionary which contains the first key and value matrix for which the number of zeros is minimal.
public static Dictionary<string, int[,]> MinNumOfZeros(Dictionary<string, int[,]> iDict)
{
    var KeyOfMinimum = iDict.Keys.ArgMin(iKey => CountZeros(iDict[iKey]));
    return new Dictionary<string, int[,]> { { KeyOfMinimum, iDict[KeyOfMinimum] } };
}

A: You can do that by modifying your calcul_zero a bit. ie:
{
// ...
var minKV = c.ToList()
    .OrderBy(k => calcul_zero(k.Value))
    .First();

Console.WriteLine(minKV.Key);
//...
}
public static int calcul_zero(int[,] m)
{
    int zeros=0;
    for (int i = 0; i < m.GetLength(0); i++)
    {
        for (int j = 0; j < m.GetLength(1); j++)
        {
            if (m[i, j] == 0) zeros++;
        }
    }
    return zeros;
}


text:
Q: Custom post type routing with hierarchy I've been playing around with a lot of custom post types lately and I am pretty anal about my URL structure / routing.
An issue I ran in to a with a site that I just developed was this:

*

*I had many custom post types, for example: videos

*The URL structure to 'view' the video list (ie: archive of sorts) was /media/videos/

*This 'view' was basically a custom WP_Query displaying things properly from a custom .php template.

*When an individual 'video' link is clicked you are taken to the post type URL structure, ie: www.site.com/videos/{slug}

*This causes all loss of URL structure/parental relationship to structure.

I would love to solve this problem:

*

*When you navigate to /media/videos/ you get the custom loaded template file

*When you click a video permalink(), you will be linked to /media/videos/{slug}

*Ideally this would perserve hierarchy of URL structure (so if something like Breadcrumb NavXT it would still have a relationship).

I made a teacher/student/etc module one time where I did custom routing via add_rewrite_rule to handle these problems, but I would rather figure out how to handle hierarchy appropriately in this situation.
Can someone please point me in to the right direction?
Thanks!
Tre

A: When you declare the custom post type, there is a parameter "rewrite" where you declare the slug for the post type. Change the slug to "media/videos", and then visit your Settings > Permalinks page to update your rewrite rules.
register_post_type( 'videos',
    array('labels' => array(),
        'rewrite'   => array( 'slug' => 'media/videos', 'with_front' => false )
    )
);


text:
Q: JSlider getX(), getY() JApplet When is a GUI component's position, width and height set? If layout managers are being used, how are these fields effected? I have a panel that contains two sliders and I want to draw a rectangle next to one of them. Here is my code to initialize my GUI components and paint them with a rectangle next to one of the sliders:
public PhotoSliders()
{
    initComponents();    //from the netbeans GUI designer
}

public void setColorRect()   //initialize a colored rectangle
{
    colorRect = new ColorRect(Color.RED, (double)(emSlider.getX())/getWidth(), (double)(emSlider.getY())/getHeight());
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    colorRect.paintColorRect(g, getWidth(), getHeight());
}

I have found that the emSlider.getX(), emSlider.getY(), getWidth(), and getHeight() are all 0 initially. When I resize my applet and thus causing it to be repainted, the fields are no longer zero. Why are they all zero initially? Here is the code in my applet class:
public void init()                               //initialize the Applet Class
{
   setLayout(new BorderLayout());
   slidersPanel = new PhotoSliders();
   JPanel north = new JPanel(new BorderLayout());

   north.add(slidersPanel, BorderLayout.WEST);
   add(north, BorderLayout.NORTH);
   add(photoEffect, BorderLayout.CENTER);

   slidersPanel.setColorRect();

}
   public void paint(Graphics g)                   //paint the photoEffect
   {
      super.paint(g);
      slidersPanel.setColorRect();
   }

A: A component's location and size are set when the GUI is rendered, and before that they are the default value, 0. For a desktop applicaiton, this occurs when either pack() is called on the top level window, or when setVisible(true) is called on the top level window, or on the component itself if it is added to the GUI after all has been rendered.
If it's an applet, then it's when the applet is rendered -- something that is done behind the scenes. You may be able to listen for this using one of the Swing listeners. I have to look up which one, possibly an AncestorListener.... edit, yes I think that's right, try using an AncestorListener.
Consider buying Filthy Rich Clients for a wonderful book that goes into great depths on Swing graphics.


text:
Q: Why not make versions fixed in bower.json I know most projects have minimum versions defined in bower.json for a lot of libraries.
Something I don't understand is that would this be risky that if something updates and have break-changes or bugs, it will affect your application without you knowing it? What is the design thinking behind this?
Thanks!

A: We have just faced that exact issue on a project I am on, and the solution was to change our bower.json file to target fixed versions.
Specifically, we were targeting angularjs ^1.4.8. In AngularJS v1.6,

$location now uses '!' as the default hash-prefix for hash-bang URLs,
  instead of the empty string

For better or for worse (mostly for worse) we had some hard-coded urls in a different application that pointed to this project that broke once bower automatically installed AngularJS 1.6 as part of our automated build process.
The solution was to simply lock down our versions rather than relying on the latest bug fix (i.e prefixing version numbers with ~) or minor build (i.e. prefixing version numbers with ^).
I think the reason that package managers like bower and npm default to dynamic versions is that they rely on semantic versioning, and in theory you should only encounter breaking changes when the major version number changes. Semver uses a major, minor, bugfix pattern. When the bugfix value is incremented it indicates that one or more backwards-compatible bugs have been resolved. When the minor version is incremented it indicates that new backwards-compatible functionality has been added. When the major version is incremented it indicates that new, breaking changes have been introduced.
The problem with this is that firstly, it relies on the package developer to respect the semver rules when they make changes to their packages, and secondly, even when semver is respected it can still lead to problems (as in the example I provided above).


text:
Q: How to derive from/implement a C# class hierarchy in without code duplication I am faced with a C# design problem that C#'s limitations are making hard to achieve.  I need some sort of design pattern/strategy to rescue me.
I must create the archetypical set of abstract shape classes:  Base class Shape with derived classes LineShape, RectShape, etc.  Specific implementations will derive from these.  The problem is that I really need to use classes here, not interfaces and this is forcing me to duplicate a lot of code.
To illustrate:
public abstract class Shape
{
    public abstract int      Id           { get; }      // Unique ID
    public abstract string   Name         { get; set; } // Shape name.  Defaults to the type of shape
    public abstract bool     IsLocked     { get; set; } // May the user change this shape in any way?
}

public abstract class LineShape : Shape
{
    public abstract Point P1 { get; set; }
    public abstract Point P2 { get; set; }
}

public abstract class CircleShape : Shape
{
    public abstract Point Center { get; set; }
    public abstract double Radius { get; set; }
}

When I start creating the derived implementations (LineImpl, CircleImpl, etc), I find that the implementations of the  Shape functions are identical for all the Impl classes, yet specific enough that I cannot implement them in the abstract Shape class itself.
So I need to find a way to share a common implementation of these function in my derived hierarchy.
In other words  LineImpl must derive from LineShape.  CircleImpl must derive from CircleShape, etc.  I cannot find a way to insert a ShapeImpl in there to handle the boiler plate stuff.  So I am forced to implement all those Shape functions over and over again, once in each Impl shape type.
I tried using generics to get my way out of this but unfortunately a generic class cannot specify its base class with a generic argument.   In other words, the following approach (which I might do in C++) does not work in C#
public class ShapeImpl<TBase> : T where T : Shape {  ... boiler plate implemented here)...}
public class LineImpl         : ShapeImpl<LineShape> { }
public class CircleImpl       : ShapeImpl<CircleShape> { }

So I am at a loss.  Is there some C# trick or design pattern that can get me out of this?  Or am I forced to implement the same functions multiple times?

A:
yet specific enough that I cannot implement them in the abstract Shape class itself.

You also mentioned:

I find that the implementations of the Shape functions are identical for all the Impl classes

I think that this is classic case of over-thinking for future implementation. if you say- the implementation is identical for all classes, I wouldn't bother too much over thinking for something in the future that may never arrive.
But, if you insist, you may implement it in the following way:
    public abstract class Shape
    {
        public abstract int Id { get; }      // Unique ID
        public abstract string Name { get; set; } // Shape name.  Defaults to the type of shape
        public abstract bool IsLocked { get; set; } // May the user change this shape in any way?
        public abstract void Foo();
    }

    public abstract class SepcificShape : Shape
    {
        protected virtual void FooSpecific()
        {
            Console.WriteLine("Specific Implementation");
        }
    }

    public abstract class LineShape : SepcificShape
    {
        public abstract Point P1 { get; set; }
        public abstract Point P2 { get; set; }
    }

    public class LineImp : SepcificShape
    {
        public override int Id { get; }
        public override string Name { get; set; }
        public override bool IsLocked { get; set; }
        public override void Foo()
        {
            base.FooSpecific();
        }
    }

A: The only way to achieve something similar to multiple inheritance in C# I can think of would be to use default interface implementations, e.g. like this:
    interface IShapeSdk
    {
        string GetNameSdk() => "Shape SDK name";
    }

    abstract class Shape
    {
        public abstract string GetName();
    }

    class ShapeImpl : Shape, IShapeSdk
    {
        public override string GetName()
        {
            return ((IShapeSdk)this).GetNameSdk();
        }
    }

This way all shapes will inherit from Shape, but only the external-SDK-shapes will inherit the common logic defined in IShapeSdk.
Not the cleanest approach, and a lot of C# developers are against the usage of this relatively new feature (which by the way is available only in C# 8 and above and .NET Core 3.0 and above).


text:
Q: How to brand my masterpage using provider hosted apps? I'm working with SharePoint apps and I want to learn to modify the css of the masterpage. I cant find any good guides out there so can you guys help me out?
Im using a copy of the default masterpage to play with. I have created a provider hosted app with a module including the custom masterpage. how can I add css and apply them to change things on the sitecollection? Am I on the right track?

A: Step 1: Get SharePoint collection path.
Log in as an administrator at your site collection. (VERY IMPORTANT! to mark the "remember me" checkbox before pressing Login button). Go to site settings -> Design manager -> upload designfiles and copy the linkadress that's in there.
Step2: Map network drive
Go to File explorer on your computer and rightclick on "Network". Choose map network drive... choose a drive and press finnish.

This wil only work if you have ckecked the "remember me" button at step 1
Step 3: Add css to the drive
Add a folder containing your css. (to override exsisting css you have to look at the sites source code (F12 when you are on the site you want to style) from your browser and find and copy the classes or ids and put them in your css file here in the mapped drive folder. Thats how you override them.
Step 4: Upload to Sharepoint
Go in to site settings -> Master pages and page layouts. Find yor css in here and hit the arrow down symbol to the right of the item. hit "Publish a Mayor version" and now it should work.
If you want to do this for the public page you have to do step 1 again but you have to be on the adress yoursite-public.sharepoint.com instead of yoursite.sharepoint.com


text:
Q: Power Shell: Save Path after file is found via foreach loop I´m still quite new to PS, so it might be easy to answer for the veterans.
I want to grab the path of a file after a search through the drives.
Current code:
$Drives = Get-PSDrive -PSProvider 'FileSystem'

foreach($Drive in $Drives)
{
    Get-ChildItem -Path $Drive.Root -include FindMe.txt -Recurse -ErrorAction SilentlyContinue | Invoke-Item

}

The goal is to save info like BIOS info in the found file.
But how can I grab the Path of the file or the found file itself to use it as a save file?
Thanks in advance

A: As commenter Lee_Dailey suggested, just assign the command output to a variable and use the FullName property of the FileInfo class to get the absolute file path.
$Drives = Get-PSDrive -PSProvider 'FileSystem'

$foundPath = foreach($Drive in $Drives)
{
    # Find first file named FindMe.txt
    $found = Get-ChildItem -Path $Drive.Root -Filter FindMe.txt -Recurse -ErrorAction SilentlyContinue |
             Select-Object -First 1

    if( $found ) {
        # Output the full path of the found file.
        # This is implicit output which PowerShell captures in $foundPath
        $found.FullName
        break
    }
}

# Output found path to the console
$foundPath

Notes:

*

*I've replaced -Include by -Filter which is more efficient because it is handled by the underlying .NET filesystem API. Using -Include the API would return all files and the filtering would be done by PowerShell, which is slower.

*I've added Select-Object -First 1 to stop searching when the first file named 'FindMe.txt' has been found.

*Remove | Select-Object -First 1 to get all files named 'FindMe.txt'. In this case, $found will be an array when more than one files are found. Also $found.FullName could resolve as an array due to member access enumeration.


text:
Q: Create a multiline plot with axes, labels, title, and legend using crops.csv file Directions Load Data into pandas data frame Create variables for years, rice, wheat, maize, and soybean. Generate a plot that looks like below with fig size 8 by 6
 from google.colab import drive
 drive.mount(('/content/drive'), force_remount=True)
 url = '/content/drive/My_drive/crops.csv'

 import matplotlib.pyplot as plt
 import numpy as np
 plt.figure(figsize=(8, 6))
 plt.plot()
 plt.title('Crops')
 plt.xlabel('number of years')
 plt.ylabel('number of crops')
 plt.legend()
 plt.show()


text:
Q: Can i make a JTable column without borders? I have created a column with cells that contain a JTextArea + A JButton inside it, as you can see in the image below in Column 3 :

But i have faced lots of problems with my CellRenderer and CellEditor when updating the cells values in that column, as my code is a bit complicated. So instead i want to replace that column with 2 columns. One column to be of normal String cells and the other to be of JButton cells but these 2 columns should have the same look as column 3 appears in the above image. So my questions are :
1. How can i merge the headers of the 2 columns together ?
2. How can i remove the left borders of the JButtons column ?
If those are fixed, that way the 2 columns will have the same look as the above image + updating the cells values will be much easier.
-------------------------------- Edit : My code sample problems :
Ok guys ... You asked for it. My code is huge but if you can help me fix it, that would be perfect. I have created a running jar sample for my problem & included my source code too. You can download it from here :
Jar sample
The problem is that i use a button to allow sorting table rows(Move them up/down), but when i do this some of the moved cells values are not updated !
You can see the following screenshot :

The problem is in the cell editor i am using ... But i can't fix it.

A: UPDATE when you create an empty table model, create two instances of ButtonCellRenderer (instead of 4), and set one instance as both an editor and a renderer for column 2 and the second one for column 3. This fixed showing wrong values when moving rows, but sometimes draws empty cell when hovering.
And about code not working, restarting cell editing whenever a mouse is moved may introduce problems because you switch between cell editor and renderer at every mouse move. I couldn't edit any values even though you use JTextArea (which should be JTextField). Recreating table model every time you change order of rows is ok, but it is better to create a class that holds values for all columns and use Vector of these classes as a table model. This way you can reorder values in the vector and table model will be updated.
If you want to merge two headers, override getHeaderRect(int col) of JTableHeader, to return the union of super.getHeaderRect() for two columns. You might also need to override paint() method of BasicTableHeaderUI to paint the wide header over two previous ones.
This is the approach I used to merge table cells, but it should also work for headers.
Sorry, I cant give you the exact code. Personally, I'd do with writing custom cell renderer, i.e your first approach.
EDIT If you want to use Metal LaF, this code kinda does the trick of not painting the header of the second column:
    final TableCellRenderer defaultRenderer = getTableHeader().getDefaultRenderer();
    getTableHeader().setDefaultRenderer(new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            JLabel c = (JLabel) defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (column == 1)
                c.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Color.gray));
            else if (column == 2) {
                c.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 1, Color.gray));
                c.setText(null);
            } else
                c.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
            return c;
        }
    });

A: You could create a JButton without border (empty border) that implements TableCellRenderer ?


text:
Q: Showing another background when reaching the end of the NestedScrollView I've checked this concept in many websites, and wanted to make it in my app. The idea is simple, having a static background, for instance a color as a background in the app, and when the scroll is in the ends, it shows some trees in the bottom.
It's like placing the second background in the bottom of the Scrollview. I have tried to only place a background, but it shows in the bottom of the app, not in the Scrollview.
Is there a way to make this? as I have already searched and didn't find any reliable source.

A: If I understood correctly, you can achieve what you are looking for using this XML layout (or build the same structure programatically).
You just need to put an ImageView with your drawable as the "src" at the bottom of the ViewGroup inside the NestedScrollView (as ScrollViews can only have one child). You would get a ScrollView, with a ViewGroup inside, with your content followed by your image.
When a user scrolls to the bottom below your content, the image will appear from the bottom. In the code below I show you the XML and where you can set the background for the app, and for the bottom of the scroll view, and where to place the content.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/app_background">
    <!-- YOU CAN SET YOUR APP BACKGROUND COLOR OR DRAWABLE UP HERE -->

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

                <!-- YOUR CONTENT GOES HERE -->
                <TextView android:text="Your content here instead of this TextView"
                          android:layout_width="match_parent"
                          android:layout_height="1500dp" />

                <!-- YOUR FOOTER IMAGE HERE -->
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:src="@drawable/trees" />
        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</LinearLayout>

If you want the image in the bottom to show behind the ScrollView content instead of below, you need to remove the ImageView in the XML above, and instead set a background drawable to the LinearLayout inside the NestedScrollView, and use the following XML resource drawable as a background:
<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/trees"
    android:gravity="bottom|center_horizontal" />

This XML will create a new drawable that aligns to the bottom of a view when set as a background. Just save that code in an xml file called trees_background.xml in your drawable folder, and change the LinearLayout to have
android:background="@drawable/trees_background.xml"

A: If I understood you right, the simplest way to achieve desired behavior is to add an additional ViewType to your recycler's adapter and add this item to the end of your items list. It will work as a footer for Recycler View, so when user scrolls to the bottom, they will see your trees or anything.

A: You can detect whether you have reached the bottom of NestedScrollView or not in the following way and then can apply your own logic to change background accordingly .
  NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);

        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY < oldScrollY) {
                    // Scroll UP
                } else if (scrollY > oldScrollY) {
                    //Scroll down

                } else if (scrollY == 0) {
                    // TOP SCROLL
                } else if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    //You have reached  the bottom of nested scrollview
                    //Add you logic here to change background
                }
            }
        });

Hope i get you question right.


text:
Q: How to re-zip as a .jet file I have a .sqlite file and the developer zip it as a .jet file. Now I can open it with 7zip, I can edit the db but at the end I couldn't re-zip again as a .jet file. I tried every solution that I saw on the internet, but none of them answer to me.
If someone wants to take a look, file download link.
https://wetransfer.com/downloads/ea5a329dff6b4ca48363a6faca2b17af20190516110040/2b647b
Any help would be great.


text:
Q: How to implement thousand separator format using TextField in MatBlazor I'm a new beginner at using Blazor ... I'm trying to implement Thousand Separator at TextField using MatBlazor. I've been googling but no luck.
Anybody has an idea/clue how to do it ?
Thanks in advance.


text:
Q: Tomcats RemoteIPValve not invoked in Spring Boot Application deployed as a WAR file My Spring Boot 1.3.2 Application is deployed as a WAR file into a standalone tomcat7. I am trying to activate the RemoteIPValve using server.use-forward-headers=true as described in the spring boot docs.
But the RemoteIPValve is not properly configured nor invoked when handling the request. Log says:

NonEmbeddedServletContainerFactory detected.

When I start the application using the maven plugin I get a:

Initializing Spring embedded WebApplicationContext

... and RemoteIPValve is working as expected. How can I accomplish the same using WAR File deployment?

A: When you deploy a Spring Boot application to standalone Tomcat, none of the embedded server configuration takes effect. Instead, you need to update your Tomcat installation's configuration to enable the valve. To use the valve in its default configuration, add the following to server.xml:
<Valve className="org.apache.catalina.valves.RemoteIpValve"/>


text:
Q: Java 8 - Best way to transform a list: map or foreach? I have a list myListToParse where I want to filter the elements and apply a method on each element, and add the result in another list myFinalList.
With Java 8 I noticed that I can do it in 2 different ways. I would like to know the more efficient way between them and understand why one way is better than the other one.
I'm open for any suggestion about a third way.
Method 1:
myFinalList = new ArrayList<>();
myListToParse.stream()
        .filter(elt -> elt != null)
        .forEach(elt -> myFinalList.add(doSomething(elt)));

Method 2:
myFinalList = myListToParse.stream()
        .filter(elt -> elt != null)
        .map(elt -> doSomething(elt))
        .collect(Collectors.toList());

A: If you use Eclipse Collections you can use the collectIf() method.
MutableList<Integer> source =
    Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);

MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);

Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);

It evaluates eagerly and should be a bit faster than using a Stream.
Note: I am a committer for Eclipse Collections.

A: I agree with the existing answers that the second form is better because it does not have any side effects and is easier to parallelise (just use a parallel stream).
Performance wise, it appears they are equivalent until you start using parallel streams. In that case, map will perform really much better. See below the micro benchmark results:
Benchmark                         Mode  Samples    Score   Error  Units
SO28319064.forEach                avgt      100  187.310 ± 1.768  ms/op
SO28319064.map                    avgt      100  189.180 ± 1.692  ms/op
SO28319064.mapWithParallelStream  avgt      100   55,577 ± 0,782  ms/op

You can't boost the first example in the same manner because forEach is a terminal method - it returns void - so you are forced to use a stateful lambda. But that is really a bad idea if you are using parallel streams.
Finally note that your second snippet can be written in a sligthly more concise way with method references and static imports:
myFinalList = myListToParse.stream()
    .filter(Objects::nonNull)
    .map(this::doSomething)
    .collect(toList());

A: One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.
Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach method is classed as being terminal (meaning that it can produce side-effects).
The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be

*

*Non-interfering, meaning that the function should not alter the source of the stream if it is non-concurrent (e.g. ArrayList).

*Stateless to avoid unexpected results when doing parallel processing (caused by thread scheduling differences).

Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.

A: Don't worry about any performance differences, they're going to be minimal in this case normally.
Method 2 is preferable because

*

*it doesn't require mutating a collection that exists outside the lambda expression.

*it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article.)

*you can easily change the way values are collected by replacing the Collector that is used.  In some cases you may need to write your own Collector, but then the benefit is that you can easily reuse that.

A: I prefer the second way.
When you use the first way, if you decide to use a parallel stream to improve performance, you'll have no control over the order in which the elements will be added to the output list by forEach.
When you use toList, the Streams API will preserve the order even if you use a parallel stream.

A: There is a third option - using stream().toArray() - see comments under why didn't stream have a toList method. It turns out to be slower than forEach() or collect(), and less expressive. It might be optimised in later JDK builds, so adding it here just in case.
assuming List<String>
    myFinalList = Arrays.asList(
            myListToParse.stream()
                    .filter(Objects::nonNull)
                    .map(this::doSomething)
                    .toArray(String[]::new)
    );

with a micro-micro benchmark, 1M entries, 20% nulls and simple transform in doSomething()
private LongSummaryStatistics benchmark(final String testName, final Runnable methodToTest, int samples) {
    long[] timing = new long[samples];
    for (int i = 0; i < samples; i++) {
        long start = System.currentTimeMillis();
        methodToTest.run();
        timing[i] = System.currentTimeMillis() - start;
    }
    final LongSummaryStatistics stats = Arrays.stream(timing).summaryStatistics();
    System.out.println(testName + ": " + stats);
    return stats;
}

the results are
parallel:
toArray: LongSummaryStatistics{count=10, sum=3721, min=321, average=372,100000, max=535}
forEach: LongSummaryStatistics{count=10, sum=3502, min=249, average=350,200000, max=389}
collect: LongSummaryStatistics{count=10, sum=3325, min=265, average=332,500000, max=368}

sequential:
toArray: LongSummaryStatistics{count=10, sum=5493, min=517, average=549,300000, max=569}
forEach: LongSummaryStatistics{count=10, sum=5316, min=427, average=531,600000, max=571}
collect: LongSummaryStatistics{count=10, sum=5380, min=444, average=538,000000, max=557}

parallel without nulls and filter (so the stream is SIZED):
toArrays has the best performance in such case, and .forEach() fails with "indexOutOfBounds" on the recepient ArrayList, had to replace with .forEachOrdered()
toArray: LongSummaryStatistics{count=100, sum=75566, min=707, average=755,660000, max=1107}
forEach: LongSummaryStatistics{count=100, sum=115802, min=992, average=1158,020000, max=1254}
collect: LongSummaryStatistics{count=100, sum=88415, min=732, average=884,150000, max=1014}

A: May be Method 3.
I always prefer to keep logic separate.
Predicate<Long> greaterThan100 = new Predicate<Long>() {
    @Override
    public boolean test(Long currentParameter) {
        return currentParameter > 100;
    }
};

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> resultList = sourceLongList.parallelStream().filter(greaterThan100).collect(Collectors.toList());

A: If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write
ListX myListToParse;
ListX myFinalList = myListToParse.filter(elt -> elt != null)
                                 .map(elt -> doSomething(elt));
myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).
[Disclosure I am the lead developer of cyclops-react]


text:
Q: Print result of a loop in Java This code doesn't work. I get the following errors (in eclipse) that I can't seem to resolve:

Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
  Syntax error, insert ";" to complete BlockStatements
  Duplicate local variable interest

import java.util.Scanner;

public class DoWhile {

    public static void main (String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("balance: ");
        int balance = in.nextInt();
        System.out.print("interestRate: ");
        double interestRate = in.nextDouble();
        System.out.print("year: ");
        int year = in.nextInt();

        System.out.print("input: ");
        String input = in.next();
        Integer interest = null;    //to define interest

        do
        {
            double interest = balance * interestRate / 100;
            balance += interest;
            year++; // print current balance
        }
        while (input.equals("N"));
        System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
    };
}

A: The variable interest is declared twice.
Here is a slightly cleaned up version of your code:
import java.util.Scanner;

public class DoWhile {
    public static void main (String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("balance: ");
        int balance = in.nextInt();
        System.out.print("interestRate: ");
        double interestRate = in.nextDouble();
        System.out.print("year: ");
        int year = in.nextInt();

        System.out.print("press 'N' to exit");
        String input = in.next();
        double interest = 0;    //to define interest

        do
        {
            interest = balance * interestRate / 100;
            balance += interest;
            year++; // print current balance
        }
        while (input.equals("N"));

        System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
    }
}


text:
Q: How to use built in typescript definitions of a npm package (firebase in particular) I am writing a web app in typescript for firebase. But i can't get the imports working for firebaseui and firebase itself.
This is a general problem of mine that I was never able to import typedefinitions that are shipped with a library whithout a @types package. There seems something wrong with my setup but I can't find the point where I am taking the wrong turn.
I have just installed "firebaseui" via npm, and try to use it as in the documentation of firebase but I can't get the import for firebaseui and firebase.auth right. Visual Studio Code also does not offer imports for that.
I would write the imports to look like this:
import { firebase } from 'firebase';
import { firebaseui } from 'firebaseui';

I have also seen other using this which also does not work
import { firebase, firebaseui } from 'firebase';

The compiler can't find the module 'firebase'. It seems like the typings from within the package are not picked up.
My tsconfig.json looks like that:
    "compilerOptions": {
        "target": "es2015",
        "strict": true,
        "strictNullChecks": false,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true
    }
}

My TSC version is 7.15.1
I have found this question but there is no explanation and it doesn't work either.
How to get TypeScript to recognize firebase import

A: It was indeed my own mistake. I followed the official docs on the firebase website, the github page of the package has maybe more up to date or more acurate(?) docs
firebaseui has to imported as:
import firebaseui from 'firebaseui';

without the curly brackets.
Firebase is tucked away in a subfolder of firebase:
import firebase from 'firebase/compat/app';

Found the solution on the github page of the package where they use import instead of require to show the correct pathes.
https://github.com/firebase/firebaseui-web


text:
Q: Twitter Bootstrap css issue with "pull-left" class in Firefox When I add class="pull-left" to an element it works fine in all browsers except Firefox where the width of the block element doesn't seem to be respected and squished up to the left. How can I fix this issue?
The only fix I've found so far is to use a pixel width on the
 element but I want this element to resize as needed so that's not an option.
Link to site: http://julianjosephs.com/versature/bootstrap/

Code

Alison Drury

Spring Health Leisure Clubs

Edit: I am using FF version 22.0 | Chrome - latest version

A: shot in the dark but i've had good luck with this:

Alison Drury

Spring Health Leisure Clubs

A: use media-left instead of pull-left


text:
Q: .Net controls show ghost menu items; double buffering doesn't work I have a winforms application with a menu. The "New" item on the menu creates a new control which has a lot of sub-controls, so it takes about 300ms to construct the control.
When you click the "New" menu item, you see something like this for a brief moment:

As you can see, the menu disappears over some of the form, but over the toolbar, for example, you can still see it.
I tried this solution How to double buffer .NET controls on a form?, but it caused more problems than it solved (Laggy menus, crashes when window is not maximized).


text:
Q: 136 is not valid CURL hanlder--PHP this are the options i have set in CURL.
      curl_setopt($curlHandler[$j]->curl, CURLOPT_URL,$arr[$j]->URL);
      curl_setopt($curlHandler[$j]->curl, CURLOPT_FAILONERROR, true);
      curl_setopt($curlHandler[$j]->curl, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($curlHandler[$j]->curl, CURLOPT_AUTOREFERER, true);
      curl_setopt($curlHandler[$j]->curl, CURLOPT_RETURNTRANSFER,true);
      curl_setopt($curlHandler[$j]->curl, CURLOPT_CONNECTTIMEOUT, 10);
      curl_setopt($curlHandler[$j]->curl,10);

When i execute PHP curl. curl_getinfo return following array.
Array
(
    [url] => http://davidchartier.com/post/395028979/replies
    [content_type] => text/html; charset=UTF-8
    [http_code] => 404
    [header_size] => 669
    [request_size] => 224
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 1
    [total_time] => 1.939753
    [namelookup_time] => 0.079254
    [connect_time] => 0.099593
    [pretransfer_time] => 0.099693
    [size_upload] => 0
    [size_download] => 21201
    [speed_download] => 10929
    [speed_upload] => 0
    [download_content_length] => 255
    [upload_content_length] => 0
    [starttransfer_time] => 1.759269
    [redirect_time] => 0.129832
    [certinfo] => Array
        (
        )

    [redirect_url] =>
)

Warning:  (null)(): 136 is not a valid cURL handle resource in Unknown on line 0

please help me.any kind of help is appreciated.


text:
Q: Формула для расчета ЗП Есть такие данные input {workTime: 3600, keyCount: 5000, freeTime: 120} (-сколько человек работал, сколько сделал нажатий, сколько отдыхал)
И output {cash: 2400} (сколько заработает, если будет работать столько, сколько в input). Таких вариаций может быть много.
Я получаю данные workTime, keyCount, freeTime, они могут быть любыми. Нужно получить то, сколько заработает человек.
Я пробовал вывести формулу, но не получилось. Я думаю, что можно использовать нейросеть (brain.js например). Я попробовал поиграться, но оказывается, что данные должны быть от 0 до 1. Я попробовал подавать данные для обучения в таком формате: 1/input. Но почему-то для любых вариаций было примерно одинаковое значение.
Вот то, что я пробовал

const net = new brain.NeuralNetwork({
  hiddenLayers: [10],
  iterations: 20000
});

net.train([{
    input: [1 / 5000, 1 / 3600, 0],
    output: [1 / 2400]
  },
  {
    input: [1 / 5000, 1 / 3600, 1 / 240],
    output: [1 / 1800]
  },
  {
    input: [1 / 3000, 1 / 3600, 1 / 120],
    output: [1 / 1800]
  },
  {
    input: [1 / 6000, 1 / 7200, 1 / 120],
    output: [1 / 3600]
  },
]);

const output = net.run([1 / 3000, 1 / 7200, 1 / 120]); // { white: 0.99, black: 0.002 }
console.log(1 / output);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/brain/0.6.3/brain.min.js"></script>
</head>

<body>

</body>

</html>

Как сделать такую нейронную сеть? Или какую можно придумать формулу?

A: Вы тренируете на  близких к нулю значениях, и получаете близкое к нулю значение.
Нормализуйте все подряд.

const net = new brain.NeuralNetwork({
  hiddenLayers: [10],
  iterations: 20000
});

net.train([{
    input: [1 / 5, 1 / 1, 0],
    output: [1 / 4]
  },
  {
    input: [1 / 5, 1 / 1, 1 / 2],
    output: [1 / 3]
  },
  {
    input: [1 / 3, 1 / 1, 1],
    output: [1 / 3]
  },
  {
    input: [1 / 6, 1 / 2, 1],
    output: [1 / 6]
  },
]);

const output = net.run([1 / 5, 1 / 1, 1 / 2]);
console.log(1 / output); // примерно 3
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/brain/0.6.3/brain.min.js"></script>
</head>

<body>

</body>

</html>


text:
Q: xml data from API has multiple undefined name spaces - how to use xslt to display it in html? I am using a REST api to get XML data from a database and am trying to display it in an html format using xslt. Unfortunately the xml data comes back with a few namespaces that are not defined. I can get the style sheet to work just fine on a local copy of the data if I strip the namespaces or define them. Striping the name spaces feels like a hack and no the correct way to do this.
this is essentially an example of the data I get back:
<root>
<entity:Entity ns1:atrib="foo">
    <g:Value>foo1</g:value>
    <g:Name>fooName</g:Name>
</entity:Entity>

xmlhttprequest methods in JS to get this information and XSLTProcessor to transform it then add it into a . It's not displaying the transformed information and i'm 100% positive it's the namespaces that is causing the issue.
I've googled everything I can think of with no luck. Road blocks like this are almost always due to me missing something fundamental.

A: XSLT will only operate on XML that is well-formed, and it requires all namespaces to be declared. If you want to process this data you should ideally fix it at source; if you can't do that you need to repair it before processing.
There are some XML parsers that allow you to process non-namespace-aware XML, and you could use such a parser as the basis of your repair tool, but this is such an unusual requirement that I'll have to leave you to research how to do that yourself.


text:
Q: Scope of javax.jms.Queue in a managed context I'd like to know what is the expected scope of a javax.jms.Queue in a a java EE managed context.
Is it a good practice to keep reference of Queue instances locally or should I resolve it each time I post a message.
I suppose keeping the reference is better than multiple jndi lookups as you often see code like this in stateless beans :
@Resource(lookup = "jms/QueueName")
private Queue queue;

Anyway I'am currently experiencing problems (XA operation failed Cannot start, session is already doing work in a transaction XidImpl) using cached  Queue instances resolved using javax.jms.Session#createQueue("queueName").
This leads me to another question, is there a difference between resolving the queue using a jndi lookup or using Session#createQueue("queueName");


text:
Q: General formula for a recurrence relation? I was solving a coding question, and found out the following relation to find the number of possible arrangements:
one[1] = two[1] = three[1] = 1
one[i] = two[i-1] + three[i-1]
two[i] = one[i-1] + three[i-1]
three[i] = one[i-1] + two[i-1] + three[i-1]
I could have easily used a for loop to find out the values of the individual arrays till n, but the value of n is of the order 10^9, and I won't be able to iterate from 1 to such a huge number.
For every value of n, I need to output the value of (one[n] + two[n] + three[n]) % 10^9+7 in O(1) time.
Some results:

*

*For n = 1, result = 3

*For n = 2, result = 7

*For n = 3, result = 17

*For n = 4, result = 41

I was not able to find out a general formula for n for the above after spending hours on it. Can someone help me out.
Edit:
n = 1, result(1) = 3
n = 2, result(2) = 7
n = 3, result(3) = result(2)*2 + result(1) = 17
n = 4, result(4) = result(3)*2 + result(2) = 41

So, result(n) = result(n-1)*2 + result(n-2) OR
    T(n) = 2T(n-1) + T(n-2)

A: You can use a matrix to represent the recurrence relation. (I've renamed one, two, three to a, b, c).
(a[n+1]) = ( 0 1 1 ) (a[n])
(b[n+1])   ( 1 0 1 ) (b[n])
(c[n+1])   ( 1 1 1 ) (c[n])

With this representation, it's feasible to compute values for large n, by matrix exponentation (modulo your large number), using exponentation by squaring. That'll give you the result in O(log n) time.
(a[n]) = ( 0 1 1 )^(n-1) (1)
(b[n])   ( 1 0 1 )       (1)
(c[n])   ( 1 1 1 )       (1)

Here's some Python that implements this all from scratch:
# compute a*b mod K where a and b are square matrices of the same size
def mmul(a, b, K):
    n = len(a)
    return [
        [sum(a[i][k] * b[k][j] for k in xrange(n)) % K for j in xrange(n)]
        for i in xrange(n)]

# compute a^n mod K where a is a square matrix
def mpow(a, n, K):
    if n == 0: return [[i == j for i in xrange(len(a))] for j in xrange(len(a))]
    if n % 2: return mmul(mpow(a, n-1, K), a, K)
    a2 = mpow(a, n//2, K)
    return mmul(a2, a2, K)

M = [[0, 1, 1], [1, 0, 1], [1, 1, 1]]

def f(n):
    K = 10**9+7
    return sum(sum(a) for a in mpow(M, n-1, K)) % K

print f(1), f(2), f(3), f(4)
print f(10 ** 9)

Output:
3 7 17 41
999999966

It runs effectively instantly, even for the n=10**9 case.


text:
Q: Object clone in react I am making a simple react application which has some basic inputs like first name, last name etc..,
The state of the inputs are handled in context api like,
context.js
import React, { useState } from "react";

export const FormContext = React.createContext();

export function FormProvider({ children }) {
  const [formValue, setFormValue] = useState({
    basicDetails: {
      firstName: "",
      lastName: "",
      address: {
        city: "",
        zip: ""
      }
    }
  });

  return (
    <FormContext.Provider value={[formValue, setFormValue]}>
      {children}
    </FormContext.Provider>
  );
}

In basic details component fetching the context like,
  const [value, setValue] = React.useContext(FormContext);
  const { basicDetails } = value;

Here to make a copy of initial value of context, I have tried using spread operator like,
  const initialValue = { ...value };

And in handleSubmit function tried to get the initially copied value (i.e..,) initialValue but this is logging the values of latest changes.
Working example:

Requirement:
On click of the form submission, I am in the need to reset the form values with initial context data.
To achieve the resetting of values to initial data only I have tried spread operator { ...value } but I think I am wrong with the approach.
Even JSON.parse(JSON.stringify(value)) doen't work in this case..
Kindly anyone help me to achieve of setting the form value to initial context on submit.

A: if you just want to keep the initialValue always as the first time value, you need to do it like
const initialValue = useMemo(() => value, []);

as your code, the function runs whenever the value changes, so the initialValue changes every time when the value changes

A: The other answer here seems sufficient. You could also save the initial field values in a React ref (const initialValue = React.useRef(value);) and access later as initialValue.current.
In reality you want your context to have more control over the context state. I suggest creating a reset function to include in the context that children can consume.
context.js
Factor out the initial state definition, provide a default context value, and pass the state and callbacks to the context value.
const initialFormState = {
  basicDetails: {
    firstName: "",
    lastName: "",
    address: {
      city: "",
      zip: "123"
    }
  }
};

export const FormContext = React.createContext({
  formValue: initialFormState,
  setFormValue: () => {},
  reset: () => {}
});

export function FormProvider({ children }) {
  const [formValue, setFormValue] = useState(initialFormState);

  const reset = () => setFormValue(initialFormState);

  return (
    <FormContext.Provider
      value={{ value: formValue, setValue: setFormValue, reset }}
    >
      {children}
    </FormContext.Provider>
  );
}

basicDetails.js
Consume and destructure the context value. Change the submit button to be of type="submit" so you can submit the form, and call reset in the submit handler to reset the form state.
const BasicDetails = () => {
  const {value, setValue, reset} = React.useContext(FormContext);
  const { basicDetails } = value;

  const handleInputChange = (event) => {
    const { name, value: val } = event.target;
    setValue((prev) => {
      const basicDetails = {
        ...prev.basicDetails,
        ...(value.basicDetails[name] !== undefined
          ? { [name]: val }
          : { address: { ...value.basicDetails.address, [name]: val } })
      };
      return { ...prev, basicDetails };
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    // Do what you need with the current form values
    console.log("Values", value);

    // Finally reset the form
    e.target.reset();
  };

  return (

 Basic Details

      <form onSubmit={handleSubmit} onReset={reset}>
        First Name:
        <input
          type="text"
          className="form-control"
          id="firstName"
          name="firstName"
          value={basicDetails.firstName}
          onChange={handleInputChange}
        />

        Last Name:
        <input
          type="text"
          className="form-control"
          id="lastName"
          name="lastName"
          value={basicDetails.lastName}
          onChange={handleInputChange}
        />

        City:
        <input
          type="text"
          id="city"
          name="city"
          value={basicDetails.address.city}
          onChange={handleInputChange}
        />

        Zip:
        <input
          type="text"
          className="form-control"
          id="lastName"
          name="zip"
          value={basicDetails.address.zip}
          onChange={handleInputChange}
        />

        <button type="submit">
          Submit
        </button>
      </form>

  );
};


text:
Q: Is there a continuous bijection from open unit interval to open unit disc? I came across a problem asking the reverse of the titular question:

Prove that there is no continuous bijection from $B_1(\mathbb{0}) = \{ (x,y) \in \mathbb{R}^2 : x^2 + y^2 < 1\}$ to $(0,1)$.

This I did as follows:
Suppose for the sake of contradiction that there is such a map $f$. Consider the map $g : B_1(\mathbb{0}) \setminus \{ \mathbb{0} \} \to (0,1) \setminus \{ f(\mathbb{0}) \}$ given by $g(\mathbb{x}) = f(\mathbb{x})$. Then $g$ is also a continuous bijection. The continuous image of a connected set must be connected, and the domain is connected, so the image must be contained in either $(0,f(\mathbb{0}))$ or $(f(\mathbb{0}),1)$, which contradicts surjectivity. Hence, proved.

I then decided to try and prove the claim in the other direction:

Q. Is there a continuous bijection $f : (0,1) \to B_1(\mathbb{0})$?

But, the same idea failed to work.
After removing a point from the domain and its image from the codomain, I have two disjoint intervals on the one hand and a connected space on the other. I tried taking a path in the codomain connecting two points, each lying in the image of the two components of the domain. But since the inverse of $f$ is not assumed to be continuous, I couldn't proceed further.
I'm not sure what to do next. Can someone help me prove or disprove the claim? Thanks!

A: Note that $(0,1)$ is the countable union of the compact sets $\left[\frac1n,1-\frac1n\right]$ ($n>2$). It turns out that the interior of $C_n=f\left(\left[\frac1n,1-\frac1n\right]\right)$ is empty. Suppose otherwise.  Since $\left[\frac1n,1-\frac1n\right]$ is compact and $B_1(0)$ is Hausdorff, $f$ induces a homeomorphism from $\left[\frac1n,1-\frac1n\right]$ onto $C_n$. Therefore, the restriction of $f^{-1}$ to an open ball contained in $C_n$ is a homeomorphism from that open ball in $B_1(0)$ onto a subset of $(0,1)$. That cannot be by the connectedness argument that you mentioned.
So, $f\bigl((0,1)\bigr)$ is a countable union of closed sets with empty interior. Now, the Baire Category Theorem tells us that $f\bigl((0,1)\bigr)$ cannot be $B_1(0)$.


text:
Q: How to fetch the Data from MySQL Db which is greater than Or equal to Today's date I want to fetch the Data from MySQL Db which is greater than Or equal to Today's date, In my Db, the date format is in d/m/Y. And I have nearly 50 records which are greater than today's date but it is retrieving only a few records.
<?php
$currentdate = date('Y-m-d');
$date = str_replace('-', '/', $currentdate);
$tdate= date('d/m/Y', strtotime($date));
// $tdate = date("Y/m/d");
echo $query1 = "SELECT * FROM strategic_batch where batch_sdate ='$tdate'";
?>

Please help me if there is another way. I found the other way but the data is not fetching.
<?php
echo SELECT * FROM strategic_batch WHERE batch_sdate >= CURDATE();
?>

My database records.  Click here to view
when I try to fetch the data I get only this records. Click here to view

A: change 'batch_sdate =' to 'batch_sdate >='
The equal sign will check for exact match. Since you want all records greater than or equals to a particular date, you have to use the >= sign.
This will only work if batch_sdate type is date or datetime as mysql would know how to interpret it. If it is a string, it will not work.


text:
Q: Squid, autossh and acl denial I've got a squid.conf that looks like this:

cache_mgr me@example.com
visible_hostname example.com
httpd_suppress_version_string on
via off

http_port 3128 transparent

acl all src all
acl SSL_ports port 443
acl CONNECT method CONNECT
acl manager proto cache_object
acl localhost src 127.0.0.1/32

http_access allow manager localhost
http_access allow localhost
http_access deny manager
http_access deny CONNECT !SSL_ports
http_access deny all

access_log /var/log/squid/access.log squid

coredump_dir /var/cache/squid

And an autossh tunnel that looks like this:

sudo autossh -C -N -L 3128:example.com:3128 -i /home/me/.ssh/id_rsa -M 20000 me@example.com

I must have some misconfiguration: every http connection over the tunnel is 403'ed at squid. I don't see what I've done wrong. Can someone pull me out of the woods?

A: Try using -L 3128:localhost:3128 instead so you connect to squid on the loopback interface.


text:
Q: 3.999999999 returns 4 When I try the following in R, it returns 4
(i = 3.999999999)
#> [1] 4

Created on 2020-09-02 by the reprex package (v0.3.0)
I was expecting it to return 3.999999999. Can someone explain why is it happening, is it due to floating point error?
Also, in the RStudio IDE, the variable is shown to have value 3.999999999, but 4 on the console.


text:
Q: Setting Application.ErrorCheckingOptions.BackgroundChecking with Spreadsheetgear What's the equivalent of doing Application.ErrorCheckingOptions.BackgroundChecking = False with Spreadsheetgear ?
Thanks

A: SpreadsheetGear does not provide formula error-checking options like this, so there are no equivalent options in SpreadsheetGear's API.
As I understand it, BackgroundChecking is a setting specific to the Excel Application itself and nothing that could be set in the XLS or XLSX/XLSM file format itself.  So even if we did support such a feature, I don't think it would persist within the workbook file and upon opening in Excel later on, if that is what you are trying to do.


text:
Q: I have a red line under the script tag when linking to jquery Trying to link to jquery. My code works but there still is a red line under the script so i dont know what might be wrong
Here is the code
Here is what it says on the  with red line under

A: How to include jQuery from jQuery CDN: https://code.jquery.com/
Latest jQuery 3 version:
<script
    src="https://code.jquery.com/jquery-3.6.0.min.js"
    integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
    crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource
Integrity (SRI) checking. This allows browsers to ensure that
resources hosted on third-party servers have not been tampered with.
Use of SRI is recommended as a best-practice, whenever libraries are
loaded from a third-party source.

I think all is said shortly and clearly and there's no need to add something else.
About integrity attribute of the minified version 3.3.1
<script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>


text:
Q: Existence of a unique root Suppose I would like to maximize $$ (\Phi (m+\frac{1}{2}x)-\Phi (m-\frac{1}{2}x)) \cdot \Phi (g(x)) $$ with respect to $x $. Taking the log and then a derivative, I get the following first order condition: $$
\frac{\frac{1}{2}\phi(m+\frac{1}{2}x)+\frac{1}{2}\phi(m-\frac{1}{2}x)}{\Phi(m+\frac{1}{2}x)-\Phi(m-\frac{1}{2}x)}+\frac{\phi(g(x))}{\Phi(g(x))}\cdot \frac{\partial g(x)}{\partial x} = 0
$$
where $ \phi $ and $ \Phi $ are the standard normal PDF and CDF, respectively, and $ m $ is some constant. Note that $g(x) $ is a continuous and differentiable function, $ g'(x) < 0 $, $ g''(x) > 0 $.
I am interested in the value of $ x $ that solves this. Now, this seems impossible to solve analytically but suppose I would like to prove the existence of a unique solution. Any ideas on how to approach this type of a proof?
Edit:
I forgot to mention, it is OK to restrict the domain of $ x $ to $ x > 0 $.