text:
Q: Bind Style-Resource to StackPanel items I am trying to bind a a Style-Resource which is defined in the local ResourceDictionary of a UserControl to all items in a StackPanel.
The ItemSource of the StackPanel is bound to an ObservableCollection<Button> in the ViewModel.
Thus, the aim is to bind the Style-Resource to the Style-Property of these Buttons.
The following simplified approach results in this error:

ArgumentException: Style object is not allowed to affect the Style property of the object to which it applies.

MyViewModel.cs:
 public class MyViewModel
 {
        public ObservableCollection<Button> MyButtons { get; private set; }
 }

MyView.xaml
<UserControl x:Class="MyView"
             d:DataContext="{d:DesignInstance Type=MyViewModel}">

    <UserControl.Resources>
        <ResourceDictionary>
            <Style x:Key="StyleStackPanelButton" TargetType="{x:Type Button}"
                   BasedOn="{StaticResource MyDefaultStyle}">
                <Setter Property="Margin" Value="15" />
                <Setter Property="HorizontalAlignment" Value="Center" />
                <Setter Property="VerticalAlignment" Value="Center" />
            </Style>
        </ResourceDictionary>
    </UserControl.Resources>

    <StackPanel>
        <ItemsControl ItemsSource="{Binding MyButtons}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal">
                        <StackPanel.Resources>
                            <Style TargetType="{x:Type Button}">
                                <Setter Property="Style" Value="{StaticResource StyleStackPanelButton}" />
                            </Style>
                        </StackPanel.Resources>
                    </StackPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>

        <Button Style="{StaticResource StyleStackPanelButton}" />
     </StackPanel>

</UserControl>

I've also tried to use a Converter as suggested here
Binding for WPF Styles
as follows:
...
       <ItemsControl ItemsSource="{Binding ButtonExtensions}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal">
                        <StackPanel.Resources>
                            <Style TargetType="{x:Type Button}">
                                <Setter Property="Style">
                                    <Setter.Value>
                                        <MultiBinding Converter="{StaticResource StyleConverter}">
                                            <MultiBinding.Bindings>
                                                <Binding RelativeSource="{RelativeSource Self}" />
                                                <Binding Source="{StaticResource StyleStackPanelButton}" />
                                            </MultiBinding.Bindings>
                                        </MultiBinding>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </StackPanel.Resources>
                    </StackPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
...

This results in the same error:

ArgumentException: Style object is not allowed to affect the Style property of the object to which it applies.

Is there a any other way to bind a lcoal Style-Resource to a Setter-Property of an Item in a Stackpanel-ItemSource?

A: Since you are adding Buttons directly to the ItemsSource collection, it is sufficient to assign the Button Style to the ItemContainerStyle property of the ItemsControl:
<ItemsControl ItemsSource="{Binding MyButtons}"
              ItemContainerStyle="{StaticResource StyleStackPanelButton}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

Alternatively, declare a default Button Style - without x:Key - in the StackPanel Resources:
<ItemsControl ItemsSource="{Binding MyButtons}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <Style TargetType="Button"
                           BasedOn="{StaticResource StyleStackPanelButton}"/>
                </StackPanel.Resources>
            </StackPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>


text:
Q: Admin: how to make a custom list filter button send GET queryvars I've setted custom columns for a custom post type, and I want to add a filtering functionality. I need to use custom data, so I can't take advantage from things like wp_dropdown_categories and the like.
My current code:
// add select
function add_filter_by_macroarea() {
    global $typenow;
    $post_type = 'distributor';
    $macroaree = array('italy','france','spain','world');

    if($typenow == $post_type) {
      $html = '<select id="filter-by-macroarea" name="macroarea">';

      foreach($macroaree as $macroarea){
        $html .= '<option value="' . $macroarea . '">' . $macroarea . '</option>';
      }

      $html .= '</select>';
      echo $html;
    };
}

add_action('restrict_manage_posts', 'add_filter_by_macroarea');

// add filtered contents
function convert_id_to_term_in_query($query){
  global $pagenow;
  $post_type = 'distributor';
  $q_vars = &$query->query_vars; // stop, not finished
  var_dump($q_vars); // just to see query vars, not already setted

}

add_filter('parse_query', 'convert_id_to_term_in_query');

Now, I'm at the point I need to read a custom GET queryvar, the filter selection. Say it's called 'macroarea' and the values should be 'italy', 'france', 'spain' or'world'.
My issue is: how can I pass such a custom queryvar?

A: Thanks to @cybmeta I was able to solve my issue. Below I post all the relevant code. Keep in mind it refers to a 'distributor' custom post type that uses 4 custom taxonomies ('italy','france','spain','world').
// add columns
function add_distributor_columns($table_columns){
  $area_column = array('area' => 'Area');
  $macroarea_column = array('macroarea' => 'Macroarea');
  // put them on the right position
  $table_columns = array_slice($table_columns, 0, 2, true) + $area_column + $macroarea_column + array_slice($table_columns, 2, NULL, true);
  return $table_columns;
}

add_filter('manage_distributor_posts_columns', 'add_distributor_columns', 10);

// add contents to columns
function add_contents_to_distributor_columns($column_name, $id){
  global $post;
  $post_id = $post->ID;

  if($column_name == 'area'){
    $italy_areas = (array) get_the_terms($post_id,'italy');
    $france_areas = (array) get_the_terms($post_id,'france');
    $spain_areas = (array) get_the_terms($post_id,'spain');
    $world_areas = (array) get_the_terms($post_id,'world');

    $areas = $italy_areas + $france_areas + $spain_areas + $world_areas;

    if(!empty($areas) && $areas[0] !== false){
      $areas_names = array();

      foreach($areas as $area){
        $area_name = $area->name;
        $areas_names[] = $area_name;
      }

      echo implode(', ',$areas_names);
    }
  }//end if

  if($column_name == 'macroarea'){
    $macroareas = array();

    if(has_taxonomy('italy', $post_id)) $macroareas[] = 'Italia';
    if(has_taxonomy('france', $post_id)) $macroareas[] = 'Francia';
    if(has_taxonomy('spain', $post_id)) $macroareas[] = 'Spagna';
    if(has_taxonomy('world', $post_id)) $macroareas[] = 'Mondo';

    if(!empty($macroareas)) echo implode(', ',$macroareas);
  }//end if

}// add_contents_to_distributor_columns

add_action('manage_distributor_posts_custom_column', 'add_contents_to_distributor_columns', 10, 2);

// add macroarea filter
function add_filter_by_macroarea() {
    global $typenow;
    $post_type = 'distributor';
    $macroaree = array('all','italy','france','spain','world');
    $selected = isset($_GET['macroarea']) ? $_GET['macroarea'] : '';

    if($typenow == $post_type) {
      $html = '<select id="filter-by-macroarea" name="macroarea">';

      foreach($macroaree as $macroarea){
        $s = ($macroarea == $selected) ? ' selected="selected"' : '';
        $html .= '<option value="' . $macroarea . '"' . $s . '>' . $macroarea . '</option>';
      }

      echo $html .= '</select>';
    };
}

add_action('restrict_manage_posts', 'add_filter_by_macroarea');

// add contents to filtered list
function convert_id_to_term_in_query($query){
  global $pagenow, $post_type;

  if($pagenow == 'edit.php' && $post_type == 'distributor'){
    $selected = isset($_GET['macroarea']) ? $_GET['macroarea'] : null;

    if($selected && $selected != 'all'){
      $terms_ids = wp_list_pluck(get_terms($selected), 'term_id');

      $query->query_vars['tax_query'] = array(
        array(
          'taxonomy' => $selected,
          'field' => 'term_id',
          'terms'    => $terms_ids,
        )
      );
    }// if selected
  }// if right page
}// end filter

add_filter('parse_query', 'convert_id_to_term_in_query');

// UTILITY FUNCTIONS ---------- //

