text:
Q: How can I ensure that my welb application is compatible with latest browser versions I have a web applicaiton written in Perl,C++ and MYSQL how can I ensure that the application is compatible with the latest version of the Browsers that are available in the market.How can I ensure it.

A: I think the more reliable way is to test your application yourself with the latest version of the major browers.


text:
Q: when the searched product does not exist in database then how to show that searched product? In the search engine i have searched one product.that product not in the database but product is moving to add to cart page and store in the database and it will show the message not in stock but in short time will give you the product.
How to do that?

A: there are a magento simple way  via admin configuration , if you enable this, you will have this product
https://bsscommerce.com/blog/how-to-enable-stock-alert-and-display-out-of-stock-product-in-magento-2/
https://www.magestore.com/magento-2-tutorial/magento-2-displaydisable-out-of-stock-product-by-your-own/
if I right understood ...

A: this is easy, first search where you can get a query from search  and then just create product with this name , sku etc. and just use this :
protected $formKey;
protected $cart;
protected $product;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
array $data = []) {
    $this->formKey = $formKey;
    $this->cart = $cart;
    $this->product = $product;
    parent::__construct($context);
}

public function execute()
 {
  $productId =10;
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, //product Id
                'qty'   =>1 //quantity of product
            );
    //Load the product based on productID
    $_product = $this->product->load($productId);
    $this->cart->addProduct($_product, $params);
    $this->cart->save();
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP can I copy a file outside the webfolder? I am using XAMPP
The DocumentRoot is C:/xampp/htdocs
I want to upload files to C:/DATA/SLIDES
Is this possible (without changing Apache's default DocumentRoot).
I'd like to add its a FRESH install of XAMPP.
PHP INI files are the default settings.
What changes do I need to make to PHP.INI to make this work?

A: Yes. PHP does not know or care about Apache's DocumentRoot setting. All that matters are OS-level file/directory permissions and any restrictions you've enabled in php.ini
Example:
$tmp_name = $_FILES['uploaded']['tmp_name'];
$destination = 'c:/DATA/SLIDES/' . $_FILES['uploaded']['name'];
move_uploaded_file($tmp_name, $destination);


text:
Q: Create a bitmap using double values instead of int Android In my code I need create a Bitmap using double values. It´s important use the correct value.
I´m using:
Bitmap bmp = Bitmap.createBitmap(int, int, Bitmap.Config.ARGB_8888);

... When i would need something like:
Bitmap bmp = Bitmap.createBitmap(double, double, Bitmap.Config.ARGB_8888);

Everything I've trying to make the conversion ( possible ? ) Only returns the initial value or integer
How I can use double values when creating the bitmap?

A: Perhaps I misunderstand the question, but bitmaps are rasters of whole pixels.  You can't have fractions of pixels, so you can only have integer numbers of rows and columns in the parameters for createBitmap.
Having said that, you can rescale how the bitmap is drawn using float scale factors applied via Matrix drawBitmap methods, e.g.
Canvas.drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)
Matrix matrix = new android.graphics.Matrix();
matrix.postScale(3.14f, 3.14f);
canvas.drawBitmap(bitmap, matrix, paint);

However, when it comes to rendering this on screen, it will again draw only whole pixels, so you still don't get fractional pixels displayed.

A: Try this, convert double to int:
double myDouble = 10.4;
int myInt = (int) (myDouble);

Using (int) casts the double into an int


text:
Q: Why won't my Ubuntu 12.04 Preseed file work with LVM Here is my preseed file:
d-i partman-auto/disk string /dev/sda
d-i partman-auto/method string lvm
d-i partman-lvm/device_remove_lvm boolean true
d-i partman-lvm/device_remove_lvm_span boolean true
d-i partman-auto/purge_lvm_from_device boolean true
d-i partman-auto-lvm/guided_size string max
d-i partman-md/device_remove_md boolean true
d-i partman-auto-lvm/new_vg_name string vg0
d-i partman/alignment select cylinder
d-i partman-auto/choose_recipe select boot-root
d-i partman-auto/expert_recipe string                           \
    boot-root ::                                            \
            256 8000 256 ext2                               \
                    $primary{ }                             \
                    $bootable{ }                            \
                    method{ format }                        \
                    format{ }                               \
                    use_filesystem{ }                       \
                    filesystem{ ext2 }                      \
                    mountpoint{ /boot } .                   \
             30000 7000 1000000000  ext4                    \
                    $primary{ }                             \
                    $defaultignore{ }                       \
                    method{ lvm }                           \
                    device{ /dev/sda }                      \
                    vg_name{ vg0 } .                        \
             30000 5000 1000000000 ext4                     \
                    $lvmok{ }                               \
                    in_vg{ vg0 }                            \
                    lv_name{ root }                         \
                    method{ format }                        \
                    format{ }                               \
                    use_filesystem{ }                       \
                    filesystem{ ext4 }                      \
                    mountpoint{ / } .                       \
             256 6000 512 swap                              \
                    $lvmok{ }                               \
                    in_vg{ vg0 }                            \
                    lv_name{ swap }                         \
                    method{ swap }                          \
                    format{ } .                             \
d-i partman/default_filesystem string ext4
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/choose_partition select finish
d-i partman-md/confirm boolean true
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm_nooverwrite boolean true

So why does the installer completely ignore it and choose instead to do this:
  --- Logical volume ---
  LV Name                /dev/vg0/root
  VG Name                vg0
  LV UUID                Y8CeAF-SzBy-A3V3-Wvhw-UB0r-r1oE-8sTTuc
  LV Write Access        read/write
  LV Status              available
  # open                 1
  LV Size                1.76 GiB
  Current LE             450
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:0

    --- Logical volume ---
  LV Name                /dev/vg0/swap_1
  VG Name                vg0
  LV UUID                63CL5Q-UDAq-zDtn-VrY0-I638-uZ1D-XSkm8E
  LV Write Access        read/write
  LV Status              available
  # open                 2
  LV Size                8.00 GiB
  Current LE             2048
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:1


text:
Q: How to wait for a linux kernel thread (kthread)to exit?

I have just started programing on Linux kernel threads. I have a problem which I would like to share with you guys. My code is:
void do_big_things(void *data)
{
   // do some really big things
}
struct task_struct *t1;
struct task_struct *t2;

void calling_fucntion()
{
   for(j =0; j < 100; j++)
   {
      t1 = kthread_run(do_big_things, &data1, "thread1");
      t2 = kthread_run(do_big_things, &data2, "thread2");
   }
}

Now as far as I have concluded to this problem (I may be wrong) is that threads t1 and t2 are created and run by kernel and then program goes back at the start of loop to created and run another two threads. As there is no condition to wait for these threads to finish, the kernel creates so many threads hence causing a stack overflow.
All I want is to know that how to make program wait for these two threads to finish and then go back to loop starting another two threads.
Any help would be appreciated.

A: /* Wait for kthread_stop */
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
    schedule();
    set_current_state(TASK_INTERRUPTIBLE);
}

Check this article for more information: "Sleeping in the Kernel".

A: Read about wait queues. This is a good place to look at.
Essentially, you need to keep track of how many threads are running (lock protected counter), and put the creating thread on a wait queue, until all threads are done. The last thread finishing its job can wake up the thread on the wait queue, so that it can repeat the process with another pair of threads.

A: It depends what you're doing, but you may not even want to start your own kernel threads.
You can submit a job to be run on the kernel's global workqueue using schedule_work().
If you do use your own thread you typically write it as a loop around kthread_should_stop(). Then the code which wants the thread to terminate calls kthread_stop(), which tells the thread to stop and then waits for it to stop.

A: YOu can also go for completions.
The linux mass storage driver http://lxr.free-electrons.com/source/drivers/usb/storage/usb.c
 has a very good implementation of kthreads.
   Good Luck.


text:
Q: Replacing all instances of one set of words with another word I wish to replace all instances of Bezier and bezier with B\'{e}zier in my LaTeX document. It's in a masters thesis of 30 pages.
Two questions. How could one achieve the above with a new command or similar approach? And, is it going to be worth the amount of time i save or will it likely cause some issues further down the line?

A: In Texmaker, you can use Replace All. You use hot key Ctrl + R.

A: If you're willing and able to use LuaLaTeX, one could write a Lua function that performs the string replacement job "on the fly".
That said, I'd say it must be easier to do this replacement once and for all in one's text editor.
% !TeX program = lualatex
\documentclass{article}
\usepackage{luacode}
\begin{luacode}
   function bezier ( s )
      return ( string.gsub ( s , "[Bb]ezier", "B\\'ezier" ) )
   end
\end{luacode}
\AtBeginDocument{\directlua{luatexbase.add_to_callback(
   "process_input_buffer", bezier, "bezier" )}}

\begin{document}
aaa bezier bbb Bezier ccc
\end{document}


text:
Q: Fire function on order creation to remove coupons from parent subscription I have the following function, I want it fire every time an order for a subscription is created.
I then want it to remove the store credit coupons from the parent subscription (as renewal orders will contain the coupon).
I'm getting the error:

"PHP message: PHP Fatal error:  Uncaught Error: Call to undefined method WC_Order_Item_Coupon::get_discount_type()".

Where am I going wrong?
Is it passing in the parent subscription item in the right way?
   function remove_store_credit($subscription) {

      $coupons = $subscription->get_items( 'coupon' );
      foreach ( $coupons as $coupon ) {
        if($coupon->get_discount_type() == "smart_coupon"){
          $subscription->remove_coupon( $coupon->get_code() );
        }
      }

    }
    add_action('woocommerce_subscription_payment_complete','remove_store_credit',10,1);

