text:
Q: How to improve loading performance in Tabbed Page xamarin forms I am trying to create bottom tabbed page in Xamarin forms and i am doing this for Android.
here i am using latest version of Xamarin Forms.
My sample Bottom tabbed page like below.
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:views="clr-namespace:SampleTabbedPage.Views"
            xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
            android:TabbedPage.ToolbarPlacement="Bottom"
            android:TabbedPage.BarItemColor="Gray"
            android:TabbedPage.BarSelectedItemColor="Blue"
             mc:Ignorable="d"
             x:Class="SampleTabbedPage.Views.SampleTabbed">
  <!--Pages can be added as references or inline-->

    <NavigationPage
        Title="Main"
        NavigationPage.HasNavigationBar="False">
        <x:Arguments>
            <views:SampleDetailsPage/>
        </x:Arguments>
    </NavigationPage>

    <ContentPage Title="Tab 1" />
  <ContentPage Title="Tab 2" />
</TabbedPage>

My sample details page like
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="SampleTabbedPage.Views.SampleDetailsPage"
             BackgroundColor="Gray">
    <ContentPage.Content>
        <StackLayout>
            <ListView BackgroundColor="White" ItemTapped="ListView_ItemTapped">
                <ListView.ItemsSource>
                    <x:Array Type="{x:Type x:String}">
                        <x:String>Mango</x:String>
                        <x:String>Banana</x:String>
                        <x:String>Pinaple</x:String>
                        <x:String>Apple</x:String>
                        <x:String>Avacado</x:String>
                        <x:String>Coconut</x:String>
                        <x:String>Dragan Fruit</x:String>
                        <x:String>Pomaganate</x:String>
                        <x:String>Wood Apple</x:String>
                    </x:Array>
                </ListView.ItemsSource>
            </ListView>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

And the navigation i am doing as follows
in App.xamal.cs
MainPage = new NavigationPage(new FirstPage());

I have simple first page
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="SampleTabbedPage.Views.FirstPage">
    <ContentPage.Content>
        <StackLayout>
            <Button Text="Click Me!" Clicked="Button_Clicked"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

here in button click event i do the navigation to "Sample Tabbed Page"
await Navigation.PushAsync(new SampleTabbed());

This is working fine.
but there is a performance issue.
if i run this and click on button in First page it is taking 3 seconds to load tabbed page.
if i remove list view in sample detail page it take 2 seconds to load.
but if i add just a content page to click event it take only milliseconds to load.
Am i doing some thing wrong with implementing tabbed page?
or
is there any way to improve the loading performance with tabbed pages.

A: A solution is to make the heavy pages load their content in a lazy manner, only when their tab becomes selected. This way, since these pages are now empty when TabbedPage is created, navigating to the TabbedPage suddenly becomes very fast!
1.create a behavior for the TabbedPage page, called ActivePageTabbedPageBehavior.
class ActivePageTabbedPageBehavior : Behavior<TabbedPage>
{
 protected override void OnAttachedTo(TabbedPage tabbedPage)
  {
    base.OnAttachedTo(tabbedPage);
    tabbedPage.CurrentPageChanged += OnTabbedPageCurrentPageChanged;
  }

 protected override void OnDetachingFrom(TabbedPage tabbedPage)
  {
    base.OnDetachingFrom(tabbedPage);
    tabbedPage.CurrentPageChanged -= OnTabbedPageCurrentPageChanged;
  }

 private void OnTabbedPageCurrentPageChanged(object sender, EventArgs e)
  {
    var tabbedPage = (TabbedPage)sender;

    // Deactivate previously selected page
    IActiveAware prevActiveAwarePage = tabbedPage.Children.OfType<IActiveAware>()
        .FirstOrDefault(c => c.IsActive && tabbedPage.CurrentPage != c);
    if (prevActiveAwarePage != null)
    {
        prevActiveAwarePage.IsActive = false;
    }

    // Activate selected page
    if (tabbedPage.CurrentPage is IActiveAware activeAwarePage)
    {
        activeAwarePage.IsActive = true;
    }
  }
}

2.define IActiveAware interface
interface IActiveAware
  {
    bool IsActive { get; set; }
    event EventHandler IsActiveChanged;
  }

3.create a base generic abstract class called LoadContentOnActivateBehavior
abstract class LoadContentOnActivateBehavior<TActivateAwareElement> : Behavior<TActivateAwareElement>
   where TActivateAwareElement : VisualElement
 {
  public DataTemplate ContentTemplate { get; set; }

  protected override void OnAttachedTo(TActivateAwareElement element)
   {
     base.OnAttachedTo(element);
     (element as IActiveAware).IsActiveChanged += OnIsActiveChanged;
   }

  protected override void OnDetachingFrom(TActivateAwareElement element)
   {
     (element as IActiveAware).IsActiveChanged -= OnIsActiveChanged;
     base.OnDetachingFrom(element);
   }

  void OnIsActiveChanged(object sender, EventArgs e)
   {
     var element = (TActivateAwareElement)sender;
     element.Behaviors.Remove(this);
     SetContent(element, (View)ContentTemplate.CreateContent());
   }

  protected abstract void SetContent(TActivateAwareElement element, View contentView);
}

4.the specialized LazyContentPageBehavior
class LazyContentPageBehavior : LoadContentOnActivateBehavior<ContentView>
 {
   protected override void SetContent(ContentView element, View contentView)
    {
      element.Content = contentView;
    }
 }

then we can use in xaml like this:
<TabbedPage>
  <TabbedPage.Behaviors>
    <local:ActivePageTabbedPageBehavior />
  </TabbedPage.Behaviors>

<ContentPage Title="First tab">
    <Label Text="First tab layout" />
</ContentPage>

<local:LazyLoadedContentPage Title="Second tab">
    <ContentPage.Behaviors>
        <local:LazyContentPageBehavior ContentTemplate="{StaticResource ContentTemplate}" />
    </ContentPage.Behaviors>
    <ContentPage.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="ContentTemplate">
                <!-- Complex and slow to render layout -->
                <local:SlowContentView />
            </DataTemplate>
        </ResourceDictionary>
    </ContentPage.Resources>
</local:LazyLoadedContentPage>
</TabbedPage>

we moved the ContentPage complex layout to become a DataTemplate.
Here's the custom LazyLoadedContentPage page which is activation aware:
class LazyLoadedContentPage : ContentPage, IActiveAware
{
  public event EventHandler IsActiveChanged;

  bool _isActive;
  public bool IsActive
   {
     get => _isActive;
     set
      {
        if (_isActive != value)
        {
            _isActive = value;
            IsActiveChanged?.Invoke(this, EventArgs.Empty);
        }
      }
   }
 }

SlowContentView  do some complex things
 public partial class SlowContentView : ContentView
{
    public SlowContentView()
    {
        InitializeComponent();

        // Simulating a complex view
        ...
    }
}


