How can I get return result when I use viewModelScope.launch?

Question: I hope to get a Int return result, the code return mDBVoiceRepository.edit(aMVoice) doesn't work, how can I fix it?
Code A
@Dao
interface DBVoiceDao{
   @Update
   suspend fun edit(aMVoice: MVoice): Int
}

class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    suspend fun edit(aMVoice: MVoice):Int{
        return mDBVoiceDao.edit(aMVoice)
    }
}

class HomeViewModel(private val mDBVoiceRepository: DBVoiceRepository) : ViewModel() {

    fun edit(aMVoice: MVoice):Int{
        viewModelScope.launch {
           return mDBVoiceRepository.edit(aMVoice)
        }
    }

}

Added content 1:
Is there a simple way if I redesign result type as LiveData<Int> ?
Code B
@Dao
interface DBVoiceDao{
    @Update
    suspend fun edit(aMVoice: MVoice): LiveData<Int>
}

class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    suspend fun edit(aMVoice: MVoice): LiveData<Int>{
        return mDBVoiceDao.edit(aMVoice)
    }
}

class HomeViewModel(private val mDBVoiceRepository: DBVoiceRepository) : ViewModel() {

    fun edit(aMVoice: MVoice):LiveData<Int>{
       //How can I do?
    }

}

Added content 2:
I run your code in Fragment, Code C can get correct result, and Code D can't get correct result, why?
 //Code C
//Return correct ID
binding.button.setOnClickListener {
     val aMVoice = MVoice()
     var id=mHomeViewModel.edit(aMVoice)
     id.observe(viewLifecycleOwner){ rowId-> binding.button.text="ID is: "+ rowId.toString()}
}

//Code D
//ID value return null
binding.button.setOnClickListener {
   lifecycleScope.launch{
       val aMVoice = MVoice()
       var id=mHomeViewModel.edit(aMVoice)
       binding.button.text="ID is: "+ id.value.toString()
   }
}

Comment: `viewModelScope.launch {` indicates that this is not a synchronous operation, meaning you won't be able to just return a value from this, you could use callbacks, i'm not sure if there's a better solution for coroutines purely
Answer: If you don't have access to flow then use live data
fun edit(aMVoice: MVoice):LiveData<Int>{
   val result = MutableLiveData<Int>()
    viewModelScope.launch {
      val data = mDBVoiceRepository.edit(aMVoice)
      result.value = data //or result.postValue(data)
    }
   return result
}

flow version would look like
suspend fun edit(aMVoice: MVoice):Flow<Int>{
     return flow {
           val data = mDBVoiceRepository.edit(aMVoice)
           emit(data)
     }.flowOn(Dispatchers.IO)
}

this you can collect{} in your activity or fragment using the lifecycleScope.launch{}
Edit:
suspend fun edit(aMVoice: MVoice):LiveData<Int>{
   //here return the repository version of the edit
   mDBVoiceRepository.edit(aMVoice)
}

now above setup can be directly observed in the activity or fragment inside lifecycleScope.launch{}
or you can modify a bit more to remove the suspend contract.
 fun edit(aMVoice: MVoice):LiveData<Int>{
     val result = MutableLiveData<Int>()
      viewModelScope.launch(Dispatchers.IO) {
       //here return the repository version of the edit
       result.value = mDBVoiceRepository.edit(aMVoice).value
      }
     return result
   }

and observe this directly in fragment or activity without coroutines scope. Adjust minor changes accordingly if needed.
Comment: Thanks! Can I use `withContext()`  in `ViewModel` to get return value?
Comment: this is another way of launching coroutines but again you can't return this directly, in that case also you will either launch in lifecycleScope to direclty access it's value in main or return a live data from viewmodel
Comment: Thanks! Would you please to see my added content in the question?
Comment: Thanks! Would you please to see my "added content 2" in the question?  it seems that  `lifecycleScope.launch{}` can't work well.
Comment: The flow version of the function should not be marked `suspend` (second code block). And in the last code block you are changing the live data value off the main thread, which will throw an exception.


Using confidence intervals instead of pairwise comparisons

Question: Is it possible to use confidence intervals in order to determine if there is a statistically significant difference in means between two (or more) groups instead of conducting pairwise comparisons? For example, if we have the following 95% confidence intervals for the mean of each group:
<code> Control   |   Group A   |   Group B
[0.1,0.2]     [0.3,0.6]     [0.5,0.7]
</code>
Can we say that both Group A and Group B have a significantly different mean than the control at 95% confidence level, and non-significantly different means from each other?
Answer: Confidence intervals and hypothesis tests are closely related, and intervals that could be used in the manner you desire can be constructed. However, your intervals are intervals for the means themselves rather than the differences between means.
If you wanted to invert the intervals into hypothesis tests with the null hypotheses that the true means were a fixed value (generally zero, but any number is possible) then your intervals would be what you need.
When you are comparing the groups you would be interested in the differences between means and so the interval that would be directly reflect that difference is the confidence interval of the difference.
You might find this question and Whuber's answer helpful: Relation between confidence interval and testing statistical hypothesis for t-test
Answer: In general, no. Instead, compute confidence intervals on the differences among means. It is possible for confidence intervals on means to overlap yet the difference still be significant. In computing these intervals, you should probably use the studentized range distribution rather than the t distribution to control the Type I error rate.


WHMCS changing database

Question: I'm still trying to understand why in WHMCS on the same MySQL database if I try to connect to a different db, he still tries to search a table in his default database.
Example: I'm trying to connect to the table "test" in "admin_test" so he needs to search for "admin_test.test", but instead he gives me the error:
VPN Database Query Error: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'admin_billing.test' doesn't exist (SQL: insert into test (user_id) values (fdffddfg))
So I think he doesn't want to change db, I tried to write this module based on the freeradius module, as it works fine and has his own db on the same localhost mysql.. I don't know how to fix this as of now.
function rscmodule_DatabaseInsert()
{

    try {

    $vpnsql = rscmodule_DatabaseConnect();
    if (is_string($vpnsql)) {
        return $vpnsql; // Error condition
    }

        Capsule::connection()->transaction(
        function ($vpnsql)
        {
            /** @var \Illuminate\Database\Connection $connectionManager */
            $vpnsql->table('test')->insert(
                [
                    'user_id' => 'fdffddfg',
                ]
            );
        }
    );

    } catch (\Exception $e) {
        return "VPN Database Query Error: " . $e->getMessage();
    }

    return "success";

}

function rscmodule_DatabaseConnect()
{
        $pdo = null;
    try {
        $pdo = Capsule::getInstance()->getConnection('rscmodule');
    } catch (\Exception $e) {

        $config = array(
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'admin_test',
            'username' => 'admin_test',
            'password' => '*****',
            'charset'  => 'utf8',
        );

        try {
            Capsule::getInstance()->addConnection(
                $config,
                'rscmodule'
            );

            $pdo = Capsule::getInstance()->getConnection('rscmodule');

        } catch (\Exception $e) {
            return "Unable to connect to rscmodule Database.  "
            . "Please check rscmodule server configuration.  "
            . $e->getMessage();
        }
    }

    if (is_object($pdo)) {
        if (method_exists($pdo, 'query')) {
            $ret = $pdo->query();
        } else {
            $processor = $pdo->getPostProcessor();
            $ret = new \Illuminate\Database\Query\Builder($pdo, $pdo->getQueryGrammar(), $processor);
        }
    } else {
        $ret = $pdo;
    }

    return $ret;
}

Answer: Well turns out WHMCS doesn't want other DBs inside the same connection IP, so we created a VM on a new IP and on that the connection works properly.

WHMCS changing database


Immutable NSMutableArray

Question: On my viewDidLoad I load from a webservice the first 5 items of an array and put them on a NSMutableArray of mine. Also on this View I have UITableViewController that displays the items of my NSMutableArray with the contents from the webservice. When I scroll to the last item of the UITableView I am loading the 5 next items from the webservice and add them to my NSMutableArray and reloading the table data in order to display all the 10 items.
The problem is that when I try to add to my existing NSMutableArray the 5 new objects from the webservice the program crashes with the message: Exception: -[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
The way I am accessing the NSMutableArray in  cellForRowAtIndexPath: is like this:
cell.textLabel.text = [[self.myMutableArray objectAtIndex:indexPath.row]objectForKey:@"name"];

Any idea on what it could be?
Comment: My guess is that you don't have an NSMutableArray, but a plain old NSArray.  Just because the pointer is named "mutable" does not make the object mutable.
Comment: please show the code of how you initialize the array :-)
Comment: Can you paste the declaration of your myMutableArray property?
Answer: First, look for warnings in your compiler output. You likely have are assigning an NSArray to an NSMutableArray variable. This will often generate a warning. Your build should have no warnings in it. This is critical for ObjC code (many things you would think of as "errors" are only warnings in ObjC). If you're ignoring warnings, then you're going to have a lot of problems.
You can have this situation without creating a warning if something is cast to id. For example, if you fetch your "NSMutableArray" (really an NSArray) from an array or dictionary, you won't get a warning about the type mismatch. Look for these situations. Basically, audit each point you assign myMutableArray and make sure that you're actually assigning a mutable array.
Comment: I was setting the result of the webservice call directly to the nsmutablearray. Now I allocated and initialized it first and then added the objects one by one, and it worked fine. Thanks a lot! :)

Immutable NSMutableArray


Django uploaded files not displaying in template page

Question: I am trying to display the top 5 recently posted files but doesnt seem to show up.
When i get all the objects by using Model.objects.all(), it gives me all the objects from Db but when i am trying to get the top 5, it does not display.
Kindly help and suggest me. Thanks
my views.py is
def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
    'posts':Help.objects.filter().order_by('-date')[0],
    'documents':Help.objects.filter().order_by('-document')[:5]
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            return HttpResponseRedirect('/about/%s/' %ex_link_name)
            #return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name }))

  else:
      form = AboutHelp()

  return render(request, 'about_experiment.html', context)

destination template page

 List of file(s) uploaded:

            {% if documents %}

 {{ documents.document }}

            {% else %}

No such documents available.

            {% endif %}

Answer: documents is a queryset and you are picking top 5. You need to do this like this.

 List of file(s) uploaded:

            {% for doc in documents %}

 {{ doc.document }}

            {% empty %}

No such documents available.

            {% endfor %}


Menu unserialized warning when using autocomplete in a custom module