A: The method get_discount_type() belongs to WC_Coupon Class but not to WC_Order_Item_Coupon Class.
So try you need to get an instance object of the WC_Coupon inside the coupon items foreach loop.
function remove_store_credit( $subscription ) {
    // Loop through order coupon items
    foreach ( $subscription->get_items( 'coupon' ) as $item ) {
        $coupon = new WC_Coupon( $item->get_code() ); // get an instance of the WC_Coupon Object

        if( $coupon->get_discount_type() == "smart_coupon" ){
            $subscription->remove_coupon( $item->get_code() );
        }
    }
}
add_action('woocommerce_subscription_payment_complete', 'remove_store_credit', 10, 1);

It should solve this error.


text:
Q: Change color of two text field My static table view has two separate groups of fields:
 Group 1
     Row 1: UITextField - emailOne
     Row 2: UITextField - confirmEmailOne

 Group 2
     Row 3: UITextField - emailTwo
     Row 4: UITextField - confirmEmailTwo

I would want to change a field's color according to the next logic: then I type in a character in emailOne it should immediately check if it is equal to the text of confirmEmailOne field. If it is not - it should spotlight both of fields: emailOne and confirmEmailOne.  I connected email fields to the storyboard:
 @IBOutlet weak var firstEmailOne: UITextField!
 @IBOutlet weak var firstEmailTwo: UITextField!
 @IBOutlet weak var secondEmailOne: UITextField!
 @IBOutlet weak var secondEmailTwo: UITextField!

After, I added this field in array in viewDidLoad and add targets:
 comparableArray[firstEmailOne] = 1
 comparableArray[firstEmailTwo] = 1
 comparableArray[secondEmailOne] = 2
 comparableArray[secondEmailTwo] = 2
 for row in comparableArray {
     row.key.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
 }

