text:
Q: Why isn't this instance of "so" preceded by a comma even though it's beginning a new independent clause? William Strunk writes in the 1914 edition of his Elements of Style:

*Place a comma before and or but introducing an independent clause.
...
Two-part sentences of which the second member is introduced by as (in the sense of because), for, or, nor, and while (in the sense of and at the same time) likewise require a comma before the conjunction.
...

*Do not join independent clauses by a comma.
...
If a conjunction is inserted, the proper mark is a comma (Rule 4).

Now more than a hundred years later, a grammar stylistic rule commonly taught by today's writing-style guides categorically states that whenever the word so connects two independent sentences, a comma should be placed before that so. But in this example, so apparently connects two independent clauses, but no comma is placed.

Fees for higher education are expensive and not affordable for everyone so according to some university should be free for all people, regardless of their background.

Why was that written without a comma before the so? Shouldn't it have been written at least like this:

Fees for higher education are expensive and not affordable for everyone, so according to some university should be free for all people, regardless of their background.

Or like this:

Fees for higher education are expensive and not affordable for everyone, so according to some, university should be free for all people, regardless of their background.

Or even like this:

Fees for higher education are expensive and not affordable for everyone, so, according to some, university should be free for all people, regardless of their background.

Why did the original leave out that critical comma? Is this not required? Any explanation on this strange lapse compared with what I thought the proper rule always had to be would be very much appreciated.


text:
Q: Create a Multi Sheet Excel and send it as ByteArrayInputStream for downloading I have created an excel file using Apache POI library, Excel is having Multiple Sheets.
The code is working fine but the only problem is that I'm creating a file in current directory(project directory). Is there any way to build an excel in memory and pass the byte for downloading it instead of creating an external file ("ExcelDownload.xlsx")

ServiceClass below

public class GenericExcelService {

  public static <T> void writeToExcelInMultiSheets(final String fileName, final String sheetName, final List<T> data) {
    XSSFWorkbook workbook = null;
    FileOutputStream fos = null;
    try {
      File file = new File(fileName);
      Sheet sheet = null;
      if (file.exists()) {
        workbook = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
      } else {
        workbook = new XSSFWorkbook();
      }
      sheet = workbook.createSheet(sheetName);
      .
      .
      .
      .
      .
      fos = new FileOutputStream(file);
      workbook.write(fos);
      fos.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (workbook != null) {
          workbook.close();
        }
      } catch (IOException e) {
        System.out.println("Inside Last IOException");
      }
    }
    }
  }

Controller below

@RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public void writeToExcelInMultiSheets(){

    File currDir = new File(".");
    String path = currDir.getAbsolutePath();
    String fileLocation = path.substring(0, path.length() - 1) + "ExcelDownloadDemo.xlsx";

    GenericExcelService.writeToExcelInMultiSheets(fileLocation, "Person Details", persons);
    GenericExcelService.writeToExcelInMultiSheets(fileLocation, "User Details", users);
    GenericExcelService.writeToExcelInMultiSheets(fileLocation, "Contact Details", contacts);
}

I tried implementing the same code for a non-void method to return a downloadable excel file using ByteArrayInputStream but I was unable to return more than one value. Kindly assist
Made the following changes in controller & service but didn't work.

change in service is below, instead of void return type is ByteArrayInputStream

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//in place of
//fos = new FileOutputStream(file);
//workbook.write(fos);

workBook.write(outputStream);

return new ByteArrayInputStream(outputStream);

change in controller return type to ResponseEntity<InputStreamResource>
  and below

ByteArrayInputStream bis;
bis = GenericExcelService.writeToExcelInMultiSheets(fileLocation, "Contact Details", contacts);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition", "attachment; filename=" + "Details.xlsx");

        return ResponseEntity
                .ok()
                .headers(headers)
                .body(new InputStreamResource(bis));

Can anyone please help me with this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aggregate root and Entity Framework I am struggling with pure implementation of Aggregate root with Entity Framework Code First. Suppose we have a standard problem of Order and OrderItem, the latter being the child of the former. We need to have a read only collection of OrderItem items in Order class so we can (by design) control the Adding, Removing or Updating of OrderItems in it's aggregate root (ie Order class).

*

*How do we implement this list of OrderItem(s)? This list needs to be read-only so that other developers don't try adding OrderItem(s) inside the list by hand, avoiding methods that should be used instead.

*How do we map that collection in EF Code First? Private properties are not mappable.

A:

*

*How do we implement this list of OrderItem(s)? This list needs to be read-only so that other developers don't try adding OrderItem(s) inside the list by hand, avoiding methods that should be used instead.

A read only list will not prevent other developers from Adding and Removing items to it. It will only prevent them from changing the reference pointer of OrderItems.
What you can do is make the list private, and have a method AddItem, RemoveItem and UpdateItem on Order and an IEnumerable getter of the list for iteration purposes.

*

*How do we map that collection in EF Code First? Private properties are not mappable.

I've never used EF, but from having done some DDD before, it's useful to have one set of entities for your application and logic, your true domain model, and another set of entities for your data access framework, in this case EF. And use something like AutoMapper to map from your EF entities to your domain entities.
You don't have to always have two set of entities, but for those that are problematic like this one, make the entity EF wants, and just add the extra step of mapping from object to object(s).


text:
Q: Why am I seeing "Error: length(rows) == 1 is not TRUE" with ddply? I have a data frame, say payroll, like:
payroll <- read.table(text="
AgencyName          Rate             PayBasis     Status    NumRate
HousingAuthority    $26,843.00   Annual           Full-Time 26843.00
HousingAuthority    $14,970.00   ProratedAnnual   Part-Time 14970.00
HousingAuthority    $26,843.00   Annual           Full-Time 26843.00
HousingAuthority    $14,970.00   ProratedAnnual   Part-Time 14970.00
HousingAuthority    $13.50           Hourly           Part-Time 13.50
HousingAuthority    $14,970.00   ProratedAnnual   Part-Time 14970.00
HousingAuthority    $26,843.00   Annual           Full-Time 26843.00", header = TRUE)

The "NumRate" is actually numeric:
payroll$NumRate <- as.numeric(payroll$NumRate)

And I'd like to get a know the max, min and mean salaries by PayBasis. I expect this to work:
ddply(payroll, "PayBasis", summarize)

But instead I'm getting an error: Error: length(rows) == 1 is not TRUE
What am I missing here?

A: Probably because you've mistaken summarize for summary (which won't work like you expect in this context). You probably wanted:
ddply(payroll, "PayBasis", summarize,mx = max(NumRate),mn = min(NumRate),avg = mean(NumRate))
        PayBasis      mx      mn     avg
1         Annual 26843.0 26843.0 26843.0
2         Hourly    13.5    13.5    13.5
3 ProratedAnnual 14970.0 14970.0 14970.0

And be sure to look more carefully at the examples in ?summarize and ?ddply.

A: It could also be the plyr library. Try either not to load it, or, if you need it be careful whether you load it before or after other libraries such as dplyr, or tidyverse which automatically fires up the dplyr

A: to make sure you are using the correct command use dplyr::summarize. As you can guess there are a lot of libraries that uses "summarizes" command


text:
Q: Sending out Ping Requests Using WinpCap and trying to generate my own ping requests.
On both machines I see the ping request and the only differences between the ones I've generated the ones Windows has generated is my checksum is 0 (been told that's ok) and the identified is 100 instead of an ever increasing value like Windows uses. (I increase each time I try to send a ping request).
Should I paste the hex dump here? :P
EDIT:
I guess my question here is to find out what could cause Windows to NOT respond to ping requests that show up as valid in Wireshark.

A: Yes, you should probably paste the hex dump here.
It could be the fact that the checksum is wrong. Unlike UDP, I believe ICMP (ping) checksum is not optional and should be correct. This is also what I got from RFC 792.
If you want to use WinPcap with .NET, you can use Pcap.Net, which will allow you to create and send any ICMP packet by writing very few lines of code.


text:
Q: Add a value from one datatable to another c# My knowledge of databases and so on are weak, and I am quite frustrated with it, so I ask help.
If I want to add a value from one datatable to another while executing on click scenario that adds the new values all in the same time, what should I do?
So here is my scenario, I have a dataset with 3 datatables (for this issue we need only two of them, Business and Users)
Datatable 1 (Business)

*

*B_ID

*B_Name

*B_Pass

Datatable 2 (Users)

*

*User_ID

*User_Business

*User_Name

*User_Password

*User_Email

*User_Shortcode

*User_AdminRights

*User_UserRights