function get_taxonomies_info($post_id = null){
  if(!$post_id){ // if not passed, try to get the ID
    global $wp_query;
    $post_id = $wp_query->get_queried_object_id();//current post id
  }

  global $wpdb;
  return $wpdb->get_results($wpdb->prepare("
      select tax.taxonomy as taxonomy, group_concat(tr.name) as term_names, group_concat(tr.term_id) as term_ids
      from " . $wpdb->prefix . "term_taxonomy tax
      INNER JOIN " . $wpdb->prefix . "term_relationships rel ON tax.term_taxonomy_id =rel.term_taxonomy_id
      INNER JOIN " . $wpdb->prefix . "terms tr ON tr.term_id = tax.term_id
      WHERE rel.object_id = %d
      GROUP BY taxonomy
  ",$post_id),OBJECT_K);
}

function has_taxonomy($taxonomy_slug, $post_id = null){
  if(!$post_id){// if not passed, try to get the ID
    global $wp_query;
    $post_id = $wp_query->get_queried_object_id();//current post id
  }

  return array_key_exists($taxonomy_slug, get_taxonomies_info($post_id));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to back up only the structure without data when backing up mongodb? When backing up mongodb, I want to back up only the collection information about the database. Is there a way?
I am asking if there is a way to back up only the colllection without data using mongodump.

A: It has been noted that MongoDB is and remains schema-less, so unless you use Mongoose or another ORM, is it difficult to get the schema directly from the data.
That being said, there is a tool called mongodb-schema that can read your documents and INFER a schema from them. It creates a probability metric for each of the potential fields and also the assigned type. It may be useful if you want to retrospectively analyse the collections without resorting to a dump and manual inspection.
You can also use MongoDB Compass to analyse your schemas. This is, again, based on the sampling of your data.
I believe this is the desired output, but for more clarity in your use case, please update the question accordingly.


text:
Q: VB6 equivalent for IntPtr usage I am developing in VB6, and I'm trying to work with C++ dll.
The SDK i have has samples in C#, and i am trying to get the following function to work in VB6:
This is what is see in the .h file:
BS_API_EXPORT void* BS_CALLING_CONVENTION BS2_AllocateContext();
BS_API_EXPORT int BS_CALLING_CONVENTION BS2_Initialize(void* context);

declarations in C#:
extern public static IntPtr BS2_AllocateContext();
extern public static int BS2_Initialize(IntPtr context);

usage in C#:
private IntPtr sdkContext;
sdkContext = IntPtr.Zero;
.
.
sdkContext = API.BS2_AllocateContext();
result = API.BS2_Initialize(sdkContext);

Now I am trying to do the same in VB6:
Declarations:
Public Declare Function BS2_AllocateContext Lib "BS_SDK_V2" () As Long
Public Declare Function BS2_Initialize Lib "BS_SDK_V2" (ByRef Context As Long) As Long

Usage:
Dim sdkContext As Long
sdkContext = BS2_AllocateContext()
result = BS2_Initialize(sdkContext)
                                  <--- VB6 environment crashes

From what I understand , IntPtr is eqvivilant to Long in VB6
but what about void* ?
(I also tried to change the ByRef to ByVal, but than i get "Bad DLL calling convention")
So why does it crash?
I am not getting an error message. The entire VB6 environment is crashing:
"Visual Basic has stopped working
A problem caused the program to stop working correctly.
Windows will close...."

A: In order to call the API you need to marshal the address of the VB integer variable. This can be accomplished using 'VarPtr' on the 'sdkContext' when calling 'BS2_Initialize'.
E.g.
result = BS2_Initialize(VarPtr(sdkContext))


text:
Q: How to add load more feature inside a dropdown option Bellow my simple html code for dropdown option

<select class="form-control" id="myList">
  <option  value="">Please select</option>
  <option  value="1">1</option>
  <option  value="2">2</option>
  <option  value="3">3</option>
  <option  value="4">4</option>
  <option  value="5">5</option>
  <option  value="6">6</option>
  <option  value="7">7</option>
  <option  value="8">8</option>
  <option  value="9">9</option>
  <option value="load">

Load more

  </option>
</select>

What i want to achive. I will show the option 1-5 after when click loadmore then will show more 5. I have researched few resource those are too poor and not so clear instruction. If you guys help me about it i will be glad for that. Thanks to all seniours developers.

A: Use this function on onClick on loadMore id
function addMore() {
    var optionsArr = ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']
    for (let i = 0; i < optionsArr.length; i++) {
        var options = `<option value="${optionsArr[i]}">${optionsArr[i]}</option>`
        $("#myList").append(options)
    }
}

Hope this will help you


text:
Q: Determine phone number based on time zone? I have a (potentially international) phone number. It may or may not have a country code prefix. Does anyone know of a database that will help me map phone number => time zone? I would even just like to map phone number => country, since I can probably create country => time zone by scraping existing data on the web. This is a more complicated problem than it looks; for example, how do I know if it's a US-based number -- e.g. is it a USA area code, or an international country calling code?
Any language is fine; I can port it.

A: The best library I know of for parsing phone numbers in arbitrary formats is libphonenumber.
You can't map countries to time zones for what should be obvious reasons. Both you and someone in California are in the same country, you're not even in close to the same time zones. Other countries are even wider.

A: No. Your primary problem here lwill be that lots of countries share each timezone. Eg UK and Ireland, France, Germany, ITaly etc.
You may be able to guess based on number structure, but your best bet I'm afraid is to try to get the code in any new data.


text:
Q: Why does C correctly output an integer when I only allocate 1 byte for it? I've been digging into memory allocation and pointers in C. I was under the impression that if you do not allocate enough memory for a value and then try to put that value in that memory cell, the program would either crash or behave incorrectly.
But what I get is a seemingly correct output where I'd expect something else.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    // Here we intentionally allocate only 1 byte,
    // even though an `int` takes up 4 bytes
    int * address = malloc(1);

    address[0] = 16777215; // this value surely takes more than 3 bytes. It cannot fit 1 byte.
    address[1] = 1337; // just for demo, let's put a random other number in the next memory cell.

    printf("%i\n", address[0]); // Prints 16777215. How?! Didn't we overwrite a part of the number?

    return 0;
}

Why does this work? Does malloc actually allocate more than the number of bytes that we pass to it?
EDIT
Thanks for the comments! But I wish to note that being able to write to unassigned memory is not the part that surprises me and it's not part of the question. I know that writing out of bounds is possible and it is "undefined behavior".
For me, the unexpected part is that the line address[1] = 1337; does not in any way corrupt the int value at address[0].
It seems that the explanations for this diverge, too.

*

*@Mini suggests that the reason for this is that malloc actually allocates more than what's passed, because of cross-platform differences.

*@P__J__ in the comments says that address[1] for some reason points to the next sizeof(int) byte, not to the next byte. But I don't think I understand what controls this behavior then, because malloc doesn't seem to know about what types we will put into the allocated blocks.
EDIT 2
So thanks to the comments, I believe I understand the program behavior now.
The answer lies in the pointer arithmetic. The program "knows" that an address pointer is of type int, and therefore adding 1 to it (or accessing via address[1]) gives an address of the block that lies 4 (sizeof(int)) bytes ahead.
And if we really wanted, we could move just one byte and really corrupt the value at address[0] by coercing address to char * as described in this answer
Thanks to all and to @P__J__ and @Blastfurnace in particular!

A: malloc often allocates more than you actually ask for (all system/environment/OS dependent), which is why it works in you scenario (sometimes). However, this is still undefined behavior it can actually allocate only 1 byte (and you are writing to what may not be allocated heap memory).

A: C doesn't mandate any kinds of bounds checking on array accesses, and it's possible to overflow storage and write into memory you don't technically own.  As long as you don't clobber anything "important", your code will appear to work as intended.
However, the behavior on buffer overruns is undefined, so the results will not generally be predictable or repeatable.


text:
Q: In django which is the best way to make a slideshow of background images? I have three images in my urls file that randomly become my homepage background
but what is the best way to constantly make the home page change background image every 5 seconds from the from the three pictures specified in the urls file?
Whats the best way to do it?

Django
def homePage(request):
    images = ['RockTop', 'TheThree', 'ThreeBoys']
    background_image = 'static/' + images[random.randint(0,2)] + '.JPG'
    return render(request, 'homePage.html', {'background_image': background_image})

A: i would render all images to frontend and slide with jquery.
something like: (you need to adjust variables names accordingly, these are almost pseudo ones)
{% for im in all_images %}
   <img src="im.url" id="im_{{ forloop.counter }}" />
{% endfor %}

jquery:
var random_im_id = Math.floor(Math.random() * 3) + 1; // random number between 1 - 3
var background_image = 'url(' + $('#im_' + random_im_id).attr('src') +  ')';

$('body').css('background-image', background_image);


text:
Q: Problem with publishing GIS resources in ArcGIS Server I have ArcGIS 9.3 on Win 7 sp1 integrated with VB.Net 2008. I have connected my server in ArcCatalog and publish mxd to ArcGIS Server without any problem, put after I open ArcGIS Server Manager and publish GIS services to GIS resources it gives me this error:

A: Checking and posting the event log as Jamie suggests would be very helpful.  Based on your description though, it sounds like either the data in your published map document is not on a network resource that the server can see, or the ArcGISSOC user does not have permissions to read the data store. Check the permissions on your data. See the "Grant permissions to data diretories" section in ArcGIS Server Help.


text:
Q: nice URL relative link issue I am using nice urls without rewrites (e.g. /my/site/index.php/some/page). I am having trouble with stylesheet links. For example, sheet.css is getting interpreted as /my/site/index.php/some/sheet.css.
How can I get it to link correctly, for any prefix (/my/site/) and any depth suffix (/some/page)?

A: add a / in front of any resource to point them to the root directory of your site:
<link rel="stylesheet" type="text/css" href="/sheet.css">

You can always setup a CONSTANT in your included config file and add the site path to it
define('HOST_URL', 'http://www.example.org/my/site/');
define('HOST_URL', 'http://www.example.net/my/site2/');

then  you can call any file and change the paths whenever you want from 1 single file.
Eg:
<link rel="stylesheet" type="text/css" href="<?php echo HOST_URL; ?>sheet.css" />
<script type="text/javascript" src="<?php echo HOST_URL; ?>script.js"></script>
<img src="" alt="<?php echo HOST_URL; ?>images/image.jpg" border="0" />


text:
Q: Assertion for .dat reading fails Here are the functions I am calling:
bool getPlayer(int& jerseyNumber, string& firstName, string& lastName, int& minutesPlayed){
    infile >> jerseyNumber;
    assert(!infile.fail());
    infile >> firstName;
    assert(!infile.fail());
    infile >> lastName;
    assert(!infile.fail());
    infile >> minutesPlayed;
    assert(!infile.fail());

    //set values
    return true;
}

void getShooting(int& fga, int& fgm, int& tpa, int& tpm, int& fta, int& ftm){
    infile >> fga;
    assert(!infile.fail()); //check if it failed, and abort.
    infile >> fgm;
    assert(!infile.fail());
    infile >> tpa;
    assert(!infile.fail());
    infile >> tpm;
    assert(!infile.fail());
    infile >> fta;
    assert(!infile.fail());
    infile >> ftm;
    assert(!infile.fail());
    return;
}

My main function is calling them in this way:
infile.open("lab3.dat");
fout.open("output.txt");
for (int i = 0; i < SIZE; i++){
    getPlayer(jersNums[i], firstNames[i], lastNames[i], totalMinutes[i]);
    getShooting(fgas[i], fgms[i], tpas[i], tpms[i], ftas[i], ftms[i]);
}
infile.close();fout.close();

The getShooting functions assertion fails right after the infile >> fta; line.
I have no idea why. The structure of lab3.dat is as follows (each number is a different data point):
99 George Mikan 379 179 72 0 0 81 62 58 86 0 0 19 0 42

This isn't necessarily the way I want to do it but this is for a computer science assignment, so I have to do it this way. Is there any obvious reason why this assertion is failing?


text:
Q: jpa save worked but no data I saved data for test by use hibernate but when i call it there is no data and i dont know why..
my test code is like this
 @Test
void postPerson() throws Exception{
    PersonDto personDto = PersonDto.of("martin", "programming", "판교", LocalDate.now(),
"programmer", "010-1111-2222");
    mockMvc.perform(
            MockMvcRequestBuilders.post("/api/person")
            .contentType(MediaType.APPLICATION_JSON)
            .content(toJsonString(personDto)))
            .andDo(print())
            .andExpect(status().isCreated());

    Person result = personRepository.findAll(Sort.by(Sort.Direction.DESC, "id")).get(0);

    assertAll(
            () -> assertThat(result.getName()).isEqualTo("martin")
    );
}

and controller
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void postPerson(@RequestBody PersonDto personDto){
    personService.put(personDto);
}

and service
@Transactional
public void put(PersonDto personDto) {
    Person person = new Person();
    person.set(personDto);
    person.setName(personDto.getName());
    personRepository.save(person);
}

save worked so 201 returned but there is no saved data .. i cant understand..

A: Tests are rolled back by default. That's why it works but you see no data.
You might temporary add
@Rollback(false)

to your test.


text:
Q: Strange behavior of StampedLock with Thread class I'm running this code in IntellijIDEA Community on Windows
import static java.lang.Thread.sleep;

public class Main {
    public static void main(String[] args) {

        StampedLock lock = new StampedLock();
        Thread th = new Thread(() -> {
            long stamp = lock.tryOptimisticRead();
            try {
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
                sleep(1);
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
                sleep(2);
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
            } catch (InterruptedException ex) {
            } finally {
                lock.unlock(stamp);
            }
        });

        th.start();
        try {
            th.join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

and I'm getting the valid output, but with the IllegalMonitorStateException
"C:\Program Files\Java\jdk1.8.0_171\bin\java.exe" "-javaagent:C:\Users\izotova\IntelliJ IDEA Community Edition 2019.3.3\lib\idea_rt.jar=54575:C:\Users\izotova\IntelliJ IDEA Community Edition 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_171\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\rt.jar;C:\Users\izotova\Documents\case-study-java-backend\Tasks\out\production\tasks" Main
Optimistic Lock Valid: true
Optimistic Lock Valid: true
Optimistic Lock Valid: true
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.util.concurrent.locks.StampedLock.unlock(StampedLock.java:609)
    at Main.lambda$main$0(Main.java:22)
    at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 0

I honestly have no ideas, what could cause this, the stamp and lock are fine, no idea, what I'm doing incorrectly. Maybe you have some ideas or insights about how stamped locks work internally?

A: I'm going to double down on the guess in my comment above and say that I don't think that optimistic locks can be unlocked (or need to be).
Here is an example pulled straight from the documentation of StampedLock.  Notice that in the unlock portion of the code they are careful to call unlock() only if the stamp has been upgraded from an optimistic lock to a read lock.  The example does NOT try to unlock if the lock is still an optimistic lock.
   // a read-only method
   // upgrade from optimistic read to read lock
   double distanceFromOrigin() {
     long stamp = sl.tryOptimisticRead();
     try {
       retryHoldingLock: for (;; stamp = sl.readLock()) {
         if (stamp == 0L)
           continue retryHoldingLock;
         // possibly racy reads
         double currentX = x;
         double currentY = y;
         if (!sl.validate(stamp))
           continue retryHoldingLock;
         return Math.hypot(currentX, currentY);
       }
     } finally {
       if (StampedLock.isReadLockStamp(stamp))
         sl.unlockRead(stamp);
     }
   }


text:
Q: Why can't I read session variables I have a c# .net web application.  I create session variables but when I try to read them after I leave the page that they were created from I can't.
Created on page 1
Session["UserName"] = "WhatEver";

Then I do
Response.Redirect("~/whatever.aspx");

and try to read to read the session variable in the Page_Load method of the new page
string userName = Session["UserName"].ToString();

I receive Object reference not set to an instance of an object.
Why am I receiving this error and what can I do to fix the problem?

A: This may help:
Response.Redirect("~/whatever.aspx",false);

From this article:

This does not abort the thread and thus conserve the session token. Actually, this overload is used internally by RedirectFromLoginPage.

A: Might be sessionState is turned off in your config file
<sessionState mode="Off/>

Change to InProc [Depends]
<sessionState mode="InProc" timeout ="60" />

A: I had the exact same problem, and I managed to overcome this issue, but frankly I don't understand the solution 100%, anyways, what I done was to create a "Global.asax" file to my project from the "Add New Item" menu. Just copy-paste the following code inside your global file. The code inside this file is as follows:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;

using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ENTER_YOUR_NAMESPACE
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {

        }

        void Application_End(object sender, EventArgs e)
        {
            /* Code that runs on application shutdown */
            Session_End(sender, e);
        }

        void Application_Error(object sender, EventArgs e)
        {

        }

        void Session_Start(object sender, EventArgs e)
        {

        }//end void Session_Start

        void Session_End(object sender, EventArgs e)
        {

        }//end void Session_End

    }//end class Global
}//end namespace


text:
Q: Не получается сделать плавное раскрытие меню при наведении Есть меню, элементы которого содержат подменю хочу раскрывать при наведении на эти пункты и переворачивать стрелку вниз. Пишу код, но почему-то не выходит

$('.menu').hover(function() {
  $(this).siblings('ul').toggle(400);
});
.children {
  display: none;
}
.menu li {
  list-style: none;
}
.menu > li.cat-item > a {
  overflow: auto;
  /* очищает обтекание */
}
.menu > li.cat-item > a:after {
  font-family: 'fontawesome';
  font-size: 14px;
  content: "\f0da";
  float: right;
  margin-right: 15px;
  display: block;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

Name 1

Subname 1

Subname 2

Name 2

Name 3

A: Не верно используется метод siblings он ищет соседние элементы удовлетворяющие условию, а вам нужно искать дочерние, то есть, либо find либо children

$('.menu').hover(function() {
  $(this).find('ul').toggle(400);
});
.children {
  display: none;
}
.menu li {
  list-style: none;
}
.menu > li.cat-item > a {
  overflow: auto;
  /* очищает обтекание */
}
.menu > li.cat-item > a:after {
  font-family: 'fontawesome';
  font-size: 14px;
  content: "\f0da";
  float: right;
  margin-right: 15px;
  display: block;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

Name 1

Subname 1

Subname 2

Name 2

Name 3

A: Я бы рекомендовал делать так, до версии  jQuery 1.8 включительно, если версия выше то по примеру @Grundy
var toggleMenu = function() {
    var $this = $(this);
    if (!$this.hasClass('menu')) {
        return false;
    }
    $this.find('ul').toggle(400);
};
$(document).off('hover', '.menu', toggleMenu);
$(document).on('hover', '.menu', toggleMenu);

Данный кусок не нужно вешать на DomReady


text:
Q: How to get the names of the json columns from firebase? I leave an example below my question
I would like to list the names of the dates, such as 24_1_2020, 25_1_2020, etc ...

A: Assuming that teLm ... IWV2 is the uid of the authenticated user, to display only those keys 24_1_2020, 25_1_2020, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Mensaje").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();
            Log.d(TAG, key);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

See, I have used the getChildren() method to loop through the DataSnapshot object, which basically contains all children under the uid node. Calling getKey(), you can get each key that is corresponding to each child.
If teLm ... IWV2 is not the uid of the authenticated user, then simply add that String directly in your reference:
DatabaseReference uidRef = rootRef.child("Mensaje").child("teLm ... IWV2");


text:
Q: Php Simple Dom Parser Unable to store data in array I'm using Simple Html Dom to read an external site and its underpage to get some information for some car objects, either way, when echoing everything I've found with simple html the page loads in about 10 second which is expected but when i try to save it inside an array the page gets stuck and memory gets eaten.
$html = file_get_html($dealer);
$cars = $html->find('div[id=item_list]',0);
foreach($cars->find('a.item_link') as $carObj){
     $carlink = $carObj->href;
     $carhtml = file_get_html($carlink);
     $cardata = $carhtml->find('div[id=view_body] div.span14',0);
     (string) $title = $carhtml->find('div[id=view_header] div h2',0);

if i put this row after the code it gets stuck in a infinite loop
     //$carsarray[] = array('ctitle' => $title);

but echoing the same variable works with no problem
     echo $title;

rest of the code
     unset($images);
     $cardata->clear();

     unset($cardata);

}
$cars->clear();
unset($cars);

A: You should already be able to use the variable like an array.  Its not really an array though, its a DOM object that Simple Dom Parser creates.  I'm not sure why, but it causes that infinite loop problem when looped through a certain way.  Making good use of $yourobject->find to keep traversing down the DOM, and $yourobject->plaintext method worked for me.
Looks like in your case $carsarray[] = array('ctitle' => $title->plaintext); might do the trick. Hope this helps.


text:
Q: Updating after delete | mysql trigger I have two tables for example table1 and table2. If something is deleted in table1 i want to update a column in table2. Is this even possible with a trigger in phpmyadmin? if yes what do i have to add or which syntax i have to use for it to work?
I tried this so far:
DELIMITER //
CREATE TRIGGER `update` AFTER DELETE ON table1
FOR EACH ROW BEGIN
-- this is the part i dont know what to do and i couldnt find any related to my task

END//
DELIMITER ;

A: Well, in your TRIGGER you can access the value you just deleted with OLD.your_column_name.
So just do :
DELIMITER //
CREATE TRIGGER `update` AFTER DELETE ON table1
FOR EACH ROW BEGIN

UPDATE table2 SET column_name = your_new_value WHERE column_name = OLD.old_value;

END//
DELIMITER ;


text:
Q: Remove duplicate JSON keys in python I have a 2M entries json that looks like this with some keys as integers that occasionally repeat and I'm trying to figure out how to remove all duplicates in a dictionary:
{
"1": {
    "id": 1,
    "some_data": "some_data_1",
},
"2": {
    "id": 2,
    "some_data": "some_data_2",
},
"2": {
    "id": 2,
    "some_data": "some_data_2",
},
"3": {
    "id": 3,
    "some_data": "some_data_3",
},

}
So, basically, I'm looking for a generic function that will iterate over dict_keys, look for duplicates and return a clean json. Tried flicking with { each[''] : each for each in te }.values(), but to no avail.


text:
Q: How to build a version of Boost with _GLIBCXX_DEBUG? When debugging my code, I like to build it with -g -D_GLIBCXX_DEBUG GCC flags (and no -O3 -DNDEBUG). Unfortunately, using these flags prevents it from linking with "normal" Boost.
Is there a simple recipe for building Boost with custom GCC flags like this? (Another SO question about this doesn't seem to cover -D_GLIBCXX_DEBUG)

A: You can build the boost libraries as described here: https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html
You can specify the macros for the boost libraries on the b2 command line by adding: define=MACRO_NAME=MACRO_VALUE for each macro.


text:
Q: Is it possible make a back-end for WordPress with WordPress? Here's what my boss wants me to do on our website: display how often one of our other websites has been 'Up and Running' by percentage of time per month. I told him I would need to make an AWS instance that pings that other website and stores the historic data (and sends it to our WordPress site when requested). But he says it is possible to do all of this through WordPress. Who is right? Are there plug-ins for this kind of thing?

A: Why not just tell him to sign up to uptimerobot.com, more accurate than most with SMS, Email and Push alerts to downtime.


text:
Q: Salesforce button uses same Docusign template regardless of related Opportunity when I use the button, the same Docusign template is used regardless of the associated Opportunity.  If I move the (OPPNAME = 'WorldQuant LLC%') line to the end, a different template is used, but again its the same regardless of Opportunity Name.  I am new to Javascript so feel free to dumb down any answers, thanks.
var OPPNAME;
var PICKDSTEMPLATE;
OPPNAME == '{!JSENCODE(Opportunity.Name)}';
PICKDSTEMPLATE = '{!Opportunity.Type_of_Opportunity__c}';
if (OPPNAME = 'WorldQuant LLC%')
{
DST = '75E95019-6513-4EE9-8f6B-C2FD9A99B9C2';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corp/Ind')
{
DST='38FE916A-0F28-46FD-BBAB-28CA54621B7E';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corporate from Lead')
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corporate')
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}

A: Got this to work with some help:
var ACCNAME;
var PICKDSTEMPLATE;
ACCNAME = '{!Opportunity.Account}';
PICKDSTEMPLATE = '{!Opportunity.Type_of_Opportunity__c}';
if ((ACCNAME == 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corp/Ind' || PICKDSTEMPLATE == 'Corporate'))
{
DST = '75e95019-6513-4ee9-8f6b-c2fd9a99b9c2';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corp/Ind'))
{
DST='38FE916A-0F28-46FD-BBAB-28CA54621B7E';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corporate from Lead'))
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corporate'))
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}


text:
Q: Images dissapears in mobile view of wordpress theme I faced off with such problem: the web site http://amfibija.lv/, and when it shows mobile layout, images displayed for 2-3 seconds and then dissapeared, instead of it just transparent rectangle with a digit:
Any ideas how to fix it?

A: Yes, It looks like your images are trying to pull a retina version of the image. If you look at the paths to the images while you're in mobile view you will see the following:
<img src="http://amfibija.lv/wp-content/uploads/2014/11/model-334739_150-80x80@2x.jpg" alt="Георгий avatar" width="80" height="80">

From what I can tell after trying to view the image via the path provided, the image doesn't exist.
I would recommend uploading a retna version of your image to that specific location. That should solve your problem.
If you view the page using chrome and open it using the mobile developer tools, you can see the same results and view the page code to help you see the issue.


text:
Q: How do I increase the width of a navbar dropdown? I'm using bootstrap and trying to put a search form inside a navbar dropdown menu, but I'm finding the form looks squashed because the width of the dropdown is too small. Also, the form elements are not how I would like. How do I fix this?
I'm new to CSS and web design in general. Please help!
Current layout:

What I'm trying to achieve:

      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
        Toggle navigation

      </button>
      Brand

Home

Browse

        Locate

            <form class="navbar-form navbar-left" role="search">

                <button type="button" class="btn btn-default navbar-btn">

</button>
                <input type="text" class="form-control" placeholder="Address">

                <button type="submit" class="btn btn-default">Search</button>

Link

Link

            </form>

        USER

 Link

 Link

 Link

A: Try this:
.navbar-nav>li>.dropdown-menu { width: yourwidth }

You can add display: inline-block  so that its width will be according to its content automatically

A: You can increase the "min-width" value in the dropdown.less
or make a new line in the css
.dropdown-menu { min-width: 200px }


text:
Q: Selenium not able to find the search field Here is the website - https://www.phptravels.net/m-hotels
I am not able to find the field called the city field(see attached screenshot) Even the selenium is not able to record that field. I want to enter the text in that field.

This is what i have tried but it is not working:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.phptravels.net/m-hotels")
a = driver.find_element_by_class_name("select2-choice")
a.click()
city = driver.find_element_by_css_selector(".select2-input.select2-focused")
city.send_keys("Test")

A: Try to use below code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.phptravels.net/m-hotels")

wait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Search by Hotel or City Name"))).click()
wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#select2-drop .select2-input"))).send_keys("Test")

A: another alternative, using xpath
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.phptravels.net/m-hotels")
a = driver.find_element_by_class_name("select2-choice")
a.click()
city = driver.find_elements_by_xpath('(//*[@id="select2-drop"]/div/input)')
city[0].send_keys("Jakarta")


text:
Q: Numerical instability creating wrong result on Mixed-Integer Linear Program, bug or error? I created a bug ticket for Google or-tools Java library.
I was told it is a feature of Mixed-Integer solvers.
But those results for this simple program makes me think it is a bug, since I would have to round every coefficients in order to not get a wrong result.
Program:
Minimize epsPlus + epsMinus
x, y : integer
epsPlus, epsMinus : linear
19 <= x <= 23
21 <= y <= 47
x + y <= 60
x - 0.499999999y - epsPlus + epsMinus = 0

Results with different y coefficients on the last constraint:
0.499999990 working : objective=0.000000, x=20.000000, y=40.000000, epsPlus=0.000000, epsMinus=0.000000
0.499999999 failing : objective=1.500000, x=19.000000, y=41.000000, epsPlus=0.000000, epsMinus=1.500000
0.500000000 working : objective=0.000000, x=20.000000, y=40.000000, epsPlus=0.000000, epsMinus=0.000000

Can you confirm it is not a bug?
Minimal code:
Loader.loadNativeLibraries();
MPSolver solver = MPSolver.createSolver("SCIP");

// variables
MPVariable x = solver.makeIntVar(19, 23, "x");
MPVariable y = solver.makeIntVar(21, 47, "y");
MPVariable epsPlus = solver.makeNumVar(0, Double.POSITIVE_INFINITY, "epsPlus");
MPVariable epsMinus = solver.makeNumVar(0, Double.POSITIVE_INFINITY, "epsMinus");

// constraints
MPConstraint constraint1 = solver.makeConstraint(60, 60, "constraint1");
constraint1.setCoefficient(x, 1);
constraint1.setCoefficient(y, 1);
MPConstraint constraint2 = solver.makeConstraint(0, 0, "constraint2");
constraint2.setCoefficient(x, 1);
constraint2.setCoefficient(y, -0.499999999);
constraint2.setCoefficient(epsPlus, -1);
constraint2.setCoefficient(epsMinus, 1);

// objective
MPObjective objective = solver.objective();
objective.setCoefficient(epsPlus, 1);
objective.setCoefficient(epsMinus, 1);
objective.setMinimization();

// result
solver.solve();
System.out.println(String.format("objective=%f, x=%f, y=%f, epsPlus=%f, epsMinus=%f", objective.value(), x.solutionValue(), y.solutionValue(), epsPlus.solutionValue(), epsMinus.solutionValue()));

https://github.com/google/or-tools/issues/3098
Thanks :)


text:
Q: pl/sql need to know the techniques behind May I know wat kind of technique used in below to update and how it works
This question has been taken from our forum::
update  demo_table new
set     (new.quantity, new.actual_cost) =
        (
        SELECT  old.quantity, old.actual_cost
        FROM    demo_table old
        WHERE   old.object_name = new.object_name
            and old.object_type = new.object_type
            and old.trans_date = new.trans_date
            and old.trans_type = 1
)
where new.trans_type = 9

A: Here's a basic structure of how an update query works:
UPDATE tableName SET column = value WHERE condition = true;

In your case, you're updating the demo_table new table with a condition of new.trans_type = 9.
The tricky thing here is you're using your sub query as your value to set the columns as. A sub query is basically another query that would return a result. In this case, your sub query is a select statement from the demo_table old table.


text:
Q: Convert NoSQL data to SQL data Python I try to use Python access Redshift database, and use the following code to see a few records. (credential is not shown, but it works) And it's at NoSQL format. How can I change it to relational data structure format or a dataframe? Thanks!
import psycopg2
con=psycopg2.connect(...)

cur = con.cursor()
cur.execute("SELECT * FROM public.sku_lu limit 2;")
cur.fetchall()

Output:
[('sku_1', 'true'),
('sku_2', 'false')]
The output is NoSQL format without a column name. How may I change it to a relational data structure format or a dataframe like below?

Sku
Base

sku_1
true

sku_2
false

A: import numpy as np
import pandas as pd

np_array = np.array(cur.fetchall())
data = pd.DataFrame(np_array, columns=['Sku', 'base'])

Solve with above by adding column names


text:
Q: Windows 8 / Ubuntu in GRUB I had problem with mounting "Windows disk" in ubuntu, I have solved this. But now I need help with GRUB. I can't boot Windows by selecting windows drive because I have installed GRUB on all disks. So, is there any way to add Windows into grub menu?

A: You need to repair windows boot for grub to find it, lets see the relevant log:
00000190  64 69 73 6b 20 72 65 61  64 20 65 72 72 6f 72 20  |disk read error |
000001a0  6f 63 63 75 72 72 65 64  00 0d 0a 42 4f 4f 54 4d  |occurred...BOOTM|
000001b0  47 52 20 69 73 20 6d 69  73 73 69 6e 67 00 0d 0a  |GR is missing...|
000001c0  42 4f 4f 54 4d 47 52 20  69 73 20 63 6f 6d 70 72  |BOOTMGR is compr|
000001d0  65 73 73 65 64 00 0d 0a  50 72 65 73 73 20 43 74  |essed...Press Ct|
000001e0  72 6c 2b 41 6c 74 2b 44  65 6c 20 74 6f 20 72 65  |rl+Alt+Del to re|
000001f0  73 74 61 72 74 0d 0a 00  8c a9 be d6 00 00 55 aa  |start.........U.|
Once you fix your windows boot, repair grub and you most likely will be done.


text:
Q: Parent component state change is not detected by child component when using redux-form and connect Parent component state change is not detected by child component when using redux-form and connect but when you edit someother field then it populates.
Here is the Sandbox code to reproduce this problem:
https://codesandbox.io/s/xljrpxk0yo

A: I was mutating the data unknowingly.
Ref to the solution:
https://twitter.com/kailashvele/status/958336847423270914


text:
Q: Attempting to create a multiple linear regression model with variables of differing lengths? I am trying to run a multiple linear regression but my variables have slightly different lengths. My variables are SVI_1 (N=133), SVI_2 (N=131), SVI_3 (N=135), and SVI_4 (N=132). I am trying to assess the impact of these 4 variables on my dependent variable which is Anx_Diff (difference in anxiety scores).
My large data file is "Cohort" with many different columns of data. I have created the subsets below to select out the column "svi_avg" for each subgroup (the SVI 1-4 numbers correspond to quartiles):
SVI_1 = subset(Cohort, svi_avg >= 0.61175, select=c(svi_avg))
SVI_2 = subset(Cohort, svi_avg >= 0.32600 & svi_avg < 0.61175, select=c(svi_avg))
SVI_3 = subset(Cohort, svi_avg >= 0.11650 & svi_avg < 0.32600, select=c(svi_avg))
SVI_4 = subset(Cohort, svi_avg <= 0.11650, select=c(svi_avg))
This was the model I tried to use (I used the unlist() function because I realized this needs to be a vector):
SVI_model <- lm(Diff_Anx ~ unlist(SVI_1 + SVI_2 + SVI_3 + SVI_4), data = Cohort)
But I get this error message:
Error in Ops.data.frame(SVI_1, SVI_2) :
'+' only defined for equally-sized data frames
I don't know how to set up a multiple linear regression model for variables of differing size and I am assuming that is the problem. I am pretty new to R and I am also worried I may have subsetted my data wrong and that is the issue? Any help appreciated.


text:
Q: How to convert a div css line to django template line for this particular line? I want to convert a particular template  line containing  and inline css into django template line which will show the static files too. The template line is

What will be the django static template line to load the image?

A: Maybe You can try something like this

Happy Coding!


text:
Q: Arrays and Referencing Consider the following code:
public static void resize(int[] x){
x = new int[x.length*2];
System.out.println(x.length + " ");
}

public static void main(String[] args){
int[] x = {1,2};
resize(x);
System.out.println(x.length);
}

The output is "4 2". The question is: I thought that when we are defining an array in the code of the new length, the other array (the previous one with length 2) would be discarded, as now the value of the array points to the "larger" array. So, why would then print out at the end as length 2? I used Arrays.toString to verify, and indeed, the actual values of the array after the void method are {1,2}. This is confusing, as I thought that the array itself would be changed as the value is a pointer to the memory address (in contrast with using the method on a char/int variable, which would not affect the value of the variable).

A: When you call resize, you pass an array object to the method. This is the basic flow of your program:
initialize array of size 2
pass that array to resize()
  resize has a reference to the value of the array
  resize points it's reference to a new array twice the size of the old reference
  prints "4"
main() prints the size of the initial array "2"

You don't change the original array in the new method, it merely has an array of the same value.

A: Because Java passes by value, the array doesn't change after your call to resize. (I'm assuming the output is actually 4 2, not 2 4.)
If you want resize to effect a permanent change, you should have the method return x; as its final statement (or use a global variable):
public static int[] resize(int[] x){
x = new int[x.length*2];
System.out.println(x.length + " ");
return x;
}

public static void main(String[] args){
int[] x = {1,2};
x = resize(x);
System.out.println(x.length);
}

A: The scope of your x variable in resize
public static void resize(int[] x){
   x = new int[x.length*2];
}

is local to that function. It does not affect the x that was passed in. This means that as soon as resize completes, that local copy disappears and is eventually garbage collected.
If you want to resize the original array, return it. For example:
public static int[] getNewArrayOfDoubleLength(int orig_length){
   return  new int[orig_length * 2];
}

And call it with
x = getNewArrayOfDoubleLength(x.length);

Since arrays are immutable, this is a new array. The original one still exists (although it's inaccessible) until it's garbage collected.


text:
Q: What is the purpose of the "databases" line here in this Firestore security rule? In the documentation bout recursive wildcards: https://firebase.google.com/docs/firestore/security/rules-structure#recursive_wildcards
We have the following:
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the cities collection as well as any document
    // in a subcollection.
    match /cities/{document=**} {
      allow read, write: if <condition>;
    }
  }
}

What is the purpose of the line match /databases/{database}/documents {? I thought I could only create one database per project in Firestore. Does this mean I can create database A and database B within the same project? Do I even need this line if I only want to have 1 database?

A: firebaser here
Currently you can indeed only have one Firestore database per project, but that may change in the future. At that point, the {database} variable can be used to differentiate between the database instances in your project.


text:
Q: Bottom Navigation Bar Floating Button with action covering the whole screen - how to do this? I have an Android application with Bottom Navigation Bar. In the Main Activity I  have a floating button and when I press it, I would like to open a Fragment (or another activity?) that will cover the whole screen (the Bottom NavBar and other content will be below my new opened fragment). I would like to add that this newly opened fragment will be used for adding some item and when the user fills all fileds like name, weight etc. and click "add", the fragment should be closed and we should see our bottom nav bar with its' fragments.
Could you provide the solution to my problem? I would be grateful for some code enabling to do this!
Here are the most important parts of my code:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment_activity_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:navGraph="@navigation/mobile_navigation" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/buttonAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="84dp"
        android:contentDescription="@string/add_button"
        android:src="@drawable/ic_add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt:
package com.example.myapp

import android.os.Bundle
import android.view.View
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.myapp.databinding.ActivityMainBinding
import com.example.myapp.ui.AddProductFragment
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navView: BottomNavigationView = binding.navView

        val navController = findNavController(R.id.nav_host_fragment_activity_main)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(setOf(
                R.id.navigation_expiring, R.id.navigation_storages, R.id.navigation_notifications))
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        // floating button:
        val buttonAdd: View = findViewById(R.id.buttonAdd)
        buttonAdd.setOnClickListener {
            //navigate(R.id.action_login_to_registration)
            //view.findNavController().navigate(R.id.actionAddProduct)
            supportFragmentManager
                .beginTransaction().add(R.id.nav_host_fragment_activity_main, AddProductFragment())
                .commit()
        }
    }
}

fragment_storages.xml: (other fragments I already have are almost the same)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.storages.StoragesFragment">

    <TextView
        android:id="@+id/text_dashboard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

StoragesFragment.kt: (other fragments I already have are almost the same)
package com.example.myapp.ui.storages

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.myapp.databinding.FragmentStoragesBinding

class StoragesFragment : Fragment() {

    private var _binding: FragmentStoragesBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        val dashboardViewModel =
                ViewModelProvider(this).get(StoragesViewModel::class.java)

        _binding = FragmentStoragesBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val textView: TextView = binding.textDashboard
        dashboardViewModel.text.observe(viewLifecycleOwner) {
            textView.text = it
        }
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

fragment_add_product.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.AddProductFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Add Product Fragment" />

</androidx.constraintlayout.widget.ConstraintLayout>

AddProductFragment.kt:
package com.example.myapp.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.myapp.R

class AddProductFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_add_product, container, false)
    }
}

bottom_nav_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_expiring"
        android:icon="@drawable/ic_expiring"
        android:title="@string/title_expiring" />

    <item
        android:id="@+id/navigation_storages"
        android:icon="@drawable/ic_storages"
        android:title="@string/title_storages" />

    <item
        android:id="@+id/navigation_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notifications" />

</menu>

mobile_navigation.xml:
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
    app:startDestination="@+id/navigation_expiring">

    <fragment
        android:id="@+id/navigation_expiring"
        android:name="com.example.myapp.ui.expiring.ExpiringFragment"
        android:label="@string/title_expiring"
        tools:layout="@layout/fragment_expiring" >
    </fragment>

    <fragment
        android:id="@+id/navigation_storages"
        android:name="com.example.myapp.ui.storages.StoragesFragment"
        android:label="@string/title_storages"
        tools:layout="@layout/fragment_storages" />

    <fragment
        android:id="@+id/navigation_notifications"
        android:name="com.example.myapp.ui.notifications.NotificationsFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_notifications" />

    <fragment
        android:id="@+id/navigation_add_product"
        android:name="com.example.myapp.ui.AddProductFragment"
        android:label="Add product"
        tools:layout="@layout/fragment_notifications" />

</navigation>

A: I have a solution. It worked for me.
First, you just write this code in your activity where BottomNavigationView is located.
MainActivity.xml
 binding.fab.setOnClickListener(object : View.OnClickListener {
        override fun onClick(view: View) {
            binding.bottomNavigationView.selectedItemId = R.id.nav_cards
            navController.navigate(R.id.nav_cards)
        }
    })
    binding.bottomNavigationView.setOnItemSelectedListener {
        when (it.itemId) {
            R.id.nav_home -> {
                navController.navigate(R.id.nav_home)
                true
            }
            R.id.nav_book -> {
                navController.navigate(R.id.nav_book)
                true
            }
            R.id.nav_bookmark -> {
                navController.navigate(R.id.nav_bookmark)
                true
            }
            R.id.nav_settings -> {
                navController.navigate(R.id.nav_settings)
                true
            }
            else -> false
        }
    }

After that, you should use onBackPressed function. Otherwise, you may appear another problem which belongs to collecting backStacks.
  override fun onBackPressed() {
    if (binding.bottomNavigationView.selectedItemId == R.id.nav_home) {
        binding.bottomNavigationView.selectedItemId = R.id.nav_home
        super.onBackPressed()
        finish()
    } else {
        binding.bottomNavigationView.selectedItemId = R.id.nav_home
    }
}

A: Instead of navigating to the fragment, try to start another Activity after clicking "Add" floating action button.
Your new Activity will not have bottom navigation bar as you expected.


text:
Q: Cant start geany debugger I've installed geany 1.32 and also installed plugins using
sudo apt-get install geany-plugins

And it worked for me but when I start geany and open plugin manager I cant see the debugger plugin.

A: If you compiled and installed Geany from source, you also need to download the corresponding geany-plugins version and compile and install that one. The version of geany-plugins from apt-get might differ from the one you compiled and that could be why you don't see all plugins.
https://plugins.geany.org/geany-plugins/


text:
Q: Return SQL query as array The reserva_disponibilidade return the same  Array(29), when should return...29,30, 31...
Is there a way to fix this?
    function estoque($data, $dias, $tipo) {

        //Ajusta a data...
        $inicio = strtotime($data);
        $edia = date('d', $inicio);
        $emes = date('m', $inicio);
        $eano = date('Y', $inicio);

        //Conecta ao db...
        $db = new DBConfig();
        $db->config();
        $db->conn();

        //Arrays
        $smarty_array = array();
        $smarty_data_array = array();

        $query_quartos = mysql_query("SELECT * FROM quartos AS quartos
                                        INNER JOIN tipos AS tipos
                                        LEFT JOIN reservas AS reservas
                                        ON quartos.quarto_tipo = tipos.tipo_id
                                        AND quartos.quarto_numero = reservas.reserva_quarto_id
                                        WHERE quartos.quarto_tipo = '".$tipo."'
                                        GROUP BY quartos.quarto_id HAVING Count(*) >= 1") or die(mysql_error());
        while($row = mysql_fetch_assoc($query_quartos)){
            $quartoid = $row["quarto_id"];

            while($i <= $dias) {
                $today = strtotime(date('Y-m-d',mktime(0,0,0,date($emes),date($edia)+$i,date($eano))));
                $query = mysql_query("SELECT * FROM quartos AS quartos
                              LEFT JOIN reservas AS reservas
                              ON quartos.quarto_numero = reservas.reserva_quarto_id
                              AND ".$today." BETWEEN reservas.reserva_checkin AND reservas.reserva_checkout
                              WHERE quartos.quarto_id = '".$quartoid."'
                              GROUP BY quartos.quarto_id HAVING Count(*) >= 1") or die(mysql_error());
                while($rowe = mysql_fetch_assoc($query)){
                    if (empty($rowe["reserva_status"])) {
                        $rowe["reserva_status"] = "0";
                    }
                    $smarty_data_array[] = $rowe["reserva_status"];
                }
                $i++;
            }

            $row["reserva_disponibilidade"] = $smarty_data_array;
            $smarty_array[] = $row;
        }

        $db->close();
        return $smarty_array;
    }

Output
Smarty_Variable Object (3)
->value = Array (3)
  0 => Array (16)
    quarto_id => "12"
    quarto_tipo => "1"
    quarto_numero => "1"
    quarto_descricao => "Quarto padrão"
    tipo_id => "1"
    tipo_nome => "Standard"
    tipo_foto => "03f9efa3b682512c74a9275656622b03.jpg"
    reserva_id => "2"
    reserva_quarto_id => "1"
    reserva_valor => "400"
    reserva_status => "2"
    reserva_cliente_id => "58"
    reserva_checkin => "1303794000"
    reserva_checkout => "1303966800"
    reserva_obs => "Aguardando pagamento"
    reserva_disponibilidade => Array (29)
      0 => "0"
      1 => "0"
      2 => "0"
      3 => "0"
      4 => "0"
      5 => "0"
      6 => "0"
      7 => "0"
      8 => "0"
      9 => "0"
      10 => "0"
      11 => "0"
      12 => "2"
      13 => "2"
      14 => "2"
      15 => "0"
      16 => "0"
      17 => "0"
      18 => "0"
      19 => "0"
      20 => "0"
      21 => "0"
      22 => "0"
      23 => "0"
      24 => "0"
      25 => "0"
      26 => "0"
      27 => "0"
      28 => "0"
  1 => Array (16)
    quarto_id => "15"
    quarto_tipo => "1"
    quarto_numero => "5"
    quarto_descricao => "Deluxe "
    tipo_id => "1"
    tipo_nome => "Standard"
    tipo_foto => "03f9efa3b682512c74a9275656622b03.jpg"
    reserva_id => null
    reserva_quarto_id => null
    reserva_valor => null
    reserva_status => null
    reserva_cliente_id => null
    reserva_checkin => null
    reserva_checkout => null
    reserva_obs => null
    reserva_disponibilidade => Array (29)
      0 => "0"
      1 => "0"
      2 => "0"
      3 => "0"
      4 => "0"
      5 => "0"
      6 => "0"
      7 => "0"
      8 => "0"
      9 => "0"
      10 => "0"
      11 => "0"
      12 => "2"
      13 => "2"
      14 => "2"
      15 => "0"
      16 => "0"
      17 => "0"
      18 => "0"
      19 => "0"
      20 => "0"
      21 => "0"
      22 => "0"
      23 => "0"
      24 => "0"
      25 => "0"
      26 => "0"
      27 => "0"
      28 => "0"
  2 => Array (16)
    quarto_id => "26"
    quarto_tipo => "1"
    quarto_numero => "80"
    quarto_descricao => "Quarto novo "
    tipo_id => "1"
    tipo_nome => "Standard"
    tipo_foto => "03f9efa3b682512c74a9275656622b03.jpg"
    reserva_id => null
    reserva_quarto_id => null
    reserva_valor => null
    reserva_status => null
    reserva_cliente_id => null
    reserva_checkin => null
    reserva_checkout => null
    reserva_obs => null
    reserva_disponibilidade => Array (29)
      0 => "0"
      1 => "0"
      2 => "0"
      3 => "0"
      4 => "0"
      5 => "0"
      6 => "0"
      7 => "0"
      8 => "0"
      9 => "0"
      10 => "0"
      11 => "0"
      12 => "2"
      13 => "2"
      14 => "2"
      15 => "0"
      16 => "0"
      17 => "0"
      18 => "0"
      19 => "0"
      20 => "0"
      21 => "0"
      22 => "0"
      23 => "0"
      24 => "0"
      25 => "0"
      26 => "0"
      27 => "0"
      28 => "0"
->nocache = false
->scope = "Smarty root"

A: The issue here is with when you assign the value for $quartoid.  If you look at just this section of code:
while($row = mysql_fetch_assoc($query_quartos)){
        $quartoid = $row["quarto_id"];

        while($i <= $dias) {
            $today = strtotime(date('Y-m-d',mktime(0,0,0,date($emes),date($edia)+$i,date($eano))));
            $query = mysql_query("SELECT * FROM quartos AS quartos
                          LEFT JOIN reservas AS reservas
                          ON quartos.quarto_numero = reservas.reserva_quarto_id
                          AND ".$today." BETWEEN reservas.reserva_checkin AND reservas.reserva_checkout
                          WHERE quartos.quarto_id = '".$quartoid."'
                          GROUP BY quartos.quarto_id HAVING Count(*) >= 1") or die(mysql_error());
            while($rowe = mysql_fetch_assoc($query)){
                if (empty($rowe["reserva_status"])) {
                    $rowe["reserva_status"] = "0";
                }
                $smarty_data_array[] = $rowe["reserva_status"];
            }
            $i++;
        }

Your second while loop that begins with while($i <= $dias) { has the exact same SQL query inside of it, executing $dias times.  The values for your variables will never change during this iteration as $today and $quartoid are going to be the same.  I hope that answered your question, sorry if I totally missed on the problem, your row naming was vaguely confusing to me :)


text:
Q: put buttons at bottom right of material-ui dialog I've got some quite nice react hooks based state management that implements a multi-step form inside a material-ui dialog.
I want the dialog to stay the same size and I want the back/forward buttons that take the user through the steps to stay in the same place even though the size and number of the input elements are slightly different from step to step.
I've managed to force the dialog to a fixed viewport % but bottom/right aligning the buttons is defeating me.
Any ideas?
I found a great example similar to my requirement: https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/checkout
I want something like this but I want a UX which is more stable. The example has variable height. I'd like to fix the height to the height of the maximum height tab/step and then I'd like the next/back/submit buttons to be in the same place on each tab/step, so, for example you can click next to step through without moving the mouse.


text:
Q: Some class is conflicting with my css and i can't figure it out I'm trying to simply making 3 columns for 50 states like in my jfiddle http://jsfiddle.net/efhr833n/
But when i go live. It's the exact code and for some reason there is margin on each subsequent div:
live site: http://unclestevesny.com/test-accordion/
Here's a screenshot: https://www.dropbox.com/s/d9k7h8d4ku92are/acc.png?dl=0
I have no idea what is making this happen.
/* accordion header */
.accordion .thestate {
background:#A91414;
width:250px;
font-size:18px;
font-weight:bold;
cursor:pointer;
color: #fff;
margin:15px;
text-align:center;
text-transform:uppercase;
float:left;
}

html

     New York
    New York
    New York
District of Columbia
New York
New York

A: I would say to remove the
 tags and add some margin-bottom;

A: In your live site there are
 tags , so the lines are broken.
Delete the
 tags and site should work


text:
Q: Android: Customize photo size I have one application in which mobile capture photo then it upload to the server. I want to check the size of photo first then reduce photo size to some particular size depending on actual photo size. Actually on server it not allow photo which have greater than some particular size (say 200 kb).
Or can I restrict the camera to capture photo only in particular size even some one change the setting of camera.
lot of question ask here which retrieve width and height of the photo. But I want to customize size in byte.
To open the camera I an using cameraIntent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);

A: This is the only possible solution AFAIK, to reduce the size..
public void onActivityResult(int requestcode, int resultcode, Intent data) {
        if (resultcode == RESULT_OK) {
            if (requestcode == SELECT_PICTURE) {
                Uri uri = data.getData();
                String imagePath = getPath(uri);
                int SCALE = 2;
                try{

                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = SCALE;
                Bitmap bitmap= BitmapFactory.decodeFile(imagePath, o2);
                OutputStream os = new FileOutputStream(imagePath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 85, os);
                os.flush();
                os.close();
                File file = new File(imagePath);
                Log.i("Bitmap", "Height Width "+bitmap.getHeight()+" "+bitmap.getWidth());
                Log.i("File","Size in bytes "+file.length());
                while(file.length()>100*1024)
                {
                    SCALE +=2;
                    o2.inSampleSize = SCALE;
                    bitmap= BitmapFactory.decodeFile(imagePath, o2);
                    os = new FileOutputStream(imagePath);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 85, os);
                    os.flush();
                    os.close();
                    file = new File(imagePath);
                    Log.i("Bitmap", "Height Width "+bitmap.getHeight()+" "+bitmap.getWidth());
                    Log.i("File","Size in bytes "+file.length());
                }
                bitmap = BitmapFactory.decodeFile(imagePath, o2);

                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                txtimagepath.setText(imagePath);

            }
        }
    }

protected String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(columnIndex);

    }

A: You can't dynamically specify the size of the resulting file and do a scaling. You have to re-size the height and width, which in turn would reduce the file size.
May be, a recurring approach, that can finally keep the file size within your limits would help. I can't think of any other solution. At-least, the Android SDK doesn't provide such an API.
If you want to retain the width/height, then you could try compressing techniques, and that would result in loss in quality, and eventually, file size. But again, there is no direct API to achieve this.

A: Bitmap bt=Bitmap.createScaledBitmap(YourOrignalBitmap,320, 300, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bt.compress(Bitmap.CompressFormat.PNG,100, bos);

here you can fix the size and maintain image Quality..


text:
Q: Is it possible to get output of "tail -f" command to java programme? According to:
Java IO implementation of unix/linux "tail -f"
Java "tail -f" wrapper
I assume its possible but I have the following problem.
String TailCommand = "tail -f /path/PATH.txt| grep (...)";
Runtime r = Runtime.getRuntime();
Process p = r.exec(TailCommand);

//handle buffer

while (running) {
    // handle output
}

Process p terminates. It works fine with commands that doesnt have constant updates unlike "top" or "tail -f".
I wonder if I missed something, there is some buffer limitations or whatever?
Im using eclipse but i guess that should not have any impact on process behavior.
In fact maybe there is another simply way to solve my issue that i missed. Im using "tail -f" since i have to analyze quite fat(some GBs) log thats constantly appending and dont intend to open it and read the whole file. I need only to controll the appending lines. However i found no suitable tail implementation
Thanks in advance.

A: You can't execute piped commands from inside java.
If you want piped output, execute '/bin/sh' like this:
String tailCommand = "/bin/sh -c 'tail -f /path/PATH.txt| grep (...)'";

Also, your java program must consume the output of the process fast enough, so its buffers do not overflow.
You may want to read this article When Runtime.exec() won't, for description of common pitfalls when trying to execute a process from Java.


text:
Q: Stylesheets interpreted as cookies in Internet Explorer Good morning,
I have the following problem: some elements of the webpage like .css and javascripts are treated as cookies in Internet Explorer(the webpage works fine  with Firefox and Chrome). Then these elements are blocked and they appeared in the websites blocked due to privacy issues.
If I visit the website using its IP address, it works well. However, If I use the domain, I have the problem with these elements. The website is accessed using a link from other website.
The website was developed using Icefaces.
I think that the cause of the problem is to have the main page and its link in different servers and with different names. I haven't had much permissions to modify server settings.
I haven't configured privacy policies(p3p) but I have already checked problems with domain names like underscores.
Could you please give some suggestions in how to solve the problem?. For me, it is not a proper solution just to lower the privacy settings to make IE accept the content.
Regards,


text:
Q: Way to determine if within a running scheduled task? How can I tell, within the graph processing logic, if it's being executed through a Scheduled task rather than through user interaction?
PXProcessing doesn't seem to have much, nor does the records within the AUSchedule table
Reason:  If I'm in an interactive session, I want to redirect to multiple screens for the document(s) I've created.  In a Scheduled task, I don't want to clutter up the server with these Redirects

A: Take a look through the code repository at SOShipmentEntry. Search for SOInvoiceEntry and it will get you to the Action function where it creates the invoice. You can see that they call the adapter.MassProcess function to see if it is running in a process or not and throws exceptions, sets info, or errors based on the status.
You can also see the AllowRedirect flag in use.
Here is an example of redirecting to the invoice at the end of a shipment invoice creation:
SOInvoiceEntry ie = PXGraph.CreateInstance<SOInvoiceEntry>();
......
......
if (adapter.AllowRedirect && !adapter.MassProcess && created.Count > 0)
{
    using (new PXTimeStampScope(null))
    {
        ie.Clear();
        ie.Document.Current = ie.Document.Search<ARInvoice.docType, ARInvoice.refNbr>(((ARInvoice)created[0]).DocType, ((ARInvoice)created[0]).RefNbr, ((ARInvoice)created[0]).DocType);
        throw new PXRedirectRequiredException(ie, "Invoice");
    }
}


text:
Q: Watson AlchemyLanguage difference in score for URL and text from same URL Why there are significant differences for Sentiment/Emotion scores, between input method as URL, and direct text from the same URL?
For example:

*

*URL: http://economictimes.indiatimes.com/markets/stocks/news/greed-could-turn-into-fear-anytime-keep-strict-stop-losses-for-long-positions-jimeet-modi/articleshow/53569552.cms.

*Text(extracted from the url above):
The Nifty50 opened with high spirit at the beginning of the week, dipped mid-week, but managed to bounce back supported by liquidity gush in the system. The PMI data points towards an acceleration in the economy. The macro indicator suggests whopping 5.2 percent expansion in July as against 2.8 percent in May and 2.8 percent in the corresponding previous year.       Markets too are continuously discounting the encouraging macroeconomic numbers. July automobiles growth numbers surprised the Street.      Passenger vehicles registered on an average 12 per cent growth signaling a loud and clear economic robustness in the system. Path breaking new laws will spearhead the country to become the second-largest economy in the world by the turn of this decade.      Key events of the week: Foundation for the historic path-breaking tax reform has been laid down last week. Now the superstructure will be built over a period of time through the state approvals etc. GST will truly lead India to accelerated corruption free inclusive growth for the masses in the country.      Far reaching amendments were cleared by the lawmakers for speedy and hassle free debt recovery in a time bound manner further enhancing the Bankruptcy Code for making India Bad Debt free economy.      Potentially now, the ecosystem for PSU Banks will change permanently and they too will emerge as profitable as their private sector peers.  We recommend this Video for youADSPARC PTY LTDRecommended By Colombia    Technical Outlook:  The Nifty50 has renewed the upward momentum amid overextended rally. However, the rally is not supported by the momentum indicators. But, markets can remain at overbought levels for extended periods of time during liquidity driven rallies.      Greed is keeping the markets at alleviated levels. However, the sentiments can change from greed towards fear, overnight on the occurrence of some negative news, causing corrections to begin.      Traders should trail their stops on their long positions and investors should stay on the sidelines till the market comes to touch the lower level of the regression channel which comes at around 8300-8400 levels in Nifty50. Long term trend is firmly intact but short term is ripe for a correction.             Expectations for the week: The market is mesmerised in hopes of macro factors being in favour for further economic growth and expansion. The market will show a lot of activity in the mid cap space and therefore the front line index may not show the underlying volatility in the mid-cap space.      Companies operating in the industry wherein lot of unorganized player operate will get benefitted out of GST. Favourable monsoon and coming festive season will keep the market at alleviated levels.      Any correction should be utilized for building long-term portfolios. Traders should play the momentum stocks and trail the profits. The Nifty50 closed higher by 0.52 percent at 8,683.

A: When using a URL, AlchemyLanguage tries to extract the important information from a web page, removing navigation links, advertisements, and other undesired content. In this case, I think the extracted text seems to be different than the one you supplied manually using the text endpoint.
If you use TEXT, you are basically sending the text you want to analyze so you don't have irrelevant text like with the URL.

AlchemyLanguage allows you to see the extracted text when using a URL. Just  add showSourceText=1 to the request. That will show you the text that was used during the analysis.
See: http://www.ibm.com/watson/developercloud/alchemy-language/api/v1/#emotion_analysis

A: Watson tries to extract the most relevant input data from URL. But in some cases it may not get exact text data as per our definition of main content.
In your case as per your definition of main content last para of the article was extracted extra from URL. (Last para of the article is ambiguous, someone may consider it as part of the article, someone may not.)
Last Para Text from URL:

(The author is CEO, SAMCO Securities. Views and recommendations expressed in this section are his own and do not represent those of ETMarkets.com. Please consult your financial advisor before taking any position.)

As there are some Entities/Keywords/Tokens in last para which can affect overall sentiment score, you will find some difference between 2 scores.
You can check online demo for more information : Online Demo
For API you can check : showSourceText and sourceText Parameters
Ref : Alchemy Sentiment API


text:
Q: Execute ReactiveUI Command from Event in Xamarin Forms I have entry fields in a Xamarin Forms page that I want to trigger a ReactiveUI command when the user is finished entering text into them. I am using ReactiveUI.Events.XamForms and am trying to trigger a command based off of the Unfocused event, but I am not sure how to set up the command to get that to work.
Here is my XAML:
<?xml version="1.0" encoding="utf-8" ?>
<rxui:ReactiveContentPage
  x:Class="XamarinReactiveUISwipeView.MainPage"
  x:TypeArguments="vm:MainPageViewModel"
  xmlns:vm="clr-namespace:XamarinReactiveUITest.ViewModel;assembly=XamarinReactiveUITest"
  xmlns:rxui="clr-namespace:ReactiveUI.XamForms;assembly=ReactiveUI.XamForms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:ios="clr- namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
  xmlns="http://xamarin.com/schemas/2014/forms"
    ios:Page.UseSafeArea="true">
    <StackLayout>
        <StackLayout Margin="10,0,0,0" Orientation="Horizontal">
            <Label Text="Task ID: " />
            <Entry x:Name="EntryTaskID" />
        </StackLayout>
        <StackLayout Margin="10,0,0,0" Orientation="Horizontal">
            <Label Text="Task Name: " />
            <Entry x:Name="EntryTaskName" />
        </StackLayout>
    </StackLayout>
</rxui:ReactiveContentPage>

Here is my code behind:
public partial class MainPage : ReactiveContentPage<MainPageViewModel>
{
    public MainPage()
    {
        InitializeComponent();
        ViewModel = new MainPageViewModel();

        this.WhenActivated(disposable =>
        {
            this.Bind(ViewModel, vm => vm.TheTaskItem.TaskID, page => page.EntryTaskID.Text)
            .DisposeWith(disposable);
            this.Bind(ViewModel, vm => vm.TheTaskItem.TaskName, page => page.EntryTaskName.Text)
            .DisposeWith(disposable);
            EntryTaskName.Events().Unfocused.InvokeCommand(ViewModel, vm => vm.TheCommand);
        });
    }
}

here is my model:
public class TaskItem
{
    public TaskItem() { }

    public string TaskID { get; set; }
    public string TaskName { get; set; }
}

and here is my view model:
public class MainPageViewModel : ReactiveObject
{

    public MainPageViewModel()
    {
        TheTaskItem = new TaskItem { TaskID = "1", TaskName = "TheTaskName" };

        TheCommand = ReactiveCommand.Create<FocusEventArgs, Unit>(ExecuteTheCommand);
    }

    public ReactiveCommand<FocusEventArgs, Unit> TheCommand { get; }

    private void ExecuteTheCommand(FocusEventArgs args)
    {
        //do something
    }

    private TaskItem _theTaskItem;

    public TaskItem TheTaskItem
    {
        get => _theTaskItem;
        set => this.RaiseAndSetIfChanged(ref _theTaskItem, value);
    }

}

In the view model above, it won't compile, but I can't figure out how to set up the ExecuteTheCommand method. The error is:

'void MainPageViewModel.ExecuteTheCommand(FocusEventArgs)' has the wrong return type

But in looking at examples, it looked like methods with void returns use the Unit type.
What do I need to do here to set up the command properly to get this to work?

A: In comment above, OP says that this works if change:
TheCommand = ReactiveCommand.Create<FocusEventArgs, Unit>(ExecuteTheCommand);

to:
TheCommand = ReactiveCommand.Create<FocusEventArgs>(ExecuteTheCommand);

Unexpectedly, the type of the variable that holds the result of Create, does not use that same generic type signature. It needs to be:
public ReactiveCommand<FocusEventArgs, Unit> TheCommand { get; }

According to the doc in link by Rodney Littles in comment, Unit is used to represent "void return type". (Generic type "TOutput" would be "void"; but "void" is not a valid Generic type.)


text:
Q: NGINX and React :net::ERR_ABORTED 404 I created a react demo with create-react-app,it runs at http://localhost:3000,and I use NGINX as reverse proxy,nginx.conf is like this:
server {
        listen       3001;
        server_name  localhost;

        location / {
            proxy_pass http://localhost:3000;
        }

        location /api {
            proxy_pass  http://192.168.33.3:8080;
        }

 }

when I access http://localhost:3001,there is an error:

What should I do?

A: Try to add root in your server pointing to react bundle:
server {
    root /var/www/html/bundle
}


text:
Q: Elasticsearch sorting based on several fields and time condition I have a little online store application and I would like to sort items based on their active price. So there is a normal price and optionally a discounted price. But the discounted price is valid for a time range only and the index is not updated when discount ends. For example:
{price: 2.00, discount:{price:1.10, start:2016-08-11, end:2016-09-14}}

Is it possible to include such condition on sorting? The goal is to ensure the correct sort order any given time.
Edit: At the moment the ES version is rather old but update to the latest is not an issue.

A: This is for Elasticsearch 5 and 6 (you didn't mention, as I said, the version and the mapping of that discount field). Also, you need to explicitly pass as a parameter the current date and time in milliseconds whenever you run that query:
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": "if (doc['discount.price']!=null && doc['discount.start'].date.getMillis() < params['time'] && doc['discount.end'].date.getMillis() > params['time']) return doc['discount.price'].value; else return doc['price'].value",
        "params": {
          "time": 1512717897000
        }
      },
      "order": "desc"
    }
  }


text:
Q: A Proof that the Natural Numbers Form a pca? It is known that the set of natural numbers with the operation ab = {a}b, where {a} represents the index of a recursive function, forms a partial combinatory algebra (pca). All the references I have so far consulted mention the set of natural numbers as an example of a pca with no proof. If possible, I would appreciate if someone could refer me to such proof.

A: For a formalization of Turing machines you could look at

Andrea Asperti and Wilmer Ricciotti: Formalizing Turing Machines. Lecture Notes in Computer Science Volume 7456, 2012, pp 1-25.

The book

Martin Davis. Computability and Unsolvability. Courier Dover Publications, 1982 (3rd reprint).

contains an amazing amount of detail about Turing machines.
Given these references, let us take as granted the details of the numbering $\varphi$ of partial computable maps, the s-m-n and u-t-m theorems from computability theory, and one bit of knowledge: if we fix one argument of a partial computable map of two arguments we obtain a partial computable map again.
With s-m-n and u-t-m theorems in hand, it is not hard to show that Kleene's first algebra is a partial combinatory algebra. We just need to construct the $\mathsf{K}$ and $\mathsf{S}$ combinators.
To get the $\mathsf{K}$ combinator, consider the partial computable map
$$f(x, y) = x.$$
By the s-m-n theorem there exists $p$ such that $\varphi_{s(p, x)}(y) \simeq f(x,y)$ for all $x, y \in \mathbb{N}$. Here $s$ is the total computable map appearing in the s-m-n theorem and $\simeq$ is Kleene equality "if one side is defined then so it the other and they are equal". Now the map $x \mapsto s(p, x)$ is total and computable, hence there is $\mathsf{K}$ such that $\varphi_{\mathsf{K}}(x) = s(p, x)$ for all $x$. We now have (I write $a \cdot b$ for Kleene application, i.e., $a \cdot b = \lbrace a \rbrace b = \varphi_a(b)$):
$$(\mathsf{K} \cdot x) \cdot y = \varphi_{\mathsf{K}}(x) \cdot y = s(p,x) \cdot y = \varphi_{s(p,x)}(y) = f(x,y) = x.$$
For the $\mathsf{S}$ combinator, let $u$ be the universal computable map from the u-t-m theorem. It has the property that, for all $t$ and $m$,
$$u(t, m) \simeq \varphi_t(m).$$
In other words, $u(t,m) \simeq t \cdot m$ so the u-t-m theorem is just saying that Kleene application is computable.
Consider the map
$$g(x,y,z) = u(u(x, z), u(y,z)).$$
We have
$$g(x,y,z) \simeq u(x,z) \cdot u(y,z) \simeq (x \cdot z) \cdot (y \cdot z).$$
We just need a code for $g$, which we get by appying the s-m-n theorem twice.
By the s-m-n theorem there is $p$ such that $\varphi_{s^{(2)}(p, x, y)}(z) \simeq g(x,y,z)$ for all $x,y,z$. Let $r$ be such that $\varphi_r(x,y) = s^{(2)}(p, x, y)$ for all $x, y$. Note that $\varphi_r$ is total because the map $s^{(2)}$ from the s-m-n theorem is total. By the s-m-n theorem there is $q$ such that $\varphi_{s(q,x)}(y) = \varphi_r(x,y)$ for all $x,y$. Let $\mathsf{S}$ be such that $\varphi_\mathsf{S}(x) = s(q,x)$ for all $x$. Now finally compute
$$((\mathsf{S} \cdot x) \cdot y) \cdot z \simeq
(s(q,x) \cdot y) \cdot z \simeq
\varphi_{s(q,x)}(y) \cdot z \simeq
\varphi_r(x,y) \cdot z \simeq$$
$$
s^{(2)}(p,x,y) \cdot z \simeq
\varphi_{s^{(2)}(p,x,y)}(z) \simeq
g(x,y,z) = (x \cdot z) \cdot (y \cdot z).$$
Also, since $\mathsf{S} \cdot x \cdot y = s^{(2)}(p,x,y)$ we see that $\mathsf{S} \cdot x \cdot y$ is defined for all $x, y$, as required.

A: You may be interested in the following demonstration how natural numbers can be implemented within pca's: (see pages 19-20) http://www.mathematik.tu-darmstadt.de/~streicher/REAL/REAL.pdf


text:
Q: Addition for two dimensional Excel I needed some help with conditional addition in Excel.
This is an example data:
    A      B        C            D
1 Animal January February      March
2 Cat      5       6             7
3 Cat      2       3             5
4 Dog      1       4             8

How can I write SUMIF on the conditions on, add total cats for the month of March?
I have been trying to experiment with SUMIF and written something like:
=SUMIF(A:A,Cat,D:D)

This is only going to work on one dimensional, meaning colum. How do I write a formula to calculate the sum of total cats in March? Column+ March , two dimensional.

A: You may try this:
=SUMIF(A1:A4;"Cat";INDEX(B1:D4; 0; 3))

The value of 3 in INDEX function means the third column (March), you may change it into 2 for February, and change it into 1 for January


text:
Q: Prove a basic lemma in Isabelle I'm working on a project using Isabelle.
For some reason I have to simulate a bit/byte system, like this:
type_synonym bit = bool
datatype byte = B bit bit bit bit bit bit bit bit

fun byte_inc :: "byte => byte" where
"byte_inc (B a7 a6 a5 a4 a3 a2 a1 False) = (B a7 a6 a5 a4 a3 a2 a1 True)" |
"byte_inc (B a7 a6 a5 a4 a3 a2 False True) = (B a7 a6 a5 a4 a3 a2 True False)" |
"byte_inc (B a7 a6 a5 a4 a3 False True True) = (B a7 a6 a5 a4 a3 True False False)" |
"byte_inc (B a7 a6 a5 a4 False True True True) = (B a7 a6 a5 a4 True False False False)" |
"byte_inc (B a7 a6 a5 False True True True True) = (B a7 a6 a5 True False False False False)" |
"byte_inc (B a7 a6 False True True True True True) = (B a7 a6 True False False False False False)" |
"byte_inc (B a7 False True True True True True True) = (B a7 True False False False False False False)" |
"byte_inc (B False True True True True True True True) = (B True False False False False False False False)" |
"byte_inc (B True True True True True True True True) = (B False False False False False False False False)"

lemma [simp]: "b ≠ byte_inc b"
sorry

I use (B T T T T T T T T) to represent (11111111), (B F F F F F F F F) to represent (00000000).
But I can not prove such an obvious lemma: b != b + 1
I really need some help.

A: You will need to make a case distinction over the parameter b so that you can apply the simp rules for byte_inc. Just do "by (cases b rule: byte_inc.cases, simp_all)"

A: You should also take a look at the existing library for machine words over bits: $ISABELLE_HOME/src/HOL/Word/Word.thy
That is quite advanced stuff, though, but for real applications it is worth investing time to figure out how it works.