And here @objc func:
 @objc func textFieldDidChange(_ textField: UITextField) {

    let groupOfField = comparableArray[textField]
    var checkedArray = [UITextField]()
    for row in comparableArray {
        if row.value == groupOfField {
            checkedArray.append(row.key)
        }
    }
    if checkedArray[0].text == checkedArray[1].text {
          // Error here: the color does not change.
          checkedArray[0].textColor = UIColor.black
          checkedArray[1].textColor = UIColor.black

    } else {
          // Error here: the color does not change.
          checkedArray[0].textColor = UIColor.red
          checkedArray[1].textColor = UIColor.red
    }

The problem: the color does not change on both fields. It always changes in a field with current focus. I tried to execute checkedArray[0].textColor in DispatchQueue.main but it didn't change anyway.


text:
Q: Hbase Schema design I have to design an Hbase table to store users information, this information is targeted for social networking, like: age, sex, education, hobbies, read books, traveled countries ...
NOTE: we could add more information in future,  we dont know all information now.
for example:
name: Olha, age: 25, sex: female, education: bachelor Information technology, education: master computer science, hobby: basket ball, hobby: ping pong, book: gone with the wind, book: Davinci code, language: english, language: french, Country: Germany
The main idea is to be able to do queries like:
return all people who are  female, age: 22 years old, speak: english, speak: french, read the book gone with the wind, like ping pong, like basket ball and German.
so you can add any criteria to the search query.
what is your suggestion about the HBASE table schema ( row key, column family ... ) that optimized this kind of search queries ( taking into consideration that we will add more information in future )
what is the best way to write such query ( scan, get, MapReduce ).
Thank you

A: I would agree with Ian Varley that Solr/Lucene and it's faceted queries and joins allow you to pivot the data in the way you want to see it - however - I also think your question might be a "counting" question or a "membership" question....
It sounds like you are after a list of people who match (N) attributes - the problem you have is that for each attribute you could have millions of user ids?
HBase is a good fit when all you are trying to do is compute intersection/union sizes.. Your key/value pairs can be put into Hbase, and you can "encode" the IDs of the users into either a Bloom Filter and HyperLogLog. Trading speed for accuracy and memory. Likely running map/reduce style jobs hourly/nightly on click-streams of log aggregation of some type.
Others have done this in the advertising space and online space for exactly the type of queries you are running ("find people who like red bull and pop-tarts that live in florida")
References
Contextual Advertising using Apache Hive and Amazon EMR http://aws.amazon.com/articles/2855
Scaling Distributed Counters: http://whynosql.com/scaling-distributed-counters/
Google: Sharding counters https://developers.google.com/appengine/articles/sharding_counters
Distributed Counter Performance in HBase - Part 1 http://palominodb.com/blog/2012/08/24/distributed-counter-performance-hbase-part-1
Facebook's New Realtime Analytics System: HBase To Process 20 Billion Events Per Day http://highscalability.com/blog/2011/3/22/facebooks-new-realtime-analytics-system-hbase-to-process-20.html
Realtime Analytics with Hadoop and HBase - http://www.slideshare.net/larsgeorge/realtime-analytics-with-hadoop-and-hbase
Log Event Processing with HBase http://tellapart.com/log-event-processing-with-hbase
Clickstream Analytics at BazaarVoice http://www.slideshare.net/bazaarvoice_engineering/austin-scales-clickstream-analytics
Realtime Analytics with HBase - http://www.slideshare.net/alexbaranau/realtime-analytics-with-hbase-long-version

A: This isn't a great use of HBase, in the sense that this is exactly the kind of thing that search indexes (like Lucene) are good for.
One normal schema to store users and their information might look a lot like a relational database, in that you'd have 1 row per user, and store all the attributes as columns & values (age=22, language=french, etc). This works well for the extensibility you mention (you don't need to change any schema in order to store new attributes). With this schema, you could look up any one user (and all of their attributes) by the unique user id. That'd be blazingly fast to do, no matter how many users you have.
However, with that schema, if you want to search in the way you describe ("return all users whose age is 22"), every single query is going to end up being a scan of the entire table, because HBase only allows you to access things via their primary key; it does not have secondary indexing of any kind. That will be extremely inefficient (picture having to scan a million rows every time you want to do any single query).
How to fix this? You could "reverse" the ordering of the data and put the values in the row key and then point to all the users with that value. For example, the row key could be "age:22", and then in the columns of the row could be all the userids that are age 22. This is problematic for a lot of reasons, not least of which is that it will be extremely expensive and tricky to make updates. But it would perform well for those specific queries.
The trick? That's exactly what a search index (like Lucene) does, and it does it much better than you could by rolling your own with HBase. That sounds like the tool you want to be using here.
If you must use HBase (as you say, since it's a research project) it might be worth looking into using HBase and Lucene together; google that for pointers.


text:
Q: Why is selenium only iterating 5 times instead of completing the data set I'm using selenium to scrape data on a dynamic website. after picking the elements I set a for loop to append to a list instead of iterating the whole set of data. it iterates only 5x and stops. what could be the cause of this?
import time
from selenium import webdriver
from selenium.webdriver.chrome import service
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

ser= Service("C:\Program Files (x86)\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options,service=ser)
driver.get('https://soundcloud.com/jujubucks')
print(driver.title)

wait = WebDriverWait(driver,30)

wait.until(EC.element_to_be_clickable((By.ID,"onetrust-accept-btn-handler"))).click()

song_contents = driver.find_elements(By.CLASS_NAME, 'soundList__item')

song_list = []

for option in song_contents:
    search = option.find_element(By.XPATH, ".//a[contains(@class,'soundTitle__username')]/span").text
    search_song = option.find_element(By.XPATH, ".//a[contains(@class,'soundTitle__title')]/span").text
    search_date = option.find_element(By.XPATH, ".//time[contains(@class,'relativeTime')]/span").text
    search_plays = option.find_element(By.XPATH, ".//span[contains(@class,'sc-ministats-small')]/span").text

    option ={
        'Artist': search,
        'Song_title': search_song,
        'Date': search_date,
        'Streams': search_plays
    }

    song_list.append(option)

df = pd.DataFrame(song_list)
print(df)

driver.quit()

Output
Stream Juju Bucks music | Listen to songs, albums, playlists for free on SoundCloud
       Artist                              Song_title               Date Streams
0  Juju Bucks  Squad Too Deep Ft. Cool Prince (Outro)  Posted 1 year ago      31
1  Juju Bucks            Tropikana ft. P-Dogg Amazing  Posted 1 year ago      31
2  Juju Bucks              Party Ka Mngani Ft. X-Poll  Posted 1 year ago      31
3  Juju Bucks      Joy Ft. Black Sushi & Gavin Bowden  Posted 1 year ago      31
4  Juju Bucks                      Amazing ft. X-Poll  Posted 1 year ago      31


text:
Q: Сохранить информацию, полученную из анализа N изображений, в другую директорию в отдельный файл для каждой каринки Здравствуйте.
Пишу код, анализирующий изображения. Необходимо извлечь информацию, распознанную на скрине, и сохранить в файл. Для 1 изображения всё работает:
def ocr_space_file(filename, overlay=True, api_key='myAPI', language='eng'):

    payload = {'isOverlayRequired': overlay,
               'apikey': api_key,
               'language': language,
               }
    with open(filename, 'rb') as f:
        r = requests.post('https://api.ocr.space/parse/image',
                          files={filename: f},
                          data=payload,
                          )

    Info = r.content.decode()
    obj = json.loads(Info)

    f = open('Data.txt', 'w')
    for i in obj['ParsedResults']:
        for j in range(0,len(i["TextOverlay"]['Lines'])):
            allInfo = i["TextOverlay"]['Lines'][j]['Words']
            for k in allInfo:
                text = k['WordText']
                coords = [k['Left'],k['Top'],k['Width'],k['Height']]
                f1 = ','.join(map(str, coords))
                f.write(text+ " "+ f1 + '\n' )
    f.close()
    return r.content.decode()

    test_file = ocr_space_file(filename='1my.png', language='eng')

Но затем, когда я пытаюсь так же обработать все изображения в директории, всё почему-то пишется в один файл Data.txt, вместо того, чтобы создавать каждый раз новый.
Закомменчены также остатки от попыток сохранить так, как работало с Images, но для str стало нерелевантно. Пытался ещё так: https://stackoverflow.com/questions/8024248/telling-python-to-save-a-txt-file-to-a-certain-directory-on-windows-and-mac, тоже не пашет.
Подскажите, пожалуйста, что именно я делаю не так. Явно в функции вместо создания идёт перезапись, но я не знаю, как фиксить.
imagePaths = [f for f in glob.glob('cropped_images/*.png')]
save_path = 'Labeled_images/'

def ocr_all_screenshots():

    for pic in imagePaths:

        #src_fname, ext = os.path.splitext(pic)  # split filename and extension
        # construct output filename, basename to remove input directory
        #save_fname = os.path.join(save_path, os.path.basename(src_fname) + '_labeled.png')
        os.chdir(save_path)
        ocr_space_file(pic)

ocr_all_screenshots()

A: надо для каждого нового файла открывать на запись новый файл с другим именем.
что то вроде такого.
def ocr_space_file(filename, overlay=True, api_key='мой API', language='eng'):
    ...обработка json
    for count, i in enumerate(obj['ParsedResults']):
        f = open('Data' +str(count) +'.txt', 'w')
        ...
        f1 = ','.join(map(str, coords))
        f.write(f1 + '\n' )
        f.close()
        return r.content.decode()

что по сути работает примерно так:
 def ocr_space_file(filename, overlay=True, api_key='мой API', language='eng'):
    ...обработка json
    count = 0
    for i in obj['ParsedResults']:
        count +=1
        f = open('Data' + str(count) +'.txt', 'w')
        ...
        f1 = ','.join(map(str, coords))
        f.write(f1 + '\n' )
        f.close()
        return r.content.decode()


text:
Q: How do I add New Line in text box based on value from Combo Box? I have crated Random Password Generator with options to select the length of password (between 8 and 20) and combination of password characters (Upper Case, Lower Case, Numbers and Special Characters).  Works FINE until I ask to generate more then one password.  I like user to be able to chose how many passwords they want to see in the Password box each password in new line.  Need help with to generate numbers of new random password based on value provided (selected) by cmbNPass.Text (ComboBox) into txtPass.Text (with each new password in new line)
Thank you,
Cheers!!!
Chirag Patel

A: Can you be a bit more explicit about what you are programming in?
I'm assuming you are in a microsoft world. Set the multiline property to true and use \r\n.
Adding new line of data to TextBox
By the way, I would not use a password generator if you paid me. Consider this scenario:
Please give your user name______________
Your randomly generated password is !Hell0World#
I now have your login details in clear text.


text:
Q: How to make a collection of two models grouped by date in Laravel 5.5? I have two models Tour and Adventure. I want to make a group of both tours and adventures grouped by date. And display it like this:
July 17
Tour 1 Tour 2 Tour 3
Adventure 1 Adventure 2 Adventure 3
July 16
Tour 1 Tour 2 Tour 3
Adventure 1 Adventure 2 Adventure 3
I know how to make the grouping of a single model. It goes like this:
Tour::orderBy('created_at', 'desc')->take(20)->get()->groupBy(function($item)
          {
            return $item->created_at->format('d-M-y');
          });

How can I join the two models and display them into a single date? With the current code day appear in different collections.
EDIT: Including the table migrations.
public function up()
    {
        Schema::create('tours', function (Blueprint $table) {
          $table->increments('id');

          $table->string('name', 125);
          $table->string('slug')->index();
          $table->text('description')->nullable();
          $table->string('duration')->nullable();
          $table->string('url')->nullable();

          $table->boolean('ended')->default(false)->index();

          $table->timestamps();
        });
        DB::statement('ALTER TABLE tours ADD FULLTEXT search(name)');
    }

The migration for the adventure model is the same as the tour. The two models does not share a relationship between them.

A: I think your looking for the merge() method for merging two collection laravel.com/docs/5.8/collections#method-merge
        //Get all Tours
        $tours= Tour::orderBy('created_at', 'desc')->get();

        //Get all adventures
        $adventures= Adventure::orderBy('created_at', 'desc')->get();

        //Merge both collection into 1 single collection and group according the date
        $dates= $tours->merge($adventures)->groupBy(function($item) {
            return $item->created_at->format('d-M-y');
        });

        return view('someView', compact('dates'));

And then you can loop within the date
        @foreach($dates as $date => $activity)

{{$date}}

                {{$activity}}

        @endforeach

A: Something like this should do the trick:
Tour::join('adventures', DB::raw('date(adventures.created_at)'), '=', DB::raw('date(tours.created_at)'))->get()

Ofcourse you still have options like grouping or ordering before running the ->get(), as the ->get() executed the query and makes your collection :)


text:
Q: How to prove four variable inequality involving sums of cube roots Suppose that $a,b,c,d>0$. Is there a proof that $$ a\sqrt[3]{\frac{1+d}{b^3+abcd}}+b\sqrt[3]{\frac{1+d}{c^3+abcd}}+c\sqrt[3]{\frac{1+d}{a^3+abcd}}\geq 3?$$
I tried for example Jensen, Karamata, Power mean and Minkowski's inequality without success.

A: The inequality can be written as
$$(1+d)\left(\sum_{\text{cyc}}\frac{a}{\sqrt[3]{b^3+abcd}}\right)^3\geq27$$
By the generalized Hölder's inequality
$$\left(\sum_{\text{cyc}}\frac{a}{\sqrt[3]{b(b^2+d\,ca)}}\right)^3\left(\sum_{\text{cyc}}ab\right)\left(\sum_{\text{cyc}}a(b^2+d\,ca)\right)\geq\left(\sum_{\text{cyc}}a\right)^5$$
This reduces the problem to
$$(1+d)\left(\sum_{\text{cyc}}a\right)^5\geq27\left(\sum_{\text{cyc}}ab\right)\left(\sum_{\text{cyc}}a(b^2+d\,ca)\right)$$
But
$$\sum_{\text{cyc}}a(b^2+d\,ca)=\sum_{\text{cyc}}ab^2+d\sum_{\text{cyc}}ca^2=(1+d)\sum_{\text{cyc}}ab^2$$
So it's just
$$\left(\sum_{\text{cyc}}a\right)^5\geq27\left(\sum_{\text{cyc}}ab\right)\left(\sum_{\text{cyc}}ab^2\right)$$
And see Inequality problem $(a+b+c)^5\geq27(ab+bc+ca)(ab^2+bc^2+ca^2)$.


text:
Q: Why do we need SSE when we have http2 bidirectional streaming? This may seem elementary but i didn't find any answers on internet.
My understanding of SSE (server sent events) is that data is sent from server to client on a TCP connection when the data is available on the server, if the connection is closed, a new connection is opened by the client.
In http2 bidirectional streaming we are streaming the data from server when it is available and connection is kept open. This does the same as SSE.
I am not referring to http2 server push.

A: In an HTTP/2 connection, you have individual streams. Those streams (except for the push promises) need to get opened by the client to send a HTTP request, then the server can send an answer.
So you still need a stream to be opened by a client, waiting for the server to send some data.
And then the whole connection might break down (just like a HTTP/1.1 connection, or a plain TCP one), which means the client still needs to open a new connection (and open a stream there).
So HTTP/2 doesn't solve anything here which would make SSE superfluous.
As mentioned by Yami Odymel in a comment, the SSE specification also specifies the exact format of the messages being sent.


text:
Q: "Object Variable or With Block Variable not Set" I am trying to loop through the workbook, take some value and store in a different sheet. Below is my code. Keepp getting VBA Object Variable or With Block Variable not Set Error.
Can someone help me spot where is wrong?
Sub analysis()

Dim i As Integer
Dim ws As Worksheet

For i = 4 To 197
    ws = ActiveWorkbook.Sheets(i)
    ws.Cells(1, 9) = ìstandardevî
    ws.Cells(2, 9) = Application.WorksheetFunction.StDev(Range("D3:D34"))
    ActiveWorkbook.Sheets(4).Cells(2, 1) = ws.Cells(2, 1)
    Sheets(4).Cells(2, 2) = ws.Cells(3, 8)
    Sheets(4).Cells(2, 3) = ws.Cells(2, 9)
Next i

End Sub

A: The first line inside the For/Next loop is this:
ws = ActiveWorkbook.Sheets(i)

Change it to this:
Set ws = ActiveWorkbook.Sheets(i)


text:
Q: Verify PayPal donation between two 3rd parties I'm working on a project where users will be allowed to send donations among each other.
I'd like to integrate it with Paypal instead of reinventing the wheel and building my own donation system, but due to the nature of the system, I will need to verify that a donation of X dollars was sent from person A to person B.
Is this possible with Paypal, or am I out of luck?

A: You will need to look at PayPal Instant Payment Notifications (IPN).
Within the call to PayPal to handle the donation/payment, you can specify the URL for a "Listener", which is a script which will be contacted by PayPal with details on the payment, and can then authenticate that payment against PayPal to ensure that it is accurate/confirmed/not faked.
Within the data passed back to the Listener is the email addresses of the Payer and the Payee, along with the amount paid, fees charged, etc.
If you are acting as an intermediary to the two parties, and so long as the payment are made through the form/site you control, then you should be able to use the IPN to get details of those payments and then use that data however you wish to.


text:
Q: Set limit on sum of elements in Java Array I am trying to create an array where the number of elements is randomized from 3 to 20 where the sum of all the elements is 45. My problem is that I cannot set a limit so the sum does not exceed the value of 45.
Assuming there are 4 elements:
My current output:
15 21 19 26
What I need:
7 11 23 4
public static void startGame(int[] cards) {
    cards = new int[45];
    Random rand = new Random();
    int sum = 45;
    int numStacks = 1;
    numStacks = rand.nextInt(18) + 3;

    for (int i = 0; i < numStacks; i++) {
        cards[i] = (rand.nextInt(45) + 1) - numStacks;
        sum += cards[i];
        System.out.println(cards[i]);
    }
}

A: You can give this implementation a shot:
  public static void startGame() {
    Random rand = new Random();
    int sum = 45;
    int numStacks = 1;
    numStacks = rand.nextInt(18) + 3;
    int[] cards = new int[numStacks];
    int upperBound = 20;
    int lowerBound = 3;
    if(lowerBound*numStacks > sum || upperBound*numStacks < sum) {
        throw new IllegalArgumentException(String.format("Cannot make the stack - improper distribution for numStacks :%d upperBound: %d lowerBound: %d", numStacks, upperBound, lowerBound));
    }
    Arrays.fill(cards, lowerBound);
    for (int i = 0; i < sum; i++)
    {
        boolean keepCalculating = true;
        while(keepCalculating) {
            int randomIndex = rand.nextInt(numStacks);
            int nextValue = cards[randomIndex] + 1;
            if(nextValue <= upperBound) {
                cards[randomIndex] = nextValue;
                keepCalculating = false;
            }
        }
    }
    System.out.printf("numStacks: %d%n", numStacks);
    System.out.printf("cards: %s%n", Arrays.toString(cards));
    System.out.printf("sum: %d%n", Arrays.stream(cards).sum());
}

cards has the result.
Sample run:
numStacks: 7
cards: [7, 7, 5, 8, 5, 2, 11]
sum: 45

In case, it cannot make the stack, here is the exception that it throws.
Exception in thread "main" java.lang.IllegalArgumentException: Cannot make the stack - improper distribution for numStacks :20 upperBound: 20 lowerBound: 3

If you want the program to "always" calculate a stack, then you can try this code:
  public static void startGame() {
    Random rand = new Random();
    int sum = 45;
    int numStacks = 1;
    int maxNumberOfCards = 18;
    int minNumberOfCards = 3;
    int upperBound = 20;
    int lowerBound = 3;
    boolean calculateValidNumberOfStacks = true;
    while(calculateValidNumberOfStacks) {
        int checkVal = rand.nextInt(maxNumberOfCards) + minNumberOfCards;
        if(lowerBound*checkVal < sum && upperBound*checkVal > sum) {
            numStacks = checkVal;
            calculateValidNumberOfStacks = false;
        }
    }
    int[] cards = new int[numStacks];
    Arrays.fill(cards, lowerBound);
    for (int i = 0; i < sum; i++) {
        boolean keepCalculating = true;
        while(keepCalculating) {
            int randomIndex = rand.nextInt(numStacks);
            int nextValue = cards[randomIndex] + 1;
            if(nextValue <= upperBound) {
                cards[randomIndex] = nextValue;
                keepCalculating = false;
            }
        }
    }
    System.out.printf("numStacks: %d%n", numStacks);
    System.out.printf("cards: %s%n", Arrays.toString(cards));
    System.out.printf("sum: %d%n", Arrays.stream(cards).sum());
}


text:
Q: page does not run jquery script on load I have an ASP.net mvc page that executes a jquery script on load.
The script calls an action on a controller and hydrates a dropdown list.
this works on my dev machine but when deployed to the webserver (Win 2k3 box running IIS 6) the page loads but it does not run the script resulting in an empty drop down list.
I have the jquery-1.3.2.js file in the scripts folder, and I have added the mapping to aspnet_isapi.dll on the webserver. is there anything else that i am missing?
this is the part of the page that hydrates the drop down lists that works on my machine but not on the webserver that it is deployed to as you can see the script call the ApplicationSettings controller to get a JSON object that hydrates the drop down list
    <asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <script src="~/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        // Wait for the document to be ready
        $(document).ready(function()
        {
            var selectedApp = $('#selectedApplication').val();
            var selectedMac = $('#selectedMachine').val();

            // Get the list of applications and populate the applications drop down list
            $.getJSON("/ApplicationSettings/Applications/List", function(data)
            {
                var items = "<option>----------- Select Application to Configure ----------</option>";
                $.each(data, function(i, application)
                {
                    var selected = (application.Value == selectedApp) ? 'selected' : '';
                    items += "<option value='" + application.Value + "'" + selected + ">" + application.Text + "</option>";
                });
                $("#Applications").html(items);
            });

            // Get the list of machines where the selected application is installed and populate the machines drop down list
            $("#Applications").change(function()
            {
                if ($("#Applications").attr("value") != "")
                {
                    // Enable the Machines DDL if a valid application is selected
                    $("#Machines").removeAttr("disabled");

                    // Populate the machines DDL with a list of machines where the selected application is installed
                    $.getJSON("/ApplicationSettings/Machines/List/" + $("#Applications > option:selected").attr("value"), function(data)
                    {
                        // Set the first item in the list
                        var items = "<option>---------- Select Machine -----------</option>";

                        // Retrieve the list of machines for th selected application from the database
                        $.each(data, function(i, machine)
                        {
                            var selected = (machine.Value == selectedMac) ? 'selected' : '';
                            items += "<option value='" + machine.Value + "'" + selected + ">" + machine.Text + "</option>";
                        });

                        // Add the items retrieved to the Machines DDL
                        $("#Machines").html(items);

                        if ($("#Machines").attr("value") != "")
                        {
                            $("#btnSearch").removeAttr("disabled");
                        }
                        else
                        {
                            $("#btnSearch").attr("disabled", "disabled");
                        }
                    });
                }
                else
                {
                    // If a valid application has not been selected then disable the Machines DDL
                    $("#Machines").attr("disabled", "disabled");
                    $("#btnSearch").attr("disabled", "disabled");
                }
            });

            if (selectedApp != "")
            {
                $("#Machines").removeAttr("disabled");

                $.getJSON("/ApplicationSettings/Machines/List/" + selectedApp, function(data)
                {
                    var items = "<option>---------- Select Machine -----------</option>";
                    $.each(data, function(i, machine)
                    {
                        var selected = (machine.Value == selectedMac) ? 'selected' : '';
                        items += "<option value='" + machine.Value + "'" + selected + ">" + machine.Text + "</option>";
                    });
                    $("#Machines").html(items);
                });

                if (selectedMac != "")
                {
                    $("#btnSearch").removeAttr("disabled");
                }
                else
                {
                    $("#btnSearch").attr("disabled", "disabled");
                }
            }
            else
            {
                $("#Machines").attr("disabled", "disabled");
                $("#btnSearch").attr("disabled", "disabled");
            }
        });

        function saveSelectedApplication()
        {
            $("#selectedApplication").val("");
            $("#selectedMachine").val("");
            $("#selectedApplication").val($("#Applications").attr("value"));
            if ($("#Applications").attr("value") != "")
            {
                $("#Machines").removeAttr("disabled");
                if ($("#Machines").attr("value") != "")
                {
                    $("#btnSearch").removeAttr("disabled");
                }
                else
                {
                    $("#btnSearch").attr("disabled", "disabled");
                }
            }
            else
            {
                $("#Machines").attr("disabled", "disabled");
                $("#btnSearch").attr("disabled", "disabled");
            }
        }

        function saveSelectedMachine()
        {
            $("#selectedMachine").val("");
            $("#selectedMachine").val($("#Machines").attr("value"));
            if ($("#Machines").attr("value") != "")
            {
                $("#btnSearch").removeAttr("disabled");
            }
            else
            {
                $("#btnSearch").attr("disabled", "disabled");
            }
        }
    </script>

A: I had an issue with script pathing.  i used this extension method to sort it.
public static class HtmlHelperExtensions
    {
        /// <summary>
        /// Scripts the specified HTML to allow for correct pathing of the resource.
        /// </summary>
        /// <param name="html">The HTML.</param>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public static string Script(this HtmlHelper html, string path)
        {
            var filePath = VirtualPathUtility.ToAbsolute(path);
            return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
        }
    }

Then put this in the master page:
<%@ Import Namespace="MYNAMESPACE.Helpers" %>

and then jsut register all scripts like:
<%=Html.Script("~/Scripts/jquery-1.3.2.min.js")%>

Try implemeting the follwoing helper as well:
public static string AbsolutePath(this HtmlHelper html, string path)
{
    return VirtualPathUtility.ToAbsolute(path);
}

and then change your call to
$.getJSON("<%=Html.AbsolutePath("~/ApplicationSettings/Machines/List/")%>"

When your view is rendered the absolute path should be inserted by MVC ViewEngine.

A: You put your code in a "$(document).ready(function() { [YOUR_CODE] });" block? If not, the DOM is probably not yet ready ;)

A: How have you coded the action? This can be important if you run in a virtual directory on the server. If you run locally as http://localhost:xxxx/controller/action, but run remotely as http://mysever/myapp/controller/action, then you need to make sure that you're using Url.Action() to resolve the real path to the action result.


text:
Q: getting error running selenium script.Not opening a session with chrome browing My tests were running fine . suddenly I am seeing this error . It opens multiple sessions but doesn't enter into the test . I used different versions of chromedriver but seeing the same error .below is the error I a seeing
Starting ChromeDriver 87.0.4280.88 (89e2380a3e36c3464b5dd1302349b1382549290d-refs/branch-heads/4280@{#1761}) on port 18242
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
[1607528549.423][WARNING]: FromSockAddr failed on netmask
ChromeDriver was started successfully.
Dec 09, 2020 7:42:31 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Starting ChromeDriver 87.0.4280.88 (89e2380a3e36c3464b5dd1302349b1382549290d-refs/branch-heads/4280@{#1761}) on port 1070
Only local connections are allowed.


text:
Q: Setting 3 textviews in a TableRow with only 2 columns - Android I am trying to make a TableRow in a TableLayout as so:
                _____________________________________
               |  ___________________   ____________ |
               | |TEXTVIEW 1         | |TEXTVIEW 2 | |
               | |                   | |___________| |
               | |                   |  ___________  |
               | |                   | |TEXTVIEW 3 | |
               | |___________________| |___________| |
               |_____________________________________|

Hopefully that makes sense.  I am trying to put 3 TextViews into one TableRow.  The first column will contain a multiline and wide TextView while the second column will contain 2 single-line short TextViews that will be stacked on top of each other.
Is this possible to do?  If not, how would I go about accomplishing this?  Below is the xml code I have started.
<TableLayout
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent" >

    <TableRow
        android:id="@+id/row1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/question"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textStyle="bold"
            android:textSize="8sp" />

        <TextView
            android:id="@+id/timer"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textStyle="bold"
            android:textSize="8sp" />

        <TextView
            android:id="@+id/points"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textStyle="bold"
            android:textSize="8sp" />
    </TableRow>
</TableLayout>

A: <TableLayout>
 <TableRow>
  Multiline Text
  <TableLayout>
   <TableRow>
    Text
   </TableRow>
   <TableRow>
    Text
  </TableRow>
  </TableLayout>
 </TableRow>
</TableLayout>


text:
Q: Return first n element from array in elasticsearch query I have an array field in document named as IP which contains above 10000 ips as element.
for e.g.
IP:["192.168.a:A","192.168.a:B","192.168.a:C","192.168.A:b"...........]

Now i made a search query with some filter and i got the results but the problem is size of result very huge because of above field.
Now I want to fetch only N ips from array let say only 10 order doesn't matters.
So How do i do that...
update:
Apart from IP field there are others fields also and i applied filter on that field not on IP .I want whole document which satisfies filters .I just want to limit the number of elements in single IP fields.(Let me know if there is any other way apart from using script also ).

A: This kind of request could solve your problem :
GET ips/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "truncate_ip": {
      "script": {
        "source": """
        String[] trunc_ip = new String[10];
        for (int i = 0; i < 10; ++i) {
              trunc_ip[i]= params['_source']['IP'][i];
            }
          return trunc_ip;
        """
      }
    }

  }
}

A: You can use scriptedFields for generating a new field from existing fields in Elastic Search. Details added as comments.
GET indexName/_search
{
  "_source": {
    "excludes": "ips"  //<======= Exclude from source the IP field (change the name based on your document)
  },
  "query": {
    "match_all": {} // <========== Define relevant filters
  },
  "script_fields": {
    "limited_ips": { // <========= add a new scipted field
      "script": {
        "source": "params['_source'].ips.stream().limit(2).collect(Collectors.toList())" // <==== Replace 2 with the number of i.ps you want in result.
      }
    }
  }
}

Note:

*

*If you remove _source then only the scripted field will be the part of the result.

*Apart from accessing the value of the field, the rest of the syntax is Java. Change as it suits you.

*Apart from non-analyzed text fields, use doc['fieldName'] to access the field with-in script. It is faster. See the below excerpt from E.S docs :

By far the fastest most efficient way to access a field value from a
script is to use the doc['field_name'] syntax, which retrieves the
field value from doc values. Doc values are a columnar field value
store, enabled by default on all fields except for analyzed text
fields

A: By default ES returns only 10 matching results so I am not sure what is your search query and what exactly you want to restrict

*

*no of elements in single ip field

*No of ip fields matching your search results

Please clarify above and provide your search query to help further.


text:
Q: EF7 Reverse Engineer Existing DB - Timeout error I am executing the following command (executing this inside the asp.net 5 project folder using cmd)
dnx ef dbcontext scaffold "Data Source=SQL2K14;Initial Catalog=movies;Integrated Security=False;User ID=sa;password=pass" EntityFramework.MicrosoftSqlServer --outputDir Models

and get the following error

System.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) period has expired.)

I know for a fact there is nothing wrong with my connection string because i use the same exact connecting string from the same exact machine (inside the asp.net project) using SqlCommand to open the connection and retrieve stuff.  So this would not be a network related issue or connection string at all, its purely to do with the dnx ef dbcontext command
According to http://ef.readthedocs.org/en/latest/getting-started/aspnet5/existing-db.html#reverse-engineer-your-model this is the way to reverse engineer it but I am not sure if they updated it to be done another way as this suggests its complex and it will be simplified but not sure when it will be

A: My commandline which works for comparism is (note connection string format is different)
dnx ef dbcontext scaffold "Server=myserver;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true" EntityFramework.MicrosoftSqlServer --context ReportingDbContext --output-dir Models
Run from the root of my project directory


text:
Q: Trying to run multiple line cmd command inside my asp.net console app raised the following error "StandardIn has not been redirected" I have the following code inside my asp.net console application:-
var processInfo = new ProcessStartInfo("cmd.exe");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;

var process = Process.Start(processInfo);
process.StandardInput.WriteLine("nslookup");
process.StandardInput.WriteLine("set type=mx");
process.StandardInput.WriteLine(domainname);

process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();

process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();

process.WaitForExit();

Console.WriteLine("ExitCode: {0}", process.ExitCode);
process.Close();

where i am trying to run the following commands and get the results:-
nslookup
set type=mx
domainname

but when the code reaches this line process.StandardInput.WriteLine("nslookup"); i got this exception StandardIn has not been redirected.

A: The Error is pretty descriptive: StandardIn has not been redirected
You have redirected stderr and stdout in the lines:
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;

But as the error says you have not redirected StandardIn
You can do that by redirecting stdin with:
processInfo.RedirectStandardInput = true;


text:
Q: Create SD Card for Emulator built from Android source code I have built the Android source for the emulator.  I need to add sdcard to this emualtor.
Following are the commands, I use after the first full build:
source build/envsetup.sh
lunch 1
mmm packages/apps/MyApp/
adb sync
adb remount

However, I am unable to see the emulator in /mnt/sdcard path
What are the steps or commands, I need to use, in order to create an sdcard, when I use the emulator(with the commands above) built from Android source code.
I have been stuck with this issue for sometime. Any help is much appreciated.

A: after executing
$ make -j4

execute
$ mksdcard -l mySdCard 1024M mySdCardFile.img

and then
$ emulator -sdcard mySdCardFile.img

A: You have to go to the Android Virtual Device Manager, create your own or use an existing one and click the "Edit" button.
Then add some MB to your virtual SD Card.

Once started you can go to DDMS tab, then File Transfer tab and SDCard folder ;)