, I am executing the following code (my registration form registers business data and user data, implements the data seperatly to the two datatables, it works fine but I have no idea how to insert the "B_ID" to "User_Business") :
                cmd = new SqlCommand("select * from Business where B_Name ='" + textBox1.Text + "'", cn);
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    dr.Close();
                    MessageBox.Show("Business with this name already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    dr.Close();
                    cmd = new SqlCommand("insert into Business values(@B_Name, @B_Password)", cn);
                    cmd.Parameters.AddWithValue("B_Name", textBox1.Text);
                    cmd.Parameters.AddWithValue("B_Password", textBox2.Text);

                    cmd.ExecuteNonQuery();

                    cmd = new SqlCommand("insert into Users values(@User_Business, @User_Name, @User_Surname, @User_Email, @User_Password, @User_Shortcode, @User_AdminRights, @User_UserRights)", cn);

                    cmd.Parameters.AddWithValue("User_Business", ???); // <- the question mark indicates where I want to add the value of B_ID which is created after inserting business data

                    cmd.Parameters.AddWithValue("User_Name", txt_name.Text);
                    cmd.Parameters.AddWithValue("User_Surname", txt_surname.Text);
                    cmd.Parameters.AddWithValue("User_Email", txt_email.Text);
                    cmd.Parameters.AddWithValue("User_Password", txt_pass.Text);
                    cmd.Parameters.AddWithValue("User_Shortcode", txt_code.Text);
                    cmd.Parameters.AddWithValue("User_UserRights", 0);
                    cmd.Parameters.AddWithValue("User_AdminRights", 1);

                    cmd.ExecuteNonQuery();

                    MessageBox.Show("Registration succesfull!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }

So at the end, I want to add the specific "B_ID" value that generates after data is inserted to Business datatable, to "User_Business" value in the Users datatable.
The code works without "User_Business" fine tho, but I am open to new suggestions, thank you.


text:
Q: CSS margin-left property doesn't exist? I am trying to center something both horizontally and vertically on my page... I have seen several threads on stackoverflow of people experiencing the same issue, but I tried the solutions posted there (things relating to overflow: hidden, different floats, inline blocks, etc.) but none seem to work.
Here you can see the CSS validation fails:
<http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.applemktcap.com%2Fcss%2Fmain.css&profile=css3&usermedium=all&warning=1&vextwarning=&lang=en>
margin-left is not a recognized property? if you go to the homepage of that site, <http://applemktcap.com>, you can see the resulting JS applet which is not centered.
I know it has nothing to do with the JS, as I stripped everything out of my site and put some simple text in the container, and it's still shifted towards the right.  Must just be some simple CSS mistake I'm looking right over.
Any ideas?

A: margin-leftâ is not a valid property.  Looks like there is a weird character after "margin-left" that needs to be removed.  It might be best to re-write that line of code.
Your CSS file shows this:
margin-left: -350px;


text:
Q: Use of Logger with Ruby and RSpec I have created logger object in "spec/logger.rb" and returned it.
I have created logger object in "spec/test1.rb" in describe method and can use it. it is working in same directory. If i need to use logger by creating logger object or by including file in different directory with and without class, then is there any way to do it ?
spec/logger.rb
class Logging
    def initialize_logger()
        log = Logger.new("test.log")
        return log
    end
end

spec/test1.rb
require 'java'
require 'rspec'
require 'logger'

require "logger.rb"

class SingleTest
  describe 'Verify Single Test' do
    # create logger object
    logger_object = Logging.new
    logger = logger_object.initialize_logger()
    logger.info 'Checking Logger'

    it 'Verify Single Test for logger is present' do
      logger.info 'Creating logger'
    end
  end
end

lib/test_lib1.rb
require 'httparty'
require '../utility/logger.rb'

@logger_object = Logging.new
@logger = @logger_object.initialize_logger()

@logger.info 'Checking Logger'

def first()
  @logger.info "first logger in lib"
end

def perform_url_request()
  @logger.info "URL"
  @logger.info "Request Method"
end

lib/test_lib2.rb
require '../utility/logger.rb'

class TestFile
  def initialize()
    @logger_object = Logging.new
    @logger = @logger_object.initialize_logger()
    @logger.info "I am intialize"
  end

  def test_method()
    @logger.info "******"
  end
end


text:
Q: yii2 ArrayHelper dropDownList Controller
public function actionIndex()
{
    $model = new FbToken();

    $listTokens = ArrayHelper::map(FbToken::find()->where(['user_id' => Yii::$app->user->getId()])->all(), 'token', 'name');

    return $this->render('index',[
        'model' => $model,
        'listTokens' => $listTokens,
    ]);
}

view
 <?php
            $form = ActiveForm::begin();
            echo   $form->field($model, 'token')->dropDownList($listTokens,
                ['onchange' => '$.post("'.Yii::$app->urlManager->createUrl(["site/adds"]).
                    '",
                    {
                    token: $(this).val()
                    },
                    function( data ) {
                    $("#test_div").html( data );
                    })'
                ]);

            ActiveForm::end();
            ?>

Как сделать что бы первое в списке было Выберите значения ?
<select>
   <option>Выберите значения</option>
   <option value="1">name1</option>
   <option value="2">name2</option>
 </select>

A: $form->field($model, 'token')->dropDownList($listTokens, [
    'prompt' => 'Please select',
    'onchange' => '$.post(...)',
]);

Начиная с Yii 2.0.11:
$form->field($model, 'token')->dropDownList($listTokens, [
    'prompt' => ['text' => 'Please select', 'options' => ['value' => 'none']],
    'onchange' => '$.post(...)',
]);

Подробная информация в документации

A: В контроллере:
$listTokens = ['' => 'Выберите значения'] + ArrayHelper::map(FbToken::find()->where(['user_id' => Yii::$app->user->getId()])->all(), 'token', 'name');
остальное без изменений


text:
Q: Please help me override this GoogleTrustedStore block! I'm having trouble overriding this block for a customization on admin orders:
Mage_GoogleTrustedStore_Block_Adminhtml_OrderCreatedConfirmation
app\code\core\Mage\GoogleTrustedStore\Block\Adminhtml\OrderCreatedConfirmation.php
class Mage_GoogleTrustedStore_Block_Adminhtml_OrderCreatedConfirmation
extends Mage_GoogleTrustedStore_Block_OrderConfirmation_Onepage
{}

    <global>
       <blocks>
          <kmd_googletrustedstore>
             <class>Kmd_Googletrustedstore_Block</class>
          </kmd_googletrustedstore>
          <googletrustedstore>
             <rewrite>
                <orderConfirmation_Onepage>Kmd_Googletrustedstore_Block_Onepage</orderConfirmation_Onepage>
             </rewrite>
             <rewrite>
                <adminhtml_OrderCreatedConfirmation>Kmd_Googletrustedstore_Block_Adminhtml_OrderCreatedConfirmation</adminhtml_OrderCreatedConfirmation>
             </rewrite>
          </googletrustedstore>
       </blocks>
    </global>

My custom file is located here:
app\code\local\Kmd\Googletrustedstore\Block\Adminhtml\OrderCreatedConfirmation.php
class Kmd_Googletrustedstore_Block_Adminhtml_OrderCreatedConfirmation
extends Kmd_Googletrustedstore_Block_Onepage
{
}

The orderConfirmation_Onepage rewrite works fine for frontend orders, but I can't get the adminhtml block rewrite to work - any suggestions would be greatly appreciated!
Update - I checked for conflicting overrides, none found.

A: This should be working:
class Kmd_Googletrustedstore_Block_Adminhtml_OrderCreatedConfirmation
  extends Mage_GoogleTrustedStore_Block_Adminhtml_OrderCreatedConfirmation
{
}

You're rewriting Mage_GoogleTrustedStore_Block_Adminhtml_OrderCreatedConfirmation according to your config.xml hence you have to extend this class.


text:
Q: P adjusted values in Deseq2 I have a metabolic pathway dataset that I run through DESeq2 and my question is why some different p-values ended up having an equal p-adjusted?
baseMean    log2FoldChange  lfcSE           stat            pvalue      padj
102.4139421 -2.779259157    0.879336287 -3.160632853    0.001574268 0.165229376
97.44804027 -2.295013504    0.735995467 -3.118244073    0.001819321 0.165229376
224.9746369 -1.223071776    0.400516301 -3.053737822    0.002260095 0.165229376
114.9366424 -1.813971541    0.621330508 -2.919495368    0.003505986 0.165229376
111.8579053 -1.748819203    0.620374587 -2.818972989    0.004817757 0.165229376
83.94472937 -2.147032598    0.771273039 -2.783751654    0.005373416 0.165229376

I do not think is related to the sample size (similar datasets give quite variable - significant results). I do not think there is anything particulary wrong with the results, I just would like to know a bit more about the reasons of the outcome. Also, some of the q values are NA.
Any answer, tip, or help would be really appreciated.


text:
Q: Prevent postgres from inlining an update subquery I have a table
CREATE TABLE author (
    id SERIAL PRIMARY KEY,
    followers INTEGER[]
);
INSERT INTO author (followers)
       SELECT '{}'::INTEGER[]
       FROM generate_series(0, 1000);

I populated it with ids and want to add random followers. Problem arises when I run
UPDATE author
SET followers = (SELECT array_agg(id)
                 FROM author
                 WHERE random() < 0.01);

Postgres is tries to be smart and executes the SELECT only once, causing same value to be repeated over and over again. What is the correct way of achieving this? I tried using OFFSET 0 and UDPATE .. FROM .. but to no avail

A: I believe that you need to create an artificial dependency between the subquery and the outer query. Something as simple as:
UPDATE Author AS A1
SET
    followers = (
             SELECT array_agg(id)
             FROM Author
             WHERE
                 A1.author_id = A1.author_id AND
                 random() < 0.01);

(I guessed at a column name of author_id, but any column should work)


text:
Q: Check multiple checkboxes using jQuery from two dimensional array I have an array like
var favorite = {};
    $.each($(".list input[type='checkbox']:checked"), function(){
        if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
            favorite[$(this).attr("name")] = [];
        }
        favorite[$(this).attr("name")].push($(this).val());
    });

With one dimensional array I can do:
$('#list [value="'+favorite.join('"],[value="')+'"]').prop('checked',true);

Which produces a selector like:
$('#list [value="1"],[value="3"],[value="4"],[value="5"]')

But how can I produce a selector from two dimensional array like:
$('#list [Name="Name[]",value="1"],[Name="Name[]",value="3"],[Name="Name[]",value="4"],[Name="Model[]",value="5"]')

I need to select all checkboxes which is in favorite array. Because after ajax Post I lose all checked checkboxes something like that:
$(function() {
    $('.list input').change(function(e){
            //e.preventDefault();
            var favorite = {};
                $.each($(".list input[type='checkbox']:checked"), function(){
                    if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
                        favorite[$(this).attr("name")] = [];
                    }
                    favorite[$(this).attr("name")].push($(this).val());
                });

        var str;
        str = $.param(favorite);

        $.ajax({
            url:'/Search.asp',
            type:'POST',
            data:str,
            dataType:'text',
            success: function(data)
            {
                $("#ExSearchForm").html(data);
                $("#ExSearchForm").find('[value=' + favorite.join('], [value=') + ']').prop("checked", true);
            }
        });

    });
});

The Html markup

Make

                    <input type='checkbox' name='Make[]' value='*FAKE*' />*FAKE*0
<input type='checkbox' name='Make[]' value='AIXAM' />AIXAM2
<input type='checkbox' name='Make[]' value='ALFA ROMEO' />ALFA ROMEO106
<input type='checkbox' name='Make[]' value='ALPINA' />ALPINA1
<input type='checkbox' name='Make[]' value='AUDI' />AUDI686
<input type='checkbox' name='Make[]' value='BMW' />BMW557
....