text:
Q: How does damage work in the Ys series? I'm asking this question as I replay the series because once again, the weird damage system seems very strange. It's most pronounced in Ys 1, where changing equipment or levelling up to slightly increase your attack stat (by like ten points; end-of-game maximum is 255 so this isn't much of a difference) can be the difference between doing 1 damage per hit and doing something like 30 or even 50 damage a hit. But then adding more attack on top of that hardly changes the damage at all. Defense is in a similar situation, where there seems to be some threshold (different for each enemy) below which you take a ton of damage and above which adding more defense doesn't seem to do much.
So... what's the formula being used here? Has anyone looked into the code of any of the various remakes?
This unusual system where a small stat change leads to large differences in damage given/taken is still present in Ys II, and to a lesser degree in The Oath in Felghana. I've yet to get to any of the later games in the series, so I can't say whether they kept it or went with something more conventional, though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing $\text{range}(A)$ dense: $A: \ell^1 \to \ell^1$, $Ax = \left(\frac{x_n}{n}\right)_{n \in \mathbb{N}}.$ Let $A : \ell^1 \to \ell^1$ be an operator where for any $x \in \ell^1$, $Ax = \left(\frac{x_n}{n}\right)_{n \in \mathbb{N}}$.
Question. I'm trying to show that $\text{range}(A)$ is dense subspace of $\ell^1$.
I know that essentially we want to show that the closure of the range is equivalent to $\ell^1$, i.e.
$$\overline{\text{range}}(A) = \{x \in \ell_1 : \exists x_n \in \text{range}(A)~\text{such that}~x_n \to x\} = \ell^1.$$
But I don't really have an idea of how to formally go about showing the above using this definition?

A: You show it by demonstrating there is $x_n \in \ell^1$ (and more precisely $Ax_n$ is Cauchy), such that $Ax_n\rightarrow y,$ for any $y\in \ell^1$.
So let $y\in \ell^1$, then
$$\sum |y_i|<\infty$$
We can now have a sequence $x_n:=y_i i1(i<n)\in\ell^1$. Now $Ax_n$ converges to $y$, and the statement is proved.

A: Hint: consider sequences with only finitely many nonzero terms.


text:
Q: What options are available to add a calculated attribute to Mage_Core_Model_Product? We've got a number of attributes which are generated by basic Excel formulas and then bulk-loaded into the catalog via imports.  The process results in "extra" attributes which are read-only and shouldn't be altered by individuals.
Ideally these values wouldn't be stored in EAV attributes, but would instead be calculated on-the-fly as needed.  I've considered (and not ruled out) extending the catalog/product model to have additional methods for this data, such as:
class My_Extension_Model_Catalog_Product extends Mage_Core_Catalog_Product {

  public function getSomeValue() {

    if (!$x = $this->getX() || !$y = $this->getY()) {
      return null;
    }

    return ($x * $y);
  }
}

The attribute needs to be available to consumers who expect it to behave like any other attribute--they should be able to call Mage::getModel('catalog/product')->load(123)->getSomeValue(); without any extra boilerplate or bootstrapping.
What other options would I have?  Would there be events that would let me calculate and set the value when the product is being loaded?  Or better could I assign the function when the product is loaded?

A: If you have a fixed amount of attributes I would suggest to implement a custom extension that creates them using the install script. The calculation can be done by rewriting the Mage_Core_Catalog_Product like you've written above.
As for as events goes you have 2 events for loading products:

*

*catalog_product_load_before

*catalog_product_load_after.

For loading product collections you have

*

*catalog_product_collection_load_before

*catalog_product_collection_load_after.


text:
Q: Firebase Admin SDk not working from backend Java I am trying to push message in firebase real time database through            firebase admin sdk java, but my problem is that the same code works
           fine on my local system and I am able to push message successfully
           in database but its not working in testing environment and testing
           environment is AWS server with ubuntu installed in
           it, on researching it on google I am not able to find solution for
           this?
public static class User {

    public String date_of_birth;
    public String full_name;
    public String nickname;

    public User(String date_of_birth, String full_name) {
        // ...
    }

    public User(String date_of_birth, String full_name, String nickname) {
        // ...
    }

}

Map<String, User> users = new HashMap<>();
users.put("alanisawesome", new User("June 23, 1912", "Alan Turing"));
users.put("gracehop", new User("December 9, 1906", "Grace Hopper"));

Code for making connection is.....
  FileInputStream serviceAccount;
  FirebaseOptions options;
  try {
        serviceAccount = new FileInputStream("/********.json");
                options = new FirebaseOptions.Builder()
                           .setDatabaseUrl("https://myDatabaseUrl")
       .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                          .build();
                FirebaseApp.initializeApp(options);

                flagForConnectionWithFirebase=true;
                LOGGER.info("Options are:: "+options);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    final FirebaseDatabase database =
                           FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference(url);
    String key=ref.push().getKey();
    ref.child(key).setValueAsync(users);

A: After a long search I found that the server was not sync with centralised time zone. post doing that code run successfully on testing environment as well.

A: I found what seems to be quite a common problem that nobody cares to resolve and it is that there an dependency conflict in one of the Firebase dependencies
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>

It can be solved by excluding the dependency from Spring Boot Test and the pring-boot-configuration-processor. Now I am having some problems when running test, still cannot tell if they are related.


text:
Q: How to extract only the capture group in a regex in R I am trying to extract a pattern from some html. I am using stringr.
I have a list of numbers such as nums<-c(">00324R<",">E223143<",">00000F<")
 I have tried str_extract(nums,">[A-Z0-9]{4,}?<") which extracts the pattern I want(  ">00324R<"  ">E223143<" ">00000F<" ) but I don't want to extract < or >
I am aware that positive lookahead may be the answer here but I don't seem to be able to create one that works and I'm not sure why not. I have tried:
str_extract(nums,"(?<=<)[A-Z0-9]{4,}?<")

A: Use the following regex
> str_extract(nums,"(?<=>)[A-Z0-9]{4,}(?=<)")
[1] "00324R"  "E223143" "00000F"

Details

*

*(?<=>) - a positive lookbehind that matches a location immediately preceded with >

*[A-Z0-9]{4,} - four or more uppercase ASCII letters or digits

*(?=<) - a positive lookahead that matches a location immediately followed with <.

See the regex demo and the regex graph:

A: If your strings are so consistent, you could just select anything that is not > or <:
str_extract(nums, "[^<>]+")
# [1] "00324R"  "E223143" "00000F"

Or gsub() them away:
gsub("[<|>]", "", nums)

A: You could remove "<" or ">" as follows:
gsub("[<| >]", ''", nums)


text:
Q: How to receive the redis key expire evenst during the application died after the app recover? I have a problem.
Assume that my app is destoryed sometimes.And there were some key expire events during the destoryed time .After I recover my app ,how can I receive the events during the destoryed time?
please,thank you!


text:
Q: How to call webservice (Http Request) when app is killed by swiping in android? Question/Requirement
How to call Web-Service (HTTP Request) when app is killed by swiping in android?
When I kill application by swiping from recent application list at that time I want to call Web-Service (or AsyncTask).
What I used?
I am trying to call AsyncTask on destroy of activity.
AsyncTask contains WebApi request (using DefaultHttpClient).
Code like this...
@Override
protected void onDestroy() {
    String url = "<webapi-url here>";
    new GetResponse().execute(url);
    super.onDestroy();
}

I am not using any background service.
Used only Activities, not containing any Fragment.
If any solution then please share here.

A: You can write an Android service component which overrides a method called onTaskRemoved() which will be triggered whenever app is removed by swiping from recents. So you can try this solution and see it fulfills your requirement.

A: No, there's no reliable way to know if your application was killed by a another process. The whole point of "killing" an app is to terminate it as soon as possible, without letting it run any code.
If you want more, see Action on application killed in android

A: You have a similar post, the next time search a little please, but you can see this posts: AsyncTask will always run even if app is destroyed? or Async task stopped when App terminates (onDestroyed is called).
In summary the AsyncTask works when app is destroyed but the app can crash if you try to modify UI. Tell me if I helps you, good programming!


text:
Q: WordPress category widget only show categories with children I'm trying to modify the inbuilt WordPress category widget to only show categories if they have children.
I was using this code:
function exclude_widget_subcategories($args){
  $all_categories = get_all_category_ids();

  $exclude_categories = array();

  foreach($all_categories as $category_id){
    $category = get_category($category_id);

if($category->parent!=0){
        $exclude_categories[] = $category_id;
    }
  }
  $exclude = implode(",",$exclude_categories); // The IDs of the excluding categories
  $args["exclude"] = $exclude;
  return $args;
}
add_filter("widget_categories_args","exclude_widget_subcategories");

Which works in that it only shows top-level categories, however my client has various child-categories which also have children themselves and she wants these to show up in the category widget.
Is there a way I can modify this code so that instead of excluding categories which aren't Parent categories it instead excludes categories that don't have children?

A: I would suggest something like this:
function exclude_widget_subcategories($args){
  $all_categories = get_terms('category', array('parent' => 0, 'fields' => 'ids'));

  $exclude_categories = array();

  foreach($all_categories as $category_id){
    $children = get_term_children($category_id, 'category');

    if(count($children)!=0){
        $exclude_categories[] = $category_id;
    }
  }
  $exclude = implode(",",$exclude_categories); // The IDs of the excluding categories
  $args["exclude"] = $exclude;
  return $args;
}
add_filter("widget_categories_args","exclude_widget_subcategories");

get_terms('category', array('parent' => 0, 'fields' => 'ids')); gets all category wordpress terms that are children of '0', ie they are top level items. It also specifies that only the ids are returned, rather than term objects. More documentation here
get_term_children should be fairly self-explanatory, though note that you need to pass the name of the taxonomy to the function call. More documentation here
Please note I haven't tested this out so there may be syntax errors - let me know if there are and I may be able to help further :)

A: My client clarified their ask and it transpired they only wanted to display a specific child-category in the category widget, rather than any child-categories with children of their own.
I modified the code I was using to the following (where 1373 is the ID of the specific sub-category), which has achieved that effect:
function exclude_widget_subcategories($args){
  $all_categories = get_all_category_ids();

  $exclude_categories = array();

  foreach($all_categories as $category_id){
    $category = get_category($category_id);

if($category_id!=1373) {
    if($category->parent!=0){
        $exclude_categories[] = $category_id;
    }
  }
  }
  $exclude = implode(",",$exclude_categories); // The IDs of the excluding categories
  $args["exclude"] = $exclude;
  return $args;
}
add_filter("widget_categories_args","exclude_widget_subcategories");

I'm not sure if this is properly an answer because it doesn't answer the question I initially posed, but it does solve my problem in this case!


text:
Q: Why do people only float in certain orientations? If the buoyant force on an object is equal to the weight of the water displaced by the object, why do people have an easier time floating on their back than vertically with their head sticking out of the water?

A: The chest region provides the least dense region in the body since it traps a large airspace. And for either scenario (back floating or vertical) the chest is submerged.
So the only difference you need to consider is that in the vertical position, the head (at least above the nostrils) needs to be above the water line so that the person can breathe. But in the back floating position the nostrils can be positioned at the highest position, and thus more of the head , relative to the vertical position can be submerged - taking advantage of Archimedes's principle.
An adult human head weighs about 15 pounds so submerging as much of it as possible can eliminate the need to dog-paddle and thus passively maintain access for breathing.
Survival experts and SCUBA instructors will always train their pupils to float on their backs to conserve energy.

A: To answer the title: because there are two forces, weight and buoyant uplift, acting on the body and these act on the body at different points: the center of weight (and the center of bouyancy, respectively. Therefore, the pair will exert a torque on the body unless line joining them is aligned with the forces. So the body will come to rest with the center of buoyancy above the center of weight ("above" in the sense of being shallower in the water). The other equilibrium configuration is with the center of weight above the center of buoyancy, but this one is not stable in the sense that small perturbations on the body will cause the body to move away from this configuration.
So you will find it easiest to float in a configuration near to the stable equilibrium one. You can even stay in the unstable one with relatively little effort: you simply need to counteract perturbations with small swim thrusts to push you back to the unstable equilibrium configuration. To keep yourself in any other configuration, you need to be imparting a constant torque to yourself from swim thrusts to counteract the torque from the gravity-buoyancy couple.
When we say that a force like gravity or buoyancy acts at a point on a rigid body, what we mean is that the force comprises many contributions at different positions in the body. It can be shown that statics and dynamics of rigid bodies can be described by finding the point about which all the contributions have a torque of nought and thinking of the force system as a lone force acting at this zero torque point: it can be shown that the results of any analysis for a rigid body will be the same whether you use this method or analyse the whole system of forces.
Weight is a sum of weight contributions from each part of your body. Buoyant uplift is a sum of pressures pushing on you at the surface of your body where it meets the water. So it should be clear that the zero torque points are in general very different for these forces.

Note: The center of weight is the same as a the center of mass in a uniform gravitational field.


text:
Q: Fauna DB GraphQL mutation updating many formInputs of a form via their ID's I have the following graphQL schema, running on faunaDB
type Form {
  name: String!
  index: Int!
  user: User
  formInputVals: [FormInputVal!] @relation
}

type FormInputVal {
  name: String!
  index: Int!
  type: String!
  formRoot: Form!
}

type User {
  name: String!
  email: String!
  password: String!
  forms: [Form] @relation
}

type Query {
  allForms: [Form!]
  allUsers: [User!]
  allFormInputVals: [FormInputVal!]
}

I'm trying to figure out how I would query and write a mutation where i would update a specific form id and update all the specificed documents related to that form via there id's or what are called references in fauna db.
I can update the form name with this mutation
mutation{
  updateForm(id:"291541554941657608",data:{name:"test"}){
    name
  }
}

but beyond that I can't seem to figure out how to update multiple FormInputVals of the type Form. I talked to faunaDB, and they said I might need a resolver throught there lambda function that allows me to do so, any one familiar with this at all. I have posted another question, but I have changed my end goal in this one, but this question is similar Designing the db and state mutations and requests of a form builder in react with graphQL, faunaDB, nextJS & Apollo
See I have a object from my form that maps to the documents ID's in the collection in fauna DB. It looks like so.
[{"291705061039407629":{"name":"test","type":"text"}},{"291705951034016264":{"name":"test","type":"text"}}]

How would I upate say two matching records in faunaDB for the FormInputVal type. The numbers represent the ID of the document in the collection.
Here's a screenshot of the GraphQL docs for updating a formInputVal, my issue is I want to update multiple documents at once.

and here is the updateForm docs

Update: I have figured out that create option can add multiple documents at a time, just have to figure out if I can update or replace all of them. This is what worked for adding multiple documents at once.
 mutation{
  updateForm(id:"291541554941657608",data:{
    name:"hello",
    index:0,
    formInputVals:{
      create:[
        {name:"test", index:0, type:"text"},
        {name:"test", index:0, type:"text"},
        {name:"test", index:0, type:"text"},
      ]
    }
  }){
    name
    formInputVals{
      data{
        name
        type
        index
      }
    }
  }
}


text:
Q: How can make toggle be affected on to existing radio button onClick toggle after certain db query? May be I'm not clear with my title, looks messy, so here is my code. Making a plugin in WordPress.

I have two radio buttons in a form to input data:
   <input type="radio" name="radio_btn" checked="checked" value="2">Paste a Code</input>
   , or
   <input type="radio" name="radio_btn" value="3">Put an Image</input>

And here are my two divs:

div 1

div 2

Scenario: I'm using the same form for Inserting Data and Editing data as well. When inserting, I can toggle between the two divs, where the first one is checked by default. If I click on the other, then the divs are toggling nicely, I can use any one of them at a single time. So the inserting thing is fine.
Now, when I'm going to edit my data, I'm getting the data using $_GET[] and db query, and passing them to their fields accordingly and they are doing well too. But just the matter of toggling here, when data for
 is isset showing, data for
 is isset is also showing, but if not toggled by click the field is not visible you know. :(
I tried in a basic way swapping the HTML checked="checked" from one to another, I failed, because the jQuery isn't matching them.
So, I need to change the jQuery in a way so that, the toggling works when I'm inputting, as well as when editing my data. What are the changes I can do to change my jQuery to achieve this into my desired way?

A: You have 2 options:
1) Show/hide divs in your php
2) Pass value of "test" to javascript and add
$("#togglediv" + test).click();

In fact there is a 3th option, which I prefere. Create a .hidden css class and add in your php  (to a togglediv which is hidden obvieusly) when you render the page. Then instead of hide()/show() use addClass('hidden') and removeClass('hidden'). I'm not sure if this will be slower/faster but I think it makes it more readable.
CSS
.hidden { display: none; }

JS

A: Give this a try (it worked for me).
It does not show the DIVs when initially loaded, they will show when a radio button is selected.
I added the jQuery library link I used, just in case.
<!DOCTYPE html>

   <input type="radio" name="radio_btn" value="2">Paste a Code</input>
   , or
   <input type="radio" name="radio_btn" value="3">Put an Image</input>

div 1

div 2

A: I would use two hidden inputs that I would toggle the same ways as the divs to know which form is being submited, hiding the div in which the data is entered will still set the variables inside the div for php.
So I would have
$("input[name$='radio_btn']").click(function() {
        var test = $(this).val();

        $("div.togglediv").hide();
        $("input.togglevalue").attr('disabled', 'disabled');
        $("input#toggleinput" + test).removeAttr('disabled');
        $("#togglediv" + test).show();

    });

Then in php I would have these two inputs in each of the divs

// The current div content
<input type="hidden" name="togglediv2" value="1" class="togglevalue" id="toggleinput2" />

and

// The current div content
<input type="hidden" name="togglediv3" value="1" class="togglevalue" id="toggleinput3" />

Then in php I would check for these inputs if they are set so you have:
<?php
if (isset($_GET['togglediv2'])){
// Do actions for Paste a Code
} elseif (isset($_GET['togglediv3'])){
// Do actions for Put an Image
}
?>


text:
Q: Sending a complex object from Java client to C server via Socket I want to send some complex objects from a Java client to C server via a TCP Socket.
How can I do that ?

A: Fundamentally the question is, "How to serialize/deserialize objects in a
language agnostic manner?"  Specifically Java and C in your case.  Since you'll
be sending this data over a network, it is also important to take care of network order/endianness issues.
I assume you have access to both the the client and the server.  This means you
get to choose how to serialize the data.  (If not, the answer is simple.  Write
to the specs of what the other is expecting)
Personally, I would use Protocol Buffers.
There are Java bindings
and C bindings.
If you don't like Protocol Buffers, there are other options like:

*

*JSON (already mentioned)

*YAML

*Apache Thrift

*XDR

*roll your own

*...

A: Write the fields of the Java objects to a string (perhaps JSON), send them via TCP, and have the C program read the string and use it to initialize new C variables on the other end.

A: This question is pretty old, but just in case some one is still looking for a good solution, you can try out the protocol buffers implementation, as mentioned in the previous answer by @Adam Liss: (developers.google.com/protocol-buffers/)
In short, you define any complex message type as in your protocol implementation, and the tool generates C++/Java/Python code which can serialize and deserialize it.
For the same purpose using C code, a research project at the Technische Universität München (TUM) Germany have created a code generator in standard C, that can be used with embedded-C projects. This is fully compatible(with limitations due to C structs) with Google's protobuf implementation. This works better than the C Bindings because it does not need any library to be linked with.
I had issues in getting the C Bindings to work on the embedded systems I was working with, because it needs to be linked with the support library.
This saved my (painful) day with my embedded project - passing complex network data(request-responses) between an embedded system and Android app(Java)/Desktop app(C++/Qt).


text:
Q: Installed MAMP on windows & loaded wordpress but have get HTTP ERROR 500 What I have done:
Apache Port set to 9000
Location of wordpress folder is C:\MAMP\htdocs.
Folder is called wordpress
Went to phpMyAdmin and created DB
Went to wp-config-sample.php and updated DB = wpTest, username & password = 'root'
changed wp-config-sample.php to wp-config.php
Servers are started.
What displays in chrome browser OK:
http://localhost:9000/MAMP/
http://localhost:9000/wordpress/readme.html

http://localhost:9000/wordpress/ gives the error in browser:
This page isn't working
localhost is currently unable to handle this request.
HTTP ERROR 500

I am therefore unable to set up wordpress.
One thing I have noticed is that MAMP and htdocs folder properties when read only is unchecked and applied and I open it again then read only is checked again.
I have given all users full control in security settings.
Thanks

A: the unzipping program I used to extract the wordpress files did not unzip correctly and the files within the folders wp-admin, wp-content, wp-includes were displayed but not the folders themselves. Several times I downloaded & unzipped the wordpress files and all with the same results.
I changed the unzipping programming and the folders were correctly unzipped.
In the past I have had an unzipping program fail to extract a file but never extract the files incorrectly like this before.
Initially without the folders the path to load certain files was incorrect and they couldn't be found and hence the error:
This page isn't working
localhost is currently unable to handle this request.
HTTP ERROR 500


text:
Q: How can I find the first monday of current month using cygwin bash date utilty? I need to know the first monday of the current month using Cygwin bash.

A: One Liner:
d=$(date -d "today 1300" '+%Y%m01'); w=$(date -d $d '+%w'); i=$(( (8 - $w) % 7)); answer=$(( $d + $i ));
The result is stored in $answer.  It uses working variables $d, $w, and $i.
Proof (assuming you just ran the one liner above):
echo $answer; echo $(date -d $answer '+%w')
Expected Result: Monday of current month in YYYYMMDD.  On the next line, a 1 for the day of the week.
Expanded Proof (checks the next 100 month's Mondays):
for x in {1..100}; do d=$(date -d "+$x months 1300" '+%Y%m01'); w=$(date -d $d '+%w'); i=$(( (8 - $w) % 7)); answer=$(( $d + $i )); echo $answer; echo $(date -d $answer '+%w'); done | egrep -B1 '^[^1]$'
Expected Result: NOTHING
(If there are results, something is broken)
Breaking it down
The first statement gets the first day of the current month, and stores that in $d, formatted as YYYYMMDD.
The second statement gets the day of the week number of the date $d, and stores that in $w.
The third statement computes the increment of days to add and stores it in $i.  Zero is perfectly valid here, because...
The last statement computes the sum of the date $d (as an integer) and the increment $i (as an integer).  This works because the domain of the $i is 0 to 6, and we will always start at the first day of the month.  This can quickly be converted back to a date variable (see Proof for example of this).
This has been tested on BASH v4.1 (CentOS 6), v4.4 (Ubuntu), and v5 (Archlinux)

A: This should do it, but I have no Cygwin here to test:
#!/bin/bash

# get current year and month:
year=$( date +"%Y" )
month=$( date +"%m" )

# for the first 7 days in current month :
for i in {1..7}
do
  # get day of week (dow) for that date:
  dow=$( date -d "${year}-${month}-${i}" +"%u" )" "

  # if dow is 1 (Monday):
  if [ "$dow" -eq 1 ]
  then
    # print date of that Monday in default formatting:
    date -d "${year}-${month}-${i}"
    break
  fi
done

See manpage date(1) for more information.

A: A one-liner--I hope it's correct
d=$(date -d date +%Y%m"01" +%u);date -d date +%Y%m"0"$(((9-$d)%7))
the variable d contains the day of week (1..7) where 1 is Monday
then I print the current year and month changing the day with $((9-$d))


text:
Q: Effect of DLL to execution speed First of all, I use user-defined header and corresponding cpp file. Then I include and so on. If I would switch to DLL, would the execution speed of the code be retarded?
Secondly, I know that in "DLL", "D" represents "dynamic" however, my friend said that there are two ways to use them: Statically and dynamically. If it is dynamic already, what we have to do with "static"?

A: *

*Productivity shouldn't regress, as far as calling function from dll in general similar to local function call.

*Two types of libs exists:

*

*from one poin of view, dynamic libs and static libs. Here static means, that all code from the lib will be linked statically to your exe, oppositely dynamic lib allows to separate code from executable to shared library, that code will be loaded dynamically.

*Then, dynamic libary can be linked to statically, and that means, that OS will link library to your program on startup and dynamically, that means, you obtain pointers to symbols, storied in library, by hands. While dynamic loading gives more flexibility, it more difficult way that using static linking.

A: Unless the function is very small (so it gets inlined otherwise), using a DLL has no difference whatsoever on the performance (aside from the fact that loading a DLL does increase the startup time of your application.) Large, performance-critical applications use DLLs (for instance the Intel Math library.) There are minor penalties if the compiler cannot do whole-program optimization, but these are very small differences which usually don't matter.
Regarding static/dynamic: I assume he means that you can link against a DLL the normal way (by using an import library), which forces it to be always loaded or load it dynamically at run-time (using LoadLibrary and dlopen.) No performance difference there, but using LoadLibrary allows you to delay loading the library until actually needed.


text:
Q: Right Regression for 2 binominal IVs and one metric DV My independet variables are binominal (gender and posture)
but my dependent varibale is interval scaled (it's seven steps Likert scale)
What is the right regression model for this? And how do I apply it in R?
Thanky you for any advice

A: `For the constellation 2 binominal IVs and one metric DV, it is okay to use a simple Linear model like lm in R.


text:
Q: Wordpress get first image from a post Trying to get the first image from a post, but my php code doesn't return anything, any help?
<?php while ($browndog_blog->have_posts()) : $browndog_blog->the_post();
    $args = array(
    'numberposts' => 1,
    'post_mime_type' => 'image',
   'post_parent' => $post->ID,
    'post_status' => null,
    'post_type' => 'attachment'
    );

    $attachments = get_children( $args );

    //print_r($attachments);

    if ($attachments) {
        foreach($attachments as $attachment) {
            $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' )  ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );

            echo 'ID).'">ID ).'">';
            echo '
'.get_the_excerpt($post->ID).'
';
            echo '
ID).'">Read More
';
        }
    }
endwhile; ?>

Not sure what's going wrong as I'm using a similar code to get all of the image attachments and not just one, and that works fine.

A: get_children() only returns images that have been uploaded directly to that post. If an image has been attached to a given post it will not be considered one it's children and thus wont be returned by the afore mentioned function.
An easy way to check a post's children is login to the dashboard and go to posts, edit post. Click the Add Media button above the editor and from the only drop down box select Uploaded to this post. If this is empty then get_children will not return any images regardless of the post's content.

A: I think I just did the same thing as you are looking to do... I won't claim to be a guru, but here's what I did to get this working and with any luck you will be able to adapt it to your needs.
$image_id=get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'large');
$image_url=$image_url[0];

Basically the first image in the array is the thumbnail, as I understand it, so that's why I grab the thumbnail id first, then use it to retrieve the large version of the image.


text:
Q: Detect a digital signature without WinVerifyTrust I have a large number of EXE files and need to figure out which ones have digital signatures. Does anyone know if there is a way to check without access to WinVerifyTrust (they're all on a Unix server).
I can't seem to find any information on where the digital signature actually is inside the EXE. If I could find out where it is I might be able to open the file and fseek to a location to test. I don't need to do "real" verification on the certificate, I just want to see if a digital signature is present (or, more importantly, NOT present) without having to use WinVerifyTrust.

A: As mentioned above, the solely presence of the IMAGE_DIRECTORY_ENTRY_SECURITY directory is a clear indicator to detect the presence of a signature inside a PE file. If you have a large amount of files to test and want to filter these, just testing the presence of this standard directory is valid. You don't need a library to do this.

A: I tried to solve the problem in the same situation.
I recommend osslsigncode.
This is an implementation of windows authenticode with openssl.
https://github.com/develar/osslsigncode
Below is a code block excerpt from osslsigncode.
siglen = GET_UINT32_LE(indata + peheader + 152 + pe32plus*16 + 4);

If siglen is 0 in osslsigncode, it determines that there is no signature.
If you just want to check the signature, you don't need a library.
However, see osslsigncode for help.

A: You can find this information using code from Mono.Security.dll AuthenticodeBase [1]
[1] https://github.com/mono/mono/blob/master/mcs/class/Mono.Security/Mono.Security.Authenticode/AuthenticodeBase.cs
Your best hint (if an authenticode signature is present) is:
 // 2.2. Locate IMAGE_DIRECTORY_ENTRY_SECURITY (offset and size)
 dirSecurityOffset = BitConverterLE.ToInt32 (fileblock, peOffset + 152);
 dirSecuritySize = BitConverterLE.ToInt32 (fileblock, peOffset + 156);

if dirSecuritySize is larger than 8 then there's an signature entry (valid or not).


text:
Q: I want to align my caption to the left side I am writing a paper, however, i have been faced with a problem; Caption is located at the middle side of my paper and i cannot control the locus of it. (see the attached file)

the codes are;
\begin{figure*}[H]
\includegraphics[width=\columnwidth]{figure_1a.pdf}
\caption{aa//left-aligned}
 \label{fig:figure_1a.pdf}
\end{figure*}

what should i do?

A: I suspect, that you like to have your image placed in one column and caption centered below image, something like this:

For this the MWE is:
\documentclass[twocolumn]{article}

\usepackage{lipsum}

\begin{document}
\lipsum[1]
\begin{figure}[htb] % <-- see difference between your code and this MWE
    \includegraphics[width=\columnwidth]{example-image}
\caption{aa//left-aligned}
    \label{fig:figure_1a.pdf}
\end{figure}
\lipsum
\end{document}

A: I don't know whether you want to put the image inside a text or you want text and image on two different columns. If you are in the first case you can use wrapfig package (http://ctan.mirror.garr.it/mirrors/CTAN/macros/latex/contrib/wrapfig/wrapfig-doc.pdf) which helps you to manage pictures in the middle of a text. Here's an example:
\documentclass{article}

\usepackage{lipsum}
\usepackage{graphicx}
\usepackage{wrapfig}
\begin{document}

    \begin{wrapfloat}{figure}{I}{0pt}
        \includegraphics[width=0.5\textwidth]{tiRFF.png}
        \caption{This is an example}
        \label{fig: wrapfloat}
    \end{wrapfloat}
    \lipsum

\end{document}

A: Use the threeparttable package for that. It defines a measuredfigure environment, which… measures the figure, and centres the caption w.r.t. the figure width.
From the documentation of the package:

For figures, there is an equivalent measuredfigure environment. It is fairly
  fragile though, and should be used only for a single graphic above a single
  caption.

I didn't test it in a two column document.
\usepackage{threeparttable}
.....
\begin{document}

\begin{figure}
\begin{measuredfigure}
\includegraphics[width=\columnwidth]{figure_1a.pdf}
\caption{aa//left-aligned}
 \label{fig:figure_1a.pdf}
\end{measuredfigure}
\end{figure}


text:
Q: Как преобразовать объёмную однолистовую книгу .xlsm в csv? Здравствуйте!
Имеется файл в формате .xlsm. В нём находится один лист. Надо преобразовать в .csv с разделителем-запятой.
Пробовал PHPExcel, но он не работает с файлом .xlsm размером 10 МБ (выпадает по таймауту). На маленьких всё нормально.
Собственно, делаю вот этой функцией:
function convertXLStoCSV($infile,$outfile)
{
    $fileType = PHPExcel_IOFactory::identify($infile);
    $objReader = PHPExcel_IOFactory::createReader($fileType);

    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($infile);

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
    $objWriter->save($outfile);
}

A: Когда сталкивался со схожей задачей (прайсы автомагазина, до 50 мег), проще оказалось набросать скрипт на питоне с использованием библиотеки xlrd (заявлена поддержка xls, xlsx, не думаю, что xlsm будет проблемой). Причем потребление памяти в разы меньше, а работает секунды.
Перед вызовом сохраняем файл, используем system() или что больше нравится, потом забираем файл.
Пример взял отсюда
import xlrd
 import csv

 def csv_from_excel():

    wb = xlrd.open_workbook('your_workbook.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('your_csv_file.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in xrange(sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()


text:
Q: filter a rendered grid result from selectbox value in jquery UPDATE: my question became lot simpler I think. how can I do to tell:
 var query = $(":input[name=filter]").val(),

To take $("select[name=PR_Type]").val(), as parameter?
I tried something like this:
var query = $(":input[name=filter]").val() || $("select[name=PR_Type]").val(),

but this take only $("select[name=PR_Type]").val(),as filter result...

Im trying to filter a result based on a value selected from a selectbox. The renderResult() function renders a grid that has some labels and the rendered data and it looks something like this:
renderResult: function () {
 var query = $(":input[name=filter]").val(),
 querySelect = $("select[name=PR_Type]").val(),
 queryRegexp = query === "" ? undefined : new RegExp(query, "i"),
 console.time("productos.renderResult()");
     $("#result").html("");
         productos.sort();
     $.each(productos.models, function (i, row) {
     if (!row.transformed) {...

So I came up with something like this:
$('[name=PR_Type]').on('change', function (event) {

        var selection = $(this).val(), //Changed here and now I get the value

        products.renderResult(selection);
    });

and a selectbox like this:
<select name="PR_Type"></select>

This selectbox get its values from a json file that connects to the servlet. and this is how I set the options to the selectbox:
 var types = [];
    for (var type in productos.productosTypes) types.push(productos.productosTypes[type] + "|" + type);
    $("[name=PR_Type]").setOptions(types);

I also created a function to get the values to do something like this:
this.getValue("PR_Type"),

but Im not sure how to implement this anymore
getValue: function (name) {
        var $elemSelect = $("select[name=" + name + "]");
        return $elemSelect.val() ? escape($elemSelect.val()) : "";
    },

I know Im missing something on the $('[name=PR_Type]').on('change', function (event) { but im not sure what it is. Thanks everyone in advance for any advise!

A: SOLVED! All the poroblem lays in renderResult() there I tried to look if the selectbox value was empty or null, which it was wrong. I should look if it was null ori undefined, then I had to change a litle bit the regExp if scentence. So at the end I changed this:
querySelect = $("select[name=PR_Type]").val(),
queryRegexp = query === "" ? undefined : new RegExp(query, "i"),

and added this:
querySelectRegexp = querySelect === null ? undefined : new RegExp(querySelect, "i"),

so now it looks like this:
renderResult: function () {
        var query = $(":input[name=filter]").val(),
            querySelect = $("select[name=PR_Type]").val(),
            queryRegexp = query === "" ? undefined : new RegExp(query, "i"),
            querySelectRegexp = querySelect === null ? undefined : new RegExp(querySelect, "i"),

And the regExp if scentence was like this:
  if (querySelectRegexp !== undefined) {

                    if (queryRegexp !== undefined) {
                        if (row.name.match(queryRegexp)) {
                            row.classes = row.classes.replace(/hide/g, "");
                        } else {
                            if (row.classes.indexOf("hide") === -1) {
                                row.classes += " hide";
                            }
                        }
                    } else if (querySelectRegexp !== undefined) { (row.type.match(querySelectRegexp)) {
                            row.classes = row.classes.replace(/hide/g, "");
                        } else {
                            if (row.classes.indexOf("hide") === -1) {
                                row.classes += " hide";
                            }
                        }
                    } else {
                        row.classes = row.classes.replace(/hide/g, "");
                    }

and now it looks like this:
  if (querySelectRegexp !== undefined) {
                        if (row.type.match(querySelectRegexp)) {
                            row.classes = row.classes.replace(/hide/g, "");
                        } else {
                            if (row.classes.indexOf("hide") === -1) {
                                row.classes += " hide";
                            }
                        }
                    }
                    if (queryRegexp !== undefined) {
                        if (row.name.match(queryRegexp)) {
                            row.classes = row.classes.replace(/hide/g, "");
                        } else {
                            if (row.classes.indexOf("hide") === -1) {
                                row.classes += " hide";
                            }
                        }
                    } else {
                        row.classes = row.classes.replace(/hide/g, "");
                    }


text:
Q: Как из всего текста выбрать только нужное? Из текста:
{"result":  [{"spa_id":153048737,"mmr":354.727809161879,"season_number":43,"calibrationBattlesLeft":0,"number":1,"skip":false,"updated_at":"2022-12-18 12:50:57","score":6547,"nickname":"Luc1que_","clan_tag":"PWNZ"}

нужно отобразить только clan_tag, nickname и score
как это сделать?

A: Если исходник такой:
data = {"result":
{"spa_id": 153048737, "mmr": 354.727809161879, "season_number": 43, "calibrationBattlesLeft": 0, "number": 1, "skip": False, "updated_at": "2022-12-18 12:50:57", "score": 6547, "nickname": "Luc1que_", "clan_tag": "PWNZ"}}

ТО примерно так:
print(data["result"]["clan_tag"])
print(data["result"]["nickname"])
print(data["result"]["score"])


text:
Q: Trying to sequence numbers for multiple lines in Emmet wrap abbreviation for Sublime New to the coding game, and familiarizing myself with Sublime Text and its plugins on Windows10.
After much searching, I finally figured out that v 3 and 4 do not offer the inherent ctrl+shift+g macro to wrap with abbreviation, so I manually binded those keys to that command:
{"keys": ["ctrl+shift+g"], "command": "emmet_wrap_with_abbreviation"},
The problem now is I can't get $$ for multiple lines to sequence, i.e. 01-07. It instead outputs 01-01.
For example:
Typed Monday-Sunday on separate lines. Shif+right-click highlight days to tag and wrap individual lines. ctrl+shift+g to bring up emmet wrap abbreviation command line.
In line typed  li.day-$$>span
Output:

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday

But should have been:

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday

as it was in a tutorial I was watching. Although, the tutorial was from 2014, so it would have been an older version of Sublime as well as Emmet, if that matters. Additionally, since the binded keys performed the function of bringing up the wrap abbreviation command line, I suspect a function in the line itself, but I'm not sure what or why.

A: It looks like you've used multiple cursors to select each line individually then wrapped it with abbreviation. Instead, you should select text you want to wrap as a single selection.
Also, when wrapping multiline text, you should mark repeated element with *. In your case, abbreviation should look like this: li.day-$$*>span
https://docs.emmet.io/actions/wrap-with-abbreviation/#wrapping-individual-lines


text:
Q: exec-maven-plugin:1.2.1 in Ecipse When importing a Maven project into Eclipse I get the following error:

No marketplace entries exec-maven-plugin:1.2.1 error

And it looks like it results in further build problems post import - like

Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:exec-maven-plugin:1.2.1:java (execution: default, phase: generate-sources)

Am I missing a plugin or is there anything wrong with my pom.xml?
Installed m2e:

m2e - Maven Integration for Eclipse (includes Incubating components)  1.5.0.20131218-1208 org.eclipse.m2e.feature.feature.group   Eclipse.org - m2e
Eclipse Java Development Tools    3.8.2.v20130116-090414-8-8nFu3FNOfwKLRuqgXKIy9z0I83 org.eclipse.jdt.feature.group   Eclipse.org
Eclipse Platform  4.2.1.v20130118-173121-9MF7GHYdG0B5kx4E_SkfZV-1mNjVATf67ZAb7    org.eclipse.platform.feature.group  Eclipse.org
Eclipse RCP   4.2.2.v20130129-152330-7IARAABrMQkGSvMgQnUlz-DQz00h org.eclipse.rcp.feature.group   Eclipse.org

Thanks in advance.

A: The problem is that the m2e plugin of Eclipse doesn't know of exec-maven-plugin you could solve that by the following:
   <build>
      <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.codehaus.mojo</groupId>
                                        <artifactId>exec-maven-plugin</artifactId>
                                        <versionRange>[1.2.1,)</versionRange>
                                        <goals>
                                            <goal>java</goal>
                                            <goal>exec</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore/>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
   </build>


text:
Q: How to compile the main from a chapter when the main is in another directory (with arara)? This solution works perfectly if the main is in the same directory of the chapter file.
But suppose I have:
maindirectory
  main.tex
  chapterdirectory
    chapter.tex

How can I compile main.tex from chapter.tex? (I'm using Windows 10).
I tried with:
% arara: pdflatex: { files: [ "C:\maindirectory\main.tex" ] }

and other various combinations but it seems that arara accepts only the file name.
This is the same naive question Diaa Abidou asked in his comment, which remained unanswered, unfortunately.

A:
This has been a discussion since the dawn of time, whether we should use only the file name or the entire reference. Hence, version 4.0 has two variables for that:

*

*file refers to the the file name, as main.tex (no directory reference), and

*reference refers to the full (normalized, canonical) path.

Note: You can take a look at the list of extracted directives in the log file (namely, arara.log, enabled with the --log command line option) and see the actual values for file and reference. Also observe that, for each element of files, the tool will add a directive of its own.
Sometimes we are restricted to the coverage of TeX tools, so we opted for the easiest solution. However, I must point out that version 4.0 allows project-based rules, so the cleanest solution in your case is to have:

*

*an arara configuration file, and

*a custom pdflatex rule with reference instead of file
Then
% arara: pdflatex: { files: [ 'chapters/main.tex' ] }

will work as expected. Another possibility (way more advanced) is to keep file but change the working directory during command creation. I will present both solutions as follows.
Regarding security issues, we have a Turing-complete environment in the rule scope, so little to nothing could be done in this case. Deeply sorry. :)
So let us cover the possibilities. Here is a possible solution using a project-based configuration file and a modified engine rule (in this example, I will use pdflatex). First, I create the following configuration file (version 4.0 allows 4 names for the configuration file: araraconfig.yaml, .araraconfig.yaml, arararc.yaml and .arararc.yaml. I will use the first option. Note that there is a lookup order, so take a look at the user manual for more details):
araraconfig.yaml (placed at the root level of your project)
!config
paths:
- '.'

Now, let us copy the original pdflatex.yaml rule to the root level of the project. Now, pdflatex directives will refer to this rule instead of the default one (as the paths key in the configuration file sets the current directory to be searchable first).
First approach: replace file by reference
This is the easiest solution. Simply replace lines 16 and 17 of pdflatex.yaml
    return getCommand('pdflatex', interaction, draft, shell,
           synctex, options, file);

by these two:
    return getCommand('pdflatex', interaction, draft, shell,
           synctex, options, reference);

Note that we simply replaced file by reference. That should suffice. The directive usage would be as follows:
% arara: pdflatex: { files: [ 'chapters/main.tex' ] }

Second approach: add a working directory option
This solution involves adding an extra argument to our rule (we can append these lines to pdflatex.yaml):
- identifier: directory
  flag: >
    @{
        parameters.directory
    }

Now we should replace lines 16 and 17 of pdflatex.yaml
    return getCommand('pdflatex', interaction, draft, shell,
           synctex, options, file);

by these:
    if (isEmpty(directory)) {
        return getCommand('pdflatex', interaction, draft, shell,
               synctex, options, file);
    }
    else {
        return getCommandWithWorkingDirectory(directory, 'pdflatex',
               interaction, draft, shell, synctex, options, file);
    }

And then the directive usage should be along those lines:
% arara: pdflatex: { files: [ 'main.tex' ], directory: chapters }

Hope that helps! :)


text:
Q: How to outline a circle on a grid? I want to outline my circle of cells, to do that I need a path that travels from each outer corner of the circle. Ive tried to illustrate it below.
Yellow is the circle, in red I've noted some coordinates the way I store them, and blue are where the path points would need to be:

To get the circle of cells surrounding cell at gridX, gridZ I use the following code:
public List<Cell> GetSurroundingCellsCircle(int gridX, int gridZ, int distance)
    {
        List<Cell> matches = new List<Cell>();
        int EX = distance + gridX;
        int EY = distance + gridZ;
        int SQ = distance * distance;

        for (int x = gridX - distance; x <= EX; x++)
        {
            for (int z = gridZ - distance; z <= EY; z++)
            {
                int c = x - gridX;
                int d = z - gridZ;

                if ((c * c + d * d) < SQ)
                {
                    Cell cell = GetCell(x, z);
                    if (cell != null)
                        matches.Add(cell);
                }
            }
        }

        return matches;
    }

So in this List I have access to all the cells in the circle. Now I need to find the border cells, then find the path of the outer corner of those cells. I do not really even know where to start.

A: Once you have the list of cells:

*

*For each column find the coordinates of the top cell (the one with the maximum Y coordinate). This gives you the cells at the top, so draw a line above each cell.

*For each row find the coordinates of the right-most cell (the one with the maximum X coordinate). This gives you the cells on the right side of the circle, so draw the line on the right of each cell.

*For each column find the coordinates of the bottom cell (the one with the minimum Y coordinate). This gives you the cells at the bottom of the circle, so draw the lines below each cell.

*For each row find the coordinates of the left-most cell (the one with the minimum X coordinate). This gives you the cells on the left side of the circle, so draw the lines on the left side of each cell.

This isn't the most efficient way of doing this, but if your grid isn't huge it should be quick enough.


text:
Q: Hide subfolder in URL with .htaccess I have a URL structure like this: www.mydomain.com/foo/bar/index
and I want achieve this: www.mydomain.com/bar/index
I already have a rewrite rule like this to remove .php from the URL:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(([A-Za-z0-9\-]+/)*[A-Za-z0-9\-]+)?$ $1.php

So, how can I add a new rule to hide the foo subfolder in compliance with the rule already implemented?

A: You can use this. Put this before your existing RewriteRules
RewriteEngine on
RewriteRule ^bar/ /foo%{REQUEST_URI} [L]

A: You can have your htaccess as this one:
RewriteEngine On

# add /foo/ if not there
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^foo/ foo%{REQUEST_URI} [L,NC]

# add .php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]


text:
Q: Visual Flow Lookup from Lookup Can I not have a fast/record lookup that returns a collection of IDs and then do a second fast/record lookup using that collection of IDs in the filter criteria?
I think the answer to this is that flows don't allow it, but I want to confirm.

A: The straightforward and short answer is, currently what you're trying to achieve is not possible in Flow.
Possible solution: - There is a plugin created by a community member (I think I heard about it on success community workflow group) to overcome it.


text:
Q: A doubt on Sonic Boom My textbook says that:

Sonic Boom :
Sonic boom is an impulsive noise similar to thunder........
From the perspective of the aircraft, the boom appears to be swept backwards as it travels away from the aircraft. If the plane makes a sharp turn or pulls up, the boom will hit the ground in front of the aircraft.

I don't get it what they mean by that sentence in bold. What do they mean by 'the ground infront of aircraft'? Do they mean that it hits the area which was infront of the aircraft before it takes a sharp turn or pulls up?

A: The shock wave itself is just a nonlinear sound wave that steepened to the point of reaching a stable discontinuity.  If a supersonic jet makes an abrupt turn while moving faster than the speed of sound, the shock wave produced prior to the turn will continue to propagate in the original direction of the jet prior to its turn.  In this way, the sonic boom could be heard before the jet physically passed over the observer.  This is what is meant by the last sentence.

A: Yes, I'd say it's poorly worded. I'm pretty sure they meant "the ground that was ahead of the aircraft before it turned or pulled up".


text:
Q: MySQL trigger after insert and after update I have two tables with one named att as follows
CREATE TABLE att (
  SID varchar(50) NOT NULL,
  CID varchar(50) NOT NULL,
  Date date NOT NULL,
  H1 varchar(1) NOT NULL DEFAULT 0,
  H2 varchar(1) NOT NULL DEFAULT 0,
  H3 varchar(1) NOT NULL DEFAULT 0,
  H4 varchar(1) NOT NULL DEFAULT 0,
  H5 varchar(1) NOT NULL DEFAULT 0,
  H6 varchar(1) NOT NULL DEFAULT 0,
  H7 varchar(1) NOT NULL DEFAULT 0,
  H8 varchar(1) NOT NULL DEFAULT 0,
  H9 varchar(1) NOT NULL DEFAULT 0,
  H10 varchar(1) NOT NULL DEFAULT 0,
  INDEX (SID, CID)
);

The other table is per with following fields:
SID CID Per
How do I write a trigger for the following:
If an update occurs in any of the fields from h1-h0 on att table then
update the per column in the per table with the following values:
((total no of 1s - total no of 0s)/(total no of 1s + total no of 0s))/100
Thanks in advance
i Developed a Trigger,but it not working,its saying error in line 11,can you say what is the problem??
create TRIGGER `att_up` AFTER UPDATE ON `attentance`
FOR EACH ROW BEGIN
  DECLARE Zeros INT;
  DECLARE Ones INT;
  DECLARE total INT;
  DECLARE atted FLOAT;
  SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8))
      INTO Zeros FROM attentance
      WHERE StudID=NEW.StudID;
  SELECT SUM(h1+h2+h3+h4+h5+h6+h7+h8)
      INTO Ones FROM attentance
      WHERE StudID=NEW.StudID;
  SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8))+ SUM(h1+h2+h3+h4+h5+h6+h7+h8)
      INTO total FROM attentance
      WHERE StudID=NEW.StudID;
  set atted=((ZEROS-Ones)/total)/100;
  INSERT into per(per) values (atted);
END$$

A: Make sure you change the delimiter before defining the trigger. Also make sure you're using the same table and column names when you create the table and the trigger (you're using att and attendance, and SID and StudID, in your examples).
As it is, the trigger definition caused no error when I tested it in MySQL 5.1.55 after setting the delimiter.
delimiter $$
CREATE TRIGGER `att_up`
  AFTER UPDATE ON `attendance`
FOR EACH ROW
BEGIN
  DECLARE Zeros INT;
  DECLARE Ones INT;
  DECLARE total INT;
  DECLARE attend FLOAT;
  SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)),
         SUM(h1+h2+h3+h4+h5+h6+h7+h8),
         SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)) + SUM(h1+h2+h3+h4+h5+h6+h7+h8)
    INTO Zeros, Ones, Total FROM attendance
    WHERE SID=NEW.SID;
  SET attend=((Zeros-Ones)/total)/100;
  INSERT INTO per (SID, CID, per) values (NEW.SID, NEW.CID, attend)
    ON DUPLICATE KEY UPDATE per=attend;
END$$
delimiter ;

A: DELIMITER $$

CREATE TRIGGER `att_up` AFTER UPDATE ON `attentance`
FOR EACH ROW

BEGIN

SET @zeros = 0;
SET @ones = 0;
SET @total = 0;
SET @atted = 0;

(SELECT (8-SUM(h1)+SUM(h2)+SUM(h3)+SUM(h4)+SUM(h5)+SUM(h6)+SUM(h7)+SUM(h8)) INTO @zeros FROM attentance WHERE StudID=NEW.StudID);
(SELECT SUM(h1+h2+h3+h4+h5+h6+h7+h8) INTO @ones FROM attentance WHERE StudID=NEW.StudID);
(SELECT (SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8))+ SUM(h1+h2+h3+h4+h5+h6+h7+h8)) INTO @total FROM attentance WHERE StudID=NEW.StudID);

SELECT (((@zeros-@ones)/@total)/100) INTO @atted FROM (SELECT 1) AS x;

END$$


text:
Q: WCF REST Service save text file while hosting using Windows services I wrote a small test WCF REST service using C#, within the WCF service, if it receive POST info from client, the WCF will collect the HTTP Request message from client and write it to a text file.  I am using Stream to collect HTTP request and using StreamWriter to write it to a text file. I can specify any folder/path for the text file.
At this point, everything is working when I host the WCF REST service using a local console app.
However, I want to host the WCF service by using Windows service, the Windows service self is fine, it can be started/stoped no issue, my issue is, when client send HTTP POST request, the WCF suppose to create the text file but I can't see the text file. I tried to search the file on the PC, I could not find it, the text file actually never generated (in my view,  Windows Service is not responsible to write the file, it is still WCF responsibility)
btw, the HTTP GET works from client (means the WCF Windows service works at least for GET).
any hints are much appreciated


text:
Q: "Log in" or "Log on"? What is correct?

*

*He was logging on to the Bitrack database.

*He was logging in to the Bitrack database.

*Please note a password is required to log on/in to the database.

A: You generally log in (when entering usernames and passwords.) Log on can be used just to mean to visit a website, but that's not so common. I don't think you ever log on when you're entering a password unless you're confusing the two terms (which I'm sure happens a lot.)

A: Microsoft Manual of Style page 329 states

Use log on or log on to to refer to creating a user session on a computer or network.  Use log off or log off from to refer to ending a user session on a computer or a network  Use sign in and sign out to refer to creating and ending a user session on the Internet.
Do not use log in, login, log onto, log off, logout, sign off, or sign on unless these terms appear in the user interface.

All that said, 'on' implies a platform, such as a particular machine or service while 'in' implies being surrounded, such as by data.


text:
Q: Relation between dimensions of a body and pixels in box2d iphone Could anyone tell me about the relation between the dimensions of a body and number of pixels(in box2d). How many pixels contributes to one meter length?
To be more specific, I'm using the below line of code in my program
polygon_body.SetAsBox(1, 1);
In this code what are the parameters of SetASBox. I mean whether it is a pixel value or some other units.

A: one meter is about 32 pixels.
without looking at the manual, my guess is that since SetAsBox() is a box2d function, it takes parameters in meters. So if you have pixel values, you could just use this definition to easily convert to meters:
#define PTM_RATIO 32
including this in your files allows you to forget the ratio and just use this definition whenever you need to convert between pixels and meters. when you actually do the conversion, you can just divide or multiply by this ratio (32/1) depending on the context. Eg:
CGSize winSize = [[CCDirector sharedDirector] winSize];
b2Body *body = world->GetBodyList();

if(body->GetPosition().x*PTM_RATIO > winSize.width/2){
    // do stuff....
}

This conditional wouldn't work if you compared meters (GetPosition) to pixels (winSize), so this is a great example of where this conversion is useful.
Or, in your case:
float pixel_width, pixel_height;
polygon_body.SetAsBox(pixel_width/PTM_RATIO, pixel_height/PTM_RATIO);


text:
Q: IE refuse to change array elements into text I have problem with my javascript code working on IE. I think I know exactly why it is working wrong, although I dont know how to change it.
Let me explain:
My code consist of small part of code inside $(document).ready() and a lot of inside $ajax.success(). The first part works normally, then I thought I have problem with ajax - that it simply dont work on IE. The error was:
Script65535 unexpected call to method or property access.
Jquery - 1.7.2.min.js line 5847, character 5
And line 5847 is APPEND function!!! It simply must work!
5844  append: function() {
5845    return this.domManip(arguments, true, function( elem ) {
5846        if ( this.nodeType === 1 ) {
5847            this.appendChild( elem );
5848        }
5849    });
5850  }

Then I found on google, that IE have problems when the multi-dimension array is changed to text. And only two appends in my ajax.success() function appends the content of arrays!
$('.display_info_here').append(tab_szablony[i][lang_number-2].toUpperCase()+'

');

I tried to change the array to text in another way, but it didnt worked
var arrr = tab_szablony[i][lang_number-2];
$('.display_info_here').append(arrr.toUpperCase()+'

');

It works on IE 9+, but not in 8 :(
Thanks for any help :)


text:
Q: Does Snowpack support importing files using a glob pattern? I am trying import all the files matching a glob pattern using Snowpack:
import allFiles from '../static/posts/**/*.md';

In Rollup you can achieve it with rollup-plugin-glob, is there anything like that in Snowpack ecosystem?

A: Snowpack has just released support for glob importing in 3.2.1! The syntax mirrors Vite's glob import support, so code like…
const modules = import.meta.glob('./dir/*.js')

would be transformed into the following:
const modules = {
  './dir/foo.js': () => import('./dir/foo.js'),
  './dir/bar.js': () => import('./dir/bar.js')
}

A: Currently Snowpack doesn't support importing multiple files matching a glob pattern, but there is an open issue to implement this feature, so I guess this will eventually be supported.


text:
Q: Redux - Ngrx action dispatch asynchronous treatment I have a time slider that trigger action to filter data every change
this.selectedDate$
  .pipe(
    switchMap(elm => {
      this.selectedTime = elm.timeSelect;
      this.store.dispatch(new GetSchedulesByTime(elm.timeSelect.toString()));
      return this.store.pipe(select(selectSchedulings));
    })
  )
  .subscribe((schedules: ISchedule[]) => {
...});

GetSchedulesByTime update a store with new data;
selectSchedulings is a selector of this new data
What happens is when selectedDate the action is dispatched , selector still points to last state, so my treatment is distorted.
Here's my action code
case ESchedulesActions.GetSchedulesByTime: {
  let time = action.payload;
  return { ...state, actualTrips: [...(state.schedulings[time] || [])] };
}

And selector
export const selectSchedulings = createSelector(
  schedulings,
  (state: ISchedulesState) => state.actualTrips
);

How to be sure that selector is pointing to the new state before return it  ?

A: Here's a little understanding on how the dispatch and select actually work.
Dispatch
When you dispatch an action, it calls for an effect if it exists. The output of effect or the action payload is directly transferred to the reducer that updates the state.
select
The selectors help you select a particular part of your state. this.store.select basically returns you an observable that you can subscribe to. This subscription means that anytime there is a change in state, your subscription callback will be called.
Hence, what you essentially need to do is to take out the selector and subscribe to it as shown below:
this.scheduling$ = this.store.select(scheduleSelectors.selectSchedulings);
this.scheduling$.subscribe((data)->{
//do something with the data
//This is called everything state changes
})

Thus, you do not need to pipe the selector each time. Just subscribing to it once is sufficient. On every dispatch of action, your state should change and that will in turn call the above subscription. To validate this fact, you can debug your code and check for yourself.


text:
Q: Регулярное выражение для автозамены символов Ăă, Ââ на Aa, Îî на Ii, Șș на Ss, Țț на Tt Помогите пожалуйста разобраться, сайт работает на Opencart, использую модуль Simple, в нём есть возможность использовать регулярные выражения в текстовых полях, может эта инфа поможет, не нашёл ответа на форумах, вопрос оказался эксклюзивным

A: Регулярные выражения в модуле "Simple" немного не для вашей задачи. Если прописать регулярное выражение оно лишь запретит ввод, но не будет заменять буквы. То есть пользователь будет вводить "Â" а в поле будет просто пустота.
В вашем случае нужно использовать не большой js код.
Войдите в админке в модуль "Simple" перейдите в раздел "JAVASCRIPT" и используйте там следующий код:
function transliterate(word, template){
  return word.split('').map(function (char) {
    return template[char] || char;
  }).join("");
}
$('[name="customer[firstname]"]').on("keyup paste", function() {
let th = $(this);
let val = th.val();
let template = {'Ă':'A', 'ă':'a', 'Â':'A', 'â':'a', 'Î':'I', 'î':'i', 'Ș':'S', 'ș':'s', 'Ț':'T', 'ț':'t'};
val = transliterate(val, template);
th.val(val);
});

Естественно не забудьте изменить имя "customer[firstname]" на имя того поля, в котором вы хотите выполнять замену. Его имя можно узнать, воспользовавшись chrome devtools, кликнув на input и скопировав значение атрибута "name"
Так же советую вам выполнять замену не только тех символов, что вы указали, добавьте полный список символов из итальянского, французского, чешского, польского языков, если это конечно необходимо, например хотя бы эти:
'Á', 'á','Č', 'č','Ď', 'ď','É', 'é','Ě', 'ě','Ň', 'ň','Ó', 'ó','Ř', 'ř','Š', 'š','Ť', 'ť','Ú', 'ú','Ů', 'ů','Ý', 'ý','Ž', 'ž', 'í', 'Í', 'É', 'é', 'Â', 'â', 'Ê', 'ê', 'Î', 'î', 'Ô', 'ô', 'Û', 'û', 'À', 'à', 'È', 'è', 'Ù', 'ù', 'Ë' , 'ë', 'Ï', 'ï', 'Ü', 'ü', 'Ÿ', 'ÿ', 'Ç', 'ç'


text:
Q: Retaining "height" declaration in jQuery after an Ajax call (dropdown selection loads product data, resets height on other page elements) I have some jQuery setting a height on product descriptions, this can be seen here:
https://www.gabbyandlaird.com/product/truition-products/truition-healthy-weight-loss-pack
The code I'm using to achieve this is:
$(document).ready(function() {

var $dscr = $('.commerce-product-field-field-long-description'),
    $switch = $('#toggle'),
    $initHeight = 70; // Initial height

$dscr.each(function() {
    $.data(this, "realHeight", $(this).height());    // Create new property realHeight
    }).css({ overflow: "hidden", height: $initHeight + 'px' });

$switch.toggle(function() {
      $dscr.animate({ height: $dscr.data("realHeight") }, 200);
      $switch.html("- Read More").toggleClass('toggled');

    }, function() {
        $dscr.animate({ height: $initHeight}, 200);
        $switch.html("+ Read More").toggleClass();
    });
});

I am by no means a Javascript expert (or even an amateur for that matter). My knowledge of jQuery is fairly limited, so I'm not sure what needs to be changed above so that when the dropdown selection reloads the data on the page, I don't lose the height value on the "Read More" section of the product description. Any assistance is greatly appreciated. Thanks!

A: as per your code above it looks you are doing everything when the document is ready.
here is what you can do.
var initialHeight = function(){
    // you height initialization code here
}

$(function () {
    $(document).ready(initialHeight); // initializes the height on document ready
    $("#yourSelectBox").change(initialHeight); // initializes the height on combobox selection change

});

hope this helps.


text:
Q: Not able to write #include statements properly in Geany IDE Whenever I want to include a header in my source code, the IDE doesn't allow me to type the .h extension. If I type <stdio.h> it accepts only <stdio>, and I'm unable to type any further. I made no changes to the default settings built-in to the IDE. I am using the latest version 1.37.1. I have to manually #include header files from Edit > Insert "include<..>". Any suggestions on how I can disable this behaviour of the IDE?

A: I consider this to be just on the right side of the on/offtopic definition, using the exception for "tools regularily used by programmers".
So I recommend to find out your configuration for "drop rest of word for auto completion" (within editor completion preferences). It could be active and I suspect you do not want it active.
If this does not help, but seems kind of interesting, read for inspiration https://www.geany.org/manual/1.23.1/index.html#editor-completions-preferences and bearby sibling pages.


text:
Q: How to find more than one element in focus I have a HTML where more that one element is active.
`document.activeElement `

returns the first one, but I need to find the second element which is in focus.
sample code as follows.
`

My Element

`

I need to find My Element in the above code which is dynamic(Some tags part will have different combination of tags), also position of li in UL2 will vary.
Please help to get the second element with javascript.

A: document.querySelectorAll('[Active="true"] [Active="true"]')

this will select every active child of every active element. Sadly, though it will also select the 3rd, 4th... nth child.
So if you have any other way to differentiate which one is the 2nd one, then the task will be much simpler.
If it makes any difference - the very fist element in the returned array will be what you need. but If you have several "2nd active children" you want to select - then you'll have no luck.
also:
document.querySelector('[Active="true"] [Active="true"]')

will return the first match, which is an active child of an active element.


text:
Q: Body moves too fast after ApplyLinearImpulse() I have top-down game for iPhone (no gravity) and I'm using Cocos2d and Box2d.
I try to move a bullet by this code:
// 'targetPosition' is a point of touch

b2Vec2 touchInWorld = b2Vec2(targetPosition.x/PTM_RATIO, targetPosition.y/PTM_RATIO);

b2Vec2 direction = b2Vec2(touchInWorld.x - ballBodyDef.position.x, touchInWorld.y - ballBodyDef.position.y);

b2Vec2 force = b2Vec2(direction.x, direction.y);

force.Normalize();

ballBody->ApplyLinearImpulse(force, ballBodyDef.position);

The problem is that the ball moves waaaay to fast if the sprite is small (10x10 px).
If the sprite is 50x50, then the speed is smaller and looks okay.
It's driving me crazy because I can't control the speed at all.
And not only that, if I don't put force.Normalize() the the speed is different depending on the direction of touch ...
Everything was working great when I was using just Cocos2d and animations. I tried using Box2d to implement collisions but it seems such a HUGE amount of effort that I am considering doing the physics myself :(

A: First thing , i am not sure but why are you dividing by PTM_Ratios here, i don think you need that, may be you are handling it some other way.
Second, 10x10 travels faster than 50x50 because you are setting SetMassFromShapes, so assuming you are creating a 50/PTM_RATIOSx50/PTM_RATIO body for 50x50 sprite, the body has greater mass than 10x10 body. so it travels slow.
Third, you are using Distance for Impulse so definatly it you are not going to Normalize you are going to get a Proportional Impulse to your distance
and for the Hackish Solution , if nothing else works for you just Decrease the PTM_RATIO!


text:
Q: WLAN issue with Tenda W307R I'm new to the program so please if this is the wrong place to ask redirect me and I'll pull down my question.
I have a Tenda W307R that I am trying to set up as a wireless access point for my office. When I finished setting it up, I attempted to access it wirelessly (unplugged the LAN cable) using my laptop (the Win7 computer I directly connected to in order to set up the router) and while it seemed to be able to connect to the router it never got past the identifying stage and would ultimately just loop forever trying to identify. I then tried connecting using another machine (Win7) only to find this one didn't even get that far, it simply said that it could not connect. I tried this once more with a Vista Home machine and again no dice.
I thought to myself, perhaps this is a WPA2 connectivity issue, so I did a factory reset and set it up completely unprotected. Same result.
The only way I've been able to find that it will work is if I directly connect using a LAN cable while attempting to access the wireless connection, then it works. Does anyone have any ideas? I can provide more details on request.

A: An access point's role is to bridge a wireless user to a wired network. To test, you should disconnect the LAN cable from your LAPTOP, not the wireless access point.


text:
Q: java based CMS for NEWS site management I am looking for a CMS which can manage NEWS site. It can also support video and audio data for news. I looked into some of the content management systems http://java-source.net/open-source/content-managment-systems but I am not able to find any suitable CMS for NEWS site.
I also need to integrate this CMS with mobile client (Android) for content display.
Kindly suggest any good CMS!
Thanks,
Raju

A: If you're open to look outside of Java, Wordpress can work very well.
I hear If you're looking for Java, look at this posting. Look at Liferay, which seems to be very popular, and has some news sites running on it.
I've also heard a bit of buzz about Weceem, which runs on Grails.

A: The referenced page included a link to magnolia and magnolia seems to have a news template. Android is almost always a challenge, because I guess that most CMS solutions heavily depend on big third-party libs (spring, hibernate, ...)


text:
Q: sencha touch prompt issue I try to create a prompt dialog in the following manner:
Ext.Msg.prompt('Add item',
   'Add an item to this list:',
    function(btn, text){
      if(btn == 'ok'){
        //do stuff...
      }
    },
    null, false, 'foo', null);

Unfortunately this gives me an empty prompt box (no possibility of entering text, and the default value 'foo' does not appear in the text field).
What am I doing wrong? (tested on chromium and an android 2.1 phone).
Cheers

A: Probably Sencha bug
Instead of promptConfig set to null, try to set maxlength property in it
Example:
Ext.Msg.prompt('Add item',
'Add an item to this list:',
    function(btn, text){
         if(btn == 'ok'){
             //do stuff...
         }
    },
this, false, 'foo', {maxlength: 100});

Works in Chrome 15


text:
Q: Trouble with member function accepting template function pointer I'm trying to create a member method on my array class for sorting. I typedef'd two function pointers in my class one for a generic sorting method, and the other for the comparator. I'm having trouble navigating through the errors to determine exactly what is wrong with the way I'm calling it. I hope I've provided enough information, but here's what I got.
The error I'm getting:
main.cpp: In function 'int main(int, char**)':
main.cpp:222:67: error: no matching function for call to 'array<int>::sort(<unresolved overloaded function type>, <unresolved overloaded function type>)'
 sort(wrap_insertion_sort_recursive<int>, custom_comparator<int>);
                                                                ^
main.cpp:55:6: note: candidate: void array<T>::sort(array<T>::p_sort_func, array<T>::p_comparator_func) [with T = int; array<T>::p_sort_func = void (*)(array<int>&, bool (*)(int, int)); array<T>::p_comparator_func = bool (*)(int, int)]
 void array<T>::sort(array<T>::p_sort_func sort_func,
      ^~~~~~~~
main.cpp:55:6: note:   no known conversion for argument 1 from '<unresolved overloaded function type>' to 'array<int>::p_sort_func {aka void (*)(array<int>&, bool (*)(int, int))}'

I'm defining my typedefs here:
template <typename T>
class array {
 public:
  typedef bool (*p_comparator_func)(T a, T b);
  typedef void (*p_sort_func)(class array<T> &array, p_comparator_func);
  ...
  void sort(array::p_sort_func sort_func,
      array::p_comparator_func comparator_func);

  ...
}

My implementation of sort:
template <typename T>
void array<T>::sort(array<T>::p_sort_func sort_func,
                    array<T>::p_comparator_func comparator_func)
{
  if(comparator_func == nullptr) {
    comparator_func = this->default_comparator;
  }

  if(sort_func == nullptr) {
    sort_func = this->default_sort;
  }

  sort_func(*this, comparator_func);
}

The sort function I am passing:
template <typename T>
void wrap_insertion_sort_recursive(class array<T> &array,
  class array<T>::p_comparator_func comparator)
{
  insertion_sort_recursive(array, array.get_capacity(), comparator);
}

My custom comparator:
template <typename T>
bool custom_comparator(T a, T b)
{
  return a < b;
}

And where I'm calling it in main:
class array<int> a(5);
a[0] = 8;
a[1] = 6;
a[2] = 7;
a[3] = 1;
a[4] = 3;

std::cout << "attempting sort" << std::endl;
a.sort(wrap_insertion_sort_recursive<int>, custom_comparator<int>);

A: The problem specifically was with:
template <typename T>
void wrap_insertion_sort_recursive(class array<T> &array,
  class array<T>::p_comparator_func comparator)
{
  insertion_sort_recursive(array, array.get_capacity(), comparator);
}

Instead of class I should have used typename as described in this nice article all about typename here.
So the fixed version would be:
template <typename T>
void wrap_insertion_sort_recursive(class array<T> &array,
  typename array<T>::p_comparator_func comparator)
{
  insertion_sort_recursive(array, array.get_capacity(), comparator);
}


text:
Q: Code organisation and differentiation between tools and utils packages About code organisation in packages, i have seen both tools and util used for the same purpose, ie. to contain classes that help with trivial and frequent tasks.
Example:
+ foo.util
|--  StringManipulation.java
|--  MyLogger.java
+ foo.tools
|--  InputSanitization.java
|--  IdentifyOS.java
|--  Whatever.java

From your experience, is there anything that distinguishes tools from utils?
How should such reusable code be organised?
What is the generaly accepted responsibility (historically or semantically) of both and when should I use one over the other when organizing my code.
Conversely, where should I expect to find the more specialized or on the contrary more low level code in those.

A: Classes within the same package usually share the same or similar functionalities, or they together achieve a set of similar functionalities.  In addition, classes within the same package can access all package-private variables (i.e., those variables defined without public, protected, and private) within their package.
As for naming, while Oracle has defined a convention for java naming packages, it is developer's responsibility to have a clear naming for each package.  In your case, it is better to have some descriptions to describe the utilities and tools.  Here are some examples:
foo.connection.tools
foo.string.utils

In this way, users can know the tools is for connections, utils is for string manipulations.

A: Both "tools" and "utils" are bad names for classes/packages.  It is not object oriented.  It is a way of saying, "I don't know what to name this thing so I'll just give it a generic name".
What you should do is figure out what these tools/utils are really doing and name them appropriately.


text:
Q: How can I use CMake to link vtk library to multiple source file? Here is a typical Cmakelist file with only one source file:
cmake_minimum_required(VERSION 2.8)

PROJECT(test)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

add_executable(test MACOSX_BUNDLE test)

if(VTK_LIBRARIES)
  target_link_libraries(test ${VTK_LIBRARIES})
else()
  target_link_libraries(test vtkHybrid vtkWidgets)
endif()

The above example is if I have test.cxx and CMakeLists.txt only. What do I do if I also have a test2.cxx source file (random class) and another test3.cxx source file? I want to keep test.cxx as my main, and the other as random classes, still using the vtk library.

A: add_executable can be used to choose source files to use for this project.
add_executable(test MACOSX_BUNDLE test.cxx test2.cxx test42.cxx)

same as
SET(CXX_SRC_FILES test.cxx test2.cxx test42.cxx)
add_executable(test MACOSX_BUNDLE ${CXX_SRC_FILES})


text:
Q: Descend finite etale algebras Let $\pi:X\to\mathcal X$ be a presentation of an Artin stack $\mathcal X$ of finite type over a field $k,$ and let $f:Y\to X$ be a finite \'etale covering. Does there exist a finite \'etale covering $Y'\to X$ factoring through $Y,$ such that $Y'$ can be given descent structure, i.e. there exists an isomorphism $pr_1^*Y'\cong pr_2^*Y'$ over $X\times_{\mathcal X}X$ satisfying cocycle condition, so that $Y'\to X$ descend to a finite \'etale covering $\mathcal Y\to\mathcal X$?

A: I don't think so (finite etale covers cannot be localized in smooth topology in the sense that you describe). Say, $\mathcal{X}$ is a point, and $X$ is a smooth variety with non-trivial fundamental group, say, an elliptic curve (or $\mathbb{A}^1-\{0\}$). Then $\pi$ is a presentation. Let $f:Y\to X$ be a non-trivial finite etale cover, say, the cover of the elliptic curve by an isogeneous elliptic curve. Then your question becomes: `is there a trivial (i.e., lifted from $\mathcal{X}$) cover $Y'$ of $X$ with a map to $Y$? This is of course not true.