text:
Q: Conflict between lstlisting and twocolumn command Avoiding the usage of the multicols package, what would be the proper way of having a piece of text in a page (doesn't matter if it is a new page, although it would be desired if it is halfway a two-columns page) that spans two columns and a code right there that also spans them?
MWE:
The following MWE shows what I've tried, but an error arises when uncommenting the lstlisting environment (ergo the question title).
\documentclass[journal,twoside]{IEEEtran}
\usepackage{listings}

\begin{document}
This is an empty example page.
\twocolumn[
  \begin{@twocolumnfalse}
This part of the document must span the two columns when it is too large.
%\begin{lstlisting}
%A code listing is needed here.
%\end{lstlisting}
  \end{@twocolumnfalse}
]
This part of the document doesn't span the two columns when it is too large.
\end{document}

Just to let people looking for the error find this page I'll cite the appearing error:
Argument of \lst@next has an extra }.
<inserted text>
                \par
l.13 ]

Additional Questions (if allowed):
The main idea is to meet the initial request, however, if your kindness go beyond sight, you may want to answer to me:

*

*Why the conflict happens?

*How should one solve it?

A: @Troy's comment provides a good reference for why you're experiencing the problem, using the approach you've outlined in your posting.
I interpret your typographic objective (as opposed to the way you've tried to implement the objective) as follows: typeset some material, which includes a lstlisting environment, in single-column mode at the start, i.e., top of a page. If that's the case, you could employ a table* environment. Note that this approach automatically provides for some whitespace being inserted between the single-column and two-column parts of the page.

\documentclass[journal,twoside]{IEEEtran}
\usepackage{listings,lipsum}
\newcommand{\blurb}{This part of the document must span both columns when it is too large.\ }

\begin{document}
This starts off a non-empty page

\begin{table*} % this will be placed at the top of the *next* page
\blurb\blurb\blurb

\begin{lstlisting}
A code listing is needed here.
A code listing is needed here.
\end{lstlisting}

\blurb\blurb\blurb
\end{table*} % note that we don't provide a "\caption" statement.

\lipsum[1-20] % filler text for pages 1 and 2
\end{document}


text:
Q: Find and replace string with regex This may be a newbie regex question (still learning), but I'm trying to uncapitalize all the objects in my code (but not classes); i.e for the code snippet:
Bishop_Piece Bishop;

Bishop.move()...

I want it to instead be:
Bishop_Piece bishop;

bishop.move()...

What I tried:
find . -type f | xargs sed -i  's/Bishop[;.]/bishop./g'

However this results in:
Bishop_Piece bishop.

bishop.move()...

Basically, I want the character after what I'm searching for (i.e Bishop), to be 'kept' (be it ; or .), which is what explains the bishop./g.

A: You can use
find . -type f | xargs sed -i 's/Bishop\([;.]\)/bishop\1/g'

Note that the \([;.]\) here defines a capturing group whose value is referred to with \1 from the replacement pattern.
The (...) parentheses are escaped since this is a POSIX BRE compliant regular expression.
See the online demo:
s='Bishop_Piece bishop;
bishop.move()...'
sed 's/Bishop\([;.]\)/bishop\1/g' <<< "$s"

Output:
Bishop_Piece bishop;
bishop.move()...


text:
Q: ServiceModel.DuplexClientBase missing in .net portable subset I've tried to make a wcf service referecne to a net.tcp duplex from a portable class library (VS2012). The generated code refers to some classes of System.ServiceModel wich are not included in the .net portable subset (for eg: System.ServiceModel.DuplexClientBase).
Is there a way to get wcf duplex channel work in a portable class library? or is it just not supported by now?
thanks!


text:
Q: Unexpected argument error in sns.kdeplot() I'm working in a project in which I need to create a KDE plot. Here's my code:
sns.kdeplot(x = 'total_attempts', hue = 'status', fill = True, data = toplot)
Where toplot is a pd.DataFrame with two columns, total_attempts (integer) and status (boolean).
However, I receive the following error:
_bivariate_kdeplot() got multiple values for argument 'x'
This error normally comes when a both a positional and a keyword argument are specified in the calling of the function. But I don't see that this is the case in my code.
Any idea on why this is happening? Thanks.

A: As Alex pointed out in the comments, upgrading seaborn >= 0.11 fixed the problem.


text:
Q: How do I use a JButton in more than 1 method? So I've been coding my TicTacToe project as a side project for some time now, and have hit another obstacle. I want to use a JButton in more than one method, but I don't know how to go about doing that. Here's my code till now.
`
import java.util.Random ;
import java.util.Scanner ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import java.util.InputMismatchException ;
import java.awt.BorderLayout ;
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.JTextArea ;
import javax.swing.JButton ;
import javax.swing.JRadioButton ;

class TicTacToe
 {
    public int count = 1 ;
    public String letter;
    public boolean b1bool = true ;
    public boolean b2bool = true ;
    public boolean b3bool = true ;
    public boolean b4bool = true ;
    public boolean b5bool = true ;
    public boolean b6bool = true ;
    public boolean b7bool = true ;
    public boolean b8bool = true ;
    public boolean b9bool = true ;
     public boolean win = false ;

    public void main(String []args)
    {

        popupintroscreen();

    }
    public void popupintroscreen()
    {

        JTextArea introtext = new JTextArea("Welcome to TicTacToe v1.0. This is a Simple Tic Tac Toe app coded  by Abhishek Pisharody. Press the button below to play, or view the        instructions first, if you prefer. We hope you enjoy playing. Thank you.");
        introtext.setEditable(false);
        introtext.setLineWrap(true);

        JButton startgamebutton = new JButton("Start Game");
        startgamebutton.setToolTipText("Start a game of Tic-Tac-Toe");
        startgamebutton.addActionListener(new ActionListener()
        {
           @Override
           public void actionPerformed(ActionEvent gamestart)
           {
            JOptionPane.showMessageDialog(null, "Loading.....done!");
            tictactoe();
           }
        });

        JButton showinstructions = new JButton("Show Instructions");
        showinstructions.setToolTipText("View game instructions. Worth checking out even if you know how to play.");
        showinstructions.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent displayinstructionsprompt)
            {
              JOptionPane.showMessageDialog(null, "Nothing to see here..yet..off you go!");
            }
        });

        JButton highscoresbutton = new JButton("High Scores");
        highscoresbutton.setToolTipText("Show high scores for the game");
        highscoresbutton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent highscoresbuttonclicked)
            {
                JOptionPane.showMessageDialog(null,"Not coded yet!");
            }
        });

        JButton quitgamebutton = new JButton("Quit Game");
        quitgamebutton.setToolTipText("Quit the game. But why? :(");
        quitgamebutton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent onquitgamebuttonclick)
            {
                JOptionPane.showConfirmDialog(null, "Really quit?");
                System.exit(0);
            }
        });

        JPanel gamebuttonsholder = new JPanel(new BorderLayout());
        gamebuttonsholder.setSize(400,100);
        gamebuttonsholder.add(introtext,BorderLayout.PAGE_START);
        gamebuttonsholder.add(startgamebutton,BorderLayout.PAGE_END);
        gamebuttonsholder.add(showinstructions,BorderLayout.LINE_START);
        gamebuttonsholder.add(highscoresbutton,BorderLayout.CENTER);
        gamebuttonsholder.add(quitgamebutton,BorderLayout.LINE_END);

        JFrame introscreen = new JFrame("Tic Tac Toe");
        introscreen.setSize(400,400);
        introscreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        introscreen.setLocationRelativeTo(null);
        introscreen.add(gamebuttonsholder);
        introscreen.setVisible(true);
    }

        public int tictactoe()
        {

            final JButton b1 = new JButton("");
            b1.setToolTipText("Mark this box");
            b1.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                   if (b1bool == true){ count++;
                    if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                b1.setText(letter);
                b1bool = false ;
                calculatevictory();
                processturn();

            }}});

            final JButton b2 = new JButton("");
            b2.setToolTipText("Mark this box");
            b2.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                   if (b2bool == true){ count++;
                    if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                b2.setText(letter);
                b2bool = false ;
                calculatevictory();
                processturn();
            }}
                });

            final JButton b3 = new JButton("");
            b3.setToolTipText("Mark this box");
            b3.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                     if(b3bool == true){
                         count++;
                    if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                b3.setText(letter);
                b3bool = false ;
                calculatevictory();
                processturn();
            }}

            });

            final JButton b4 = new JButton("");
            b4.setToolTipText("Mark this box");
            b4.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                    if(b4bool == true){

                    count++;
                        if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                    b4.setText(letter);
                    b4bool = false ;
                    calculatevictory();
                    processturn();
                }}
            });

            final JButton b5 = new JButton("");
            b5.setToolTipText("Mark this box");
            b5.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                    if (b5bool == true){
                        count++;
                        if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                    b5.setText(letter);
                    b5bool = false ;
                    calculatevictory();
                    processturn();
                }}
            });

            final JButton b6 = new JButton("");
            b6.setToolTipText("Mark this box");
            b6.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                    if (b6bool == true){
                        count++;
                        if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                    b6.setText(letter);
                    b6bool = false ;
                    calculatevictory();
                    processturn();
                }}
            });

            final JButton b7 = new JButton("");
            b7.setToolTipText("Mark this box");
            b7.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                    if (b7bool == true){
                        count++;
                        if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                    b7.setText(letter);
                    b7bool = false ;
                    calculatevictory();
                    processturn();
                }}
            });

            final JButton b8 = new JButton("");
            b8.setToolTipText("Mark this box");
            b8.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                    if(b8bool == true){
                        count++;
                        if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                    b8.setText(letter);
                    b8bool = false ;
                    calculatevictory();
                    processturn();
                }}
            });

            final JButton b9 = new JButton("");
            b9.setToolTipText("Mark this box");
            b9.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent onclickb1)
                {
                   if(b9bool == true){
                       count++;
                        if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
                    {
                      letter = "O" ;

                }
                else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
                {
                    letter = "X" ;

                }
                    b9.setText(letter);
                    b9bool = false ;
                    calculatevictory();
                    processturn();
                }}
            });

            GridLayout gamescreenlayout = new GridLayout(3,3);

            JPanel gamescreencontent = new JPanel();
            gamescreencontent.setLayout(gamescreenlayout);
            gamescreencontent.setSize(400,400);
            gamescreencontent.add(b1);
            gamescreencontent.add(b2);
            gamescreencontent.add(b3);
            gamescreencontent.add(b4);
            gamescreencontent.add(b5);
            gamescreencontent.add(b5);
            gamescreencontent.add(b6);
            gamescreencontent.add(b7);
            gamescreencontent.add(b8);
            gamescreencontent.add(b9);

            JFrame gamescreen = new JFrame("Tic-Tac-Toe");
            gamescreen.setSize(400,400) ;
            gamescreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            gamescreen.setLocationRelativeTo(null);
            gamescreen.add(gamescreencontent);
            gamescreen.setVisible(true);

            int sexyshit = 1 ;
            return sexyshit ;
        }

        public void calculatevictory(){
            if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
            {
                win = true ;
            }
            else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
            {
                win = true ;
            }
            else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
            {
                win = true ;
            }
            else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
            {
                win = true ;
            }
            else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
            {
                win = true ;
            }
            else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
            {
                win = true ;
            }
            else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
            {
                win = true ;
            }
            else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
            {
                win = true ;
            }
            else
            {
                win = false ;
            }
        }

            public void processturn()
            {
            if (win == true)
            {
                JOptionPane.showMessageDialog(null, letter + "wins!");
            }
            else if ( count == 9 && win == false)
            {
                JOptionPane.showMessageDialog(null, "Tie Game");
            }
        }

    }`

When I try to run this, it tells me that the compiler couldn't find symbol b1. Would I have to make the buttons public(if so, how?), or use Inheritance? If it's the latter, please explain in simple terms, because I really haven't begun to learn inheritance yet.
Thank you in advance.

A: Declare your JButton outside the method, in the same place as where you are declaring your int, String, and booleans. In other words, something like
class TicTacToe
{
    //...
    JButton b1;
    //...
    public int TicTacToe()
    {
        b1 = new JButton(); //note that you don't need the ""
    }
}

Incidentally, I'd recommend using arrays and looping through them rather than having 9 of everything and having to copy-paste code lots of times.


text:
Q: The Milnor Conjecture on the Unknotting Number of a Torus Knot Let $f \colon (\mathbb{C}^{n},\mathbf{0}) \to (\mathbb{C},0)$ be a complex analytic function with isolated critical point at the origin. Define the singular hypersurface $V_{f, \kappa} = f^{-1}(\kappa)$ for small $\kappa > 0$. Let $\pi \colon \tilde{V} \to V$ be a resolution of $V = V_{f,0}$, and let $p_{g} = \dim H^{n-2}(\tilde{V}, \mathcal{O})$ denote the corresponding geometric genus of $V$, which is independent of the chosen resolution. (This is the same geometric genus in the Yau-Durfee Theorem: $\mu \geq n! \ p_{g}$ for $n > 2$, See Y93 or Y06.)
Define the map $\varphi_{f} = f/\| f \| \colon S_{\epsilon}^{2n-1} \setminus V_{f, \kappa} \to S^{1}$, where $\epsilon > 0$ is sufficiently small. The intersection of $V_{\kappa}$ with a small sphere $S_{\epsilon}^{2n-1}$ is an algebraic link.
Consider the Brieskorn-Pham polynomial $f = \sum_{i = 1}^{n} z_{i}^{a_{i}}$ with $a_{i} \geq 2$. In particular, for $f = z_{1}^{p} + z_{2}^{q}$, the intersection above is a torus knot $T_{p,q}$ if $p$ and $q$ are coprime. In 1968, Milnor conjectured that the unknotting number $u(T_{p,q})$ is related to the dimension of the local algebra $A_{f} = \mathbb{C}[x,y] / \langle x^{p-1}, y^{q-1} \rangle$, which is also the rank of the middle homology group $H_{1}(F_{f,0}; \mathbb{Z})$ of the corresponding fiber $F_{f,0} = \varphi_{f}^{-1}(e^{i \theta})$.
In 1928, Brauner proved $\mu(f) = \text{rank} \ H_{1}(F_{f,0}, \mathbb{Z}) = (p-1)(q-1)$ for $f = x^{p} + y^{q}$. In 1994, Kronheimer and Mrowka proved the Thom conjecture, and as a consequence, the Milnor conjecture followed.
(Edited) Question(s): Is the genus $g$ of the fiber $F_{f,0}$ related to the geometric genus $p_{g}$ of $V$ for $n > 2$? Is there a geometric genus-like object for $n = 2$? If so, how might it relate to invariants of the torus knots?
(Also posted on MO.)
Thanks!


text:
Q: po translation files: what are automatic comments for? When I translate some stuff, sometimes there are strings that are put in comments and stay after everything else. What are those comments for?
For example:
#~ msgid ""
#~ "You tried to register but your email is already known.\n"
#~ "To try again to login, click on the following link:\n"
#~ "{}{}"
#~ msgstr ""
#~ "Vous avez essayé de vous enregistrer, mais votre email est déjà connu."
#~ "Pour vous connecter, cliquez sur le lien suivant :\n"
#~ "{}{}"

What is the ~ for?
Sometime there's a pipe like this:
#~| msgid "Show your activity"
#~ msgid "your activities"
#~ msgstr "Montrer mon activité"

What is the | for?

A: #~ comments are obsolete strings. When a string has translation but does not appear in the current template (.pot), the msgmerge tool will comment it out with #~, but leave it in.
If the string appears again in future, it will uncomment the translation again, so you won't have to retranslate it. It will also use thus commented entries as source for suggestions via fuzzy matching.

The #~| is a result of commenting out a #| comment. A #| comment is the original text when creating a suggestion via fuzzy matching. For example if the catalogue has
msgid "Open"
msgstr "Otevři"

and the template has
msgid "Open!"
msgstr ""

then msgmerge will create:
#,fuzzy
#| msgid "Open"
msgid "Open!"
msgstr "Otevři"

The po editors like poedit, pootle or weblate should remove the #| comment when the string is fixed and fuzzy flag removed. But if somebody edits the .po in a text editor, they may erroneously leave it in.


text:
Q: How to consume an API via OData protocol in .Net Core? I'm trying to consume a public endpoint to get a list of objects in json. However, the API implements the OData protocol, and it always returns an invalid request. I think it's due to the way of calling this API. What should I adapt to my code to consume this API?
This is my code:
[HttpGet]
public async Task<List<TaxaSelic>> ObterTaxaSelic()
{
    List<TaxaSelic> taxasSelic = new List<TaxaSelic>();
    string apiResponse = string.Empty;

    Uri uri = new Uri("https://api.bcb.gov.br/dados/serie/bcdata.sgs.4390/dados/ultimos/10/");

    using (HttpClient httpClient = new HttpClient())
    {
        using (HttpResponseMessage response = await httpClient.GetAsync(uri))
        {
            if (response.IsSuccessStatusCode)
                apiResponse = await response.Content.ReadAsStringAsync();

            taxasSelic = JsonConvert.DeserializeObject<List<TaxaSelic>>(apiResponse);
        }
    }

    return taxasSelic;
}

and...
public class TaxaSelic : Entity
{
    [JsonProperty("data")]
    public string Data { get; set; }

    [JsonProperty("valor")]
    public string Valor { get; set; }
}

A: The website's server in some way checks the caller's user-agent. When I set a user-agent as following, it works like a charm.
using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Linux; Android 9; SM-G973U Build/PPR1.180610.011) " +
                                                               "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile " +
                                                               "Safari/537.36");
            using (HttpResponseMessage response = await httpClient.GetAsync(uri))
            {

 ... rest of your code
 .
 .
 .

Example output I got,
HTTP/1.1 200 OK
ETag: W/"173-8/kblablablaMdY/QZ9jQ"
Access-Control-Allow-Origin: *
Date: Mon, 18 Jul 2022 11:48:19 GMT
Set-Cookie: cookie_p=!ptxb5qIxn7aCp0blablablablaTOUoak=; path=/; Httponly; Secure
Set-Cookie: TS01799025=01blablablacae675f; Path=/
Strict-Transport-Security: max-age=16070400; includeSubDomains
Content-Type: application/json; charset=utf-8
Content-Length: 371

[{"data":"01/10/2021","valor":"0.49"},{"data":"01/11/2021","valor":"0.59"},{"data":"01/12/2021","valor":"0.77"},{"data":"01/01/2022","valor":"0.73"},{"data":"01/02/2022","valor":"0.76"},{"data":"01/03/2022","valor":"0.93"},{"data":"01/04/2022","valor":"0.83"},{"data":"01/05/2022","valor":"1.03"},{"data":"01/06/2022","valor":"1.02"},{"data":"01/07/2022","valor":"0.54"}]


text:
Q: Why spring dependency doesn't viewed? I have installed STS, created simple console maven application. After I would like add springframework, but seems that master of adding dependency doesn't find nothing.
Should I fix some settings about Maven?
Thanks.

A: I would rather search http://search.maven.org and paste the XML by hand.
Think how can your Eclipse client find your dependencies among the HUGE amount of artifacts in the server? m2e downloads an index file (which may not always be available) from the Maven repo. This file is very large and it is much less efficient than using a server-side search engine like http://search.maven.org .


text:
Q: Hiding Iphone Keyboard on loss of focus Using what I've read online people say put a button in the background of the app then when clicked that button handles closing the keyboard. However reading some other people they say resign first repsonder for the text field - does that mean the textfield has taken control of the keyboard and wont release it until specifically told to?
My .h has:
@interface SearchItems : UIViewController {

    IBOutlet UIButton *btnKeyboard;
    IBOutlet UITextField *txtWhat;
    IBOutlet UITextField *txtWhere;

}

@property (nonatomic, retain) IBOutlet UIButton *btnKeyboard;
@property (nonatomic, retain) IBOutlet UITextField *txtWhat;
@property (nonatomic, retain) IBOutlet UITextField *txtWhere;

-(IBAction)closeKeyboard;

@end

The .m (cut down)
@synthesize btnKeyboard, txtWhat, txtWhere;

-(IBAction)closeKeyboard {

    [txtWhere resignFirstResponder];
    [txtWhat resignFirstResponder];

}

Which isn't working, any ideas?
Thanks
Tom

A: Try using the delegate methods to resignResponder:
 - (BOOL)textFieldShouldReturn:(UITextField *)textField
 {
    [textField resignFirstResponder];
    return YES;
}

Apart from this one you can also use this delegate method:
 - (void)textFieldDidEndEditing:(UITextField *)textField
 {
     [textField resignFirstResponder];
 }

These two methods mainly should be able to solve your keyboard hiding problem rather than using the background button technique.


text:
Q: Explanation of pandas DataFrame.assign() behaviour using lambda import pandas as pd
import numpy as np

np.random.seed(99)
rows = 10
df = pd.DataFrame ({'A' : np.random.choice(range(0, 2), rows, replace = True),
                    'B' : np.random.choice(range(0, 2), rows, replace = True)})

def get_C1(row):
    return row.A + row.B

def get_C2(row):
    return 'X' if row.A + row.B == 0 else 'Y'

def get_C3(row):
    is_zero = row.A + row.B
    return "X" if is_zero else "Y"

df = df.assign(C = lambda row: get_C3(row))

Why the get_C2 and get_C3 functions return an error?

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: You're thinking that df.assign, when passed a function, behaves like df.apply with axis=1, which calls the function for each row.
That's incorrect.
Per the docs for df.assign

Where the value is a callable, evaluated on df

That means that the function you pass to assign is called on the whole dataframe instead of each individual row.

So, in your function get_C3, the row parameter is not a row at all. It's a whole dataframe (and should be renamed to df or something else) and so row.A and row.B are two whole columns, rather than single cell values.
Thus, is_zero is a whole column as well, and ... if is_zero ... will not work.


text:
Q: ContainsKey returns unit and not bool? It's odd to me that the following code throws a compile time error. I'm not sure why ContainsKey is returning unit. The documentation says it returns bool.
open System.Collections.Generic

let mydict = new Dictionary<string,'a>()

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] = newkey