A: You should create array of values based on favorite object:
$('.list input[type=checkbox]').on('change', function () {
    var favorite = {};

    $('.list input[type=checkbox]:checked').each(function () {
        var $el = $(this);
        var name = $el.attr('name');
        if (typeof (favorite[name]) === 'undefined') {
            favorite[name] = [];
        }
        favorite[name].push($el.val());
    });

    $.ajax({
        url: '/Search.asp',
        type: 'POST',
        data: $.param(favorite),
        dataType: 'text',
        success: function (data) {
            $("#ExSearchForm").html(data)
                .find('input[type=checkbox]').each(function () {
                    var $el = $(this);
                    var name = $el.attr('name');
                    var value = $el.attr('value')
                    if (favorite[name] && favorite[name].indexOf(value) !== -1) {
                        $el.prop('checked', true);
                    }
                });
        }
    });
});

Notice: But such kind of selectors are very complicated and could be extremely slow.

A: I would suggest using an array of objects instead then you can easily iterate over that array which would also be significantly faster.
Something like this

$(function() {
    $('.list input').change(function(e){
            //e.preventDefault();
            var favorite = {};
                $.each($(".list input[type='checkbox']:checked"), function(){
                    if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
                        var item = {
                          value: 1,
                          name : favorite[$(this).attr("name")
                        }
                    } else {
                        var item = {
                          value: 0,
                          name : favorite[$(this).attr("name")
                        }
                    }

                    favorite[$(this).attr("name")].push(item);

                });

    });
});


text:
Q: What if I install Ubuntu in a laptop that has a recovery partition? If I install Ubuntu dual-boot on laptop that has recovery partition will it become useless the recovery option provided by the BIOS and accessibility of recovery partition?

A: Yes it may become useless if you install GRUB at the beginning of your hard disk (master boot record).  (At least for my case, on a Dell XPS 15). The master boot record is the normal place for GRUB to be installed; Ubuntu's installer will almost always pick the MBR if you allow it to automatically choose. Sometimes, when GRUB's boot entries are created,  it may detect your recovery partition as bootable, and create a menu entry for it, allow you to select it and enter it to perform (or attempt) recovery.
If install GRUB into some other partition and use windows boot loader to load ubuntu, possibly you won't loose access to the recovery. (I am not very sure as I don't know how the recovery button is implemented. It does vary manufacture to manufacture)
A bit advanced thing:
A windows recovery is nothing but a .wim file. You can assign a drive letter and open it to copy the wim image for backup. Later point of time you can apply the wim image from a bootable disk with winPE. Which is very easy.
Best option: Generally the preinstalled windows systems come with a special software that can create a recovery disc (DVD/USB). You can use these disc for recovery instead of the image in recovery partitoin.
Whatever you do first create recovery disc and/or copy the wim image somewhere else.

A: My recovery partition worked for me, even after I installed Ubuntu. My situation was similar to yours, so I think your recovery partition will probably work as well.
I have eMachines eM355 that comes by default with Win7 and a recovery partition. During last three months of usage (Ubuntu 12.04.1 LTS) I saw no problems. I even used Recovery partition for another install of Win7 because I got some nasty Trojan. Everything went fine. And even more, I don't really use Windows at all lately.
I'm just a newbie as I suppose you are, so maybe I'm missing something. I guess you should take this answer with a grain of salt.


text:
Q: Title does not appear in TabBarItem, but the image does I've added a tab bar controller and am trying to add a title and image to the item, but only the image shows. The title is nowhere to be seen. Any suggestions would be greatly appreciated.
_tabbarController = [[UITabBarController alloc] init];
_showsController = [[showsController alloc] init];
_showsController.title = @"Test1";
_showsController.tabBarItem.image = [UIImage imageNamed:@"Glass.png"];
[_tabbarController setViewControllers: [NSArray arrayWithObjects: _showsController, nil]];

UPDATE:
After searching stackoverflow for a while, I finally found the solution by adding the following code:
*self.view = _tabbarController.view;*
I apologize for not giving more information (that this was not the rootViewController but added as a subview instead), and thank you for your help.

A: You also need to set the title on the UITabBarItem object.
_showsController.tabBarItem.title = _showsController.title;

Personally, I prefer to let the UIViewController subclass handle its own titles when possible. This makes your code more self-contained and doesn't always force the UIViewController's creator to initialize it properly.
For example, in your UIViewController subclass:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]))
    {
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Test1"
                                                           image:[UIImage imageNamed:@"Glass.png"]
                                                             tag:1];
        [self setTabBarItem:item];
        [item release];
    }

    return self;
}

A: You need to set the UITabBarItem title:
 _showsController.tabBarItem.title = @"Test1";

Or set them both in one go:
_showsController.title = _showsController.tabBarItem.title = @"Test1";


text:
Q: TypeError: Cannot read properties of undefined (reading 'up') MUI In my Header component my custom styling are coming from style.js where I've used makeStyles from @mui/styles. But In there while setting up the [theme.breakpoints.up("sm")] I'm getting the error above. I tried wrapping the index.js with themeProvider and passed createTheme as prop. but it is giving me another error. I tried looking up the docs but couldn't figure it out.
styles.js
import { makeStyles } from "@mui/styles";
import { alpha } from "@mui/material/styles";

export default makeStyles((theme) => ({
  title: {
    display: "none",
    [theme.breakpoints.up("sm")]: {
      display: "block",
    },
  },
...
})
)

Header component
import React from "react";
import useStyles from "./styles";
import { AppBar, Toolbar, Typography, InputBase, Box } from "@mui/material";
import { Autocomplete } from "@react-google-maps/api";
import { SearchIcon } from "@mui/icons-material/Search";

const Header = () => {
  const classes = useStyles();
  return (
    <AppBar position="static">
      <Toolbar className={classes.toolbar}>
        <Typography variant="h5" className={classes.title}>
          Travel Companion
        </Typography>
        <Box display="flex">
          <Typography variant="h6" className={classes.title}>
            Explore new places
          </Typography>
          <Autocomplete>

                <SearchIcon />

              <InputBase
                classes={{ root: classes.inputRoot, input: classes.inputInput }}
                placeholder="Search"
              />

          </Autocomplete>
        </Box>
      </Toolbar>
    </AppBar>
  );
};

export default Header;


text:
Q: Rust: error[E0495]: cannot infer an appropriate lifetime for autorefdue to conflicting requirements in closure Raw idea
In a dummy project I have, I would like to use cycling iterators (to generate integers for example).
use std::iter::Cycle;

type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>;

fn generate_cycles() -> [IntegerCycle; 2] {
  let mut cycles = [
    [1, 2].iter().cycle(),
    [2, 4].iter().cycle(),
  ];

  cycles
}

fn main() {
  let mut cycles = generate_cycles();
  // ...
}

Refactor
Although the previous piece of code works as intended, my real world example is a bit more complicated, so I am looking to adapt the generate_cycles function to be able to perform more operations (in the following example, multiply by 2, then generate the cycling iterators).
For this, I tried to use arraymap:
extern crate arraymap;

use arraymap::ArrayMap;
use std::iter::Cycle;

type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>;

fn generate_cycles() -> [IntegerCycle; 2] {
  let mut cycles = [
    [1, 2],
    [2, 4],
  ];

  cycles
    .map(|points| {
      points.map(|point| point*2)
    })
    .map(|points| {
      points.iter().cycle()
    })
}

fn main() {
  let mut cycles = generate_cycles();
  // ...
}

The problem
The above solution does not work, and, as a Rust beginner recently exposed to the concept of "lifetime", I do not understand why the compiler is complaining here, or what I can do to make him happy.
error[E0495]: cannot infer an appropriate lifetime for autorefdue to conflicting requirements
  --> src/main.rs:20:14
   |
20 |       points.iter().cycle()
   |              ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 19:10...
  --> src/main.rs:19:10
   |
19 |       .map(|points| {
   |  __________^
20 | |       points.iter().cycle()
21 | |     })
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:20:7
   |