Question: I am working on creating a form with Autocomplete feature for the text field. This is the code I have so far..
    /**
     * Implementation of hook_menu()
     */
    function suggest_feature_menu() {
      $item['suggest_feature/autocomplete'] = array(
        'page callback' => '_suggest_feature_autocomplete',
        'access arguments' => user_access('access example autocomplete'),
        'type' => MENU_CALLBACK
        );

        return $item;
      }

    /**
     * Implementation of autocomplete
     */

 function suggest_feature_autocomplete($string){

    $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title'))
    ->condition('status', 1) //Published.
    ->condition('type', array('e_hood', 'oranization'))
    ->condition('n.title','%'.db_like($string) . '%', 'LIKE')
    ->orderBy('created', 'DESC') //Most recent first.
    ->range(0,10)
    ->execute();

    $items = array();

    foreach ($query as $node){
       $items[$node->nid] = check_plain($node->title);
    }

    return drupal_json_output($items);

  }

    /**
     * Implementation of hook_form()
     */

    function suggest_feature_form($form_state) {
     $form = array();

       $form['test_item'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'suggest_feature/autocomplete'
        );

      return $form;
    }

all my functionality works but i get a warning which says

Warning: Invalid argument supplied for foreach() in menu_unserialize()
  (line 393 of C:\xampp\htdocs\drupal7\includes\menu.inc).

Please let me know how to solve this. Is this an issue with my code ? Also I use superfish menu's in my drupal. Is this related ?
Answer: There are three functions calling menu_unserialize(), the function for which the error is reported:

menu_get_item() uses it in the following code
  if ($router_item['access']) {
    $router_item['map'] = $map;
    $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
    $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
  }

_menu_check_access() uses it in the following code
$arguments = menu_unserialize($item['access_arguments'], $map);

_menu_item_localize() uses it in the following code
$item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));

The Invalid argument supplied for foreach() error simply means that foreach() is getting a value that is not an array. With the code you are showing, that is happening only for $arguments = menu_unserialize($item['access_arguments'], $map); since you are setting $item['suggest_feature/autocomplete']['access arguments'] to TRUE when it should be an array.
In your case, the code should be the following one.
/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

For Drupal that code would be equivalent to the following one.
/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

You can understand now why your code is wrong.
It's not the access arguments that you can set to a boolean value, but the access callback. See what the documentation for hook_menu() says. (Emphasis is mine.)

"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).

And for the access arguments, it says:

"access arguments": An array of arguments to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.
Answer: This is a bit of a shot in the dark, but the 'title' property is required for items defined in hook_menu(), and it's missing in your code.
I can think of a couple of scenarios where a lack of the 'title' property might cause this error in menu_unserialize() so it's worth adding it to see if that helps. Remember to flush the caches once you make the code change.
Comment: Thanks for your reply but it didn't work..
Comment: Also do you know how to filter autocomplete results based on type ?
Answer: Your "access argument" in hook_menu must be an array e.g "access argument" => array() in your custom module.


jq select field based on contains from another field

Question: I am trying to pull out of this list the ip_prefix based on where region contains us-west- and list them in csv.  When I try jq '.prefixes[] | .ip_prefix,.region | select(contains("us")?)' file.json I only get  a list of regions.
{
  "syncToken": "15985471",
  "createDate": "2021-10-08-20-13-16",
  "prefixes": [
    {
      "ip_prefix": "18.104.22.168/22",
      "region": "ap-northeast-2",
      "service": "AMAZON",
      "network_border_group": "ap-northeast-2"
    },
    {
      "ip_prefix": "126.96.36.199/27",
      "region": "ap-southeast-4",
      "service": "AMAZON",
      "network_border_group": "ap-southeast-4"
    },
    {
      "ip_prefix": "18.104.22.168/16",
      "region": "eu-west-3",
      "service": "AMAZON",
      "network_border_group": "eu-west-3"
    },
    {
      "ip_prefix": "18.104.22.168/32",
      "region": "eu-west-2",
      "service": "AMAZON",
      "network_border_group": "eu-west-2"
    },
    {
      "ip_prefix": "184.108.40.206/32",
      "region": "us-west-1",
      "service": "AMAZON",
      "network_border_group": "us-west-1"
    }
  ]
}

Answer: You have the filters in the wrong order. Try:
jq '.prefixes[] | select(.region|startswith("us-west")) | .ip_prefix' <your json file>

What this is doing is getting the prefixes array, filtering for elements where the region starts with "us-west" and then selecting the ip_prefix.


Creating a function in r with a boolean option: How do i return the dataframe if no boolean option is presented when calling the function?

Question: I got the following code for a function:
data_function <- function(df,condtion_a,condition_b, condition_c= TRUE) {
  df <- df %>%
    filter(col_a == condtion_a & col_b == condition_b)
    if(condition_c == TRUE) {
      df %>% filter(col_c== TRUE)
    } else if(condition_c== FALSE) {
      df %>% filter(col_c == FALSE)
    }
    else {
  return(df)
    }
}

The code works when I give either TRUE or FALSE to the condition_c. However, I want an option to just return the df <- df %>% filter(col_a == condtion_a & col_b == condition_b)  portion of the code when neither condition_c is TRUE or FALSE. For example, I want to use this function to work on three ways:
data_function(df,condtion_a,condition_b, condition_c= TRUE)
data_function(df,condtion_a,condition_b, condition_c= FALSE)
data_function(df,condtion_a,condition_b)
with the latter just returning just the  df <- df %>% filter(col_a == condtion_a & col_b == condition_b) part when condition_c is not present when calling the function. I feel this is a very simple thing but cannot think of how to fix this. Thanks!
Answer: Based on the function, the return(df) is returning the dataset before the if/else condition was applied because the output from that is not updated to 'df'
data_function <- function(df,condtion_a,condition_b, condition_c) {
 # subset the rows of the dataset and update it to same object
  df <- df %>%
         filter(col_a == condtion_a & col_b == condition_b)
 df1 <- if(missing(condition_c)) {
        df
    } else {
 # apply the `if/else if/else` and assign it to a new object or same object
      if(condition_c) {
         df %>%
             filter(col_c)
       } else if(!condition_c) {
          df %>%
             filter(!col_c)
     }else {
            df
           }
      }

    return(df1)
  }

Comment: I must apologize, you answer was correct in the first place. I missed the "missing" and of course it wouldn't allow me to get the correct results.Thank you for your help!
Comment: Unfortunately, this does not achieve the result I want. It works correctly when `condition_c = TRUE` or `condition_c = FALSE` but when I leave out `condition_c`, for example `data_function(df,condtion_a,condition_b)` it returns the wrong one. It should return df with the filtered with the conditions on `filter(col_a == condtion_a & col_b == condition_b) `. Thank you for the help!
Comment: @BoniPhila Please update with a small reproducible example and expected output
Comment: @BoniPhila without a reproducible example, it is difficult to test.  I updated though
Comment: Essentially I have a master dataframe with thousands of rows. This dataframe will go through the function. In order for the function to be succesful, `col_a` and `col_b` need to be filtered out. So  in the end I want to keep those results (what I hoped my original return would do). That would give me successful result A (which is a filtered out data frame). In this df, `condition_c` is not involved, hence why I want the function to not include it. Continued below...
Comment: @BoniPhila I understsand the problem.  But, to test the function, i would suggest to create a small example dataset
Comment: Got it, I'll create one in a sec


Cookie not set with jQuery

Question: This rather simplistic code is not working for me, which puzzles me :
$(document).ready( function(){
    $.cookie('the_cookie', 'the_value');
    var myCookie = $.cookie('the_cookie');
    alert(myCookie);
});

jsFiddle test
I had imported the jquery.cookie.js.
What am I doing wrong ?

Note : when I look for a the cookie in my browser's tab ressources, I can't find it either. Tried it this far with jsFiddle and localhost, none work.
Answer: What you are doing wrong is the cookie.js doesn't link to a javascript file, it links to a GitHub Gist page
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
Just copy the code into JSFiddle
and then
 alert(myCookie); // Will work

Demo
CDN : http://cdn.jsdelivr.net/jquery.cookie/1.3.1/jquery.cookie.js
Comment: Any chance I can still get the plug-in from internet and have it work ?
Answer: You are not supposed to hot link from github
download the jquery.cookie.js to your local drive and reference to that and it will work.
Comment: Reference to your local drive?
Comment: @Connor : he means basically downloading the file.
Comment: Well, that doesn't make sense.
Comment: What doesn't it make sense ?
Answer: It looks like the jQuery cookie plugin file is not loading. Check the JS console to view the errors. The URL you've included as the cookie plugin is returning HTML.

Cookie not set with jQuery


Comparing to paired categorical variables

Question: I have a variable X with 100 samples, each is 1 (success) or 0 (failure)
Thereafter I perform somekind of manipulation, and recollect data, so I get 100 more samples that are 1 or 0,
How can I check for significane rise
Comment: Are you sure that it's paired? For example, does #53 in the first batch correspond to #53 in the second batch?
Comment: Yes, they are paired for sure
Answer: McNemar's test seems relevant here. You can basically summarize your data in a 2 X 2 table, indicating how many were 0/1 in each of iteration 0/1 of the test. This is the settings for McNemar's.
In Python, you can use statsmodels.stats.contingency_tables.mcnemar from statsmodels.
Here's an example of how to use it:
import numpy as np

from statsmodels.stats import contingency_tables

>>> contingency_tables.mcnemar(np.array([[50, 60], [50, 40]])).pvalue
0.39092745669950518

>>> contingency_tables.mcnemar(np.array([[50, 90], [50, 10]])).pvalue
0.00091311287400158204

Comment: Do you have an example on how to use this module in python? couldn't find an example, not even in the docs itself
Comment: @oren See update. You need to give it a 2 X 2 contingency table (see the Wikipedia entry), and it will return an object containing the statistic & pvalue.
Comment: I'll note that in R, the _mcnemar.test_ function can handle tables larger than 2 x 2.  Also, you can construct an exact test by binomial or multinomial test.  Details are here: http://rcompanion.org/handbook/H_05.html .
Comment: @Ami Thanks a lot. I was not sure whether I should give table of counters or the row vector of the samples itself. So based on the wiki entry, here, [50, 60] is [cou(before_1_after_1) , cou(before_1_after_0)] and [40,40] is [cou(before_0_after_1), cou(before_0_after_0)] , right?
Comment: @oren No problem. That was not the example I wanted to give, though (typo), since, in your case, the rows & columns must each sum 10 100. In the above 2 examples, before is 50/50% A change to 60/40% is not very significant, but a change to 90/10% is.
Comment: @AmiTavory sorry for nagging but I failed to understand something: If I only give him the total number of 1's and 0's before and after, how can the test use the fact that samples are paired?
For example, it won't notice the difference between the two following scenarios:

scenario A:
before: 0 0 0 1 1
After : 1 0 0 1 1
scenario B:
before: 0 0 0 1 1
after: 1 1 1 0 0
Even though they should probably have different outcome, taking into account that samples are paired.
Comment: @oren Consider [the example in the Wikipedia entry](https://en.wikipedia.org/wiki/McNemar%27s_test#Examples). Since it has a cell for before-present/after-present (for example), the pairing is there - to fill this in, you'd need to look at *pairs*, and ask how many had this attribute. If you'd only have *total* numbers for before and after, you couldn't fill it in. Does that make sense?
Comment: @Ami That what I meant in my previous question, perhaps I wasn't clear. Actually, the rows corresponds to the wiki table - so [40 60] means 40 = number of before absent and after present and 60 = number of before absent and after absent? Or 40 = number of zeros after , 60 = number of ones after?
if the first answer, it makes sense :) If the latter, it doesn't..
Comment: @oren Your first interpretation seems right. Just to sync, this corresponds to the second row, if using the labels in the example in Wikipedia.
Comment: @oren No problem. All the best.


How to compare two logarithmic functions using derivatives?

Question: I have two expressions: $\log_2 5$ and $\log_3 13$.
And I need to determine which expression is greater using exactly derivatives and not having a calculator.
I know that $(y = \log_2 5)'$ = $\frac{1}{5ln2}$ and $(y = \log_3 13)'$ = $\frac{1}{13ln3}$
But what are the further steps(algorithm) in such cases to determine what is greater?
Comment: Derivative of a constant is zero. To compare both these you can use properties of logarithmic function, first make their bases equal then see that logarithmic function is monotonic increasing.
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: Did the problem composer explicitly require that derivatives be employed?
Comment: I need any possible solution to the problems of such kind(if possible derivatives) excluding the way of making the bases equal and calculator.
Answer: Addendum added to respond to the comment of
vortexsf24.

A very similar problem was posted on MathSE recently.  Another reviewer found the following solution that I would not have thought of.  If I remember correctly, it was Dietrich Burde; I could be mistaken about who found the solution.  I can't find the original posting; it may have been deleted.
You can show, with minimal calculation (without a calculator) that
$$3 \times \log_2(5) < 7 < 3 \times \log_3(13).$$
This simplifies to showing that
$$\log_2\left(5^3\right) < 7 < \log_3\left(13^3\right).\tag1 $$
In (1) above, the LHS inequality is fairly easy.  Simply notice that $~5^3 = 125 < 128 = 2^7.~$  So, since $~2^7 > 125,~$ you must have that $~\displaystyle \log_2\left(5^3\right)~$ must be $~< 7.$
In (1) above, the RHS inequality is more difficult, but can still be confirmed by pencil and paper (again without a calculator).  Simply verify that
$$3^7 = 2187 < 2197 = 13^3.$$
So, since $~3^7 < 13^3,~$ you must have that $~\displaystyle \log_3\left(13^3\right)~$ is $~> 7.$

$\underline{\text{Addendum}}$
Responding to the comment of vortexsf24.

Thanks, but I already know this solution. As I wrote in comments I have a task to do it differently.

"I need any possible solution to the problems of such kind(if possible derivatives) excluding the way of making the bases equal and calculator"
My answer did not make the bases equal.
Also, it isn't really appropriate to try to use derivatives to attack this type of problem.  Both sides of the inequality are constants.  The derivative of a constant is $~0.~$
One approach for trying to force-fit the use of derivatives onto this problem is as follows:
The problem can be restated as :
Prove that
$$\frac{\log(5)}{\log(2)} < \frac{\log(13)}{\log(3)},$$
where $~\log(x)~$ refers to the natural logarithm.
This can be re-stated as
Prove that $$\frac{\log(5) \times \log(3)}{\log(2)} < \log(13). \tag2 $$
Then, using (2) above as the starting point of your analysis, you would set
$$f(x) = \log(x) - \frac{\log(5) \times \log(3)}{\log(2)}. \tag3 $$
It is easy to see that on $~\Bbb{R^+},~$ since $~f'(x) = \dfrac{1}{x} > 0,~$ the function $~f(x)~$ is strictly increasing.
Further, since $~\log(1) = 0,~$ you know that $~f(1) < 0.~$  Therefore, since $~\lim_{x\to\infty} \log(x) = \infty,~$ you also know that $~f(x)~$ must cross the $~x$-axis exactly once, for $~x \in (1, +\infty).$
So, the problem is reduced to determining whether the (sole) root of the equation $~f(x) = 0~$ is less than $~13,~$ equal to $~13,~$ or greater than $~13.~$
Personally, I don't see how this approach gets anywhere.  You know that :

$\displaystyle f(1) = - \frac{\log(5) \times \log(3)}{\log(2)}.$

$f'(x) = \dfrac{1}{x}, ~f''(x) = \dfrac{-1}{x^2}, f'''(x) = \dfrac{2}{x^3}, \cdots $

I don't see any way of using these insights to determine whether the rate of increase of $~f(x)~$ is slowed down enough so that $~f(x)~$ crosses the $~x$-axis before $~x=13,~$ rather than after.
Comment: @vortexsf24 See the Addendum that I have just added to the end of my answer.
Comment: Thanks, but I already know this solution. As I wrote in comments I have a task to do it differently.


How to use a receiver info at other activity or fragment, in Android?

Question: I'm trying to make a receiver that will notify if and when the phone is connected to the Internet.
Now, the thing is that I have got a main activity that handles two fragments.
In one of the fragments, I have a search method that needs to use the Internet.
So, what I am trying to do is: if there's no Internet, then the user will get a toast, after he/she pressed the search button.
In order to do this - I've written the following class in the main activity -
public class ConnectionChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

       Boolean netBol;

    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetInfo = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    boolean isConnected = activeNetInfo != null
        && activeNetInfo.isConnectedOrConnecting();

    if (isConnected){

         Boolean netBol = true;

    }else{

        netBol = false;
    Toast.makeText(context, R.string.no_internet, Toast.LENGTH_LONG).show();
    }
}

}

As you can see, I'm trying to use the Boolean netBol, to determine if there's a connection or not.
But the point is that i want to pass it to the search fragment, and I don't know how to do that.
I've also added the following line to the manifest:
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

and I also put the following code in the main activity;
   ConnectionChangeReceiver netReceiver = new ConnectionChangeReceiver();
            IntentFilter filterNet = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");

            registerReceiver(netReceiver, filterNet);

For my understanding this is saying that I've declared on a receiver, but I need one at the fragment.
So what I'm asking is: what should I do in order to pass the info from the receiver to the fragment, so that I could know if there's internet or not?
Answer: Simple. Use otto
You will find the sample application here.
Change your code as follows:
You can do something like this in your receiver:
if (isConnected){

BusProvider.getInstance().post(new InternetAvailable(true));

}else{

BusProvider.getInstance().post(new InternetAvailable(false));
Toast.makeText(context, R.string.no_internet, Toast.LENGTH_LONG).show();

}

InternetAvailable class can be like this:
public class InternetAvailable {
  private static boolean isInternetAvalable;

  public InternetAvailable(boolean isInternetAvailableParam) {
  isInternetAvailable = isInternetAvailableParam
  }

  @Produce public InternetAvailable isInternetAvailable() {
    return isInternetAvailable;

  }
}

The BusProvider class is like this:
public final class BusProvider {
  private static final Bus BUS = new Bus();

  public static Bus getInstance() {
    return BUS;
  }

  private BusProvider() {
    // No instances.
  }
}

Modify your SearchFragment like this:
@Override public void onResume() {
  super.onResume();
  BusProvider.getInstance().register(this);
}

@Override public void onPause() {
  super.onPause();
  BusProvider.getInstance().unregister(this);
}

Comment: Thank you for the reply, i must say that i never heard of this. But i haver a question - is there no way to aplly a reciver in the fragment? let's say adding a ConnectionChangeReceiver instance in the fregmant, and trying to  retrive any info from the class of it?
Comment: Using otto you're doing the same thing, but if you want you can send intents to your own activity/fragment from the receiver and pass info about internet state.
Comment: @4this If you found this helpful, kindly upvote or accept answer.
Comment: So what should i do if i want to do it in the old fashion way, what should i add to the fregment? what info should the reciver send and what should the fregment will recive?
Comment: You can have a BroadcastReceiver as an inner class in your Fragment. Instantiate and attach it. Since Inner classes have access to outer class fields, update a field variable in the Fragment. That field will contain if internet is accessible or not.


Text document to dictionary Python

Question: Okay, I have a text file that "relationships.txt" that has the following inside:
Elizabeth: Peter, Angela, Thomas
Mary: Tom
Angela: Fred, Alison
Alison: Beatrice, Dick, Harry

mother Elizabeth
mother Tom
mother Angela
mother Gurgle

The first 4 lines are set up as Mother: Child, Child, Child etc
The bottom 4 lines are statements that should return a result. Eg:
mother Elizabeth should return: Mother not known
while
mother Tom should return: Mary
I am meant to create a dictionary to allow this to work, but I have no clue what to do. Help is appreciated.
So far I have the following:
test_file = open('relationships.txt', 'w')
test_file.write('''Elizabeth: Peter, Angela, Thomas
Mary: Tom
Angela: Fred, Alison
Alison: Beatrice, Dick, Harry

mother Elizabeth
mother Tom
mother Angela
mother Gurgle
''')
test_file.close()

def create_list():
    open_file = open('relationships.txt', 'r')
    lines = open_file.readlines()
    return(lines)