error FS0001: This expression was expected to have type
      'bool'     but here has type
      'unit'

Am I missing something here?

A: if is an expression so both branches must have the same type. If the else branch is not specified an empty one of type unit is inserted. This means your then branch must also have type unit. However mydict.["mykey"] = newkey has type bool. If you want to insert a new value for mykey you should use <- instead of =:
if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] <- newkey


text:
Q: Maximum given a list of integers, and any combination of the operators $( ) ,+, *$ Given a list of integers, insert the operations $( ) +$ and $*$ to yield the maximum value.
Examples:
$2$ $1$ $1$ $2$ is maximized with $(2 + 1)  * (2 + 1) = 9,$ and $1$ $1$ $1$ $1$ $1$ $1$ is maximized with $(1 + 1 + 1) * (1 + 1 + 1) = 9.$
Is there an algorithm that works every time to solve this problem?

A: First, we will proof an optimal constructive method, next proof that constructive methods gives the best solution.
a)
Let $a=a_0a_1a_2\cdots$ the optimal solution found until now (where $a_i$ can be an addition of numbers). Let $x=a_0$ and $y=a_1a_2\cdots$, $a=xy$.
Now, we must include number $z$ in the solution. It can be included as new factor $xyz$ or as an addition to one of the already existing ones $(x+z)y$. The inequality to consider is:
$xyz \ge (x+z)y$
that concludes that:
if $z \ge 2$ then $xyz \ge (x+z)y$
if $z = 1$ then $xyz \lt (x+z)y$
in conclusion, new number must included multiplying all expression except if number is 1.
b) In case of new number equal to 1, add it to which existing factor?. The inequality is now:
$(x+1)y \ge x(y+1)$
with solution $y \ge x$, thus, add 1 to the smaller factor.
(initial case with $a=a_0$ is straightforward).
c) sequence to use in the constructive method.
Assume we must include two numbers $z_1$ and $z_2$. If both are greater than 1, the method will include both multiplying $a$, thus, same result if be include $z_1$ and next $z_2$ than if we include $z_2$ next $z_1$.
If both numbers are equal to one, obviously sequence is the same.
Finally, if we must include 1 and $z>1$, the sequences to consider are (assuming $x<y$ and $z<x$, $z<y$, remainder cases are straightforward):
$(x+1)yz \ge xy(z+1)$
with no solution, thus, include first $z$ next the 1.