20 |       points.iter().cycle()
   |       ^^^^^^
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected [std::iter::Cycle<std::slice::Iter<'static, i32>>; 2]
              found [std::iter::Cycle<std::slice::Iter<'_, i32>>; 2]

Here is a REPL with the code trying to make use of the arraymap: https://repl.it/repls/ShadowyStrikingFirm .

A: In your type declaration:
type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>;

You say that you the underlying slices you use to build your iterators must have 'static lifetime, that is, they must live forever. Then you use literal arrays such as [1, 2] that, as all literals, have 'static'  lifetime and all goes well:
let r: &'static [i32; 2] = &[1, 2]; //Ok

But then, you try a code similar to this simpler one:
let a = [1, 2].map(|x| 2 * x);
let r: &'static [i32; 2] = &a; //error: borrowed value does not live long enough

That is the result of arraymap::map is a normal array, not a literal one, so it does not have a 'static lifetime. It cannot be static because you are computing the values in runtime. It will live as long as necessary, in my case as long as the variable a.
In your case, since the returns of arraymap::map are not assigned to variables, they are temporary values and they are quickly dropped. But even if you assigned it to a local variable, you could not return a reference to it, because the local variable is dropped when the function ends.
The solution is to return an iterator that owns the value. Something like this works:
type IntegerCycle = Cycle<std::vec::IntoIter<i32>>;

fn generate_cycles() -> [IntegerCycle; 2] {
  let cycles = [
    [1, 2],
    [2, 4],
  ];
  cycles
    .map(|points| {
      points.map(|point| point*2)
    })
    .map(|points| {
      points.to_vec().into_iter().cycle()
    })
}

Unfortunately you have to use a Vec instead of an array, because there is not an IntoIterator implementation for arrays, (there are for slices, but they do not own the values).
If you want to avoid the extra allocation of Vec you can use the arrayvec crate that does allow to take an iterator to an array:
type IntegerCycle = Cycle<arrayvec::IntoIter<[i32; 2]>>;

fn generate_cycles() -> [IntegerCycle; 2] {
  let cycles = [
    [1, 2],
    [2, 4],
  ];

  cycles
    .map(|points| {
      points.map(|point| point*2)
    })
    .map(|points| {
        let a = arrayvec::ArrayVec::from(*points);
        a.into_iter().cycle()
    })
}

NOTE: It looks like there is an attempt to add a proper IntoIterator impl for arrays by value to the std, but there are still some pending issues.


text:
Q: Filling the whole screen with Gridview items I have a GridView (with 2 columns and 2 rows) and want to stretch the rows to fill the whole screen. It should look the same on all devices.

That means I don't want some empty space under the last row. So I searched a little bit and found a solution to set the minimum height of the GridView dynamically with following code:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int width = metrics.widthPixels;
int height = metrics.heightPixels;

In addition I added these lines of code in my Adapter:
gridView = inflater.inflate(R.layout.act_main_menu_sub, null);
gridView.setMinimumHeight(ActMainMenu.height/2);

But now it looks like this:

The View is scrollable now and the items have the same size. But it doesn't fit on the screen.
Here is the code of my layout including the GridView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:id="@+id/layout_main_menu"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="#b2b2b2"
          android:orientation="vertical">

<!-- android:layout_height="wrap_content" -->
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    android:padding="2dp"
    app:titleMarginStart="20dp"
    app:titleTextAppearance="@style/MyMaterialTheme.Base.TitleTextStyle"
    app:titleTextColor="@color/textColorPrimary">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="MASTERFITNESS TRAINERSCHULUNG"
        android:textColor="@android:color/white"
        android:textStyle="bold|italic"/>

</android.support.v7.widget.Toolbar>

<!--android:columnWidth="160dp"-->
<GridView
    android:id="@+id/grid_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:gravity="center"
    android:horizontalSpacing="20dp"
    android:numColumns="2"
    android:stretchMode="columnWidth"
    android:verticalSpacing="20dp"></GridView>

</LinearLayout>

What is the problem here?

A: The problem with your 2nd screen shots in the height calculation.  metrics.heightPixels gives you the full height of the screen, including the toolbar and any margins you have.  These should 1st be subtracted out, then divide the screen in half.
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    // your layout has 10dp margin (top & bottom) + 20 dp between grid items, 10+10+20=40
    int marginSizeDp = 40;
    float scale = metrics.density;
    int marginSizePx = Math.round (marginSizeDp * scale);

    int appBarHeight = getAppBarHeight();

    int height = metrics.heightPixels;
    int minHt = Math.round((height - marginSizePx - appBarHeight)/2);
    gridView.setMinimumHeight(minHt);

Get the toolbar height thanks to AZ13 at https://stackoverflow.com/a/7167086/7292819
    // returns height of app bar in pixels
    private int getAppBarHeight() {
        final TypedArray styledAttributes = getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.actionBarSize });
        int appBarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return appBarHeight;
    }

Truthfully, if this layout is static (there's only 4 items, no scrolling, little or no changing of the content of each item), I probably wouldn't bother with a GridView & adapter.  A RelativeLayout or GridLayout might be better.


text:
Q: How do I get my OpenGraph objects to be "liked" properly? Still more OpenGraph newbie-ism:
I define a page on my site with a full set of metatags appropriate for a "video".  This is a standard OG video; no custom stuff.  All is well; the page passes the object linter successfully, and is identified as a video:movie.  The page also contains a Like button created in the "usual" way -- a div of class "fb-like" with a set of parameters, and some activating javascript.
Joe, a user, goes to the page and clicks the Like button; the following happens:

*

*The Like overlay box appears, showing the info about the page/object, a textfield for a comment, and a Post button.

*The Like counter on the button is incremented.

*But then, the box immediately disappears, without being clicked on and without anything being entered into it.  (There was never really any chance to do so.)

*The Like increment is lost; it goes back to whatever it was before.

*Joe's Facebook profile page contains an entry "Joe likes a link", with a correct depiction of the page/object, including the ability to play the video on the profile page.

*Joe's friends do not get any notification of this liking, although the liking is marked as "public" in Joe's activity log.

Now, I define another page on my site that is virtually the same, but that has only the basic sorts of metatags, enough to get it identified as an OG 'website'.  Again, the linter is happy.  Joe now goes to this page and clicks the Like button.  This time, the behavior is correct, or at least what I expect:

*

*The Like counter is incremented.

*The overlay box appears and stays up for Joe to enter something.  He does so, and clicks the Post button.

*The Like counter retains its newly-incremented button.

*Joe's FB profile page contains an entry with his name, the comment he entered into the "like" box, and a depiction of the page/object. This can't be played as a video, since OG doesn't know it's a video.  Note, btw, that the entry is made up of only Joe's name, not "Joe likes a link" as in the other case.

*Joe's friends get an entry in their feed -- the same thing as appears on Joe's profile page.

I'm pretty baffled by this behavior -- I'd like to have the pages represented as OG videos for a variety of reasons, but the Liking behavior just isn't working.  Has anybody seen anything comparable?  Any advice out there??

A: This sounds like a bug, perhaps you should enter it in the bug tracker tool at https://developers.facebook.com/bugs/create


text:
Q: Formulário para mudar valor no banco de dados Eu tenho isso no banco de dados

Eu queria um formulário que ao clicar no botão Enviar mudasse o valor de pontos do usuário selecionado. Mas por enquanto só tenho isso, não sei como fazer o código em PHP.
    <?php
$connect = mysql_connect('xxxxxxxx','xxxxxxx','xxxxxxxxx'); $db = mysql_select_db('xxxxxxx');

<form>
Qual usuário deseja mudar?

  <select name="usuario">
    <option value="todos usuários do banco de dados aqui">todos usuários do banco de dados aqui</option>
  </select>

 Novo valor:

  <input type="text" name="pts">

   <input type="submit" value="Enviar">
</form>

A: As antigas funções mysql_* foram removidas do PHP. Você deve utilizar mysqli_* ou PDO. Vou fazer um exemplo utilizando MySQLi estruturado.

Mas por enquanto só tenho isso, não sei como fazer o código em PHP

1) Uma forma simples, é fazer um arquivo com a conexão do banco de dados e incluir ele onde e quando precisar:
Arquivo conexao_db.php:
<?php

$conexao = mysqli_connect(
    // Altere conforme necessário
    'xxxxxxxx',    // Host do banco de dados
    'xxxxxxxx',    // Usuário
    'xxxxxxxx',    // Senha
    'xxxxxxxx'     // Nome do banco de dados
);

if (mysqli_connect_errno()) {
    printf(
        'Erro na conexão com o banco de dados: %s',
        mysqli_connect_error()
    );
    die();
}

2) Exibir os usuários no select:
Arquivo index.php:
<?php

require_once('conexao_db.php');

$query = mysqli_query($conexao, 'SELECT * FROM `usuarios`;');

$usuarios = mysqli_fetch_all($query, MYSQLI_ASSOC);

?>

<form action="/setpontos.php" method="post">
    Qual usuário deseja mudar?

    <select name="usuario">
        <?php
        foreach ($usuarios as $usuario) { ?>
            <option value="<?= $usuario['ID']; ?>"><?= $usuario['login']; ?></option>
        <?php
        } ?>
    </select>

    Novo valor:

    <input type="text" name="pts">

    <input type="submit" value="Enviar">
</form>

3) Repare que, no index.php, o action do form é o arquivo setpontos.php e o método é post. Vamos fazer esse arquivo agora
Arquivo setpontos.php:
<?php

require_once('conexao_db.php');

$sql_query = (
    "UPDATE `usuarios`
    SET `pontos` = '".$_POST['pts']."'
    WHERE `ID` = '".$_POST['usuario']."';"
);

if (!($query = mysqli_query($conexao, $sql_query))) {
    printf(
        'Erro ao executar consulta no banco de dados: %s',
        mysqli_error($conexao)
    );
} else {
    echo 'Pontos do usuário definidos com sucesso!';
}

Se você "Ctrl+C » Ctrl+V" corretamente, tudo deve funcionar. Lembrando que todos os arquivos devem estar no diretório raiz.
Projeto disponível no meu GitHub/lipespry/sopt-formulario-mudar-pontos-usuario.
Esta é a melhor forma? Não. Mas vai ser um ponta-pé inicial para você entender como funciona.

A: Fala tiago blz, nao trabalho com php, mais trabalho com java, minha dica seria, você buscar pelo id, apos retornar a consulta com os campos você pode fazer um update para o pontos, existem varias formas de update, com valor fixo no proprio codigo(ex: vc possui uma variavel com um valor fixo, vc seta ela "Update 'nome tabela' SET = 'valor da variavel' WHERE id = 'id desejado'" ) ou você pode buscar o ultimo valor da coluna pontos salvar em uma variavel depois fazer o update com a sua variavel com o valor armazenado  e incrementa -- +1, +2  --- assim por diante....


text:
Q: PHP Rename all files in a directory with random names I have a directory of 5000 images on my website. What could I do in PHP to rename all of the images in the directory with completely random names (e.g ri32rif293jf32f3f or whatever)?
I need to know this so I can randomly rename them all every couple months.

A: It is pretty straight forward:

*

*You create yourself a function that can generate a random filename.

*You obtain the list of files in that directory.

*You create a second list with an entry per each file of the old list carrying the new name that has been generated with the function from 1.) and that does not exist in the list of 2.) and is not so far part of the list of 3.).

*Rename the files of 2.) with their new names of 3.)

Done. Wrap all this into a function of it's own so you can easily call it every couple months.

A: function random($numchars,$digits,$small,$capital,$splchr)
{
$dig = "0123456789";

$sml = "abcdefghijklmnopqrstuvwxyz";

$spl = "!@#$%*";

$cap = "ABCDEFGHJKLMNOPQRSTUVWXYZ";

if($digits == 1)
{
    $str .= $dig;
}

if($small == 1)
{
    $str .= $sml;
}

if($capital == 1)
{
    $str .= $cap;
}

if($splchr == 1)
{
    $str .= $spl;
}

for($j=0; $j < $numchars; $j++)
{
    $randomized .= $str{ rand() % strlen($str) };
}

return $randomized;
}

    $source = "/source direcotry/";
    $destination = "/destination directory/";
    function getDirectory( $source, $destination, $level=0)
    {
    $count =1;

       $ignore = array( 'cgi-bin', '.', '..' );
       if($handle = opendir($source))
       {
        //one by one reading a file
        while(false !== ($file = readdir($handle)))
        {
           if( is_dir( "$source/$file" ) )
              if (!file_exists($destination.$file))
                 mkdir("$destination$file", 0700);
           if( !in_array( $file, $ignore ) )
           {
              if( is_dir( "$source/$file" ) )
              {
                getDirectory( "$source$file/", "$destination$file/", ($level+1));
              }
              else
              {
                  $rand = random(16,1,1,1,1);
                  $srcfile = file_get_contents($source.$file);
                  $extfile=substr($file, strrpos($file, "."));
                  file_put_contents($destination.$rand.$extfile , $srcfile);
              }
           }
        }
        $total[$level] = $total + intval($count-1);
        echo "
 $destination  ---- ".intval($count-1)."

";
      }
      closedir($handle);
    }
    //calling getDirectory function for repeat the for all sub folders.
    getDirectory( $source , $destination, 0);