Comment: this is probably a good place to start: http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
Comment: Absolutely no idea at all? You haven't tried anything whatsoever?
Comment: People are not going to do your problem for you.  You need to post code and then people will help you with what you don't understand or what you're doing incorrectly.
Comment: I do have some idea what I need to do. I need to read the entire file into a list of lines. I could then find the blank line that separates the two parts of the file and pass one sub-list of lines to a function that returns a dictionary mapping child names to their mothers and the other sub-list to a function that processes a list of queries. But just a bit unsure how to do this :S
Comment: I do understand, I will post what I have done so far in a minute
Comment: added what I have so far.
Comment: @user2383844 What purpose does `mother Elizabeth` etc. serve? Does that have to be in that file, or are you actually looking for a function that'll find and print it out for you?
Comment: okay so basically it has to be in the file. It has to be recognized and return the correct result for whatever mother xxx is in the file.
Comment: @user2383844 Ok. It's doable. Should the result be printed out to a terminal?
Comment: So in other words, the file may change and have different mother xxx statements in it, but this script should return the correct result for whatever mother xxx statements are in it.
Comment: @timss yes. it should be
Comment: @user2383844 For the fun/practice of it I'll try to hack something together. Altough I do agree with monkut etc.; SO generally isn't for requesting code to be written for you, but to answer questions and solve problems.
Comment: @timss I completely understand, and I feel bad for doing this, I just dont really know what to do. Even if you just got me started I would be greatful :)
Comment: greatful? lol! This question smells like homework...
Comment: @timss how would I go about starting this?
Answer: I wasn't able to finish, it's late, but this should get you going, binding children to their mothers with a list of tuples.
It's kinda hacky, but the structure of your file is rather weird (and I still don't see why you would have to use something like that).
import re

rel = {}

with open("test/relationships.txt") as f:
    for line in f:
        # Valid Mother: Child, Child, [..]
        try:
            # Remove newliens and spaces
            line = re.sub('[\n ]', '', line)
            mother = line.split(':')[0]
            children = line.split(':')[1].split(',')

            # Append a tuple (child, mother)
            for c in children:
                rel.append((c, mother))

        # Something else, ignore for now
        except:
            continue

print rel

Gives:
[('Peter', 'Elizabeth'), ('Angela', 'Elizabeth'), ('Thomas', 'Elizabeth'), ('Tom', 'Mary'), ('Fred', 'Angela'), ('Alison', 'Angela'), ('Beatrice', 'Alison'), ('Dick', 'Alison'), ('Harry', 'Alison')]
So what remains is to parse the name of the children in mother child, and see if child is a key in the list.
Comment: Thanks for your help, I get the following error though

Traceback (most recent call last):
  File "C:\Users\user\Documents\untitled-1.py", line 18, in
Syntax Error: print rel: C:\Users\user\Documents\untitled-1.py, line 189
Comment: @user2383844 Something got cut out from the paste. Anyway it should've been easy enough to fix for yourself. I urge you to actually learn some Python before you try to do something like this :) I can recommend [Codeacademy's Python course](http://www.codecademy.com/tracks/python).
Comment: thanks for your help. I have actually figured out the whole thing today, but thank you for your help. :)
Comment: @user2383844 If you got it figured out you should [answer your own question](http://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-those-where-i-knew-the-answer-before-asking).

Text document to dictionary Python


Hadoop: Sorting and shuffling

Question: I'am new to hadoop area. Can you please help me whose responsibility it is to get us the output in the form of (k2,list[v2,v2,v2...]) (meaning combining key with all it's associated values)?
Thanks.
Answer: This is an example of how the MapReduce component of Hadoop works, find the maximum air temperature of Egypt per year.
given a set of temperature value per year records
sample record1: 1995, Jan, Cairo , 33, C
sample record2: 1995, Feb, Cairo , 37, C
......
......

The map function parses the input records by extracting the year and the air temperature, and emits them as its output
example map output
(1950,0)
(1950, 22)
(1950, -11)
(1949, 111)
(1949, 78)

Then, the output from the map function is processed by the MapReduce framework before being sent to the reduce function. This processing sorts and groups the key-value pairs by key
sample sort output
(1949, [111, 78])
(1950, [0, 22, −11])

Finally, each year appears with a list of all its air temperature readings. All the reduce function has to do now is iterate through the list and pick up the maximum reading:
(1949, 111)
(1950, 22)

Refernce: Hadoop: The Definitive Guide, 4th Edition
Comment: Hi Ahmed, Thanks a lot for the above information. So if i understand it correctly, sample sort output (1949,[111,78]) is written to the disk. This data will be sent to the reducer function. Can you also please help me to understand how grouping of the keys takes place (meaning what class is responsible for this operation).
Comment: The reduce function aggregates the values associated with each key in this example ( year ), so you have a reduce task instantiated for each key. Values associated with each key are automatically sorted and grouped by Hadoop before they are presented to the Reducer. As a programmer, all what you have to do is writing the map and reduce logic.
Comment: Appreciate your brisk response on this Ahmed. You mentioned  that Values associated with each key are automatically sorted and grouped by Hadoop before they are presented to the Reducer. But, what i think is keys are sorted and grouped by hadoop before they are presented to the reducer (Please Correct me if i am wrong). What i need to know is for instance, hadoop uses quick sort algorithm to sort the keys But what is used to group the keys. Thanks in advance.

Hadoop: Sorting and shuffling


Laravel push lot of data to Queue

Question: I have a model with ~500k records in the database. I need to get all items and push ~500k jobs to the queue.
I tried:
Model::cursor()->each(function ($item) {
    dispatch(new Job($item));
});
// and
Model::chunk(10000, function ($items) {
    foreach ($items as $item) {
        dispatch(new Job($item));
    }
});

But in both cases I got a memory leak because I need iterate all 500k records and call dispatch() method in any case. Is there best way to push a lot amount of data to the Laravel queue?
Answer: Working only with ids may work in your case. Give a try.
Dispatching
Model::select('id')
      ->get()
      ->pluck('id')
      ->each(function ($id) {
          Job::dispatch($id);
      });

Job
class Job implements ShouldQueue
{
    use Dispatchable, Queueable, InteractsWithQueue;

    protected $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

    public function handle()
    {
        $item = Model::find($this->id);
        // do some stuff
    }
}

Comment: Much better, thank you. But I still got a memory leak, I think I should break this huge result into chunks and use something like job batching...

Laravel push lot of data to Queue


from plumbum.cmd import git, grep, sed, wc

Question:
ImportError: cannot import name 'grep' from 'plumbum.cmd' (unknown
location)

I tried installing the module in Anaconda using conda install plumbum and it did install. Now what I am missing such that the above import do not work.
I used Spyder editor for this but planning to transition soon to Visual Studio Code if that makes any difference.
Comment: `plumbum` needs to be able to find those command line tools.  Do you have a set of Unix commands installed?  They may not be in your normal path.
Comment: Sounds more like a python library import question than a git question. Are you sure that your editor is using the anaconda environment?
Comment: Hi @TimRoberts, how do I check that? I am not sure.
Comment: If you didn't install Unix-like tools, then you don't have Unix-like tools.  They don't come with Windows.  What are you really trying to do here?  Most of `grep`, `wc`, and `sed` can be done quite efficiently in Python directly.
Comment: @TimRoberts I have adopted someone else's work and am working on it to add automation tools for git (moving from one repo to another) using Python script (reading the destination, from addresses of the repos from command line etc)
Comment: If you have `git` installed, then the tools you want are in "c:\Program Files\git\usr\bin".  You just need to add that to your PATH before running.
Comment: The tag [tag:git] is not really meant for any Git Python modules, and in any case this has nothing to do with Git at all. The actual problem has to do with setting up Python's import path and/or installing the modules that are to be imported into the places Python is going to look. I don't use Anaconda so I'm not sure what preferences those folks have, but in general, for Python environments, I prefer using virtualenv to encapsulate dependencies.
Answer: That error means plumbum was unable to find those commands in your PATH.
Try adding your unix util folder to your PATH.
Or modifying your path before importing from plumbum:
<code>os.environ["PATH"] = (
    os.path.expanduser("~/scoop/apps/git/current/usr/bin/") + ";" + os.environ["PATH"]
)

from plumbum.cmd import git, grep, sed, wc
</code>
I installed git on Windows with scoop, so that adds the unix utils that come with git to my PATH.


Expressões regulares com 'grep'

Question: Preciso extrair dados de um texto e estou tentando fazer isso usando grep. Mas a forma de fazer uso de expressões regulares com esse comando são bastante diferentes do que se faz geralmente em Ruby ou JavaScript, e não estou conseguindo fazer o que eu preciso. No texto seguinte:

Caderno Judiciário do Tribunal Regional do Trabalho da 1ª Região
DIÁRIO ELETRÔNICO DA JUSTIÇA DO TRABALHO PODER JUDICIÁRIO
Nº1697/2015
REPÚBLICA FEDERATIVA DO BRASIL
Data da disponibilização: Quarta-feira, 01 de Abril de 2015.
Tribunal Regional do Trabalho da 1ª Região

Preciso pegar apenas o número que pode ser visto na terceira linha. Este número será posteriormente utilizado para fazer uma requisição a um webservice. Tentei com o grep da seguinte forma:
pdftotext Diario_1697_1_1_4_2015.pdf -f 1 -l 1 - | grep -o /Nº(\d+\/\d+)/

Pego a primeira página de um arquivo pdf, converto em txt e passo para o comando grep fazer a extração da informação. Mas isso não funciona de jeito nenhum. Alguém sabe dizer a forma correta de fazer isso com o grep ou algum outro comando do bash?
Answer: Em primeiro lugar, o grep é um comando do shell e seus argumentos são strings simples como quaisquer outros. Ao invés de delimitar a regex com / você deve usar aspas simples (ou usar aspas duplas, se você for cuidadoso com a expansão de variáveis do shell). Além disso, você precisa escapar suas contrabarras com \\.
Em segundo lugar, a sintaxe de regex padrão do grep é meio diferente e bem fraquinha. Por exemplo, ela não entende o +, só o *. Você pode trocar pra sintaxe de Perl com a flag -P
grep -P -o 'Nº\\d+/\\d+'

ou usar a syntaxe POSIX com grep -E ou egrep.
grep -E -o 'Nº[[:digit:]]+/[[:digit:]]+'
grep -E -o 'Nº[0-9]+/[0-9]+'

Comment: @JJoao: Funciona no Bash mas não no meu shell padrão que é o Fish. A ;unica contrabarra redundante mesmo era a do `/`

Expressões regulares com 'grep'


error while downloading zip archive from server

Question: php ZipArchive can't open zip file that gets downloaded from a server.
I have a zip file that I created with winrar and uploaded to my server, file location is here: http://myserver.com/uploads/test.zip It's a valid zip file
Here is my code
When I run this code all I get is

error: Not a zip archive.