text:
Q: Setting default value of a calculated column to a user or group How can I set the default value of a calculated column as a user / group name. Basically I want to create a view with that column included and where column name = [Me] so that if I/logged-in user is a part of group, I can see object in library.

A: Calculated columns don't have default values because they are derived from values existing in another field.  Person/group fields cannot have a default value so you'd have to have some script to populate it when the form is filled out.
I'd probably just create a view in the list with a filter where Created by equals [Me] and add additioanl filters that restrict data based on other columns to achive a similar result.


text:
Q: Self-contained microservices with Docker I'm trying to setup a project built up of several microservices orchestrated with Docker. Here is the simplified schema of my project:
- Main-project
  - Dockerfile
  - docker-compose.yml (bundles Microservice1 and Microservice2)

- Microservice1
  - Dockerfile

- Microservice2
  - Dockerfile

Now, each component has many dependencies such as RabbitMQ managed by the docker-compose.yml file. I manage to make the whole project run on Docker by using the compose file.
However, I'm having problems in running the individual components by itself. The problem is that Microservice1 depends on rabbitMQ but it does not have a compose file to manage this dependency, and the same goes for all other components. So when I try to run any individual component by itself (for unit-tests, for instances) I have a problem of missing dependencies.
Should I add all the dependencies also on the Dockerfile of each component?
Should I have one docker-compose file per component?
What are the best practices to setup a system like this?
Thanks a lot!
Update:
As an important note, I forgot to mention that each microservice has its own repo.