text:
Q: Converting a column of strings with different formats that contains year from 2 digits (YY) to 4 digits (YYYY) in python pandas I have a dataframe with the following column. Each row contains different format strings.
col                  |
----------------------
GRA/B
TPP
BBMY
...
SOCBBA 0 MAX
CMBD 0 MAX
EPR 5.75 MAX
...
PMUST 5.57643 02/15/34
LEO 0 12/30/2099
RGB 3.125 09/15/14
RGB 3.375 04/15/20

I want to convert all the dates to a format that shows the full year.
Is there a way to regex this so that it looks like this.
col                  |
----------------------
GRA/B
TPP
BBMY
...
SOCBBA 0 MAX
CMBD 0 MAX
EPR 5.75 MAX
...
PMUST 5.57643 02/15/2034
LEO 0 12/30/2099
RGB 3.125 09/15/2014
RGB 3.375 04/15/2020

Right now the only thing I can think of doing is doing,
df['col'] = df['col'].str.replace('/14', '/2014')

for each year, but theres many years, also it will replace the days and months as well.
How can I achieve this properly, should I be using regex?

A: what about replacing when it "ends with a slash followed by 2 digits"?
In [9]: df["col"] = df["col"].str.replace(r"/(\d{2})$", r"/20\1", regex=True)

In [10]: df
Out[10]:
                         col
0                      GRA/B
1                        TPP
2                       BBMY
3                        ...
4               SOCBBA 0 MAX
5                 CMBD 0 MAX
6               EPR 5.75 MAX
7                        ...
8   PMUST 5.57643 02/15/2034
9           LEO 0 12/30/2099
10      RGB 3.125 09/15/2014
11      RGB 3.375 04/15/2020

regex:

*

*/: a literal forward slash

*(\d{2}): capture 2 digits

*$: end of string

substituter:

*

*/20: literally forward slash and 20

*\1: first capturing group in the regex, i.e., the last 2 digits there


text:
Q: What is the purpose of "__SRCVERSION" function at the end of each C file? I am working on the source code of a Unix-based kernel. I noticed that the last line of each source code file (.c or .h) is a specific line with the following format:
__SRCVERSION( "$URL: ... $ $Rev: 219996 $" )

The URL points to the web address of the same file. I'm wondering what does that mean, and what is it actually for? Would it be any problem if I delete this line from all of my source code files?

A: Macros like this are often used to embed versioning information into binaries when they are compiled.  They can be updated automatically when fetched out of a source control system with appropriate rules.  Removing them shouldn't cause any harm, but you will lose the benefit of being able to search a binary to identify which versions of your source files were used to compile it.
As @Keith Thompson says below, it may also be possible to configure your build to not embed the information.  Below is an example of the macro definition taken from here (different systems are likely to have different definitions).  You can see that it uses the __USESRCVERSION definition to decide which version of the __SRCVERSION macro is used:
#ifndef __USESRCVERSION
#define __SRCVERSION(id)
#else /* __USESRCVERSION */

#ifdef __QNXNTO__

#if defined __SRCVERSION
#undef __SRCVERSION
#endif /*__SRCVERSION */