It opens the file and extracts it but complains that file already exists even if I delete file.
the file that I get when I access http://myserver.com/update/test.zip get corrupted and I have no idea why, this same code that I pasted above worked just a week ago.
Answer: The problem is actually the .zip file. I downloaded it and I cannot open the file with WinZip. Please try to make a new archive and upload it again on your server.
The code looks okay so I think it just the file that is the problem.
UPDATE #1:
The .zip file is now correct. Try to delete the files before you download and extract the new files. You can use unlink("uploads/update.zip") maybe you also need to clear the uploads/temp directory first.
UPDATE #2:
The download worked now for me. Try to add this header:
<code>header("Content-Transfer-Encoding: Binary");
</code>
Also don't forget to close the ZipArchive after extracting:
<code>$zip->close();
</code>
Comment: I've installed winzip my self to test the file I download from code4fun and winzip version 20.5 (12118) opens it, what version of winzip do you have?
Comment: @Maxlight I updated my answer. I am also using WinZip version 20.5 Pro.


Put request via urlfetchapp produces "Exception: Attribute provided with invalid value: Header:Content-Length"

Question: Goal is to update "OrderStatusID" of order to "1" using urlfetchapp with a put request via Apps Script.
function updateOrderStatus(){

  var private_key = "{private_key}";
  var merchant_token = "{merchant_token}";
  var secure_url = "{secure_url}";

  var body = JSON.stringify({"OrderStatusID": "1"});
  var url ="https://apirest.3dcart.com/3dCartWebAPI/v2/Orders/{orderID}";

  var options =  {
    "method" : "put",
    "headers" : {
      "Content-Type" : "application/json",
      "Content-Length" : body.length,
      "Accept" : 'application/json',
      "SecureURL" : secure_url,
      "PrivateKey" : private_key,
      "Token" : merchant_token
    },
    "body" : body,
    "muteHttpExceptions" : false,
  }
  try{
    var response = UrlFetchApp.fetch(url, options);
  }
  catch(err){
    Logger.log(err);
  }
  finally{
    Logger.log(response);
  }
}

Code throws error Exception: Attribute provided with invalid value: Header:Content-Length
Code altered to remove sensitive information.
Comment: @Aerials that leads to the proper answer.  Content-Length calculates automatically.  All I needed to do was remove that header and change "body" to "payload" and the code worked fine.  Thank you for helping point me in the right direction.
Comment: hm, is `body` the same as you presented in the example? Has been a while since I've done GAS thoroughly, but the code looks ok to me if the stringified body consists of single-octet chars.
Comment: Does this answer your question? https://stackoverflow.com/a/26615965
Comment: @GaryD I'm glad it helped you. Would you like to post an answer to this question?
Comment: @Aerials, I added an answer, thank you.
Answer: Changing the name of the option "body" to "payload" resolved the issue.
The answer was found in this google issue tracker thread.

ek...@googlers.comek...@googlers.com #6Apr 11, 2016 07:03AM Status:
Won't Fix (Not Reproducible) UrlFetchApp doesn't have an advanced
parameter called 'contentLength'. The Content-Length header is
automatically calculated based on the length of the payload passed in.
The 'contentLength' advanced parameter you set in your sample is
simply ignored by the backend and the length automatically calculated.

The Content-Length is automatically calculated from the payload.  I thought it was supposed to be named body because the 3dCart API documentation was using body as the name of its json in the example.
Corrected Code:
function updateOrderStatus(){

  var private_key = "{private_key}";
  var merchant_token = "{merchant_token}";
  var secure_url = "{secure_url}";

  var body = JSON.stringify({"OrderStatusID": "1"});
  var url ="https://apirest.3dcart.com/3dCartWebAPI/v2/Orders/{orderID}";

  var options =  {
    "method" : "put",
    "headers" : {
      "Content-Type" : "application/json",
      //"Content-Length" : body.length,
      "Accept" : 'application/json',
      "SecureURL" : secure_url,
      "PrivateKey" : private_key,
      "Token" : merchant_token
    },
    "payload" : body,
    "muteHttpExceptions" : false,
  }
  try{
    var response = UrlFetchApp.fetch(url, options);
  }
  catch(err){
    Logger.log(err);
  }
  finally{
    Logger.log(response);
  }
}


Profile 2 fields not displaying in registration form

Question: I create 2 Profiles with distinct Fields as well as assigned each one a unique role with permissions to Administer Profile2 registration paths, but all I'm getting is the default Username and E-mail fields nothing else (On both of them).
Answer: Make sure you check to "Show during user account registration" on the profile type.
Admin > Structure > Profile Types > [Type] > Edit
Comment: When Editing the Profile Types that option does not appear, instead I am prompted with a check box for the following: "Show on all user account registration forms."
http://imgur.com/aC9Qaj0
Comment: Jason, thats what you need to enable to attach the profile to the registration page.


jquery show/hide on hover. Hiding when contents hovered

Question: http://wilwaldon.com/gift/index.html is the page is question.
Here's the pastebin of the html/jquery: http://pastebin.com/L4HQBjBc
Pastebin of jQuery: http://pastebin.com/WmEUK7Ey
If you hover the icons above the large "activate now" button on the right side (satelite dish, briefcase,lock) a div will appear.
The desired action is that the div appears on hover and disapears on hover-out.
What's happening is that if you hover over the text of the pop-up the div disappears.
Thanks in advance!
Answer: Instead of using the 2nd part of .hover() which is the same as .mouseout() leave it out, and change your 2nd function to .mouseleave(). The 2nd part of the hover will get called as soon as the mouse moves out od calloutpop, which it will be doing when the mouse goes over the text as thats in its own div. Using .mouseleave() will be called when the mouse leaves the div, not when it hovers over an element within it.
Also, you should wait for the dom to be ready before doing any jQuery functions, at the moment you are only waiting to .hide() the popup:
jQuery(document).ready(function() {
    // hides the slickbox as soon as the DOM is ready
    jQuery('#calloutpop').hide();
    jQuery('#callout').hover(function() {
        jQuery('#calloutpop').fadeIn(500);
    });
    jQuery('#calloutpop').mouseleave(function(event) {
            jQuery(this).fadeOut(500);
    });
});