A: It's true that a microservice must be self contained, which means it can be deployed and scale without other microservices. But usually a dbms or message broker or caching system are needed for service to start running. That's why most of CI system such as Gitlab CI or Drone or Jenkins have feature to start other services before executing unit test. If you are not using any CI then it would be sensible to have compose file per component.


text:
Q: How to print sql result without executing the sql statement? I have a SQL statement which will delete certain row according to their ID and area. Can I system.out.println this statement WITHOUT executing the statement itself? I just want to be sure that what I am deleting is correct.
Here is a sample statement:
PreparedStatement ps = db.getPreparedStatement("delete from tbl_traininglinks where training_title IN ('"+vwarnid+"')");
    int i=ps.executeUpdate();

A: I've noticed this question is already answered in the comments but I would like to add something which may be relevant, depending on how your application is used.
If you use SELECT and wait for user verification before you use DELETE, the data in the table might be changed in the meantime and you can end up deleting rows your didn't get in the SELECT statement and that the user did not verify for deletion. This might happen even if you just display the results of the SELECT statement and then delete immediately, but the chance is smaller.
Instead, I recommend you use SELECT and after the user verifies the deletion build a DELETE SQL command that uses the keys of the rows you received in the SELECT statement. This way you delete only what the user verified for deletion.

A: There is a feature called
ROLLBACK