#define __SRCVERSION(id) \
    __asm__(".section .ident,\"SM\",@progbits,1"); \
    __asm__(".asciz " #id); \
    __asm__(".previous");

#endif /* __QNXNTO__ */

#endif /* __USESRCVERSION */


text:
Q: xml разметка в android почему не отображается Switch элемент
 <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/mtrl_card_spacing"
            android:layout_marginTop="@dimen/mtrl_card_spacing"
            android:layout_marginRight="@dimen/mtrl_card_spacing"
            android:minHeight="200dp"
            android:layout_margin="@dimen/activity_vertical_margin">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <com.google.android.material.button.MaterialButton

                    android:padding="8dp"
                    android:paddingLeft="8dp"
                    android:paddingRight="8dp"
                    android:paddingTop="8dp"
                    android:paddingBottom="8dp"
                    android:id="@+id/material_text_button"
                    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Settings"/>

                <com.google.android.material.switchmaterial.SwitchMaterial

                    android:padding="8dp"
                    android:layout_gravity="right"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="Dark mode"/>

            </LinearLayout>

        </com.google.android.material.card.MaterialCardView>

Вот весь код
<?xml version="1.0" encoding="utf-8"?>
<com.sothree.slidinguppanel.SlidingUpPanelLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:panelHeight="66dp"
    sothree:shadowHeight="4dp"
    sothree:overlay="true"

    >

<FrameLayout
    android:id="@+id/MainFrame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".First_Layout.MainActivity"
    android:orientation="horizontal">

    <LinearLayout

        android:id="@+id/translate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <com.google.android.material.textfield.TextInputLayout
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <com.google.android.material.textfield.TextInputEditText

                android:id="@+id/wordEnglishMainActivity"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </com.google.android.material.textfield.TextInputLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal">

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/progressBar"
                android:layout_gravity="center"
                android:layout_centerHorizontal="true"
               android:layout_alignTop="@+id/Find"
                android:visibility="invisible"
                />

            <com.google.android.material.button.MaterialButton
                android:padding="8dp"
                android:paddingLeft="8dp"
                android:paddingRight="8dp"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:id="@+id/Find"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="Find"
                android:text="Translate Word" />

            <RadioGroup

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checkedButton="@+id/first"
                android:orientation="vertical">
                <RadioButton
                    android:id="@+id/first"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Red"/>
                <RadioButton
                    android:id="@+id/second"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Blue"/>
                <RadioButton
                    android:id="@+id/trid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Green"/>
            </RadioGroup>

        </RelativeLayout>

    </LinearLayout>
</LinearLayout>
    </FrameLayout>

        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/mtrl_card_spacing"
            android:layout_marginTop="@dimen/mtrl_card_spacing"
            android:layout_marginRight="@dimen/mtrl_card_spacing"
            android:minHeight="200dp"
            android:layout_margin="@dimen/activity_vertical_margin">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <com.google.android.material.button.MaterialButton

                    android:padding="8dp"
                    android:paddingLeft="8dp"
                    android:paddingRight="8dp"
                    android:paddingTop="8dp"
                    android:paddingBottom="8dp"
                    android:id="@+id/material_text_button"
                    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Settings"/>

                <com.google.android.material.switchmaterial.SwitchMaterial

                    android:padding="8dp"
                    android:layout_gravity="right"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="Dark mode"/>

            </LinearLayout>

        </com.google.android.material.card.MaterialCardView>

</com.sothree.slidinguppanel.SlidingUpPanelLayout>

A: Он отоброжается просто за пределами видимости. У вас LinearLayout с горизонтальной ориентацией, в нем кнопка с шириной match_parent. В итоге кнопка имеет ширину лайаута, а свитч помещается справа от нее, уже за пределами лайаута. Сделайте, например, так
<com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="200dp"
            android:layout_margin="@dimen/activity_vertical_margin">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <com.google.android.material.button.MaterialButton
                    android:id="@+id/material_text_button"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="Settings"/>

                <com.google.android.material.switchmaterial.SwitchMaterial
                    android:layout_gravity="center_vertical"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="Dark mode"/>
            </LinearLayout>

        </com.google.android.material.card.MaterialCardView>


text:
Q: C++ abstract class parameter error workaround The code snippet below produces an error:
#include <iostream>

using namespace std;

class A
{

public:

  virtual void print() = 0;
};

void test(A x) // ERROR: Abstract class cannot be a parameter type
{
  cout << "Hello" << endl;
}

Is there a solution/workaround for this error other/better than replacing
virtual void print() = 0;

with
virtual void print() = { }

EDIT: I want to be able to pass any class extending/implementing the base class A as parameter by using polymorphism (i.e.  A* x = new B() ; test(x); )
Cheers

A: Since you cannot instantiate an abstract class, passing one by value is almost certainly an error; you need to pass it by pointer or by reference:
void test(A& x) ...

or
void test(A* x) ...

Passing by value will result in object slicing, with is nearly guaranteed to have unexpected (in a bad way) consequences, so the compiler flags it as an error.

A: Of course, change the signature:
void test(A& x)
//or
void test(const A& x)
//or
void test(A* x)

The reason your version doesn't work is because an object of type A doesn't logically make sense. It's abstract. Passing a reference or pointer goes around this because the actual type passed as parameter is not A, but an implementing class of A (derived concrete class).

A: To be absolutely clear, the problem is, whenever you define a class:
#include <iostream>

class foo {
  public:
    char *name = (char *)"foo";
};

and pass an instance of that class to a function, it creates a copy:

void bar(foo a) {
  a.name = (char *)"bar";
}

int main() {
  foo x;
  bar(x);
  std::cout << x.name << std::endl; // foo
  return 0;
}

With regard to inheritance, it creates a copy as an instance of the base class:
#include <iostream>

class foo {
  public:
    char *name = (char *)"foo";
};

class bar: public foo {
  public:
    char *name = (char *)"bar";
};

void baz(foo a) {
  std::cout << a.name << std::endl;
}

int main() {
  bar x;
  baz(x); // again, foo
  return 0;
}

so, by doing
void baz(AbstractType a) {
  ...
}

you're telling the compiler to copy an AbstractType as an instance of AbstractType itself, which is illegal.
Pass it as const AbstractType &a to prevent copying.


text:
Q: DAX query for KPI tracking
i am trying to write a query in order to track penalty in case of KPI failure.
eg. if in month of Oct my PI is failed 98% i get a retention if fail again following month not i get another retention i get deduction. In case one month its 98% and next month i pass i get money back.
below is the formula in excel need to change them in DAX any suggestions please.
Frist month retention formula       =IF(AND(F4>=0.98,F4<1),E4,"")
**following month deduction **          =IF(AND(F5<1,F5>=0.98,J5<1,J5>=0.98),E5,IF(AND(J5<0.98,F5<0.98),I5,IF(AND(F5<1,F5>=0.98,J5<0.98),E5+I5,IF(AND(F5=1,J5<0.98),I5,""))))
refund of retention in case of pass =IF(AND(N5=1,J5<1,J5>=0.98),-K5,IF(AND(N5<1,N5>=0.98,J5<1,J5>=0.98),M5,IF(AND(J5=1,N5<1,N5>=0.98),M5,IF(AND(J5<0.98,N5<1,N5>=0.98),M5,""))))


text:
Q: MySQL: get current and next record based on date I have this table:
+----+-----------+------------+------------+-----------+
| id |   name    | date_start |  date_end  | is_active |
+----+-----------+------------+------------+-----------+
| 12 | Invernale | 2016-11-01 | 2017-03-31 |         1 |
| 15 | Estivo    | 2016-09-01 | 2016-09-01 |         1 |
+----+-----------+------------+------------+-----------+

I need to get the "current" record based on today and next record, today based.
In my example, "current" is id 15 and "next" will be 12.
Today, same query will return "NULL" (or no record) for the current and 15 for next.
On the November, 01st 2016, current will be 12 and next no record.
On the April, 01st 2017 both will need return no record.
These are my query, but both will return id 15 (at today).
$sql_current = "SELECT * FROM $table WHERE date_start <= '$now' AND date_end >= '$now'";

$sql_next = "SELECT * FROM $table WHERE date_start >= '$now' ORDER BY date_start ASC LIMIT 1";

Thank you very much

A: I guess you can get those two records (if any) in a single query with the help of UNION (if I didn't misunderstand)
(
    SELECT
    *
    FROM tableName
    WHERE CURDATE() BETWEEN date_start AND date_end
    LIMIT 1
)
UNION
(
    SELECT
    *
    FROM tableName
    WHERE date_start > CURDATE()
    ORDER BY date_start
    LIMIT 1
);

EDIT:
If you would like to know which entry is current and which one is next then you can add an extra column currentOrNext like below:
(
    SELECT
    *,
    'current' AS currentOrNext
    FROM tableName
    WHERE CURDATE() BETWEEN date_start AND date_end
    LIMIT 1
)
UNION
(
    SELECT
    *,
    'next' AS currentOrNext
    FROM tableName
    WHERE date_start > CURDATE()
    ORDER BY date_start
    LIMIT 1
)

A: If I understand the question correctly, you need to get the interval that contains the current date (CURDATE() BETWEEN date_start AND date_end) and the first interval that is in the future and doesn't contain the current date.
The following query:
SELECT *
FROM tbl
WHERE CURDATE() <= date_end
ORDER BY date_end ASC
LIMIT 2

produces the first two time intervals (or less) that are not in the past (termination date is in the future).
A couple of lines of code in client code (PHP probably) can check the value of start_date of the first returned row (if any) to decide if it can be used as "current" or "next":

*

*if no rows are returned then current is NULL and next is NULL;

*else if start_date of the first returned row is in the past then current is the first returned row and next is the second returned row(if any) orNULL` (only one row was returned by the query);

*else current is NULL, next is the first row and the second row (if any) is not needed.


text:
Q: moving mvc5 account controller code to separate project I have a solution that contains a WebApi2,MVC5 & DAL project (all RTM).
I am wanting to use the new membership bits that are now baked-in, but I don't like all the account stuff being all in the account controller. Doing a file new project (asp.net) has all of the membership stuff coupled to the account controller.
Within my DAL I am using EF6 as I like the ideal of code-first as it suits what I am trying to do. I am trying to take the account controller code and move it into my separate project.
My context within the DAL is nice and simple (taken from the MVC site)
public class ApplicationUser : IdentityUser
{
    //a user can belong to multiple stores
    public virtual ICollection<StoreModel> Stores { get; set; }
}

public class DataContext : IdentityDbContext<ApplicationUser>
{
    public DataContext(): base("name=DefaultConnection")
    {
    }
    public DbSet<Business> Businesses { get; set; }
    public DbSet<ConsumerModel> Consumers { get; set; }
    public DbSet<StoreModel> Stores { get; set; }
}

From my account controller within my login actionresult I try
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
  if (ModelState.IsValid)
     {
      var user = await UserManager.FindAsync(model.UserName, model.Password);
       if (user != null)
       {

It throws an error with User.FindAsync

The entity type ApplicationUser is not part of the model for the
  current context.

What do I need to do to allow ApplicationUser to be used in the current context?

A: I have done something similar. In order to implement separation of concerns, I fetch the UserManager from my Repository and then use it in the Presentation layer. Repository internally creates the UserManager from UserStore using the internal LoginDbContext. That way, the DbContext and Store are separated from the controller.

A: You need to create a UserManager which takes in the userstore which takes in your dbcontext
public UserController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {
    }

    public UserManager<ApplicationUser> UserManager { get; private set; }

    public UserController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
    }

A: If you create WebApi project or somthing with VisualStudio template,
please carefully see UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); in Startup.Auth.cs file.
You might miss (new ApplicationDbContext()) part. By default, it has empty parameter.

A: I believe this will help. I am pretty new to MVC5 and I have been wanting to separate my model layer from my MVC website, mainly because I imagine I will want to share the models across my various projects. I have been unable to follow all the programming mumbo jumbo I have found on the various help sites. I always end up with a lot of errors which I am unable to resolve with my limited knowledge. However, I have found an easy way to move my ApplicationDbContext out of my MVC5 model and with hardly any errors. All the work is done by the wizards already provided by Microsoft. I would like to share my little find with everyone. This is what you do (step by step):
1.  Create a MVC5 project with authentication. Call it ModelProject.
2.  Exclude everything from the project except
    a.  Properties
    b.  References
    c.  Models
    d.  packages.config

3.  The ModelProject will hold all your models (even ApplicationDbContext.) Rebuild it.
4.  Now, create a new MVC5 project with authentication. Call this Mvc5Project
5.  Import the ModelProject project into Mvc5Project .
6.  Wire the ModelProject into this project i.e. link in the reference.
7.  Exclude the following from the MVc5Project from the Models folder
    a.  AccountViewModels.cs
    b.  IdentityModels.cs
    c.  ManageViewModels.cs
8.  If you rebuild now, you will get a bunch of errors. Just go to the errors and resolve them using the right click method to get the new namespace from ModelProject. The namespace will show if you have wired the project in correctly.
9.  Also, dont forget to go to View/Manage and Views/Account of Mvc5Project and change the models in there to the new location otherwise you will get some weird cryptic errors.

That's it! Now you have a project with the models all separated out (including the applicationDbContext) -And NO ERRORS!! Good luck!


text:
Q: How to get installed packages in android? I can get my code to get all installed packages and display them in a toast. The problem is, I want my code to only display the package name containing a string  in it. How do I do that?
ActivityManager actvityManager = (ActivityManager)
    getApplicationContext().getSystemService( getApplicationContext().ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();

for(int pnum = 0; pnum < procInfos.size(); pnum++)
{
 if((procInfos.get(pnum)).processName.contains("android")||    (procInfos.get(pnum)).processName.contains("system")||(procInfos.get(pnum)).processName.contains("huawei")||(procInfos.get(pnum)).processName.contains("adil"))
 {
      //Toast.makeText(getApplicationContext(), "system apps", Toast.LENGTH_SHORT).show();
 }
else
{
    actvityManager.killBackgroundProcesses(procInfos.get(pnum).processName);
    Toast.makeText(getApplicationContext(), "killed "+procInfos.get(pnum).processName, Toast.LENGTH_SHORT).show();

}
 }

A: Here is the code that will give u all installed activities/applications on Android:
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);

Getting the list of installed non-system apps:
public static void installedApps()
{
List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
for (int i=0; i < packList.size(); i++)
{
    PackageInfo packInfo = packList.get(i);
    if (  (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
    {
        String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
        Log.e("App № " + Integer.toString(i), appName);
    }
} }

OR you can try a well structured example:
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
    Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
} }

private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false);
final int max = apps.size();
for (int i=0; i<max; i++) {
    apps.get(i).prettyPrint();
}
return apps; }

private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
    PackageInfo p = packs.get(i);
    if ((!getSysPackages) && (p.versionName == null)) {
        continue ;
    }
    PInfo newInfo = new PInfo();
    newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
    newInfo.pname = p.packageName;
    newInfo.versionName = p.versionName;
    newInfo.versionCode = p.versionCode;
    newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
    res.add(newInfo);
    }
return res; }


text:
Q: Express Running time in Big Theta Notation ? For this pseudocode, how would I express the running time in the Θ notation in terms of n?
s = 0
  for i = 0 to n:
    for j = 0 to i:
      s = (s + i)*j
print s

A: The assignment s = (s+i)*j has constant time-complexity Θ(1). For each i the inner loop gets executed exactly i times, whereas i is iterated from 0 to n. So the body of your loop (eg. the assignment) is executed
1+2+3+...+(n+1) = (n+1)(n+2)/2 = Θ(n^2).
As the body of the loop is Θ(1) you get Θ(n^2) for the whole program noting that the first and last lines are just Θ(1) so you can ignore them.


text:
Q: write a list from values for the same key MapReduce Hadoop Does anyone know how can i write to the output file the list of values for the same key in one line?
for example, I have this: (key, values)
0 [0,2,4,5] ,
1 [1,2,3]
and i want to the output:
0 0 2 4 5
1 1 2 3
instead of
0 0
0 2
0 4
... etc

A: Just concatenate all the values in your reducer to a string and write the value out as Text. For example
public void reduce(IntWritable key, Iterable<IntWritable> values, Context context) ... {

    StringBuilder sb = new StringBuilder();

    for (IntWritable value : values) {
        sb.append(String.valueOf(value.get()) + " ");
    }

    context.write(key, new Text(sb.toString()));

}


text:
Q: Hex to rgb converter in javascript I'm trying to make a simple rgb to hex converter and I keep getting stuck with Javascript, what am I doing wrong?
In html part I made a form which on submit calls convert() function.
function convert() {
    r = parseInt(document.getElementById('r').value);
    g = parseInt(document.getElementById('g').value);
    b = parseInt(document.getElementById('b').value);

    rgb(r, g, b);
    function rgb(r, g, b){
        res = ColorToHex(r) + ColorToHex(g) + ColorToHex(b);
        function ColorToHex(color) {
            if (color > 255) return "FF";
            else if (color < 0) return "00";
            else color.toString(16).padStart(2, "0").toUpperCase();
          }
    }
    document.getElementById('result').innerHTML = res;
    return false;
}

A: This returns hex from RGB
console.log(convert('255','18', '50'));

function convert(r, g, b) {
    r = parseInt(r); g = parseInt(g); b = parseInt(b);
    res = r.toString(16) + g.toString(16) + b.toString(16);
    res = res.toUpperCase();
    return res;
}

A: First, please declare your variables properly. I don't know what else you have going on in the rest of your code, it may or may not be a factor.
Second, I don't know what you are doing in your HTML. From the code shown, I am assuming your HTML has something like:
<input id="r" type="number"/>
<input id="g" type="number"/>
<input id="b" type="number"/>

And
This Space For Lease

Though I gather you have some of that enclosed in a <form> with a submit button, which is not strictly necessary. For instance you could use something like onBlur to call  convert() every time you make any input change for a more dynamic UX. And further, use ' onclick="select()" ` so that when you click in an input it auto-selects the existing contents.
Other optimizations noted in the comments in the below example.

Enter integer RGB values

    <input id="r" type="number" onclick="select()" onblur="convert()" value="00" style="width: 5em; background:#fcc;" />
    <input id="g" type="number" onclick="select()" onblur="convert()" value="00" style="width: 5em; background:#cfc;" />
    <input id="b" type="number" onclick="select()" onblur="convert()" value="00" style="width: 5em; background:#ccf;" />

Result as a HEX string

THE COLOR IS:

        #000000

And also added it as a snippet below. Please do read the code comments as they explain what and why things are as they are.
Now, as for the concatenation, it could be even tighter:
function convert() {
  colorOut.style.backgroundColor =
  resultOut.innerHTML = ("#"
      + Math.min(Math.max(inputR.value,0),255).toString(16).padStart(2,"0")
      + Math.min(Math.max(inputG.value,0),255).toString(16).padStart(2,"0")
      + Math.min(Math.max(inputB.value,0),255).toString(16).padStart(2,"0")).toUpperCase();
}

Everything all on one logical line (line breaks added only for readability), so no need to declare and assign any more variables. Though this kind of thing can impact code readability if taken too far.
When making big strings, I like to put the concatenation operator (+) at the head of each line, which is the opposite of how I'd breakup a long equation by putting the math operators at the end of each line. This makes it clear the + is for concatenation and not addition.
Let me know if any questions...

     // create variables for all "getElement..." this was the DOM
    // only needs to be parsed on page load, so future access to
   // the elements is via the variable instead for better
    let inputR = document.getElementById('r'),
          inputG = document.getElementById('g'),
        inputB = document.getElementById('b'),
        resultOut = document.getElementById('result'),
        colorOut = document.getElementById('colorPatch');

function convert() {
             // here making the assumption that the expected inputs are
      // unsigned integers, we clamp the values to 0-255, then
     // make each into a 2 char hex str with padding.
        let hexR = Math.min(Math.max(inputR.value, 0), 255).toString(16).padStart(2, "0"),
            hexG = Math.min(Math.max(inputG.value, 0), 255).toString(16).padStart(2, "0"),
            hexB = Math.min(Math.max(inputB.value, 0), 255).toString(16).padStart(2, "0");

        // concatenate to a hex color string
        let resultColor = "#" + hexR + hexG + hexB;

             // Send to output and set color of sample color patch.
            // toUpperCase() is performed once on the final string,
     // instead of the substrings
        resultOut.innerHTML =
        colorOut.style.backgroundColor = resultColor.toUpperCase();
    }
body {
    margin: 0;
    padding: 0.5em 1.5em ;
    font-family: sans-serif;
    background-color: #ffd;
    }

h2, h3 { position: relative; font-style: oblique; }
h2 { margin: 0.5em 1em 0.5em;}
h3 { margin: 0.5em 2em 1.4em;}

#r,#g,#b {
    width: 5em;
    height: 1.75em;
    font-size: 1.33em;
    font-weight: 600;
    text-align: center;
    border-radius: 0.6em;
    }
#r { background:#fcc; }
#g { background:#cfc; }
#b { background:#ccf; }

.resultDiv {
    display: inline-block;
    position: relative;
    margin: 1.33em;
    padding: 0.5em 0.5em 2em;
    background-color: #4bb4;
    border-radius: 2em;
    text-shadow: 0.15em 0.15em 0.3em #6886;
    box-shadow: inset 3px 3px 6px #0448,
                      inset 0 0 22px #4888;
    }
.resultVal {
    position: relative;
    margin: 1em 2em;
    padding: 0em;
    }

#result {
  font-size: 1.5em;
  font-weight: 500;
  letter-spacing: 0.07em;
  color: #135a;
  text-shadow: -0.05em -0.05em 0.08em #defd,
                 0.05em 0.05em 0.08em #1238;
  }