See it working here
Comment: Interesting. All four of these answers have one down vote. This one has two upvotes (makes a score of 1) and the other three have a single upvote to counter act the downvote. I wonder why. (for those who don't know, [users with 1000 reputation can see number of down and up votes instead of just the final score](http://stackoverflow.com/privileges/view-vote-counts))
Comment: @George Bailey someone commented asking why one of the other questions had a down vote yesterday. I find it very frustrating when someone down votes an answer without leaving a reason. If an answer is un-useful or not an answer I understand the need for a down vote - but people should IMHO leave a reason as to why they voted - especially when answer are genuine and accepted as an answer.....
Comment: I agree. In fact I am the one who asked why the down vote on the first two answers, but when I found a downvote was on all four answers, I deleted those comments thinking they were useless and then posted my above comment which is more up to date.
Answer: Maybe if you don't have the handler out function do anything or only use .mouseenter() your problem will be resolved. I think what is happening is that since your div that appears is covering up the triggering element, then the mouseout is fired as soon as the mouse hits something that isn't the trigger (the text of the popped up div)
The mouse out you already have in place for the popup should take care of the hiding otherwise.
Try this
jQuery('#callout').mouseenter(function() {
   jQuery('#calloutpop').fadeIn(500);
});

jQuery('#calloutpop').mouseout(function(event) {
   if (!$(event.relatedTarget).is('#callout')) {
      jQuery('#calloutpop').fadeOut(500);
   }
});

Answer: You are registering a hover listener to the whole div. The first time you hover over it it opens. Then if the user goes over one of the included icons a hover-event is fired on the included icon. In Javascript events bubble-up the DOM ( keyword: event propagation). So the hover event will be propagated to the parent div on which you have registered the hover listener. This will cause the div to hide.
You can register hover listeners on the icons that just call event.stopPropagation() to stop the propagation like this:
$('.icons_in_hover').hover(function(e){
  e.stopPropagation();
});

Answer: Tet rid of the mouseout code and change your hover code to:
jQuery('#callout').hover(
    function() {jQuery('#calloutpop').fadeIn(500)}
    ,
    function() {jQuery('#calloutpop').fadeOut(500)}
);


Can $\lim_{n\to\infty}(a_n-a_{2n})=0$ ensure $\lim_{n\to\infty}a_n=0$?

Question: Can $\lim_{n\to\infty}(a_n-a_{2n})=0$ ensure $\lim_{n\to\infty}a_n=0$? It seems difficult to find a counterexample. The often used  $\sum \frac{1}{n}$ is not such one.
Comment: What about simply $a_n=1$ for all $n$?
Comment: $a_{2^{n}}=0$ for all $n$ and $a_n=1$ when $n$ is not a power of $2$.
Comment: $a_n = \sqrt{\ln n}$
Answer: $a_n=1$ for all $n$ is a counterexample:  $\lim\limits_{n\to\infty}(a_n-a_{2n})=0,$ but $\lim\limits_{n\to\infty} a_n=1$.


Unable to upgrade from 10.1 to 10.2

Question: I've been using Composer from the start and have had no problem upgrading Drupal as it went, but somehow it refuses to upgrade from 10.1.8 to 10.2.
In my composer.json I have "drupal/core-recommended": "^10",
If I run composer update "drupal/core-*" --with-all-dependencies, it tells me there's nothing to update.
So in changed composer.json to "drupal/core-recommended": "^10.2.2",
And now when I run composer it tells me "drupal/core 10.2.2 conflicts with drupal/core 10.2.2"
Any idea what's going on?
Edit - here are more details:
with "drupal/core-recommended": "^10"
command:
composer update "drupal/core-*" --with-all-dependencies

output:
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Generating optimized autoload files

command:
composer why-not drupal/core-recommended 10.2.2

output:
drupal/core-recommended     10.2.2      requires          drupal/core (10.2.2)
drupal/recommended-project  dev-master  does not require  drupal/core (but 10.1.8 is installed)
drupal/core-recommended     10.2.2      requires          asm89/stack-cors (~v2.2.0)
drupal/recommended-project  dev-master  does not require  asm89/stack-cors (but v2.1.1 is installed)
drupal/core-recommended     10.2.2      requires          composer/semver (~3.4.0)
drupal/recommended-project  dev-master  does not require  composer/semver (but 3.3.2 is installed)
drupal/core-recommended     10.2.2      requires          guzzlehttp/guzzle (~7.8.1)
drupal/recommended-project  dev-master  does not require  guzzlehttp/guzzle (but 7.7.1 is installed)
drupal/core-recommended     10.2.2      requires          guzzlehttp/psr7 (~2.6.2)
drupal/recommended-project  dev-master  does not require  guzzlehttp/psr7 (but 2.5.1 is installed)
drupal/core-recommended     10.2.2      requires          symfony/console (~v6.4.1)
drupal/recommended-project  dev-master  does not require  symfony/console (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/dependency-injection (~v6.4.1)
drupal/recommended-project  dev-master  does not require  symfony/dependency-injection (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/deprecation-contracts (~v3.4.0)
drupal/recommended-project  dev-master  does not require  symfony/deprecation-contracts (but v3.3.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/error-handler (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/error-handler (but v6.3.5 is installed)
drupal/core-recommended     10.2.2      requires          symfony/event-dispatcher (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/event-dispatcher (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/event-dispatcher-contracts (~v3.4.0)
drupal/recommended-project  dev-master  does not require  symfony/event-dispatcher-contracts (but v3.3.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/http-foundation (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/http-foundation (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/http-kernel (~v6.4.1)
drupal/recommended-project  dev-master  does not require  symfony/http-kernel (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/mime (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/mime (but v6.3.5 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-ctype (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-ctype (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-iconv (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-iconv (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-intl-grapheme (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-intl-grapheme (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-intl-idn (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-intl-idn (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-intl-normalizer (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-intl-normalizer (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-mbstring (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-mbstring (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/polyfill-php83 (~v1.28.0)
drupal/recommended-project  dev-master  does not require  symfony/polyfill-php83 (but v1.27.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/process (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/process (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/psr-http-message-bridge (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/psr-http-message-bridge (but v2.2.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/routing (~v6.4.1)
drupal/recommended-project  dev-master  does not require  symfony/routing (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/serializer (~v6.4.1)
drupal/recommended-project  dev-master  does not require  symfony/serializer (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/service-contracts (~v3.4.0)
drupal/recommended-project  dev-master  does not require  symfony/service-contracts (but v3.3.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/string (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/string (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/translation-contracts (~v3.4.0)
drupal/recommended-project  dev-master  does not require  symfony/translation-contracts (but v3.3.0 is installed)
drupal/core-recommended     10.2.2      requires          symfony/validator (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/validator (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/var-dumper (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/var-dumper (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/var-exporter (~v6.4.1)
drupal/recommended-project  dev-master  does not require  symfony/var-exporter (but v6.3.11 is installed)
drupal/core-recommended     10.2.2      requires          symfony/yaml (~v6.4.0)
drupal/recommended-project  dev-master  does not require  symfony/yaml (but v6.3.8 is installed)
drupal/core-recommended     10.2.2      requires          twig/twig (~v3.8.0)
drupal/recommended-project  dev-master  does not require  twig/twig (but v3.6.1 is installed)

with "drupal/core-recommended": "10.2.2"
command:
composer update "drupal/core-*" --with-all-dependencies

output:
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - Root composer.json requires drupal/core-recommended 10.2.2 -> satisfiable by drupal/core-recommended[10.2.2].
    - drupal/core 10.2.2 conflicts with drupal/core 10.2.2.
    - drupal/core-recommended 10.2.2 requires drupal/core 10.2.2 -> satisfiable by drupal/core[10.2.2].
    - drush/drush is locked to version 11.6.0 and an update of this package was not requested.

Comment: If you were to share the full command and all the command output perhaps we could answer.
Comment: We also require the output of `composer why-not drupal/core-recommended 10.2.2`. These tips are documented on Drupal.org and in Composer's documentation.
Comment: Thanks, I've now added the full command and output in the question.
Answer: Your requirements could not be resolved to an installable set of packages.
  ...
  - drush/drush is locked to version 11.6.0 and an update of this package was not requested.

See the release notes of Drupal 10.2.x:

Drush versions below 12.4.3 are incompatible with Drupal 10.2.x

Users of Drush will need to upgrade to version 12.4.3 or greater.

https://www.drupal.org/project/drupal/releases/10.2.0
Comment: Ah, thank you, it turned out that composer couldn't install the latest version of Drush because I needed to update composer to the latest version. After that it all worked out.

Unable to upgrade from 10.1 to 10.2


How to select only rows containing emojis and emoticons in Python?

Question: I have DataFrame in Python Pandas like below:
sentence
------------

I like it
+1
One :-) :)
hah

I need to select only rows containing emoticons or emojis, so as a result I need something like below:
sentence
------------

+1
One :-) :)

How can I do that in Python ?
Comment: you can select the emoji with unicode, but `:-)` is tricky
Comment: You could maybe create a table to serve as a dataset with hardcoded emojis that arent actual emojis like ":)" and ":-)" and so on? And then check or match your sentences with those or if those sentences contain any elements of that dataset of hardcoded emojis?
Comment: Have you defined a set of emoticons you want to find? You could maybe put together a regex pattern if its just combos of `eye_character nose_character mouth_character`
Comment: Does this answer your question? [How to extract all the emojis from text?](https://stackoverflow.com/questions/43146528/how-to-extract-all-the-emojis-from-text)
Comment: eshirvana, but how to use some function from your link to my DataFrame, moreover I need to select rows with emoji and rows with emoticons, so not only emojis :)
Comment: @eshirvana You need to do some more reading of the comments here.
Answer: You can select the unicode emojis with a regex range:
df2 = df[df['sentence'].str.contains(r'[\u263a-\U0001f645]')]

output:
  sentence
0
2     +1

This is however much more ambiguous for the ASCII "emojis" as there is no standard definition and probably endless combinations. If you limit it to the smiley faces that contain eyes ';:' and a mouth ')(' you could use:
df[df['sentence'].str.contains(r'[\u263a-\U0001f645]|(?:[:;]\S?[\)\(])')]

output:
     sentence
0
2        +1
3  One :-) :)

But you would be missing plenty of potential ASCII possibilities: :O, :P, 8D, etc.
Comment: @JosipJuros as an enthusiast, oh yes there can https://en.wikipedia.org/wiki/List_of_emoticons
Comment: You can add more eyes/mouth characters but the more you add the more you risk to have edge cases with false positives, for instance `8D` could be found in a legitimate product ID, or `:P` in a sentence with missing space after the colon ( ͡° ͜ʖ ͡°)
Comment: Pedantic point: some ASCII emoji, such as `ツ`, are not in fact ASCII ;-)
Comment: @snakecharmerb very true, this one is actually a (unicode) Japanese katakana ;)
Comment: Having a list of those ASCII emojis and then checking for hits that way is also a possibility? There cant be that many ASCII emojis?
Comment: @Josip search for "ascii art" and you'll be amazed how creative ascii emojis can be (ツ)
Comment: Oh damn yes there is a ton yikes.... Then finding a generic solution is better at least for ones that have a ";:" and ")("
Comment: mozway, is it possible to take also sentences with :O, :P, 8D? do you know how to do that ?


Classification using ctree in R

Question: I've been trying to perform classification on Indian Liver Patients Disease dataset available at https://archive.ics.uci.edu/ml/datasets/ILPD+(Indian+Liver+Patient+Dataset)
I have used Conditional Inference Tree function from party package in R.
ilpd_ctree <- ctree(Class ~ .  ,data=train)
ilpd_ctree
plot(ilpd_ctree)
treepre <- predict(ilpd_ctree,test)
confusionMatrix(test$Class,treepre)
table(treepre,test$Class)

The problem is I am not getting any entries in the second class as a result of which Specificity and Pos. Pred. Value are coming out to be NA. However, I want numeric quantities for both of these. How do I attain it on the same dataset?
Data from a part of the dataset

structure(list(age = c(65L, 62L, 62L, 58L, 72L, 46L, 26L, 29L,
17L, 55L), gender = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L),
TB = c(0.7, 10.9, 7.3, 1, 3.9, 1.8, 0.9, 0.9, 0.9, 0.7),
DB = c(0.1, 5.5, 4.1, 0.4, 2, 0.7, 0.2, 0.3, 0.3, 0.2), Alkphos = c(187L,
699L, 490L, 182L, 195L, 208L, 154L, 202L, 202L, 290L), SGPT = c(16L,
64L, 60L, 14L, 27L, 19L, 16L, 14L, 22L, 53L), sgot = c(18L,
100L, 68L, 20L, 59L, 14L, 12L, 11L, 19L, 58L), TP = c(6.8,
7.5, 7, 6.8, 7.3, 7.6, 7, 6.7, 7.4, 6.8), ALB = c(3.3, 3.2,
3.3, 3.4, 2.4, 4.4, 3.5, 3.6, 4.1, 3.4), AG = c(0.9, 0.74,
0.89, 1, 0.4, 1.3, 1, 1.1, 1.2, 1), Class = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("One", "Two"
), class = "factor")), .Names = c("age", "gender", "TB",
"DB", "Alkphos", "SGPT", "sgot", "TP", "ALB", "AG", "Class"), row.names = c(NA,
10L), class = "data.frame")

Result

Confusion Matrix and Statistics

      Reference
 Prediction One Two
        One 124   0
        Two  49   0

           Accuracy : 0.7168
             95% CI : (0.6434, 0.7825)
No Information Rate : 1
P-Value [Acc > NIR] : 1

              Kappa : 0
Mcnemar's Test P-Value : 7.025e-12

        Sensitivity : 0.7168
        Specificity :     NA
     Pos Pred Value :     NA
     Neg Pred Value :     NA
         Prevalence : 1.0000
     Detection Rate : 0.7168

Detection Prevalence : 0.7168
      Balanced Accuracy :     NA
   'Positive' Class : One

The problem is the Pos. Pred. Value which comes down to NA.
Comment: Is that confusion matrix the one from your test data set? The problem is not that the model isn't predicting anything in the second class on the test set, it's that the test data set doesn't have any observations in the second class!
Comment: Usually "fitting this model results in strange and confusing errors" is a good indication that "this model is a poor fit to the data."
Comment: If there is a statistical question here, then please share enough information about the data and the results for us to help you with it.
Comment: @whuber Done with results and data addition.
Comment: @ssdecontrol that's what my question is, how to improve this fit?
Comment: Also, often when I have issues like this it's because I did something silly and left a variable in the data set that shouldn't have been there. With only a sample of your data, it's very hard to say what might be wrong. (I'm not asking you to post all of it obviously)
Comment: @ssdecontrol Yes it's from my test data, I don't know how but nothing from the second class goes
Answer: This looks like not to be a good solution as you have no cases predicted in your test data in your class two- are your classes very imbalanced on your train data to start with? if Yes, you might want to find a way around it ( i.e downsampling)- Trees can perform very  poorly on imbalanced data...
but if you want to calculate the specificity of your current model manually: 0/49 =0
Comment: No they are pretty well balanced on the train data.

Classification using ctree in R


squid bypass for a domain

Question: I'm using squid with adzap, it's possible that squid/adzap does not cache for a particular domain eg. cnn.com. This is my squid.conf file:
#
# Recommended minimum configuration:
#
acl manager proto cache_object
acl localhost src 127.0.0.1/32
#acl localhost src ::1/128
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32
#acl to_localhost dst ::1/128

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 192.168.1.0/24
acl localnet src 192.168.2.0/24

acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT

#
# Recommended minimum Access Permission configuration:
#
# Only allow cachemgr access from localhost
http_access allow manager localhost
http_access deny manager

# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
http_port xxx.xxx.xxx.yyy:3128 transparent
visible_hostname proxyserver.local

# We recommend you to use at least the following line.
hierarchy_stoplist cgi-bin ?

# Uncomment and adjust the following to add a disk cache directory.
cache_dir ufs /var/spool/squid 1024 16 256

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

# Add any of your own refresh_pattern entries above these.
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320
access_log /var/log/squid/squid.log squid
access_log syslog squid
redirect_program /usr/local/adzap/scripts/wrapzap

fixed using
acl allow_domains dstdomain www.cnn.com
always_direct allow allow_domains

Answer: I am surprised that always_direct is working. As others said, that only affects cache hierarchies and you don't seem to be using one.
If you want to control caching, the right configuration option to use is cache (or no_cache, depending on what version of squid you are running).
E.g.
Acl dontcache dstdomain .cnn.com
Cache deny dontcache
Cache allow all

Answer: The Squid directive always_direct says that for the specified ACLs, always connect directly to them, and never connect to an upstream cache. Many filtering proxies are set up as upstream caches, so the filter doesn't have to worry about caching (it delegates that to Squid).
Your example
acl allow_domains dstdomain www.cnn.com
always_direct allow allow_domains

defines an access control list called allow_domains, and adds www.cnn.com to it. (You probably also want to change that to .cnn.com to allow other CNN sites, but not just anything with that suffix, e.g. 'malwarecnn.com'.
Then, always_direct allow ACL_NAME will tell Squid to ignore the forwarder for that domain.
(If you answer your own question, please do it by way of an answer. Otherwise, someone will come and add much more detail for the future reader. :)
Answer: always_direct are used to specify requests which should ALWAYS be forwarded by Squid to the origin servers without using any peers. It's not related to caching. Instead of always_direct you must use something like the following
acl bypass_caching dstdomain cnn.com
cache deny bypass_caching

TAG: cache - A list of ACL elements which, if matched, cause the request to not be satisfied from the cache and the reply to not be cached. In other words, use this to force certain objects to never be cached. You must use the word 'DENY' to indicate the ACL names which should NOT be cached.

squid bypass for a domain


How to Modify Drupal 7 Bootstrap Theme Title?

Question: I cannot find where to modify the title from:
SiteName | SiteSlogan
to
SiteName - SiteSlogan
I am using the https://drupal.org/project/bootstrap theme.
Anyone have any ideas?
Answer: This thing is come under $head_title variable on html.tpl.php.
So for changing this you need to override template_preprocess_html
where replace statement
$variables['head_title'] = implode(' | ', $head_title);
with
$variables['head_title'] = implode(' - ', $head_title);
I am assuming you have enough idea about overriding of templates.
Comment: Thanks! That worked perfect. I didn't realize it was being set in the drupal core includes/theme.inc file.


Proving that languages are not regular

Question: The Nerode Lemma can be used to show whether a language is regular or not. This can be done in several ways but I need to do it by providing a set of separable items.
Example:
The language of well-formed brackets ($\Sigma = \{(,)\}, L = \{(),()(),(()), ...\}$ is not regular. That can be shown by providing the separable, infinite set $\{\epsilon,(,((,(((,...\}$ because

$)$ separates $\epsilon$ and $($ because $\epsilon) \not\in L$ but $() \in L$
$))$ separates $\epsilon$ and $(($ because $\epsilon)) \not\in L$ but $(()) \in L$
...
$)^n$ separates $(^n$ and $(^k$ for $n \neq k$ because $(^n)^n \in L$ but $(^k)^n \not\in L$

a finite state machine for that language whould therefore require an infinite number of states $\Leftrightarrow$ the language is not regular.
Now I need to repeat that for two languages:

1) $L_1 = \{u \in \Sigma^* \; | \; \exists i \leq k \leq j : u = 1^i 2^j 1^k\}, \Sigma_{L_1} = \{1,2\}$

$\hspace{1cm}$

2) The language that represents a simplified "programming language"
  that allows only declaring and using of variables. There is no
  length-restriction for variable names and a variable may be of one of
  the fictitious types X, Y or Z. Commands (usage of variables or declarations) are separated by spaces. A variable name may contain any lowercase letter (a-z). Therefore $\Sigma_{L_2} =
> \{X,Y,Z,\text{' '},a,\cdots,z\}$ and a valid word may be "X a Y ab a
  ab a" (declare a as X, ab as Y and use both, a and ab). An invalid
  world would be "X a c" or just "c" because c is not declared first.

Unfortunately I still don't know how to construct these sets apart from "trial and error" (and I'm not quite good at that).
1)
I thought about the set $\{ 2^x 1^{x+1} \; | \; x \in N\}$. If I am right this separates the words $v = 12^x1^{x+1} \not\in L$ and $w = 22^x1^{x+1} \in L$. Is this correct?
2)
I really don't know how to start creating prefixes or suffixes for that language. Can you please help me to get on with it?
Thanks in advance!
Comment: See this [related question](http://cs.stackexchange.com/q/1031/98) on cs.SE.
Answer: You should reformulate your first answer to call the infinite set the separated one (unless you have proved the equivalence of the notions before).
As for your second example, you can take any suffix that necessitates a declaration first and then either provide the declaration or not.

Proving that languages are not regular


operator overloading in python

Question:
Possible Duplicates:
Python: defining my own operators?
Rules of thumb for when to use operator overloading in python

Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <<?
Comment: Duplicate question: http://stackoverflow.com/questions/932328.  See also http://stackoverflow.com/questions/1552260 .
Comment: It may be a duplicate question, but I found the accepted answer more useful than in other questions, because it links to the description of all the __ xxx __ methods.
Comment: Since this is the first hit on google, I think it should be unlocked. Locking it forces people to have an extra click to get information and the answers below don't even give examples.
Comment: @ToolmakerSteve - Sorry, I flagged and removed that as not an answer. It was nothing more than a link, which means it was subject to linkrot.
Answer: As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you're writing, i.e., methods whose names start and end with two underscores).  All the details are here.
To complete the answers to you questions: you cannot define new operators; but << is not a new operator, it's an existing one, and it's overloaded by defining in the class the method __lshift__.
As a historical note, this is also pretty much the situation in C++ -- but the exact set of operators you can overload differs between the two languages. For example, in C++, you cannot overload attribute access, .; in Python, you can, with __getattr__ (or __getattribute__, with different semantics) and __setattr__. Vice versa, in Python = (plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it.
<< is an operator, and can be overloaded, in both languages -- that's how << and >>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ (not in Python!-).
Comment: +1 for the link to the list of __ xxx __ methods. I couldn't find that link in answers to other questions that this question is considered a duplicate of.
Answer: See: http://docs.python.org/reference/datamodel.html#special-method-names.

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python's approach to operator overloading, allowing classes to define their own behavior with respect to language operators.
Answer: Yes, and no. I don't think you can define your own operators, but you can overload the existing ones - you can do that by overriding the operator's special method. For example,
to override >, you can override __gt__(), for != override __ne__() and so on.

operator overloading in python


Switching to mobile theme while cache is enabled

Question: I have a Drupal7 website using a modified Zen subtheme that looks ugly on mobile devices and i want some kind of utility to create a separate mobile theme .
I tried to use differents modules like Mobile Switch,Mobile Detect ,Mobile Tools & Theme Key but unfortunatley they don't support Drupal Default Cache .
Is there any way or method or another module to resolve this problem.
Thank you very much
Answer: ThemeKey does support the Drupal cache.
However, the Drupal cache cannot perform device specific cacheing on a single domain since page caches are organized by absolute URLs. See this discussion for an explanation: https://www.drupal.org/node/2242303
The solution is to have a device redirect at the server level to a mobile subdomain (ie. m.mysite.com) which shares the same docroot and switches the theme there. The Boost module is recommended and the process is outlined here:
https://www.drupal.org/node/1214890


File renaming functions in wordpress upload process

Question: I have a script that loads posts automatically from a predefined array and uploads images as featured images from a physical path on a local machine.
When I copy the file into upload directory I use path and filename like so:
$upload_dir['path'].'/'.$new_post_id.$filename

This way if I upload apple.jpg several times, the file will be named 1apple.jpg, 2apple.jpg and so on and it will not be overwritten.
I would however like to use Wordpress native functions that check and rename files. In wordpress uploads if you upload apple.jpg several times it will add a new number before the extension like so: apple1.jpg, apple2.jpg and so on, and the number portion is not based on a post.
I was wondering if you could point me to the function in wordpress that does this check and creates new filename so I can use the wordpress native functions for naming my uploaded files.
Comment: I actually kinda like your solution. Why not just `split` your `$filename` and append the `$new_post_id` before the file extension?
Comment: @crowjonah I was looking for the function that wordpress uses, and it turns out to be wp_unique_filename()
Answer: I found the answer: wp_unique_filename()
Answer: You need to filter the function wp_unique_post_slug().
As discussed in WPSE.


VB.NET - Como ordenar um DataGridView por cor

Question: Tenho um DataGridView, onde eu faço uma crítica de documento. O DataGridView é preenchido por um arquivo, eu uso o OpenFileDialog para selecionar o arquivo e preencher o DataGridView. Em seguida eu chamo uma função onde é feita uma crítica pelo campo do CNPJ/CPF, atribuindo cores às linhas do grid:
 - Cinza: Cancelados;
 - Vermelho: Devolvidos;
 - Verde: Sempre entregue;
 - Amarelo: Entregue/Devolvido;
 - Branco: Primeiro registro.
Eu já tenho uma função feita onde eu verifico as críticas do documento, porém fica um carnaval dentro do DataGridView. Segue o exemplo na imagem:
Eu queria saber se tem uma forma de eu organizar esse DataGridView por cor, primeiro todas as linhas de cor cinza, depois as linhas vermelhas, depois as verdes, em seguida as linhas amarelas e por fim todas as linhas brancas.
Segue meu código atual:
Imports MySql.Data.MySqlClient

Public Class salvar_arquivo
    Dim sqlcoon = New MySqlConnection '' conexao
    Dim command As MySqlCommand
    Private datagrid As New DataTable
    ' load do form
    Private Sub salvar_arquivo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    '' carrega todo os monitoramento do banco de dados cad_monitoramento
    Dim datagrid As New DataTable
    ' INSERE COLUNAS NO GRIDVIEW
    datagrid.Columns.Add("Identificação")
        datagrid.Columns.Add("Protocolo")
        datagrid.Columns.Add("Destinatario")
        datagrid.Columns.Add("Endereço")
        datagrid.Columns.Add("Bairro")
        datagrid.Columns.Add("Cep")
        datagrid.Columns.Add("Data")
        datagrid.Columns.Add("CNPF/CPF")
        datagrid.Columns.Add("Situacao")
        datagrid.Columns.Add("Cliente")
        datagrid.Columns.Add("data_processamento")
        datagrid.Columns.Add("data_vencimento")
        datagrid.Columns.Add("numeracao")
        DataGridView1.DataSource = datagrid
        ' inserindo o a largura das colunas

        ' deixando invisivel a coluna do banco de dados
        DataGridView1.Columns("Situacao").Visible = False
        DataGridView1.Columns("Cliente").Visible = False
        DataGridView1.Columns("data_processamento").Visible = False
        DataGridView1.Columns("data_vencimento").Visible = False
        DataGridView1.Columns("numeracao").Visible = False
    ' ORDENAS OS TITULOS DA COLUNA NO CENTRALIZADO
    DataGridView1.Columns(0).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(1).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(2).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(3).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(4).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(5).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(6).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(7).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(8).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(9).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(10).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(11).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        DataGridView1.Columns(12).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter

        txtcod.Select()
    End Sub

    ' butao selecionar e ler arquivo
    Private Sub btnarquivo_Click(sender As Object, e As EventArgs) Handles btnarquivo.Click
        selecionar()

End Sub

    ' Função para ler o arquivo linha por linha separado por tab
    Private Sub selecionar()
        abrir.ShowDialog()
        '  Dim x As String = ("62210980259, 10507378001020")
        Dim separador As Char

        Dim dr As DataRow
    ' INSERE COLUNAS NO GRIDVIEW
    Try

            datagrid.Columns.Add("Identificação")
            datagrid.Columns.Add("Protocolo")
            datagrid.Columns.Add("Destinatario")
            datagrid.Columns.Add("Endereço")
            datagrid.Columns.Add("Bairro")
            datagrid.Columns.Add("Cep")
            datagrid.Columns.Add("Data")
            datagrid.Columns.Add("CNPF/CPF")
            datagrid.Columns.Add("Situacao")
            datagrid.Columns.Add("Cliente")
            datagrid.Columns.Add("data_processamento")
            datagrid.Columns.Add("data_vencimento")
            datagrid.Columns.Add("numeracao")

            DataGridView1.AutoResizeColumns()
            DataGridView1.AutoResizeRows()

            dr = datagrid.NewRow()

        '
        ' FAZ A LEITURA DO ARQUIVO - COM EXPAÇAMENTO POR TAB
        Dim arquivo As New System.IO.StreamReader(abrir.FileName)
            separador = vbTab
            ' faz um split de leitura de linha a linha do arquivo
            While arquivo.Peek() <> -1
                datagrid.Rows.Add(arquivo.ReadLine().Split(separador))
            End While
            DataGridView1.DataSource = datagrid

            TextBox2.Text = DataGridView1.RowCount.ToString
        '
        ' chama a função de critica do arquivo colocando cores nas linhas de acordo com a sentaça
        relacionar_cnpj()

        '
    Catch ex As Exception
            MessageBox.Show("ex.Message")

        End Try
    End Sub

' click f2 para abrir o form de pesquisa de selecionar cliente
Private Sub txtcod_KeyUp(sender As Object, e As KeyEventArgs) Handles txtcod.KeyUp
        If e.KeyCode = Keys.F2 Then

    End If
    End Sub

    Private Sub salvar_arquivo_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        If AscW(e.KeyChar) = 27 Then  ' vbKeyReturn = Tecla Esc
            Me.Close()
        End If
    End Sub

Private Sub salvar_arquivo_Closed(sender As Object, e As EventArgs) Handles Me.Closed
    txtcod.Clear()
    txtrazao.Clear()
End Sub

' funcção de critica do arquivo - cada sentença mostra uma cor diferente no grid.
Private Sub relacionar_cnpj()
    Dim COMMAND2 As MySqlCommand
    Using sqlcoon As MySqlConnection = GetConnectionMySQL()

        Try
            Dim READER2 As MySqlDataReader

            sqlcoon.Open()

            For r As Integer = 0 To DataGridView1.Rows.Count - 1
                Dim Query As String
                Query = "select cnpjcpf_cnpjcpf,cnpjcpf_entregue,cnpjcpf_devolvido,cnpjcpf_cancelado from speed.cnpjcpf where cnpjcpf_cnpjcpf ='" & DataGridView1.Rows(r).Cells(7).Value.ToString() & "'"

                COMMAND2 = New MySqlCommand(Query, sqlcoon)
                READER2 = COMMAND2.ExecuteReader

                While READER2.Read
                    Dim cnpjcpf_cnpjcpf = READER2.GetString("cnpjcpf_cnpjcpf")
                    Dim cnpjcpf_entregue = READER2.GetString("cnpjcpf_entregue")
                    Dim cnpjcpf_devolvido = READER2.GetString("cnpjcpf_devolvido")
                    Dim cnpjcpf_cancelado = READER2.GetString("cnpjcpf_cancelado")

                    ' se for a primeira vez do registro do cnpj
                    If cnpjcpf_entregue = "N" And cnpjcpf_devolvido = "N" And cnpjcpf_cancelado = "N" Then

                        DataGridView1.Rows(r).DefaultCellStyle.BackColor = Color.White

                        ' se for devolvido
                    ElseIf cnpjcpf_entregue = "N" And cnpjcpf_devolvido = "S" And cnpjcpf_cancelado = "N" Then

                        DataGridView1.Rows(r).DefaultCellStyle.BackColor = Color.IndianRed

                        ' se for cancelado
                    ElseIf cnpjcpf_entregue = "N" And cnpjcpf_devolvido = "S" And cnpjcpf_cancelado = "S" Then

                        DataGridView1.Rows(r).DefaultCellStyle.BackColor = Color.Silver

                        ' se for sempre entregue
                    ElseIf cnpjcpf_entregue = "S" And cnpjcpf_devolvido = "N" And cnpjcpf_cancelado = "N" Then

                        DataGridView1.Rows(r).DefaultCellStyle.BackColor = Color.ForestGreen
                        ' se for entregue e ja volto como devolvido (Ambos)
                    ElseIf cnpjcpf_entregue = "S" And cnpjcpf_devolvido = "S" And cnpjcpf_cancelado = "N" Then

                        DataGridView1.Rows(r).DefaultCellStyle.BackColor = Color.Yellow
                        ' se for entregue e ja volto como devolvido e cancelado
                    ElseIf cnpjcpf_entregue = "S" And cnpjcpf_devolvido = "S" And cnpjcpf_cancelado = "S" Then

                        DataGridView1.Rows(r).DefaultCellStyle.BackColor = Color.Yellow
                        End If

                End While

                READER2.Close()
            Next

        Catch ex As MySqlException
            MsgBox(ex.Message)
        Finally

            sqlcoon.Close()
        End Try
    End Using
End Sub
End Class

Answer: Você pode criar uma coluna unbound no seu grid e chama-la de "IndiceCor", por exemplo, e você atribuiria números na ordem que você quer que as cores apareçam:

IndiceCor = 1 -> Linhas de cor cinza;
IndiceCor = 2 -> Linhas de cor vermelha;
IndiceCor = 3 -> Linhas de cor verde;
IndiceCor = 4 -> Linhas de cor amarela;
IndiceCor = 5 -> Linhas de cor branca;

E depois organizaria o grid por essa coluna, mais ou menos assim:
DataGridView1.Rows(r).Cells("IndiceCor").Value = 1   'Linha Cinza.
DataGridView1.Rows(r).Cells("IndiceCor").Value = 2   'Linha Vermelha.
DataGridView1.Rows(r).Cells("IndiceCor").Value = 3   'Linha Verde.
DataGridView1.Rows(r).Cells("IndiceCor").Value = 4   'Linha Amarela.
DataGridView1.Rows(r).Cells("IndiceCor").Value = 5   'Linha Branca.

'[...]

DataGridView1.Sort(DataGridView1.Columns("IndiceCor"), ListSortDirection.Ascending)

O problema é que dessa forma você só poderia organizar pela cor, e não poderia colocar como segunda opção o CNPJ, por exemplo. Então, outra opção seria colocar essa coluna virtual com o índice da cor direto em um DataTable, por exemplo, que tenha os dados da sua base, assim você poderia usar mais de um campo na organização.
Comment: Funcionou Pedro. Muito Obrigado.
Comment: Que bom Jose. A melhor forma de agradecer é marcar a minha resposta como aceita. E marcar as mensagens como  úteis, quando você tiver pontuação suficiente. Leia essa página que explica o básico do funcionamento do site: https://pt.stackoverflow.com/tour
Comment: Assim que eu obter a reputação suficiente para marcas como útil eu farei sim foi de muita grande ajuda Pedro .
Comment: Legal, mas você pode aceitar a resposta desde já!  ;-)
Comment: Eu já marquei como útil :) . Seta para cima certo ?
Comment: Não, é o "tique" embaixo da seta para baixo, para aceitar a resposta!
Comment: Está Marcado Pedro . Agradeço.