if you are using transactional database.


text:
Q: Problems with R officedown when used in an automated task I have a script that creates a .docx document with all the nice formatting I have configured using officedown ("xxx.Rmd"). It runs perfectly when I execute it and produces the expected result.
This is the script:
setwd("xxx")

rmarkdown::render(
  input = "xxx.Rmd",
  output_file = "xxx.docx",
  envir = parent.frame()
)

However when I automate its execution with taskscheduleR, the output is not nice. The Table of Contents, for instance, becomes this (see below), and I loose all figures and page breaks I configured.
<w:p><w:pPr/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:rPr/><w:fldChar w:fldCharType="begin" w:dirty="true"/></w:r><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:rPr/><w:instrText xml:space="preserve" w:dirty="true">TOC \o "1-3" \h \z \u</w:instrText></w:r><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:rPr/><w:fldChar w:fldCharType="end" w:dirty="true"/></w:r></w:p>

Is there something I can do to use scheduleR and officedown and get nice outputs?


text:
Q: laravel Asset() function break down after deployment I developeded a Laravel web app, which works fine and great on local machine but
after going in production on a shared hosting server i have some issues displaying the logo and the website images using the asset() helper function.
However the css and js are accessible and works fine (also using the asset function).
I've deployed the App following the steps bellow:

*

*I created a directory called repositories outside the public_html (the root document of mydomain.com)  and i copied inside it directory soukelafalah (contining all the files of my laravel project)

*I moved the laravel public directory files into the public_html directory

*I edited the index.php in public_html as follow:
require DIR.'./../repositories/SoukElfalah/vendor/autoload.php';
$app = require_once__DIR__.'/../repositories/SoukElfalah/bootstrap/app.php';

*I run php artisan storage:link and the link is succufully created

*I had  run also:
ln -s /home/dtruxpgw/repositories/SoukElfalah/storage/app/public /home/dtruxpgw/public_html/storage

*The route and the css is working fine but the logo and the images are not displayed and shows a 404 error as shown in the image below.
So please, can any one point what i am missing?
And when i put  asset('/storage/images/thumbs/'.$img_name)}}" am i pointing to the storage directory in the public_html or in the one in the public folder of my laravel app directory.
Thank you in advance.


text:
Q: HTML doesn't get rendered, why does it happen? On a PHP+MySQL project, there's a string of text coming from a MySQL table that contains HTML tags but those tags never get rendered by Google Chrome or any browser I tried yet:

You can see that the HTML (p, strong) aren't getting interpreted by the browser.
So the result is:

EDIT: HTML/PHP

    <?php echo $this->winery['description']; ?>

$this->winery being the array result of the SQL Select.
EDIT 2: I'm the dumbest man in the world, the source contains entities. So the new question is: How do I force entities to be interpreted?
Real source:

Any suggestions? Thanks!

A: You are probably using innerText or textContent to set the content of your div, which just replace the child nodes of the div with a single text node.
Use innerHTML instead, to have the browser parse the HTML and create the appropriate DOM nodes.

A: The answer provided by @Paulpro is correct.
Also note that if you are using jQuery, be sure to use the .html() method instead of .text() method:
$('#your_element').html('
This works!
');

$('#another_element').text('
Wrong; you will see the
 in the output');


text:
Q: List, str and int help in python I have list of number like this:
146, 168
174, 196
230, 252
258, 280
286, 308
314, 336
342, 364
370, 392
the first number represent value i got from my code(start number) and the second number on the line after comma is end value. What i try to do is use both of start and end value to print the string.
here is part of my code:
root = etree.parse(f)

for lcn in root.xpath("/protein/match[@dbname='DB']/lcn"):
    start = lcn.get("start")
    end = lcn.get("end")
    print "%s, %s" % (start, end,)
    if start <= end:
        start = int(start+1)
        print start
    if start <= end:

      print list(start)

      start = int(start+1)

I got the error message saying that i can't concatenate 'str' and 'int' objects.. Side note: on the list index has one alphabet letter in it. So my goal is to print out those letter on one line per each start and end value. For example
ACTGAGCAG and possibly import to another output file. Could you please help me with this?
UPDATE: so everything work out, I got the result but now i want to make them appear on one line. I did this but i got the error message saying that TypeError: 'builtin_function_or_method' object is not subscriptable
    while start <= end:
        inRange = makeList.append[start]
        start += 1
        print inRange

A: Instead of
start = lcn.get("start")
end = lcn.get("end")

use
start = int(lcn.get("start"))
end = int(lcn.get("end"))

This is because lcn.get returns a string.
Instead of start = int(start+1), use start += 1. You no longer need to convert to an integer and start += 1 is shorthand for start = start + 1.
Instead of print "%s, %s" % (start, end,), use print "%d, %d" % (start, end). The comma at the end is unnecessary and start and end are now integers so use %d instead of %s.
UPDATE:
And instead of
while start <= end:
    inRange = makeList.append[start]
    start += 1
    print inRange

use
for i in range(start, end):
    makeList.append(i)
    print(i)

if using Python 3 or use
for i in xrange(start, end):
    makeList.append(i)
    print i

if using Python 2.


text:
Q: Finding the existence of a limit in multivariable calculus To me, it seems like we have to analyze an infinite number of paths. Stewart Calculus tries to invoke the idea of continuity - but how do we know continuity a priori, without examining a graph?
I know the epsilon-delta proof is one way, but some of the manipulations are highly nontrivial (at least to me).
Could somebody explain to a very ignorant kid who hasn't taken a class in real analysis why this is?

A: Short of doing a delta epsilon proof, you can prove that entire classes of functions are continuous. Examples of this include rational functions where they are defined, polynomials and trig functions.
Then, if you also know that the sum, product and composition of continuous functions are continuous, you are usually in quite good shape for most functions you see.
However, since you usually are given functions that aren't defined at the point of interest, often zero, common tactics include switching to polar coordinates (if at the origin) and showing that the limit is finite and independent of theta. Another way to get around the infinite path point you astutely bring up is show that for any arbitrary sequence $\vec{a_n}\rightarrow \vec{a}$, $$\lim_{n\rightarrow \infty}f(\vec{a_n})=f(\vec{a})$$
edit: Example problem for polar coordinates
$$
f(x,y)=\frac{x^3}{x^2+y^2}, (x,y)\ne \vec{0}, f(0,0)=\vec{0}
$$
Is f continous at the origin?