#colorPatch {
    min-width: 5em;
    margin: 0.5em;
    padding: 0.5em 1em 2em;
    font-size: 1.25em;
    background-color: black;
    border: 0.33em solid #999;
    border-radius: 0.75em;
    box-shadow:  2px 2px 3px #2449;
    }

Enter integer RGB values

    <input id="r" type="number" onclick="select()" onblur="convert()" value="00"/>
    <input id="g" type="number" onclick="select()" onblur="convert()" value="00"/>
    <input id="b" type="number" onclick="select()" onblur="convert()" value="00"/>

Result as a HEX string

THE COLOR IS:

        #000000


text:
Q: Application logging best practices - How to manage logging statements strewn all over your code? I just read this post on Stackoverflow and there was one aspect of logging that I didn't see addressed.  Independent of the specific logging framework, how do folks handle the fact that most approaches result in logging/trace statements placed all throughout your code, making it more difficult to actually see the meat and potatoes of the code base.  Is this just the reality of life or are there techniques/mechanisms to address this, such as perhaps:

*

*A means of selectively hiding and showing all the logging and tracing statements

*Use of class or method attributes which enable logging

*...?

I am working in .NET/Visual studio but I suppose my question applies in general.

A: Ultimately, if you want logging/tracing in your app, then there is no escaping having that code in your source.
In theory you could use aspect oriented programming (AOP) tools such as PostSharp to hook in the logging/tracing calls, but regards calling tracing in methods e.g.
public void Foo()
{
    Trace.WriteLine("About to call web service");

    Trace.WriteLine("Updating database with data");
}

There is not much you can do to "hide" those from view. In theory you could have a method that is decorated with the Conditional attribute...
[Conditional("DEBUG")]
public void Trace(string message)
{
    Trace.WriteLine(message);
}

...so that the method, and calls to it, is removed from release builds. But that isn't very helpful if you need that logging for a release build of your code!


text:
Q: LME() error - iteration limit reached In specifying a crossed mixed effects model, I am trying to include interactions. However, I get the following error message:
Error in lme.formula(rate ~ nozzle, random = ~nozzle | operator, data = Flow) :
nlminb problem, convergence error code = 1
message = iteration limit reached without convergence (10)

The model has the following:
1. 3 nozzle types (fixed effect)
2. 5 operators, each with 3 repeat measures on fuel flow from the 3 nozzle types.
I was asked to include the interaction between nozzle type and operator in the model.
This is my code for the model:
flow.lme <- lme(rate ~ nozzle, error= nozzle|operator, data=Flow)

Why would I get this error message??

A: First, this is an ANOVA model, not a mixed model.
Second, it seems to me that your model is not identified. In equation form, you have
$$
\mbox{response}_{ij} = \beta_1 \mbox{nozzle type}_{1ij} + \beta_2 \mbox{nozzle type}_{2ij} + \beta_3 \mbox{nozzle type}_{3ij} + \mbox{operator}_i + \mbox{nozzle within operator}_{ij}
$$
where nozzle types are fixed effects (dummy variables), operator is a random effect, and nozzle within operator is a random effect, too.
The last term has 15 separate values for 15 observations that you have. There are no degrees of freedom left to get any other terms in the model. Including interactions was a poor advice. You'd have to drop them whatsoever; even including them as crossed effects won't help, as they will then be perfectly collinear with the fixed effects, and won't be estimable. A maximum likelihood or REML model with 15 observations does not make sense; the asymptotic results of maximum likelihood theory simply won't work: this is a Ferrari you are trying to drive on a plowed field.

A: I haven't heard of the error argument to lme and I don't see it in the documentation. Are you sure that isn't a typo? But, to answer the question you asked:
Try ?lmeControl
Setting the maxIter, msMaxIter, niterEM, and/or msMaxEval arguments to higher values than the default may fix this. Capture the output from lmeControl to an object and then pass that object to the control argument of lme.
Or...
The new default optimizer lme uses is flaky. Half the time these sorts of problems get solved for me when I change it back to the old optimizer. You do this by setting the opt argument for lmeControl to 'optim'.
So, putting it together:
ctrl <- lmeControl(opt='optim');
flow.lme <- lme(rate ~ nozzle, error= nozzle|operator, control=ctrl, data=Flow);


text:
Q: Adjusting the div inside a table cell using DomPDF in Laravel I am adding a feature in my project wherein users can convert their data into pdf, but i am having a problem with css. How can i adjust this div so that it will align in the border of my table? padding and margin does not work since the table cell also adjusts. or a im adding the wrong px? I displayed the table border so that you can see how far the border of the div is. Here's the code

        Email

                {!! $usermodel->email !!}

A: If you want to align the div with the border of the table, you can add a vertical-align property to the td element with a value of top. This will align the top of the div with the top of the table cell.
You can also try setting the height of the td element to the height of the div plus any additional padding you want to add. This will ensure that the entire div is contained within the table cell.

      Email

        {!! $usermodel->email !!}

A: Since you are using running styles, on this occasion, I suggest (perhaps could be bettered):-

        Email

        {!! $blackmamba@gmail.com !!}

A: Try doing it in an external CSS stylesheet.


text:
Q: Trying to get folder sizes for all users directory I am trying to write a powershell that will look at a network share and write out to a CSV the full name of the share and the size in MB or GB of those folders for each user home directory folder.
This is my code so far:
$StorageLocation = '\\wgsfs01\USERDIR\USERS'
$Roots = Get-ChildItem $StorageLocation | Select Fullname
ForEach ($Root in $Roots) { (Get-ChildItem $Root -Recurse | Measure-Object -Property Length -Sum).Sum }

I believe there is something wrong with my ForEach statement as this is my error message
Get-ChildItem : Cannot find path 'C:@{FullName=\wgsfs01\USERDIR\USERS' because it does not exist.
I appreciate any advice and thank you in advance.

A: The issue you have is that FullName contains a DirectoryInfo object, you have two options;

*

*Change your select to ExpandProperty which will change it to a string of the full path.
Select-Object -ExpandProperty Fullname

*Refer to $Root using the property FullName which is a property on the DirectoryInfo Object.
Get-ChildItem -path $Root.FullName -Recurse
This is one solution to what you are trying to achieve, note that errors (e.g. access denied) are ignored.
Get-ChildItem $StorageLocation | ForEach-Object {

    $sizeInMB = (Get-ChildItem $_.FullName -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum / 1MB

    New-Object PSObject -Property @{
        FullName = $_.FullName
        SizeInMB = $sizeInMB
    }
}


text:
Q: Определение степени узла в идеально сбалансированном дереве Весь вопрос изложен в заголовке. Вариативность степени определить нетрудно - 1 или 2, иных вариантов нет, но как это написать на языке c++? Реализация дерева такая:
struct tree {
int inf;
tree*right;
tree*left;
};

tree * node(int x) {
tree*n = new tree;
n->inf;
n->left = n->right = NULL;
return n;
}

void create(tree *&tr, int n) {
int x;
if (n > 0) {
    cin >> x;
    tr = node(x);
    int nl = n / 2;
    int nr = n - nl - 1;
    create(tr->left, nl);
    create(tr->right, nr);
}
}

A: Например, так:
tr->deg = 0;
if (nl>0)   //ведь это же условие создания детки, верно?
   tr->deg++;
if (nr>0)
   tr->deg++;


text:
Q: existence of martingale having a given terminal law and deterministic quadratic variation I wonder whether there exists a continuous-time martingale satisfying the following: let $\mu$ be a centered probability measure whose support is compact (one can assume, if necessary, that support of $\mu$ is a finite set contained in an arbitrarily small neighborhood of zero).
Then, Does there exist a (bounded) martingale $X_t$ such that $X_0=0$ and it has terminal law $\mu$ (either at some finite terminal time $T$ or at infinity), and that its quadratic variation $dXdX$ is DETERMINISTIC?
Thank you.


text:
Q: Elsaticsearch - what is wrong with this url? I have this url node4:9200/search/all/_search. But it returns empty result.
Can somebody tell me please what is wrong with that? I did migration from Elasticsearch 2 to Elasticsearch 6 and some requests like this one stop working.
Thanks a lot.

A: Assuming you want to return documents from all the indexes in your ES, it would be node4:9200/_all/_search.  For a specific index, replace '_all' with your index name.


text:
Q: Unable to access JSON arrary I got json array from backend as below.I could not able to access JSON arrary
var res = '[100, 200]';

When I try to access by using alert(res[0]); I am getting the first character '['. I suppose to get '100'.
Could any one tell what could be the issue?
UPDATE :-
It is working fine if the array has number. It is giving an error if the array has alpanumric character.
var  res = '[/csv/8_copy 2.csv, /csv/9_copy 2.csv]';
alert(JSON.parse(res)[0]);

A: Your need to parse the JSON string:

var res = '[100, 200]';

alert(JSON.parse(res)[0]);

A: If you want to use JSON as data, you have to parse it.
var res = JSON.parse('[100, 200]');

A: Use JSON.parse.
var result = JSON.parse('[100, 200]');
alert(result[0]);

A: The code you posted says that your var res is equal to a string (not an array).
This means that the array accessor method you're trying will not work until you parse the string into an array.
You can use JSON.parse() to change the string into an array:
var res = '[100, 200]';
var resParsed = JSON.parse(res);

Then you can access the elements of the array as you were trying to before:
alert(resParsed[0]);


text:
Q: Move Javascript Object within Multidimensional Array / Object By ID or Path? I am working on a new kind of drag and drop nestable menu admin that uses JSON as it's source data and always rebuilds from JSON, rather than hoping that the .serialize() functions people keep using will work.
Here is a link to where I am at: https://codepen.io/ajhalls-the-selector/pen/qBaPRyr
I have a couple helper functions that get me some of what I need from the events. I need to be able to move, or copy, elements (including all sub elements) to a new destination. The copy part was easy, but the move proved more challenging, so I was looking for some help.
If I drag Harry to Gwen, I will want the Harry to be nested under Gwen. By using the callbacks, I know the id of each element, I can also get back the path for each using the findPath function, but then how to move it?
Using the moveJson() function, I can easily add the item to the new location, but I can't seem to find how to delete the original.
function moveJson( Path, NewItem){

    eval(Path).children.push(NewItem); // this works to copy
    delete NewItem;
    eval(delete NewItem); //also tried
    delete eval(NewItem); // and this
}
moveJson('jsonData[0]["children"][1]["children"][0]',jsonData[1]);

I have tried a number of ways to pass the variables in using strings, or not, and multiple ways to delete. I have tried creating new objects to return instead of modifying the global. I tried flattening it, then moving it while flattened, and unflattening, but the string.includes() doesn't work when you give it strings with brackets.
Any tips for a simpler way of relocating an object using it's ID, or using it's absolute path?
As a side note, I realize eval() is discouraged, but not sure yet a better way of keeping things extremely dynamic. Since I don't know how deeply nested this dataset may get, working with the string result from findPath was nice and easy.
Here is the data I was working with:
var jsonData = [
  {
    "id": 1,
    "parent_id": "0",
    "capacity": 2,
    "name": "Alan",
    "group": "BootstrapGlyphicon",
    "code": "",
    "prefix": "",
    "modifier": "",
    "custom": "",
    "sortorder": null,
    "status": "INACTIVE",
    "ui": {
      "draggable": "true",
      "ondragstart": "dragstart_handler(event);",
      "ondragend": "dragend_handler(event);",
      "ondrop": "drop_handler(event);",
      "ondragover": "dragover_handler(event);"
    },
    "children": [
      {
        "id": 2,
        "parent_id": "1",
        "capacity": 2,
        "name": "Samantha",
        "group": "BootstrapGlyphicon",
        "code": "",
        "prefix": "",
        "modifier": "",
        "custom": "",
        "sortorder": null,
        "status": "INACTIVE",
        "ui": {
          "draggable": "true",
          "ondragstart": "dragstart_handler(event);",
          "ondragend": "dragend_handler(event);",
          "ondrop": "drop_handler(event);",
          "ondragover": "dragover_handler(event);"
        },
        "children": [{
            "id": "5",
            "parent_id": "3",
            "capacity": 2,
            "name": "Harry",
            "group": "BootstrapGlyphicon",
            "code": "",
            "prefix": "",
            "modifier": "",
            "custom": "",
            "sortorder": null,
            "status": "INACTIVE",
            "ui": {
              "draggable": "true",
              "ondragstart": "dragstart_handler(event);",
              "ondragend": "dragend_handler(event);",
              "ondrop": "drop_handler(event);",
              "ondragover": "dragover_handler(event);"
            },
            "children": []
          },{
            "id": "7",
            "parent_id": "3",
            "capacity": 2,
            "name": "Pepper",
            "group": "BootstrapGlyphicon",
            "code": "",
            "prefix": "",
            "modifier": "",
            "custom": "",
            "sortorder": null,
            "status": "INACTIVE",
            "ui": {
              "draggable": "true",
              "ondragstart": "dragstart_handler(event);",
              "ondragend": "dragend_handler(event);",
              "ondrop": "drop_handler(event);",
              "ondragover": "dragover_handler(event);"
            },
            "children": []
          }]
      },
      {
        "id": 3,
        "parent_id": "1",
        "capacity": 2,
        "name": "Charlie",
        "group": "BootstrapGlyphicon",
        "code": "",
        "prefix": "",
        "modifier": "",
        "custom": "",
        "sortorder": null,
        "status": "INACTIVE",
        "ui": {
          "draggable": "true",
          "ondragstart": "dragstart_handler(event);",
          "ondragend": "dragend_handler(event);",
          "ondrop": "drop_handler(event);",
          "ondragover": "dragover_handler(event);"
        },
        "children": [
          {
            "id": 4,
            "parent_id": "3",
            "capacity": 2,
            "name": "Gwen",
            "group": "BootstrapGlyphicon",
            "code": "",
            "prefix": "",
            "modifier": "",
            "custom": "",
            "sortorder": null,
            "status": "INACTIVE",
            "ui": {
              "draggable": "true",
              "ondragstart": "dragstart_handler(event);",
              "ondragend": "dragend_handler(event);",
              "ondrop": "drop_handler(event);",
              "ondragover": "dragover_handler(event);"
            },
            "children": []
          }
        ]
      }
    ]
  },
        {
            "id": 6,
            "parent_id": "3",
            "capacity": 2,
            "name": "David",
            "group": "BootstrapGlyphicon",
            "code": "",
            "prefix": "",
            "modifier": "",
            "custom": "",
            "sortorder": null,
            "status": "INACTIVE",
            "ui": {
              "draggable": "true",
              "ondragstart": "dragstart_handler(event);",
              "ondragend": "dragend_handler(event);",
              "ondrop": "drop_handler(event);",
              "ondragover": "dragover_handler(event);"
            },
            "children": []
          }
];