How to eliminate direct access to files in private directory?

Question: I have set up my Drupal 7 site for private files in a directory above root (../private). I also set my filefield on my node type to upload the image files to that private directory.
I have two user roles: man and woman. Both user roles can create nodes of a certain type, containing that image file field. Men can never see another man's photo; same thing for women. Men can always see a woman's photo; same thing for women.
Here are my current results:
When a man visits a woman's node, he can view the photo within the node content: http://example.com/members/76/gallery/public/photo-123
When that man views the page source and copies the image URL, he can view that image directly in his browser: http://example.com/system/files/styles/apply_simplecrop/private/pictures/1/Public/filename.jpg?itok=ABC123&sc=abcdefghijklmnop
If that man shares that direct link with another man, that other man can view that picture as well. If he shares the direct link with a woman or a non-logged-in user they are served an Access Denied message and cannot view that picture.
If a man tries to access that image URL without the "itok=" text in the link, he receives an Access Denied message.
My desired result in all of those examples above is to display an Access Denied message.
The ../private directory has an htaccess file containing Deny from all.
Am I missing a step? What can I do to securely deny direct access to those files in the way that I described above?
Thanks!
Answer: The issue is that the other man that gets the link should get an Access denied right? (The rest seems to work.) This is not how if works unfortunately. Private files are only private if the user is explicitly denied access to them (as happens to women and anonymous users). Since any man is allowed access to that file (he can view it under certain circumstances), the system will serve him that file.
Files are served from this part of system_menu():
$items['system/files'] = array(
  'title' => 'File download',
  'page callback' => 'file_download',
  'page arguments' => array('private'),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

Then file_download():
function file_download() {
  // Merge remainder of arguments from GET['q'], into relative file path.
  $args = func_get_args();
  $scheme = array_shift($args);
  $target = implode('/', $args);
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
    $headers = file_download_headers($uri);
    if (count($headers)) {
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

As you can see, Drupal serves an access denied in case there are no headers. So, you should make sure that file_download_headers() does not return any headers.
You can achieve this by implementing hook_file_download() in a custom module and have it return the value of -1 as described in it's documentation. This will however always deny the user access to the file. So within hook_file_download you will have to find some way to conditionally allow the user access to the file. It is entirely up to you how you want to implement this, but a suggestion is:

Lookup the file object, by loading it from the file_managed table by its path.
Lookup the node(s) that have this image attached.
Lookup if the current user visited the node within x minutes by querying the history table. If not, return -1.

This gives a general idea of how Drupal serves these files and what you can do to restrict access. If you run into any problems implementing this, feel free to open a new question and reference this one.
And on a sidenote, if you are trying to prevent user from leaking photo's. If I find a pretty girl, I can also save the image and email it to a friend. If you block that I send a screenshot. In these case he does not even need an account. People will always find a way to circumvent limitations. Is it worth the effort to block this?


Visual Studio C++/CLI 2010's Intellisense doesn't work; are there alternatives?

Question:
Possible Duplicate:
What are people replacing the missing C++/CLI Intellisense in VS 2010 with?

I downloaded and installed Visual C++ 2010 Express, today.  To my shock and horror, a variable's dot was not followed with anything, an error at the bottom status bar reading:
"Intellisense: Unavailable for C++/CLI"
So... that being the case, is there an alternative to Intellisense that I can find and use?  Other stackoverflow questions addressed the possibly broken nature of Intellisense.  From what I've read, though:

They suggest Visual Assist.  Visual Assist's free trial, as I just downloaded, is not compatible with VC++ 2010 Express.
They talk about manipulating Visual C++ itself somehow, usually through the deleting of a .ncb file.  Do any of you know where this file is located?  If so, that's one answer I'm hoping for -- maybe it'll fix intellisense!

Thanks!  Of course, feel free to chime in with any other ideas!
Comment: I changed the tag and title, as C++ != C++/CLI.
Comment: Yes, there were similar entries that didn't seem to deliver.  I'm glad you could help with a practically-proven, free solution to this problem where other questions asked fell short.
Comment: Hmm... there seems to be a misunderstanding.  For the sake of future visitors: Visual Assist X was actually NOT the answer for me, as it doesn't work with VC++ 2010 Express (I couldn't install the trial).   Visual C++ 2008 Express turned out to be the (free) answer.  @Cody: You may be disregarding the non-Visual Assist X helpfulness available in the replies to my question.  Using myself as evidence, users will probably not find the "duplicate" question helpful for what I've asked.  :)  Perhaps you can edit your answer in there to include the VC++ 2008 download that works as a solution?
Comment: Update: Visual C++ 2010 will get Intellisense.  http://blogs.msdn.com/b/vcblog/archive/2011/03/03/10136696.aspx
Answer: Yes, VS 2010 doesn't support C++/CLI Intellisense. The VS team promised it would come with an update, but I'm quite sure we won't see it. Too bad, C++/CLI is amazing for creating bridge classes between C++ and C#/VB/any other .NET managed laguage.
Visual Assist X indeed brings it back, but since VS Express editions don't support extensions, you have three options:
1) Live without Intellisense
2) Get VS Professional or better (if you are student, you can get it from MSDNAA for free)
3) Downgrade to Visual C++ 2008 Express
Comment: I was going to answer my own question but am glad to see you've listed the option that ended up working for me (option 3).  To add some complementary information, I obtained VC++ 2008 Express from this link: http://www.microsoft.com/express/Downloads/.  Click the Visual Studio 2008 Express tab and Visual C++ 2008 Express Edition will be listed there.  Happy coding!
Answer: Just use Visual Studio 2008.
It's a simple matter of which feature you find more important. Pick only one:

Multiple monitor support
Intellisense for C++/CLI projects
Comment: VS 2010 has more new features than just multi-monitor support. .Net 4.0, real-time C++ syntax checks (irrelevant if OP uses CLI only though), better extension support (irrelevant in Express), box selection, C++0x features... http://msdn.microsoft.com/en-us/library/dd465215.aspx


How to prove all proofs of le equal?

Question: I'm basically trying to prove
Theorem le_unique {x y : nat} (p q : x <= y) : p = q.

without assuming any axioms (e.g. proof irrelevance). In particular, I've tried to get through le_unique by induction and inversion, but it never seems to get far
Theorem le_unique (x y : nat) (p q : x <= y) : p = q.
Proof.
  revert p q.
  induction x as [ | x rec_x]. (* induction on y similarly fruitless; induction on p, q fails *)
  - destruct p as [ | y p].
    + inversion q as [ | ]. (* destruct q fails and inversion q makes no progress *)
      admit.
    + admit.
  - admit.
Admitted.

Answer: In the standard library, this lemma can be found as Peano_dec.le_unique in the module Coq.Arith.Peano_dec.
As for a relatively simple direct proof, I like to go by induction on p itself.
After proving by hand a few induction principles that Coq doesn't automatically generate, and remembering that proofs of equality on nat are unique, the proof is a relatively straightforward induction on p followed by cases on q, giving four cases two of which are absurd.
Below is a complete Coq file proving le_unique.
Import EqNotations.
Require Eqdep_dec PeanoNat.

Lemma nat_uip {x y : nat} (p q : x = y) : p = q.
apply Eqdep_dec.UIP_dec.
exact PeanoNat.Nat.eq_dec.
Qed.

(* Generalize le_ind to prove things about the proof *)
Lemma le_ind_dependent :
  forall (n : nat) (P : forall m : nat, n <= m -> Prop),
  P n (le_n n) ->
  (forall (m : nat) (p : n <= m), P m p -> P (S m) (le_S n m p)) ->
  forall (m : nat) (p : n <= m), P m p.
exact (fun n P Hn HS => fix ind m p : P m p := match p with
  | le_n _ => Hn | le_S _ m p => HS m p (ind m p) end).
Qed.

(*
Here we give an proof-by-cases principle for <= which keeps both the left
and right hand sides fixed.
*)
Lemma le_case_remember (x y : nat) (P : x <= y -> Prop)
  (IHn : forall (e : y = x), P (rew <- e in le_n x))
  (IHS : forall y' (q' : x <= y') (e : y = S y'), P (rew <- e in le_S x y' q'))
  : forall (p : x <= y), P p.
exact (fun p => match p with le_n _ => IHn | le_S _ y' q' => IHS y' q' end eq_refl).
Qed.

Theorem le_unique {x y : nat} (p q : x <= y) : p = q.
revert q.
induction p as [|y p IHp] using le_ind_dependent;
intro q;
case q as [e|x' q' e] using le_case_remember.

- rewrite (nat_uip e eq_refl).
  reflexivity.

- (* x = S x' but x <= x', so S x' <= x', which is a contradiction *)
  exfalso.
  rewrite e in q'.
  exact (PeanoNat.Nat.nle_succ_diag_l _ q').

- (* S y' = x but x <= y', so S y' <= y', which is a contradiction *)
  exfalso; clear IHp.
  rewrite <- e in p.
  exact (PeanoNat.Nat.nle_succ_diag_l _ p).

- injection e as e'.
  (* We now get rid of e as equal to (f_equal S e'), and then destruct e'
     now that it is an equation between variables. *)
  assert (f_equal S e' = e).
  + apply nat_uip.
  + destruct H.
    destruct e'.
    change (le_S x y p = le_S x y q').
    f_equal.
    apply IHp.

Qed.

Answer: Inspired by Eqdep_dec (and with a lemma from it), I've been able to cook this proof up. The idea is that x <= y can be converted to exists k, y = k + x, and roundtripping through this conversion produces a x <= y that is indeed = to the original.
(* Existing lemmas (e.g. Nat.le_exists_sub) seem unusable (declared opaque) *)
Fixpoint le_to_add {x y : nat} (prf : x <= y) : exists k, y = k + x :=
  match prf in _ <= y return exists k, y = k + x with
  | le_n _ => ex_intro _ 0 eq_refl
  | le_S _ y prf =>
    match le_to_add prf with
    | ex_intro _ k rec =>
      ex_intro
        _ (S k)
        match rec in _ = z return S y = S z with eq_refl => eq_refl end
    end
  end.
Fixpoint add_to_le (x k : nat) : x <= k + x :=
  match k with
  | O => le_n x
  | S k => le_S x (k + x) (add_to_le x k)
  end.
Theorem rebuild_le
  {x y : nat} (prf : x <= y)
: match le_to_add prf return x <= y with
  | ex_intro _ k prf =>
    match prf in _ = z return x <= z -> x <= y with
    | eq_refl => fun p => p
    end (add_to_le x k)
  end = prf.
Proof.
  revert y prf.
  fix rec 2. (* induction is not enough *)
  destruct prf as [ | y prf].
  - reflexivity.
  - specialize (rec y prf).
    simpl in *.
    destruct (le_to_add prf) as [k ->].
    subst prf.
    reflexivity.
Defined.

Then, any two x <= ys will produce the same k, by injectivity of +. The decidability of = on nat tells us that the produced equalities are also equal. Thus, the x <= ys map to the same exists k, y = k + x, and mapping that equality back tells us the x <= ys were also equal.
Theorem le_unique (x y : nat) (p q : x <= y) : p = q.
Proof.
  rewrite <- (rebuild_le p), <- (rebuild_le q).
  destruct (le_to_add p) as [k ->], (le_to_add q) as [l prf].
  pose proof (f_equal (fun n => n - x) prf) as prf'.
  simpl in prf'.
  rewrite ?Nat.add_sub in prf'.
  subst l.
  apply K_dec with (p := prf).
  + decide equality.
  + reflexivity.
Defined.

I'm still hoping there's a better (i.e. shorter) proof available.

How to prove all proofs of le equal?


Tritone as a passing note

Question: Can a tritone be used as a passing note? (say in key of C, going from note C to G).
Comment: Any note can be used as a passing note. Very often you'd come across a D or D7 chord as a secondary dominant for the G major chord. In this case the F# is the third of that chord.
Comment: Classical harmony allows an unprepared appogiatura.  Whether you class it as a "passing note" is merely a matter of terminology.   Modern useage certainly includes unprepared non-scale tones.  Though modern theory can get strangely pedentic over notes that don't fit the prevailing chord/scale!
Comment: I believe The Simpsons' theme song employees this device.  I'm not sure that we would refer to this as a passing tone though, as a passing tone is usually step-wise motion.
Comment: What about ["Once Upon a Time in the West"](https://www.youtube.com/watch?v=DyvzfyqYm_s)?
Comment: We don't allow song search or itemized lists here, so I've edited your question a bit.  Matt and Laurence, I would consider turning your comments into answers.
Comment: Silly implementation of a silly rule.  The examples given from West Side Story help a lot in understanding the question.
Comment: @Laurence Payne - I'd have quoted 'Maria' anyway, but good point, as the OP only used that as an addendum.
Answer: Maria from West Side Story, uses exactly that for the first line (not sure if it's in that key, but hey). The underlying harmony is root, the first note is also root, and the tritone is the second, leading to a 5th on the third note. It sounds like it may modulate, but as Matt says, but it doesn't. The fact that the tritone is a semitone from the target is good, as resolutions often move that small distance.
Comment: The whole score of "West Side Story" (except "I Feel Pretty", which was a late addition) features that interval.  Mostly it's used melodically, to give a "cool jazz" flavour.  But look at the very last few bars of the score, where a C major triad with an F# bass note underlines the final tragedy.
Answer: Riffs and melodies moving quickly from #4 to 5 comprise a huge part of blues and jazz. You'll be hard pressed to find music from those genres that doesn't make ample us of that melodic transition - #4 is one of the traditonal blue notes. - that's a tritone from the root moving towards the 5 - a building block of the blues. So the answer is Yes.

Tritone as a passing note


How to Detect sip call forward to server's Voice mail?

Question: Am Using Pjsip libraries for SIP implementation . Using Pjsip lib i can able to make IP calls perfectly  . My problem is While I Make call if other End User Decline/not Reachable or No answer ,My call  will connect with Voice mail and get 200k(call connected state) from sip server as same like other end user Answering call.
    Not Reachable Case i can differentiate 200 ok By missing 183 Session Progress Message. But noanswer and decline case I couldn't get the actual State of call .
     is any way to find call connected state and Voice mail connected state ?
Answer: There isn't any one way of a user agent knowing it has reached a voicemail server versus a person answering.
Usually what will happen is that your user agent will send an INVITE to a From URI, and some proxy responsible for that URI will fork the INVITE to the various user agents the remote party uses: her phone, her voicemail service, and so on. The first user agent to return a 2xx response sets up the call.
You will however always know to which user agent you have connected, in the Contact header of the 200 OK.
Presumably a voicemail server will indicate in its SDP offer/answer that while it accepts certain incoming media streams, it will not send anything, by marking the stream with an a=recvonly attribute (See RFC 3264).
Comment: `a=recvonly` isn't a _required_ attribute. It would just be nice of the voicemail server
Comment: Thanks Frank Shearar.sorry for the stupid doubt. i have checked 200 ok message  with Wireshark. in 200 ok SDP There is no such attribute  'a=recvonly' . whether i should to Add anything @ my invite SDP ??


How to "return" an error message from a C# property setter to the user?

Question: I have a windows form that allows the user to input an integer value. This value is used to update a member of a separate class (foo) so long as it falls within a certain valid range. If the user inputs something invalid, I want an error message to tell the user that the default value for the parameter will be used.
In order to accomplish this, I have been error checking the user input within the code for the windows form before letting foo set the field in question, and simply displaying a message if the input fails the check.
But what I would like to do is send the raw user input to a property setter within the class foo and have the property setter handle all the error checking. For other functions in foo that may require a message be displayed on the user interface, I am simply returning a string, but to my knowledge there is no way to return any sort of status or value from a property setter. Is there a graceful way to bubble up a status message of some sort from a property setter to a different function? I don't want foo to modify the user interface directly.
Thanks in advance for any help or tips, and I apologize if my question is too vague or should be asked differently as I am new to StackOverflow
Comment: You might be interested in [INotifyDataErrorInfo](https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo(v=vs.110).aspx)
Comment: @ScottChamberlain Forgive me, I am very new to C# - would this be a way of allowing me to raise an event that could be caught by the windows form in some way?
Comment: Yes, you implment the interface and you can use that to provide information about which properties have errors. Google tutorials about it to learn how to implment it, it is integrated with both WinForms and WPF
Answer: I fixed my problem (as well as removed the need to return strings from nearly all my functions) by implementing INotifyPropertyChanged in my class foo and raising a PropertyChanged event to be caught by the windows form whenever it was necessary to let the user know something had changed.
in class foo-
public class foo : INotifyPropertyChanged {

    public event PropertyChangedEventHandler PropertyChanged;
    public int bar;

    private void NotifyPropertyChanged(string type) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(type));
        }
    }

    private void test(){
        bar = 1;
        NotifyPropertyChanged("changed int");
    }

}

in the windows form:
public partial class GUI : Form {
     foo fooinstance = new foo();

     public GUI(){
           InitializeComponent();
           fooinstance.PropertyChanged += doEvent;
     }

     private void doEvent(object sender, PropertyChangedEventArgs e){
        foo updated = sender as foo;
        if (object.ReferenceEquals(e.PropertyName, "changed int")) {
            ShowWhatChanged(updated.bar); //show on GUI
        }
     }

}
EDIT:
A more graceful and cleaner way that I ended up using was to utilize callbacks. The GUI passed a function pointer into foo upon instantiation and foo used it as a delegate to pass strings back to the GUI whenever necessary. No events required:
public class foo {

    public delegate void UpdateCallback(string msg);
    private UpdateCallback _ucb;
    public foo(UpdateCallback cb){
        _ucb = cb;
    }

    private void test(){
        if(_ucb != null) {
           _ucb("Message Here");
        }
    }
}

public partial class GUI : Form {

     public GUI(){
           InitializeComponent();
           foo fooinstance = new foo(showmessage);

     }

     private void showmessage(string msg){
           //do whatever with the message
     }
}


sugarCRM : creating relationship using module loader, package not installing

Question: I am trying to create relationships through module loader in SugarCRM. But the problem is my package is stopped installing after 55%. When I am viewing display log the error is:-

Failed to copy
  cache/upgrades/temp/SYWr9G/custom/metadata/accounts_contacts_1MetaData.php
  custom/metadata/accounts_contacts_1MetaData.php

I tried to change permissions also but at some point they through internal server error 500. Following are the code which I am using.
1.In manifest.php file :
    $installdefs = array(
        'id' => 'package_20170804',
        'copy' => array(
            0 => array(
                'from' => '<basepath>/accounts_contacts_1MetaData.php',
                'to' => 'custom/metadata/accounts_contacts_1MetaData.php',
                ),
            1 => array(
                'from' => '<basepath>/accounts_contacts_1.php',
                'to' => 'custom/Extension/application/Ext/TableDictionary/accounts_contacts_1.php',
                ),
            ),
        'relationships'=>array (
            array (
                'module'=> 'Accounts',
                'meta_data'=>'<basepath>/custom/metadata/accounts_contacts_1MetaData.php',
               'module_vardefs'=>'<basepath>/custom/Extension/application/Ext/TableDictionary/accounts_contacts_1.php'

                )
            ),
        );

2. In accounts_contacts_1MetaData.php file :

    <?php
    $dictionary["accounts_contacts_1"] = array (
      'true_relationship_type' => 'one-to-many',
      'from_studio' => true,
      'relationships' =>
      array (
        'accounts_contacts_1' =>
        array (
          'lhs_module' => 'Accounts',
          'lhs_table' => 'accounts',
          'lhs_key' => 'id',
          'rhs_module' => 'Contacts',
          'rhs_table' => 'contacts',
          'rhs_key' => 'id',
          'relationship_type' => 'many-to-many',
          'join_table' => 'accounts_contacts_1_c',
          'join_key_lhs' => 'accounts_contacts_1accounts_ida',
          'join_key_rhs' => 'accounts_contacts_1contacts_idb',
          ),
        ),
      'table' => 'accounts_contacts_1_c',
      'fields' =>
      array (
        0 =>
        array (
          'name' => 'id',
          'type' => 'varchar',
          'len' => 36,
          ),
        1 =>
        array (
          'name' => 'date_modified',
          'type' => 'datetime',
          ),
        2 =>
        array (
          'name' => 'deleted',
          'type' => 'bool',
          'len' => '1',
          'default' => '0',
          'required' => true,
          ),
        3 =>
        array (
          'name' => 'accounts_contacts_1accounts_ida',
          'type' => 'varchar',
          'len' => 36,
          ),
        4 =>
        array (
          'name' => 'accounts_contacts_1contacts_idb',
          'type' => 'varchar',
          'len' => 36,
          ),
        ),
      'indices' =>
      array (
        0 =>
        array (
          'name' => 'accounts_contacts_1spk',
          'type' => 'primary',
          'fields' =>
          array (
            0 => 'id',
            ),
          ),
        1 =>
        array (
          'name' => 'accounts_contacts_1_ida1',
          'type' => 'index',
          'fields' =>
          array (
            0 => 'accounts_contacts_1accounts_ida',
            ),
          ),
        2 =>
        array (
          'name' => 'accounts_contacts_1_alt',
          'type' => 'alternate_key',
          'fields' =>
          array (
            0 => 'accounts_contacts_1contacts_idb',
            ),
          ),
        ),
      );
3. In accounts_contacts_1.php file:

<?php
include('custom/metadata/accounts_contacts_1MetaData.php');
?>

I just wanted to create a field in relationship that's all . Maybe I am missing somewhere in manifest file or i needed to include some additional file.
Comment: What version of SugarCRM are you using? When you encounter the 500 error, are there any entries in your sugarcrm.log?
Comment: @Reisclef, Thanks, for the comment I am using SugarCRM EE 7.6.1. I didn't check sugar log out but I think it mostly says about permission issue. Is permission really matter for creating custom relationships through module loader.
Comment: @egg, please give a look of above code I know somewhere I am mistaking. So please help me.
Answer: I solved it. You can follow following steps to create relationships in SugarCRM through module loader.
Step 1:- Give permission to your sugar directory according to following
 For Linux: http://support.sugarcrm.com/Knowledge_Base/Platform_Management/Required_File_System_Permissions_on_Linux/
For Windows:
http://support.sugarcrm.com/Knowledge_Base/Platform_Management/Required_File_System_Permissions_on_Windows_With_IIS/
Step 2:- In manifest.php
<?php
 $manifest = array(
    'acceptable_sugar_flavors' => array('CE','PRO','CORP','ENT','ULT'),
    'acceptable_sugar_versions' => array(
        'exact_matches' => array(),
        'regex_matches' => array('(.*?)\\.(.*?)\\.(.*?)$'),
        ),
    'author' => 'Ravi Ranjan',
    'description' => 'Relationship',
    'icon' => '',
    'is_uninstallable' => true,
    'name' => 'custom relation',
    'published_date' => '2017-08-10 2017 11:45:04',
    'type' => 'module',
    'version' => '20170810',
    );

 $installdefs = array(
    'id' => 'package_20170810',
    'copy' => array(
        0 => array(
            'from' => '<basepath>/accounts_contacts_1MetaData.php',
            'to' => 'custom/metadata/accounts_contacts_1MetaData.php',
            ),

        1 => array(
            'from' => '<basepath>/accounts_contacts_1.php',
            'to' => 'custom/Extension/application/Ext/TableDictionary/accounts_contacts_1.php',
            ),

        ),

    );

 ?>

Step 3:- The contents of both  file accounts_contacts_1MetaData.php and accounts_contacts_1.php will be same as you can see in question.
Step 4:- Compress all three files and upload through module loader, after installation quick repair and rebuild.
Go in Studio > Accounts > Relationships You will see a new field there name accounts_contacts_1 That's what I wanted to create.


Comparing the results for the current time with the epg time

Question: I have got a problem with comparing the times with the EPG time. When my current time show 2017-10-10 01:23:00 and when my EPG time show 2017-10-10 06:00:00 which is 6:00AM in the morning and my current time show 1:23AM, it will always get pass on the if statement so I am not sure why.
When I try this:
EPG_Time = time.strptime('2017-10-10 01:23AM', '%d/%m/%Y %I:%M%p')
EPG_Time = datetime.datetime.fromtimestamp(time.mktime(EPG_Time))
EPG_Next_time = time.strptime('2017-10-10 06:00AM', '%d-%m-%Y %I:%M%p')
EPG_Next = datetime.datetime.fromtimestamp(time.mktime(EPG_Next_time))

if EPG_Next <= EPG_Time:
    print "it is time to delete the data from the list..........."

It will always get pass on the if statement when my current time is behind the EPG time. I want to get pass on the if statement as only when my current time is equal or greater than the EPG time which it is 06:00AM or so I can then delete the data from the list.
Can you please show me an example how I can compare my current time with the EPG time?
Answer: First of all the format strings for strptime() are inconsistent with the actual strings. I'm assuming that's a typo.
Secondly datetime.datetime includes it's own strptime() function so you don't need to convert from a time stamp:
from datetime import datetime

EPG_Time = datetime.strptime('2017-10-10 01:23AM', '%Y-%m-%d %I:%M%p')
EPG_Next = datetime.strptime('2017-10-10 06:00AM', '%Y-%m-%d %I:%M%p')

if EPG_Next <= EPG_Time:
    print "it is time to delete the data from the list..........."

In this case EPG_Time comes before EPG_Next so the print statement is not executed.
The current time can be obtained using datetime.now(). Compare that to your EPG time to determine whether you need to perform the required action:
if EPG_Next <= datetime.now():
    print "it is time to delete the data from the list..........."

Comment: Thank you for this, but when I try this: `if EPG_Next <= datetime.now():` it give me an error: `TypeError: can't compare datetime.datetime to tuple`. Any idea??
Comment: In your case `EPG_Next` does not contain a `datetime` object, it's probably a time tuple like the one returned by `time.mktime(EPG_Next_time)`. Try using the code that I show in my answer.
Answer: You aren't getting good values out of the parses, because the formatter has an incorrect format.  For both formatters you should be using
'%Y-%m-%d %I:%M%p'

The comparison should work fine.
Comment: should I change from `'%d/%m/%Y %I:%M%p'` to this `'%Y-%m-%d %I:%M%p'`??
Comment: @Daniel  Yes, change both formatters to this value: '%Y-%m-%d %I:%M%p'.  '%d-%m-%Y %I:%M%p' (the second date formatter) is also not going to provide the correct results.
Comment: Ah I see. So thank you very much for your advice. I am going to see what happens from there. If it is works then great!
Comment: @Daniel, awesome, hope your project goes well.
Comment: Thank you, when I try the code you suggested me to use, it will still get pass on the if statement when I have changed from `'%d/%m/%Y %I:%M%p` to this `%Y-%m-%d %I:%M%p` so it doesn't make any difference. Any idea?


Free resource for pitch correction on a whole track?

Question: I have a very old recording (from about 1940) in mp3 format. The pitch of it is in a little bit bellow B♭m, and for someone who has perfect pitch it's just pain in the ears. Or if you want to jam with a recording and tuning your instrument back and forth drives you nuts.
Do you know of any free resource (preferably online) that can move the pitch of this track up or down to standard 440Hz pitch, without affecting its tempo?
Sound quality does matter, but is optional, I need it all for jamming purposes, not for production, so I just need to get this job done quickly.
Answer: Audacity can do this. It's free on Windows, Mac and Linux.
Load the audio file.
Select-All (ctrl-A).
Choose "change pitch" from the "effects" menu, and you will be presented with a range of options.

This adjusts the pitch independently of the speed, with some loss of quality. The "change speed" option in the same menu will affect both speed and pitch, but with less impact on the audio quality.
Even for those without perfect pitch, this is a great feature for people wishing to play along to recordings which are not at standard pitch.
I've removed a slightly judgemental passage, and am replacing it with this: if you acknowledge that the standard pitch is arbitrarily chosen, and teach yourself to accept other pitches, you open yourself up to a lot of recordings and live performances which you currently are unable to enjoy.
Comment: It may be fairly arbitrary, but A440 is an [international standard](http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=3601), so it's *very* likely to be the most common tuning heard today - which would explain why people with a penchant for perfect pitch become attuned to that one (as @awe said, "without trying to").
Comment: @jadarnel27 no apology needed. I *was* being too judgemental.
Comment: @awe but there's nothing inherently "right" about 440Hz. They have evidently trained themselves to demand semitones relative to 440Hz. Are they irritated by period baroque string music performed at their standard of A=415Hz? I don't think that would be reasonable.
Comment: There are a few people out there with perfect pitch, and I know that it's really anoying for them to listen to off pitch music. For us "normal" people that don't have perfect pitch, it may be difficult to understand, but I know one that do, and for him this is a real problem.
Comment: They may not have trained them neccesarily to 440Hz, but to the pitch most commonly practiced. I believe the people that have this problem have natural exceptional musical abilities, and have developed perfect pitch without trying to, just to listen to music where most have a common pitch. Maybe @Shimmy can give more first hand information on this?
Comment: @jadarnel27 if they didn't train themselves (albeit unconsciously) how did they come to perceive 440Hz has "correct", when the world is so full of sound sources (including music performances and recordings) that are not at semitones relative to this arbitrary pitch?
Comment: +1 Slim.  Sorry if I was coming across as kind of a jerk.  I think your edit is a much more objective way of looking at it.
Comment: @slim Whether it's reasonable or not, it's definitely a real issue for the OP, and many others with perfect pitch, that they have little or no control over.  The people I know with Absolute Pitch didn't "train themselves" to do anything.
Comment: While I agree completely with slim that this is an OCD issue, not an ear issue, the fact remains that the OP wants a solution.
Comment: Just to make sure, I don't do it because I'm a perfect pitch, just the opposite, thanks god. I'm a very good relative pitch - perfect pitch? nah not at all.
The reason I want is I want play along with that audio track to practice it's solos and jam with it, and I'm sick of tuning my instrument back and forth.
So thanks to all of you, and sorry for the delayed input.
@slim, Do you know of an online tool or at least a standalone app that I don't have to install?
Comment: I don't know of a web site. There is a "portable audacity" that runs off a USB stick. Depends what you mean by "install".
Answer: Analog equipment would be better for this. The fact that it's mp3 means that it's been compressed for a specific sample-rate; and small shifts are likely to radically increase the aliasing artifacts because your samples are going to be out-of-phase. This is going to lower the effective Nyquist limit; so you'll probably have to run it through a low-pass filter to remove the noise and you'll lose pitch detail when you do that. The whole thing will sound like you're listening through a brick wall with a paper cup.
I think you'll need to get an uncompressed version to get usable results from digital methods.
Even better would be an LP on a turntable with pitch-correction.
Comment: Digital has the advantage of there being algorithms to adjust the pitch independently of the speed. "Usable results" is very subjective. I don't imagine a 1940 recording is particularly high-fidelity in the first place.
Comment: With decent recordings I've found you can move a whole step without perceiving a loss in quality.  I don't think moving at most half a semitone (to the nearest note) should affect the quality much in this case.
Comment: Alright, I confess! I've never actually tried. This is all guesswork based on the math.
Answer: I'll throw one more answer in here.  The original was, in all likelihood, on some sort of record.  If a semitone is 16:15, and the record was designed to be played at 33⅓ RPM, playing the record around 31.26 RPM would result in a semitone difference, plus the sound quality and tempo would likely change noticeably.  Not even a whole semitone would be necessary to be disturbing to a listener with or without perfect pitch.  Some instruments will sound different, particularly woodwinds that are no longer playing quite in the registers of the sounding pitches.  The timbre will change, possibly to be more dull, and again, the tempo will be that much slower.  So, there is more to this than pitch, and it's not "just OCD" by someone with absolute pitch.
I'll echo another answer, then, and say that if you can find the original album, just speed it up to the pitch you are expecting.  It will be harder to accomplish the same effect in MP3.  In .wav, you could simply speed up the bit rate slightly if you have software that will do so.  The Nyquist frequency would not be an issue if playback will always be at this higher bit rate.  If the recording must be translated back to a standard bit rate, then yes, a low-pass filter would be necessary, but it is unlikely that you would notice a loss of quality unless you are the type that somehow notices loss of quality when going from an analog format to CD.
Comment: +1 I was probably making a bunch of unconscious assumptions. One I now realize is that an old recording (I assume) would be assumed to require less quality (there being less *there* to preserve) and (probably) compressed to a very low bitrate.


Irreducibility of $x^{3}-3(p+q)x^{2}+3(p^{2}+q^{2})x-(p^{3}+q^{3})$ for positive integers $p$ and $q$.

Question: Let $p$ and $q$ be positive integers. How can I show that the polynomial $x^{3}-3(p+q)x^{2}+3(p^{2}+q^{2})x-(p^{3}+q^{3})$ is irreducible over the integers?
Answer: Hint:
The equation is
$$(x-p)^3+(x-q)^3=x^3.$$
Comment: But which irreducibility criterion applies in this case?
Comment: This should blind you.
Comment: A cubic is irreducible if it has no root. Having no root was already discussed [here](https://math.stackexchange.com/questions/3644503/integer-roots-to-cubic-equation-with-integer-coefficients).
Comment: I tried to prove the irreducibility of the Fermat equation over the integers using only Gauss´s Lemma on monic polynomials with integer coefficients: https://www.researchgate.net/publication/338819565_Proving_Fermats_Last_Theorem_as_a_Mean_Value_Problem_Title_Proving_Fermats_Last_Theorem_as_a_Mean_Value_Problem_Author


One-sided zero-divisors which are identity from the other side

Question: What are examples (if any) of a ring $R$ with elements $x,y \in R$ such that $xy=0$ yet $yx=1$?
Is there a characterization of rings which exhibit such pairs of elements? Do such pairs have a special name?
Answer: In any associative unital ring, these conditions imply that $x=0$, since
$$0=0x=xyx=x1=x;$$
and then $1=yx=y0=0$. So this can only hold in the trivial ring.
Answer: Assuming associativity and two-sided $1$ and $0$, there is only one such ring, because$$1=1\cdot1\\=(yx)(yx)\\=y(xy)x\\=x\cdot 0\cdot y=0$$
Comment: What about non-associative rings (or non-associative algebras)?


Estimate negative binomial dispersion parameter $k$ using mean and proportion of zeros

Question: I came across supplemental methods of a paper estimating the mean ($R$) and dispersion ($k$) of a negative binomial distribution that stated:

Page 8: "Given estimates of the mean ($\hat{R}$) and proportion of zeros ($\hat{p_0}$) of a negative binomial distribution, the parameter $k$ can be estimated by solving the equation $\hat{p_0} = (1+\frac{\hat{R}}{k})^{-k}$ numerically."

This "zero-class estimator" approach is also used here.
I would like to compare the accuracy of this method (with regards to inference of $k$) with my results using MLE. This initially seemed simple, but I have been unable to successfully estimate $k$ using this approach in R programming. I tried solving for $k$ algebraically but my algebra may be wrong (happy to post if requested, but omitting equations for readability/brevity).
Any advice on how to use this approach to estimate $k$ (in R or other statistical software) would be much appreciated.
Comment: @Henry: Unfortunately, the solution utilizing the Lambert $W$ function is incredibly numerically unstable. The denominator of the result is absolutely tiny, which is suspicious to me. I don't think the algebraic solution is feasible. That's why I deleted my answer.
Comment: @AdrianKeister perhaps you should be using the other branch of the Lambert W function.  Based on your deleted answer this would be `R=1.63;` `p=0.6667;` `-R*log(p)/(log(p)-R*lambertWm1(p^(1/R)*log(p)/R))` to get `0.1729429` as in jpsmith's table
Comment: @AdrianKeister  It is probably related to $\ln(\hat{p}_0)$ being negative, and to get a positive estimate for $k$ you want  $W\!\left(\frac{\hat{p}_0^{1/{\hat{R}}}\,\ln(\hat{p}_0)}{\hat{R}}\right) < \frac{\ln(\hat{p}_0)}{\hat{R}}$.  The upper branch of the Lambert W function does not seem to achieve that for the cases I checked (though it was often close) while the lower branch does
Comment: There [may be a solution](https://www.wolframalpha.com/input?i=solve+p%3D%281%2BR%2Fk%29%5E%28-k%29+for+k) for  $\hat k$ using the Lambert W function though you will need $p_0>0$
Comment: Thank you! This agrees with my algebraic approach but I seem to be unable to implement this in the actual statistical software. I am pasting below a computational solution I have found works
Comment: That paper to which you linked needed to be typed up in $\LaTeX.$ Looks like Word was used - very ugly.
Comment: Cross-posted at https://math.stackexchange.com/questions/4399484/solve-for-k-in-the-equation-hatp-0-1-frac-hatrk-k
Comment: @Henry: That's cool! But how to know which branch of the $W$ function is the correct one? Not sure it's obvious.
Answer: The exact answer can be given by the Lambert $W$ function as follows:
$$k=-\frac{\hat{R}\ln(\hat{p}_0)}{\ln(\hat{p}_0)-\hat{R}\,W\!\left(\frac{\hat{p}_0^{1/{\hat{R}}}\,\ln(\hat{p}_0)}{\hat{R}}\right)},$$
where $W$ is the Lambert $W$ function, which is the inverse of the function $f(x)=x\,e^{x}.$ In R, you can install the lamW package, which gives access to the lambertWm1 function (a better branch of the $W$ function to use; see Henry's comment), and then code up the equation above as follows:
install.packages('lamW')
require(lamW)
k = - R * log(p) / (log(p) - R * lambertWm1(p^(1/R) * log(p) / R))

As mentioned in the comments, this does require $p>0$ to satisfy the domain requirements of the logarithm function.
Comment: Thank you! I initially tried this formula implemented through similar code but I am not getting results that align with established estimates. For instance, using data from the first column in the table [here](https://static-content.springer.com/esm/art%3A10.1038%2Fnature04153/MediaObjects/41586_2005_BFnature04153_MOESM4_ESM.pdf), $R = 1.63$ and $p_0 = 0.6667$, which should yield $k_{pz} = 0.17$ using the zero-class estimator. Using both my and your code with the `lamW` package function (as well as attempted with an alternate `LamberW` package) yields different results, $p_z = -1.190439e+16$.
Comment: @Avraham Thank you!
Comment: I imagine we're getting some machine-epsilon problems: the denominator for your example is absolutely tiny. Lemme see if I can fix that somehow.
Comment: I'm not sure I can fix this. The denominator appears to be absolutely tiny for practically every input value you can dream up!
Comment: @jpsmith, That's because you used the $W_0$ branch and not the $W_{-1}$ branch. Using `R <- 1.63; p <- 0.6667` and `k <- - R * log(p) / (log(p) - R * lambertWm1(p^(1/R) * log(p) / R))` I get `0.1729429` for `k`. Disclosure, I am the author of the `lamW` package for `R`.
Answer: Since $(1+\frac{\hat{R}}{k})^{-k}$ is a decreasing function of $k$, the function $\hat{p}_0 -(1+\frac{\hat{R}}{k})^{-k}$ will have at most one zero.  However, when the lower asymptote of $(1+\frac{\hat{R}}{k})^{-k}$ is larger than $\hat{p}_0$, no zero will be found.  Here's some simple R code
set.seed(555)
x = rnbinom(100,size=.5,prob=.4)
p0 = mean(x==0)
mu = mean(x)
f = function(k,p0,mu){
    return(p0 - (1+mu/k)^(-k))
}
uniroot(f,c(.001,1000),p0=p0,mu=mu)

```
</code>
Comment: @jpsmith Good to hear!  Always analyze properties of the normal equations, they can help you pick the correct optimization routine and show you how a sample can fail to produce a reasonable estimator.  A simple scatter plot or 3D plot is very useful for problems with no closed-form solutions for the estimators
Comment: Perfect - perhaps my initial attempt with `uniroot` didnt offer broad enough values as you mentioned below. Thank you!
Answer: I wrote this brute-force computational function that seems to work and avoids using the Lambert W function, though more accurate/elegant solutions may still be out there:
<code># Estimate k using only proportion of zeros (z=0, or y=1) and R

findk <- function(R, p0, k.maxsearch = 50, sigdig = 5){
  p0 <- round(p0, sigdig)
  k <- seq(10^-sigdig, k.maxsearch, 10^-sigdig)
  p <- round((1+(R/k))^-k, sigdig)
  see <- cbind(k, p, p0)
  if(tail(p, n = 1) > p0) {
    paste0("k > ", k.maxsearch)
    } else {
  min(k[p == p0])
    }
}

# Test Function
    # Data rom Lloyd-Smith supplemental table 2, first page, found here:
    # browseURL("https://static-content.springer.com/esm/art%3A10.1038%2Fnature04153/MediaObjects/41586_2005_BFnature04153_MOESM4_ESM.pdf")
ls_data <- data.frame(Rs = c(1.63, 0.94, 1.88, 0.63, 0.82, 1.32, 0.70),
                      p0s = c(0.6667, 0.7273, 0.7059, 0.7394, 0.7143, 0.4054, 0.5500))

k_ests <- data.frame(ls_data,
                     k_pz = apply(ls_data, 1, function(x) findk(x[1], x[2])))

#   Rs    p0s    k_pz
# 1 1.63 0.6667 0.17294
# 2 0.94 0.7273 0.16946
# 3 1.88 0.7059 0.12576
# 4 0.63 0.7394 0.22758
# 5 0.82 0.7143 0.21317
# 6 1.32 0.4054 1.25930
# 7 0.70 0.5500 1.94307

# k_pz results match those found in paper table
```

Comment: Is the built-in ```uniroot``` function not working for you?  Should be quite easy to code, just give a big range of values for $k$ like (.001,1000)
Answer: Given that both $\hat{p}_0$ and $(1+\frac{\hat{R}}{k})^{-k}$ are by definition non-negative, you can just minimize $(\hat{p}_0 - (1+\frac{\hat{R}}{k})^{-k})^2$. Almost any software will have some generic minimization tools (e.g. ucminf in R). The only difficulty will be the scenarios where the estimate of the dispersion parameter should be 0 or $\infty$ (depending on your parametrization), which is a genuine potential issue.


Cross-country skiing world records

Question: Are there any current world records for cross-country skiing? I am mainly interrested in distances like 10 or 15 kilometers, both men and women included. Neither Google nor Wikipedia are able to answer the question.
Answer: Timing in cross country skiing has no purpose but to classify the runners. There are no international records, and even so they will be untrustable because of different conditions of snow and the fact that CC does not have a unique track like, for example, a 100 metre sprint does.
Comment: Just a comment: marathons don't have a unique track, but the IAAF now records [marathon world records](http://en.wikipedia.org/wiki/Marathon_world_record_progression). I accept that cross-country skiing courses vary more than a marathon course, but this isn't an absolute prohibition.
Comment: But even in marathon is talk of fast and less fast marathon courses (see [http://www.runnersworld.com/races/the-worlds-fastest-marathons-and-marathoners]. So you would never try to run wolrd record on a slow course.

Cross-country skiing world records


How to reference base variable with inheritance

Question: I have been trying many ways to accomplish this without any success.  Can anybody help me?
Base Object:
var Recorder = function (source) {
    this.context = source.context;
    var recording = null;

    this.start = function () {
        recording = true;
    }

    this.stop = function () {
        recording = false;
    }

}

Derived Object:
var messageRecorder = function () {

    this.isRecording = function () {
        return this.recording;
     }
}

So I have a base object, Recorder, which has a var 'recording'.  I want to have an extended/derived object, messageRecorder, which can return the value of 'recording' (from Recorder).  Any suggestions?  I have tried the jQuery extend, var audioRecorder = $.extend( {}, new Recorder(), new messageRecorder()), with no luck.  I have also tried to modify messageRecording as follows:
var messageRecorder = function () {
    Recorder.apple(this, arguments);

    this.isRecording = function () {
        return this.recording;      //declared in Recorder
     }
}

and instantiate like so: var audioRecorder = new messageRecorder(source);
In both my failed attempts, when I call audioRecorder.start() it works fine.  When I call audioRecorder.isRecording(), the var 'recording' is undefined, probably because I am not trying to access it properly.  Any suggestions?
Comment: `recording` is a [variable, not an object property](http://stackoverflow.com/q/13418669/1048572). You cannot access it outside of `Recorder`, by no means.
Answer: You can handle simple inheritance by calling the parent constructor function on the object being created, so you can do the following:
var Recorder = function (source) {
    this.context = source.context;
    this.recording = null;

    this.start = function () {
        this.recording = true;
    };

    this.stop = function () {
        this.recording = false;
    };

};

var messageRecorder = function() {
    Recorder.apply(this, arguments);

    this.isRecording = function() {
        return this.recording;
    };
};

var src = {
    context: 'something'
};
var audioRecorder = new messageRecorder(src);

audioRecorder.start();
console.log("recording? " + audioRecorder.isRecording());
audioRecorder.stop();
console.log("recording? " + audioRecorder.isRecording());

Which gives you the following output (setting this.recording correctly):
recording? true
recording? false


How many different paths are there on a lattice that pass through a given point?

Question:
When Looking at A to C by ${4\choose 2}$ we are ordering, right-r up-u 4 times, so ordering 2 r's or 2 u's determine the other 2 moves?
And same with C to B ${3\choose 2}$ ordering the 2 r's determine the order of the leftover u?
So in general can we conclude that for a given combination with n different elements we need to order just $n-1$ of them and the leftover will be determined?
Comment: Since you only have two options, choosing where you go right determines where you must go up.
Answer: $\bf{Solution::}$
No. of path from $\bf{\left(A\rightarrow B\right)}$ = No. of path from $\bf{\left(A\rightarrow C\right)}$ * No. of path from $\bf{\left(C\rightarrow B\right)}$
So which is $= $ Arranging $\bf{RRUU}$+Arranging $\bf{RRU}\displaystyle  = \frac{4!}{2!\times 2!}*\frac{3!}{2!} = 6*3=18$
Here $\bf{R} = 1\; Unit $ Rightward and $\bf{U=1\;unit}$ Upward.


Django how to hyperlink to images in static folder by ticker symbol?

Question: I have a table of ETF tickers, ETF names, and their Index names. I want each entry in the table to be clickable and linked to their associated images in the static/images folder. Each image is named after each ETF's index ticker. So when a user clicks on, for example, the first entry ETF ticker "PSCD" links to 'static/myapp/images/sample_regression_S6COND.jpg'. The substring in the link "S6COND" is the part I need as a relative link. Each ETF ticker has a different Index ticker. These Index tickers are in a model associated with the table.

In my table.html page, when I hardcode the link to the static image {{i.etf_ticker}}	 (see how I typed "S6COND" into the link?), it works, but not when I try to turn it into a relative link {{i.index_ticker}} like {{i.etf_name}}	. My static files in correctly placed inside my app folder and includes images, css, and js folders. All images are inside the static/myapp/images folder.
table.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>ETF Table</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}">

      ETF Ticker
      ETF Name
      Index Name

    {% if d %}
    {% for i in d %}

        {{i.etf_ticker}}
        {{i.etf_name}}
        {{i.index_name}}

   {% endfor %}
    {% endif %}

views.py
def table(request):
    data = Table.objects.all().values()
    context = {'d': data}
    return render(request, 'table.html', context)

models.py
class Table(models.Model):
    etf_ticker = models.CharField(max_length=10)
    etf_name = models.CharField(max_length=200)
    index_name = models.CharField(max_length=200)
    index_ticker = models.CharField(max_length=10)

Answer: Create your url in the following manner:
{{i.etf_name}}

I've broken your url into 3 parts. The first and last parts are simple strings. The middle part contains your ticker. The | is used to denote that we're using one of Django templating language's filters. The template we're using is add. It is used to add stuff to whatever comes before the pipe. If we were dealing with numbers, it would add them mathematically, but since we're using strings, it concatenates the 2 strings instead. Similarly the last part is concatenated to the first two parts and ends up generating the url you require.
The reason why your method wasn't working was that you were trying to pass a variable {{i.index_ticker}} to a string. This was creating a url that literally contains a formatterd version of {{i.index_ticker}}. Which is why you were probably getting %7B%7Bi.index_ticker%7D%7D in the url.
Comment: That worked. The links now show the associated image for each ticker. Thank you.
Comment: Great! If you could mark the answer as accepted, that would help me out


Help Evaluating $\int\left(xf'(3x^2)\right)dx$

Question: Does anyone know how to evaluate the following integral?
$\int\left(xf'(3x^2)\right)dx$
The answer is  $\frac16 f(3x^2) + C $ , but I want to see a step by step solution if possible.
Comment: Multiply the given integral by $6$ inside and by $\frac 1 6$ outside. Then recognize something that looks like $\int g'\cdot(h'\circ g)$.
Answer: setting $t=3x^2$ we get $dx=\frac{1}{6x}dt$ thus we have $\frac{1}{6}\int f'(t)dt$
Answer: Think about formula $(u(v(x)))'=v'(x)u(v(x))$
if the formula can be used here then $v(x)=3x^2$ so compute the derivative:
$v'(x)=6x$ and the result follows since $xf(3x^2)=\dfrac{1}{6} (6xf(3x^2))$


How to set channel object using the channel id in discord.py?

Question: Hello guys I'm trying to make a function that checks if few channels in the my discord server are full but I didn't know how to specify them.
The best idea I had was using the idea but couldn't set it to a channel object so how can I do that or is there any other good ideas?
def full(channel):
   while True:
       if len(channel.voice_members) == channel.user_limit:
           print("Wooo There is a full channel.")
       asyncio.sleep(10)

But I didn't know what to set the channel parameter.
Thanks in advance for your help.
Answer: You can get the channel object either by ID or by name.
Use discord.utils.get() to return a channel by its name (example for voice channels):
channel = discord.utils.get(server.channels, name="Channel_name_here", type="ChannelType.voice")

Or you can use discord.get_channel(id) if you have the ID of the channel.
So for example if you have a list of channel names you want to check:
channel_names = ['channel1', 'channel2', 'channel3']
for ch in channel_names:
    channel = discord.utils.get(server.channels, name=ch, type="ChannelType.voice")
    full(channel)

See more in the documentation:
discord.get_channel()
discord.utils.get()
Answer: If you want this to be a command, you can also take advantage of converters:
@bot.command(pass_context=True)
async def full(ctx, channel: discord.Channel):
    if len(channel.voice_members) == channel.user_limit:
        await bot.say("{} is full".format(channel.name))
    else:
        await bot.say("{} is not full".format(channel.name))


Evitar salvar dados duplicados

Question: Em meu projeto tenho uma regra que é não salvar e não mostrar no Grid dados duplicados. Por exemplo, no sistema eu faço a leitura de um XML e salvo as informações das tags numa tabela do meu banco de dados para que essas informações seja mostradas em um Grid.
Só que toda vez que eu faço essa leitura, salva-se duas vezes os dados. Digo, se eu já li uma vez e já foi salvo, por exemplo, o nome 'João' nessa primeira leitura, se eu ler de novo o XML, o nome é salvo outra vez, e assim por diante, quantas vezes eu ler o XML.
Ai eu fiz uma lógica para que não mostrasse no Grid esses dados duplicados, que é essa:
if (Convert.ToString(GetValueOrDefault(elmCertidao.Element("nome_tag_1"))) == objeto.Propriedades["Coluna1"].Valor &&
                                    Convert.ToString(GetValueOrDefault(elmCertidao.Element("nome_tag_2"))) == objeto.Propriedades["Coluna2"].Valor &&
                                    Convert.ToString(GetValueOrDefault(elmCertidao.Element("nome_tag_3"))) == objeto.Propriedades["Coluna3"].Valor)
                                    continue;

Ou seja, se acaso houver dados nessas tags que já estejam no Grid, esses dados não são mostrados...
Até aqui beleza, mas acontece que os dados duplicados são salvos na tabela do banco, e não é isso que quero.
Quero que não mostre no Grid e nem salve dados duplicados.
Essa pergunta aqui do SOpt me de uma ideia do que fazer. Mas se eu colocar os campos como Unique, toda vez que eu ler o XML, e for verificado a inconsistência, vai dar erro no SQL Server falando que o dados já existe.
Existe alguma forma que eu faça essa verificação e não mostre erro, nem do SQL Server nem no C# ? Ou seja, salvando somente uma vez o dado ?
Comment: Qual a razão de ler mais de uma vez o *xml*?
Comment: Porque no `XML` podem conter uma tag que agrupe registros e ela se repete. Tipo uma NF-e(Aqui no Brasil). Ela tem uma tag que agrupa várias outras com registros, e essa tag que agrupa se repete várias vezes. E se caso eu precisar ler esse XML mais de uma vez, não quero salvar dados que já foram salvos.
Comment: Para evitar repetições utilize *Unique*. Antes de gravar faça uma leitura para verificar se o registo já existe ou então grave e faça o *catch* do erro. Se a possibilidade de haver repetições for grande use a primeira, caso seja pequena use a segunda.
Comment: Existe alguma forma de fazer isso via c# e sem mostrar erro ? Ou somente dessa forma ?
Comment: Ambas as formas é via C# e nenhuma mostra o erro.
Comment: Teria como colocar em uma resposta um exemplo ?
Comment: Você coloca os dados lidos do *xml* em alguma *collection* antes de gravar no banco?
Comment: Eu populo em um objeto que representa minha tabela no banco, mostro os dados no *Grid* e depois salvo no banco.
Comment: Esse objecto é uma `List` onde T representa um registo da tabela?
Comment: Exatamente isso! Mas caso dê pra fazer de uma forma genérica, eu adapto a minha realidade.
Comment: Para lhe dar uma resposta necessito saber qual é a propriedade da sua classe que tem de ser única.
Comment: A Coluna1, Coluna2 e Coluna3 que estão lá no if. Ou seja, nome da pessoa, nome do pai e nome da mãe.
Comment: @ÉrikThiago, acho que você deveria tratar no momento de gravar. Uma simples rotina de verificação para saber se existe ou não no BD e aí soltar a rotina de gravação ou não. Conforme disse o ramaral.
Comment: @pnet você teria um exemplo de código que faz esse tipo de rotina?
Answer: Se os dados lidos do xml são guardados numa List<T> antes de serem gravados no banco então elimine os duplicados da lista antes de gravar.
Uma forma simples de o fazer é usar o método IQueryable.Distinct.
Para que esse método possa distinguir o que é uma linha duplicada a sua classe terá de implementar a interface IEquatable<T>:
public class SuaClasse : IEquatable<SuaClasse>
{

    //Suas Propriedades
    public string Nome { get; set; }
    public string NomePai { get; set; }
    public string NomeMae { get; set; }
    ....
    .....
    //Seus Métodos
    ....
    ....

    //Implementação da Interface
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        SuaClasse objAs = obj as SuaClasse;
        if (objAs == null) return false;
        else return Equals(objAs);
    }

    public override int GetHashCode()
    {
        return Nome.GetHashCode() ^ NomePai.GetHashCode() ^ NomeMae.GetHashCode();
    }

    public bool Equals(SuaClasse other)
    {
        if(other == null)return false;
        return Nome.Equals(other.Nome) &&
               NomePai.Equals(other.NomePai) &&
               NomeMae.Equals(other.NomeMae);
    }
}

Para obter a lista sem duplicados use:
var ListaSemDuplicados = suaLista.Distinct().ToList();

Use ListaSemDuplicados para popular a Grid e para salvar no banco.
Comment: Bem, acho que o ramaral já respondeu.

Evitar salvar dados duplicados


How much is the fine for arguing with an umpire?

Question:
How much is a player fined for arguing with an Umpire? I have heard that it is a percentage of their match fees.
Are fines for captains different for such cases?
Do umpires register allegations against players for arguing with them or does some authority decide?
Answer: The exact amount depends on which category of violation defined under the ICC Code of Conduct the offence made by the offender falls . It is decided by the Match Referee and he presents his report about the incident after the end of each match to the ICC officials .  ICC Rule Book  here.
Excerpts:

Any one of the following individuals can report an alleged offence
  under the Code of Conduct (other than Minimum Over Rate Offences - as
  to which see Appendix 2) by lodging a report in the manner described
  in Article 3.2, below (a 'Report'):
3.1.1 an Umpire that officiated in the International Match during which the alleged offence was committed;
3.1.2 the Team Manager or CEO of either of the two National Cricket Federations whose representative teams participated in the
  International Match during, or in relation to which, the alleged
  offence was committed;
3.1.3 the ICC's Chief Executive Officer; or
3.1.4 provided it is a Level 3 Offence or Level 4 Offence that is alleged to have been committed, the Match Referee that was appointed
  to officiate in the International Match during which the alleged
  offence was committed. (For the avoidance of any doubt, the Match
  Referee is not entitled to lodge a Report in relation to an alleged
  Level 1 Offence or Level 2 Offence).`
Comment: Exact documentation is under Chapter 13 of ICC Rule Book : http://static.icc-cricket.com/ugc/documents/DOC_700263D0BC21E1C8159D6ECA28249DBB_1298463333670_479.pdf
Comment: ok what is the link for that is there any link where i can read it
Comment: I wrote from whatever I had compiled from various commentaries in this subject . You can follow this link for more :http://www.livestrong.com/article/92407-rules-cricket/
Comment: @NoobUnChained What information from either link is relevant to answering the OPs question?
Comment: `I wrote from whatever I had compiled from various oral commentaries in this subject` .
Comment: @NoobUnChained What `from various oral commentaries in this subject` is helpful in answering the OPs question?
Comment: @NoobUnChained In other words, what are the categories of violations in regards to arguing with an umpire? Where in the ICC Rule Book does it give the Match Referee said power?
Answer: There are four levels of offences - level 1, level 2, level 3 and level 4. Level one is for a lesser crime whereas level four is the most serious one.
Arguing with an umpire about a decision can fall under level 1 or 2 depending on how aggressive or offensive the player is. Intimidation or assaulting the umpire falls under level 3 and 4. At the end of the match, the umpires file a report under which all these offences are documented. The match referee, on reading this report, sends a notification to the said player(s) and a disciplinary meeting is called where appropriate action (warning/fine/suspension) is taken against the player.
Based on the frequency (over a 12 month period) and offence level, the fines vary. The fine-list can be found in Article 7.3 of the ICC Code of Conduct for players.


AZURE_FUNCTIONS_ENVIRONMENT vs ASPNETCORE_ENVIRONMENT

Question: In azure functions (v2, c#), there are two environment variables that can be potentially used to identify the name of the current environment.

AZURE_FUNCTIONS_ENVIRONMENT
ASPNETCORE_ENVIRONMENT

I am planning to use AZURE_FUNCTIONS_ENVIRONMENT, and I am wondering if there are reasons to choose one over another?
In terms of behavior of the two, this is what I discovered:

AZURE_FUNCTIONS_ENVIRONMENT is set to Development locally by the functions host/runtime. It is not automatically set in azure to Production. One can set this in App Settings in azure.
ASPNETCORE_ENVIRONMENT is not set by the functions host/runtime either locally or in Azure.

I have also raised a github issue about this a couple of weeks ago, but got no response. I am hoping I might get an answer here.
Comment: Answered on GitHub.
Answer: Adding the official answer from github issue here for everyone's benefit:

You'll want to use AZURE_FUNCTIONS_ENVIRONMENT. The Functions
  runtime that powers a Function app on Azure is the WebHost project in
  this repo. As the host is initializing, it looks for the
  AZURE_FUNCTIONS_ENVIRONMENT app setting (as
  EnvironmentSettingNames.EnvironmentNameKey) and passes it to the
  IWebHostBuilder.
  Using only ASPNETCORE_ENVIRONMENT can lead to desired behavior
  changes and telemetry being missed.
Comment: Be aware that there are some quirks with this. See https://github.com/Azure/azure-functions-host/issues/6239 more more info
Answer: ASPNETCORE_ENVIRONMENT is the default environment-variable to determine the environment for IHostingEnvironment. IHostingEnvironment has current two implementations. One can be found here and is only supposed to be used internally. The other can be found here.
The exact idea on why there is AZURE_FUNCTIONS_ENVIRONMENT I cannot tell. I would suggest you to stick to IHostingEnvironment for ASP.NET Core applications. The version of IHostingEnvironment will be replaced with IWebHostEnvironment in the future. With the release of 3.0 they will continue to support both until the remove it. It will be marked as obsolete.
In your functions you can always set custom variables and just access them via Environment.GetEnvironmentVariable("MY-VAR").


NavigationController Back Skip View

Question: First off, I am aware of this question being asked in a forward manner, but in this case I am asking for a backwards manner in which the Navigation Controller is already designed. With that being said...
I have a UINavigationController with three views: Table, Get, and Avail in that order that was created in IB.
When going forward, I want to go from Table to Get to Avail, but when I hit the "Back" button on Avail I want to skip over Get and go directly back to Table. Is this possible? If so, how?
Answer: Here's how I did it:
NSArray *VCs = [self.navigationController viewControllers];
[self.navigationController popToViewController:[VCs objectAtIndex:([VCs count] - 2)] animated:YES];

To be able to override the nav controllers's back button you're going to have to subclass UINavigationController. Check out how in this tutorial: http://www.hanspinckaers.com/custom-action-on-back-button-uinavigationcontroller
Comment: then suddenly someone (or even you) updates your project and remove or add new VCs into navigation controller stack. And your code will not work (in the best case). Magic numbers is always evil.
Answer: Implement the navigation controller's delegate method:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated

It will fire for all VCs in the nav controller stack. (put this code in the VC immediately after your navigation controller, and put < UINavigationControllerDelegate > in the .h)
What you want to do is replace the entire Navigation Controller's stack without the view controller you want to remove in it. Since it's a non-mutable array, you have to convert it to a mutable array before removing the VC, remove the VC, then replace the navigation controller's stack with the call [self.navigationController setViewControllers:newVCs animated:NO];. That's the crucial part. You are replacing the stack after you have loaded the page you are on but since you're keeping the VC you're on, it's still the top item on the stack so there is no visible impact to the user. As long as you don't have a lot of VCs on the stack, it's not an expensive call.
Here's how I did it in the delegate method:
//Remove list setup page if new list was created
if ([self.navigationController topViewController].class == [ItemViewController class])
{
    NSArray *VCs = [self.navigationController viewControllers];

    if(((UITableViewController*)[VCs objectAtIndex:[VCs count]-2]).class == [NewCardTypeController class])
    {
        NewCardTypeController *removedObject = [VCs objectAtIndex:[VCs count]-2];
        if(removedObject != nil)
        {
            NSMutableArray *newArray = [NSMutableArray arrayWithArray:VCs];
            [newArray removeObject:removedObject];
            NSArray *newVCs = [NSArray arrayWithArray:newArray];
            [self.navigationController setViewControllers:newVCs animated:NO];
        }
    }
}

Comment: By the way, what this does that the other answers will not do is preserve the correct navigation bar sequence and ensure that your back button will have the correct animation behavior on transition since you are not overriding it.
Answer: Take a look at UINavigationController's -popToViewController:animated: and -popToRootViewControllerAnimated:, which do exactly what you're asking for. That is, they pop the navigation stack back to a particular view controller, or to the root view controller. You'll still need to intercept the nav controller's back button action to use them, though.

NavigationController Back Skip View


Dummy Variable, Reference Group

Question: My job is to create a dummy variable so that those who voted for the Labour Party are compared to a single reference group that includes all other voters.
1 = Conservative, 2 = Labour, 3 = Liberal Democrat, 4 = SNP, 5 = Plaid Cymru, 6 = Green Party, 7 = UKIP, 8 = BNP, 9 = Other
In this situation, would the reference group include {1, 3, 4, 5, 6, 7, 8, 9}
So, the dummy variable would be:

{2} -- > 1 (is Labour)
{1, 3, 4, 5, 6, 7, 8, 9} -- > 0 (is not Labour)

Have I taken the right approach here? I am slightly confused because the reference group in this situation is included in the dummy variable. Usually, the reference group is not included because it is already assumed in the model.
Answer: That looks correct. You would then want to include your dummy variable in a regression with a constant. Alternatively, you could create 2 dummy variables:

DLabor=1 if group=2, else DLabor=0
DOther=1 if group not equal to 2, else DOther=0

and then include the 2 dummy variables (DLabor and DOther) in a regression without a constant.

Dummy Variable, Reference Group


Contextual links don't display in a floated custom region

Question: I created two custom regions in my Drupal 7 theme and used CSS to float them side-by-side (to create columns). That worked fine, and I'm able to place blocks in the regions, but the contextual links don't display.
I tested them without the float, and the contextual links are right where they should be, leading me to believe that it's the float positioning that's causing the problem.
This isn't too big a deal, since I can go to Structure --> Blocks to administer them, but the contextual links are handy, and besides, it's bugging me and I want to figure it out. Any suggestions?
Comment: This seems to be related to positioning of contextual link region. In Firefox, Position:relative on contextual-link-region seems to be causing this. If Position:relative is disabled using Firebug links work once again, but contextual links do not.
Answer: Try to add an "overflow:hidden;" to the wrapper of both the content and the contextual links to force it to fill the dimensions of its children. Either that or add a clear as a sibling of the elements. What's probably happening is the wrapper is being rendered to 0 height.
Answer: Right click, shift click, double finger tap, or do whatever you need to bring up INSPECT ELEMENT in your browser and look around your page until you find the contextual links and then look at what CSS is no longer working with them with float.  They are most probably still there, just hidden from plain view.
Comment: I can see them in Firebug, and they're in the right place (within the HTML for the block), but they don't display. I tried changing the z-index of the contextual links wrapper, but that made no difference. None of the CSS is being overridden. "They are most probably still there, just hidden from plain view" is true, but I'm going to have to keep working on this.


Can I format a PSObject as a table with one row per property?

Question: I'm using a simple PSObject:
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name A -Value 'x'
$obj | Add-Member -MemberType NoteProperty -Name B -Value 'y'

I can format this as a table by simply writing $obj, or also by writing Write-Host ($obj | Out-String):
A B
- -
x y

However, there now is one column per property rather than one row per property. That is, I want to have this output:
A : x
B : y

I have found resources that claim that's what will happen (e.g. this tutorial), but it's not what happens when I try it.
What am I doing wrong?

To clarify my concern: If the property values become longer, the default formatting quickly gets "ugly", or even hard to read:
> $obj = New-Object -TypeName psobject
> $obj | Add-Member -MemberType NoteProperty -Name A -Value > 'https://abcdef/ghijkl/mnopqr/stuvwx?y=z'
> $obj | Add-Member -MemberType NoteProperty -Name B -Value 'https://abcdef/ghijkl/mnopqr/stuvwx?y=z'

> $obj

A                                       B
-                                       -
https://abcdef/ghijkl/mnopqr/stuvwx?y=z https://abcdef/ghijkl/mnopqr/stuvwx?y=z

Comment: Sounds like you want `Format-List`
Comment: What would be the expected output when, let's say, you get hundreds of members in the object ? Most likely nor readable if transposed like you wish.
Comment: @Civette: Uh, why? If there is one row per member (the formatting I want to get), I don't see a problem. It's rather that if there is one _column_ per member (the formatting I actually see), hundreds of members in the object will pose a problem, wouldn't you say? In the formatting as it is, I'm already expecting problems if there are just _two_ members in the object, but each of them contains a longer string than these one-letter-examples I showed above.
Answer: First, I suggest to create the object using
$obj = [pscustomobject]@{
    A = 'https://abcdef/ghijkl/mnopqr/stuvwx?y=z'
    B = 'https://abcdef/ghijkl/mnopqr/stuvwx?y=z'
}

Much easier to write, read and understand.
Second: calling the object will cause Powershell to automagically decide what's the best way to show it to you. Which is based on the number of properties, basically.
it's a DISPLAY issue: the best way to deal with this it tell Powershell "show me this stuff as a list" piping the object to Format-List:
PS > $obj | Format-List

A : https://abcdef/ghijkl/mnopqr/stuvwx?y=z
B : https://abcdef/ghijkl/mnopqr/stuvwx?y=z

(note: Format-Table does the opposite, telling Powershell to display the output as a table)
To actually force Powershell to always use the List format you'd need a Class.
Comment: oh, absolutely you did right. I was saying that now you have a NEW question, which, I'm told, would mean opening a new topic. And You can just apply the coloring to the whole thing instead of just one part. Otherwise, to my knowledge, a Class is the only way out.
Comment: It kind of works when I just write `$obj` like you did here. Unfortunately, if I use it in `Write-Host` (i.e. as `Write-Host ($obj | Format-List)`, the output is `Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData` ... anything do remedy that?
Comment: Sure: do not do that. Looks like a joke but it's not: Write-Host is not meant to be used.
Let's go back: what you want to do, exactly?
Comment: Output an object, nicely formatted (as happens with your solution), optionally with a different foregound and/or background color (as is possible with `Write-Host` ).
Comment: That's a different question and you should make a new thread for it. Except it would be marked as "Duplicate", so have a freebie.
  https://stackoverflow.com/questions/20705102/how-to-colorise-powershell-output-of-format-table/49038815   It works with `format-list` as well
Comment: First, I was asking about a way to _format_ an object - which I'd have been happy to use with `Write-Host`, which also allows me to apply a color. I did not exactly ask for a _replacement_ of `Write-Host` that gives me proper formatting at the expense of the coloration capability, so there was no way to know up-front this is a different question. I'll consider asking a separate question. Second, thank you for the link, but that other question asks for more than I do; they want to color individual parts of the formatted output, whereas I just want to apply one color to the entire thing.


Optaplanner : Initializing planning variable problem

Question: I am new to Optaplanner and to get familiar with it I tried to run a simple code.
The idea is I have one single planning variable of type integer, that has a range between 1 and 30, that I try to maximize. So normally the solver should give me a value of 30.
My code is as follows :
Planning entity and planning variable :
@PlanningEntity
public class variable {

    @PlanningVariable(valueRangeProviderRefs = "xRange")
    private Integer x;

    public variable() {

    }

    public Integer getX() {
        return x;
    }

    public void setX(Integer x) {
        this.x = x;
    }

}

Planning solution
@PlanningSolution
public class Planningsolution {
@PlanningEntityProperty
private variable variable;

@ValueRangeProvider(id="xRange")
public CountableValueRange<Integer> getxRange(){
    return ValueRangeFactory.createIntValueRange(1, 30);
}

@PlanningScore
private HardSoftScore score;

public Planningsolution() {

}

public variable getVariable() {
    return variable;
}

public void setVariable(variable variable) {
    this.variable = variable;
}

public HardSoftScore getScore() {
    return score;
}

public void setScore(HardSoftScore score) {
    this.score = score;
}

}
Constraint Provider
public class SimpleConstraintProvider implements ConstraintProvider {

     @Override
        public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
            return new Constraint[] {
                    // Hard constraints
                    maxValue(constraintFactory),

            };
     }

         private Constraint maxValue (ConstraintFactory constraintFactory) {

                return constraintFactory.forEach(variable.class)
                        .reward("maximum", HardSoftScore.ONE_SOFT,variable::getX);
                    }
}

Main :
public class SimpleApp {

     private static final Logger LOGGER = LoggerFactory.getLogger(SimpleApp.class);

        public static void main(String[] args) {
            SolverFactory<Planningsolution> solverFactory = SolverFactory.create(new SolverConfig()
                    .withSolutionClass(Planningsolution.class)
                    .withEntityClasses(variable.class)
                    .withConstraintProviderClass(SimpleConstraintProvider.class)

                    .withTerminationSpentLimit(Duration.ofSeconds(10)));

            // Load the problem
            Planningsolution problem = new Planningsolution();

            // Solve the problem
            Solver<Planningsolution> solver = solverFactory.buildSolver();
            Planningsolution solution = solver.solve(problem);

            // Visualize the solution
           System.out.println("solution: " + display(solution) + "\n" + "score: " + solution.getScore());;
        }

        public static Integer display(Planningsolution solution) {
            variable var = new variable();
            return var.getX();
        }
}

logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="appender" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d [%t] %-5p %m%n</pattern>
    </encoder>
  </appender>

  <logger name="org.optaplanner" level="info"/>

  <root level="warn">
    <appender-ref ref="appender"/>
  </root>

</configuration>

The output i get is :

solution: null
score: 0hard/0soft
Answer: In order for planning variables to be initializable, they must be able to accept null as a value. Java primitive types (such as int) are not capable of doing that, therefore your planning variable needs to be an Integer. The error message even tells you to do that, although the wording is a bit cryptic.
As a side note, I think we should be able to handle this situation better. If people don't want null in there, we should not force them. Something to consider for future development.
Comment: Thank you, this indeed fixes my initialization problem. I did run the program and it returns a value 'null'. Which means that the solver did not solve the problem (Even the score show 0hard/0soft).  What should I do in this situation ?
Comment: Please update your question with the latest code and include output of the program.
Comment: When I say outptut, I mean the logging output; not the solution, the actual system output. To understand, what the solver did or did not do, I'll need to see the scroll.
Comment: Well I didn't get any log, maybe because the solver didn't run ?? Either way, when I run the program all I get as an output is the solution. (I updated the question with the logback.xml I used)
Comment: In that case, please share the code that you used to run OptaPlanner. Because what you're describing here really sounds like you did not run it.
Comment: The code I used to run OptaPlanner is the one in the main method (public class SimpleApp {

        public static void main(String[] args) { ....). I have put my project in this github link  : https://github.com/usumake1/testing-optaplanner
Comment: Basically I got inspired by the timetable example, I wrote the code and it run perfectly. then I wanted to see if I can run a simple code from scratch. Which resulted in the code above.
Comment: Hello, I got the logging output :
2022-08-27 10:27:43,964 [main] INFO  Solving started: time spent (100), best score (0hard/0soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).
2022-08-27 10:27:43,975 [main] INFO  Skipped all phases (2): out of 0 planning entities, none are movable (non-pinned).
2022-08-27 10:27:43,983 [main] INFO  Solving ended: time spent (113), best score (0hard/0soft), score calculation speed (8/sec), phase total (2), environment mode (REPRODUCIBLE), move thread count (NONE).
Comment: That should already tell you what the issue is. Your problem seems to have no entities. In fact, looking at your SimpleApp, you never assign any value to the single entity field. Therefore there is nothing for OptaPlanner to do.
Comment: Thank you, it was looking at me the whole time. It's running fine now.


How to programmatically add / remove a value for an unlimited multivalue field?

Question: I was looking at http://php.net/manual/en/function.array-push.php but it seems one cannot use it as multi value fields are associate arrays. Any built in functions perhaps?
Here is an example array

$myfield["und"][0]["value"] = 23424;
$myfield["und"][1]["value"] = 76786;
Answer: You can use the entity_metadata_wrapper() function with entities (you'll find good examples here); it makes things a bit cleaner, but not that much.
Other than that, no - you're stuck using vanilla PHP for this, Drupal doesn't have any built in functions to help.
There's no reason you can't use array_push as normal though:
array_push($myfield[LANGUAGE_NONE], array('value' => 23424));

Although that's actually more verbose and less readable than the original.


Help needed for proof of finitely generated Abelian group isomorphism

Question: I am looking at the following proof (taken from here):

Corollary 5
  Let $A$ be a finitely generated abelian group.
  Then there is a finite subgroup $A_0$ of $A$ and an integer $m \geq 0$ such that $A \cong A_0 \times \mathbb{Z}^m$.
Proof.
  We know that $A \cong \mathbb{Z}^n/K$ for some integer $n \geq 0$ and some subgroup $K \subset \mathbb{Z}^n$, where $K$ is a free abelian group of rank $r \leq n$.
  If $r = n$ then we know from Lemma 23 that $A$ is finite, so we can take $A_0 = A$.
  Otherwise we know - also from Lemma 23 - that there exists a surjective homomorphism $f \colon A \to \mathbb{Z}$.
  Composing $f$ with the surjective quotient map $\mathbb{Z}^n \to A$, we also get a surjective homomorphism $\phi \colon \mathbb{Z}^n \to \mathbb{Z}$.
  By the last Lemma, $A \cong \ker(f) \times \mathbb{Z}$, and similarly $\mathbb{Z}^n \cong \ker(\phi) \times \mathbb{Z}$.
  Since we also know that $\ker(\phi) \subset \mathbb{Z}^n$ is free abelian of rank $t \leq n$, it follows that $t = n - 1$.
  Also $\ker(f) \cong \ker(\phi)/K$.
  By induction on $n - r$, we may assume that $\ker(f) \cong A_0 \times \mathbb{Z}^{n-1-r}$ for some finite subgroup $A_0$, and hence $A \cong \ker(f) \times \mathbb{Z} \cong A_0 \times \mathbb{Z}^{n-r}$.

It says:

By induction on $n-r$, we may assume that $\ker(f) \cong A_0×\mathbb{Z}^{n−1−r}$ for some finite subgroup $A_0$ […].

I find this assumption troubling, because, then for any $n-r$ we can infer:
$$
        \ker(f)
  \cong \ker(\phi)/K
  \cong \mathbb{Z}^{n-1}/\mathbb{Z}^r
  \cong \mathbb{Z}^{n-1-r}
$$
leaving
$$
        \ker(f)
  \cong A_0 \times \mathbb{Z}^{n−1−r}
  \cong \mathbb{Z}^{n-1-r},
$$
so $A_0=\{0\}$ all the time! I feel like this is not really a meaningful result so I must be overlooking something. Can you show me a case when $A_0$ is not the trivial set?
Comment: Yes, consider the group $\mathbb{Z}/2\mathbb{Z}\times \mathbb{Z}$ with $A_0=\mathbb{Z}/2\mathbb{Z}\neq 0$. It is certainly a finitely generated abelian group. Do you see your error? For "some" finite subgroup $A_0$.
Comment: A cleaner proof follows from two facts: a finitely generated torsion-free abelian group is free, and if $A$ is abelian f.g. , then it projects to a finitely generated torsion free abelian group, $A/\tau(A)$.
Answer: It is true that $K\cong \mathbb{Z}^r$ and $\ker(\phi)\cong\mathbb{Z}^{n-1}$, but you cannot conclude from this that $K/\ker(\phi)\cong\mathbb{Z}^{n-1-r}$.  For instance, for $r=1$ and $n=2$ you might have $K=\mathbb{Z}$ and $\ker(\phi)=2\mathbb{Z}\cong\mathbb{Z}$, but the quotient $\mathbb{Z}/2\mathbb{Z}$ is not isomorphic to $\mathbb{Z}^{n-1-r}=0$.  More generally, if $A\subseteq B$ and $C\subseteq D$ with $A\cong C$ and $B\cong D$, that does not imply $B/A\cong D/C$.
(Indeed, if your reasoning were correct, you could just conclude from the beginning that $A=\mathbb{Z}^n/K\cong\mathbb{Z}^n/\mathbb{Z}^r\cong\mathbb{Z}^{n-r}$.)
Comment: That just comes from the definition of $f$ and $\phi$.  By definition, $f:A\to\mathbb{Z}$ and $\phi$ is the composition of $f$ with the surjection $g:\mathbb{Z}^n\to A$ with kernel $K$.  The map $g$ restricts to a surjection $h:\ker(\phi)\to \ker(f)$, since $\phi(x)=f(g(x))$ so $x\in\ker(\phi)$ iff $g(x)\in\ker(f)$.  The kernel of $h$ is just $K\cap\ker(\phi)$, so $\ker(f)\cong \ker(\phi)/(K\cap\ker(\phi))$.  But $K\subseteq\ker(\phi)$ since $\phi(x)=f(g(x))=f(0)=0$ for any $x\in K$, so $K\cap \ker(\phi)$ is just $K$.
Comment: The base case is $r=n$, in which case you know $A$ is finite as noted at the beginning of the proof and then you don't construct $f$ at all.  So in the case $r=n-1$, you already know by induction that $\ker(f)$ is finite.
Comment: Thanks, this makes sense. With this cleared up however, I'm uncertain about another part of the proof; namely how does $ker(f)≅ker(ϕ)/K$ come about?
Previously I thought that: $ker(f)×ℤ≅A≅ℤ^n/K≅(ker(ϕ)×ℤ)/K$
Is this correct? If yes, why are we allowed to get rid of $ℤ$ on both sides and obtain $ker(f)≅ker(ϕ)/K$?
Comment: That was very useful too, I think I got it. I still don't understand the inductive step by the end of the original proof though: $\ker(f) \cong A_0 \times \mathbb{Z}^{n-1-r}$ so $A \cong \ker(f) \times \mathbb{Z} \cong A_0 \times \mathbb{Z}^{n-r}$.
If we are using induction here, then this should work for the base case which I think is $r=n-1$ so:
$\ker(f) \cong A_0 \times \mathbb{Z}^{0}$ => $A \cong \ker(f) \times \mathbb{Z} \cong A_0 \times \mathbb{Z}^{1} \cong \mathbb{Z}^{n}/K$
Why is this true?


Equivalence of countable choice for subsets of the reals and "second countable $\implies$ Lindelöf"

Question: Looking for a proof that in a second countable space every open cover has a countable subcover -- i.e. every s.c. space is a Lindelöf space -- I bumped into this question. That answered my question. I then left a couple of comments on both the then present answers (which are, to this date, the only ones) and received this reply, stating the axiom of countable choice for subsets of the reals is actually equivalent to every s.c. space being Lindelöf. Now it seems incredible that a special case of the axiom of countable choice, which in its general form states any countable collection of sets has a choice function, so for all countable collection of sets $A_n$ there is a function associating to each set an element of that set, provided of course the sets are non-empty, and in its particular form says so for sets which are subsets of the reals, be equivalent to s.c. implies Lindelöf. At most, I would expect the general form to be equivalent to that, since that s.c. implies Lindelöf is proven with a form of countable choice. So how can it be proved that the two results are equivalent?
Comment: @Eric: You can find this long lit of equivalences as Theorem 4.54 in Herrlich "The Axiom of Choice". I don't remember the name of the original paper, I think "disasters in topology without choice" or something similar.
Comment: It sounds to me like you've interpreted Brian's comment as something like CC($\Bbb R$) $\Rightarrow$ (SC$\to$L)($X$) for any topological space $X$, but it seems to me that he intended the more believable CC($\Bbb R$) $\Rightarrow$ (SC$\to$L)($\Bbb R$).
Comment: Well the comment says «I just checked: $\mathsf{}(\mathbb{R})$ is equivalent to every second countable space being Lindelöf.», so how do you read it that way?
Comment: I mean, let's break that down: $\mathsf{CC}(\mathbb{R})$ (subject) is equivalent to (predicate, in symbols $\iff$), every second countable space being Lindelöf (indirect object, which sounds terribly like $(\mathsf{SC}\implies\mathsf{L})(X)$ for any topological space $X$). What am I missing? @BrianMScott am I reading you right?
Comment: Ah, I missed "every".
Answer: This is not that incredible if you understand what's going on.
Given a second-countable space $X$, fix a countable basis $\{U_n\mid n\in\Bbb N\}$. Now you can observe that every open set is uniquely determined by the basis elements it contains, namely the function $U\mapsto\{n\in\Bbb N\mid U_n\subseteq U\}$ is an injective function. And since the real numbers can be thought of as subsets of $\Bbb N$, this is an injective function from the topology of $X$ into $\Bbb R$.
So if we are given an open covering, $\{V_i\mid i\in I\}$ we may assume that $|I|\leq|\Bbb R|$ by the above consideration, and for each $n\in\Bbb N$ we can look at the set $A_n=\{V_i\mid U_n\subseteq V_i\}$.
Not every $A_n$ is non-empty, but at least one of them is, of course. By the translation between open sets and real numbers, this is reduced to a countable family of sets of reals. Using $\sf AC_\omega(\Bbb R)$ we can choose from each non-empty $A_n$, and we can prove that this is a countable subcover by noting that $\{U_n\mid A_n\neq\varnothing\}$ is an open cover as well.

On the other hand, if $\{A_n\mid n\in\Bbb N\}$ is a family of pairwise disjoint sets of reals without a choice function. We may assume that each $A_n$ is a subset of $[n,n+1)$ by using canonical bijections of $[\inf A_n,\sup A_n+1)$ and $[n,n+1)$.
Now consider the open covering of $\Bbb R$ defined by $\{(-r,r)\mid\exists n: r\in A_n\}$. Since the $A_n$'s grow arbitrarily large this is an open covering indeed, so by the assumption it has a countable subcover, which gives for each $A_n$ a countable subset, so by diluting this subcover we may assume that each $A_n$ gives at most a single real number.
And therefore we found a partial choice function for the $A_n$'s. Now it is enough to show that it is indeed enough to consider partial choice functions.
Indeed recall that $\Bbb R^{<\omega}$, the finite sequences of real numbers have the same cardinality as $\Bbb R$ itself. Given a sequence of sets $X_n$ which are non-empty, consider $A_n=\prod_{k\leq n}X_n$, then the $A_n$'s are non-empty sets of finite sequences of real numbers, so by uniform encoding we may assume these are sets of real numbers. If $I\subseteq\Bbb N$ is infinite and $\sigma$ is a function choosing from $\{A_i\mid i\in I\}$, then it defines a choice function from the $X_n$ by looking at $i=\min\{j\in I\mid j>n\}$ and looking at $\sigma(i)(n)$ (recall that $\sigma(i)$ is a choice function which is defined on $X_n$).
Comment: @Mick: I've added the needed part. It's a bit half-assed, but if you need more details let me know.
Comment: @bof: Thanks for pointing out the missing piece.
Comment: So the subcover gives a countable subset of the reals for each $A_n$ by considering $\{r:r\in A_n,(-r,r)\in\text{subcover}\}$, right? What do you mean by «by diluting this subcover»? What is a partial choice function?
Comment: @Mick: No, each $A_n$ is bounded so this set cannot possibly cover $\Bbb R$, but if you take the union over all the $A_n$'s you get a cover (because they live in arbitrarily large $[n,n+1)$ intervals). Then you get a sequence of reals, so pick for each $A_n$ the real with the least index of the countable subcover that appears in $A_n$, if there is such real, there might not be one. But since no single $A_n$ produces a cover, this ensure that we will meet $A_n$ for arbitrarily large $n$, and this gives a choice function for an infinite subset of the $A_n$'s. Hence partial choice.
Comment: OK so let me get this straight. You said we consider the cover of $\mathbb{R}$ formed by the $(-r,r)$ such that $r\in A_n$ for some $n$. I agree it's a cover because the $A_n$'s grow arbitrarily large, since we have assumed WLOG $A_n\subseteq[n,n+1)$. So that is a cover. We assumed a second-countable space is Lindelöf and $\mathbb{R}$ is Lindelöf, thus this cover admits a countable subcover $\{(-r_k,r_k)\}$ for $k\in\mathbb{N}$. I was suggesting we could associate $A_n$ with the set of all $r_k\in A_n$. This maps the subsets $A_n$ to countable subsets. That was my guess to see how the finite …
Comment: … subcover «gives for each $A_n$ a countable subset», as you said. Then you said «by diluting the subcover». Now I can guess this means we only take the $r_k$ with the property that for some $n\in\mathbb{N}$, $k$ is the least integer for which $r_k\in A_n$. Right?
Comment: @Mick: Exactly. And this gives a partial choice, since perhaps we didn't pick any $r_k$ from all the even indexed $A_n$'s?
Comment: Your comment says «this set cannot possibly cover $\mathbb{R}$»: what set? The set $\{r:r\in A_n,(-r,r)\in\text{subcover}\}$? Why would I want it to cover $\mathbb{R}$?
Comment: Ah I see. That's why partial. The countable subcover extraction can prevent us from finding a nonempty set for some $A_n$s, but surely not for all but finitely many. How can I guarantee that?
Comment: Because each $A_n$ is bounded the set $\{(-r,r)\mid r\in A_n\}$ can cover at most the interval $(-n-1,n+1)$ but not more. So you couldn't possibly have chosen from only finitely many. To cover $\Bbb R$ you have to choose from infinitely many distinct $A_n$'s.
Comment: OK I see. What do you mean by «uniform encoding»?
Comment: And one last comment: $\sigma$ is the choice function, so I would see it as $\sigma(A_i)\in A_i$ for all $i\in I$, but of course we can see it as $\sigma(i)$ instead; with that, $\sigma(i)$ is a sequence, and provided $i>n$ we can take its $n$-th term, which is $\sigma(i)(n)$, which will belong to $X_n$, thus giving the desired "total" choice function for the $X_n$'s. So we are done. Thx.
Comment: @Mick: Uniform in the sense that there's no choice needed for each length, and there's no need to choose for each $A_n$ a different encoding. It's all the same encoding. And yes, you got the last part right.
Comment: So this «uniform encoding» is essentially a bijection between $\mathbb{R}$ and the set of all arbitrarily long but finite sequences of reals, which we could view as $\bigsqcup_{n\in\mathbb{N}}\mathbb{R}^n$. Has such a map ever been explicitly constructed?
Comment: @Mick: You can use the bijection between the line and the plane and apply recursively.
Answer: The discrete topology on a countable set is second countable; it has a countable base consisting of the singleton sets. Thus, the assertion that all second countable spaces are Lindelöf implies that every cover of a countable set $N$ by subsets of $N$ has a countable subcover. I will show that the latter (ostensibly weaker) assertion implies $\mathsf{AC}_\omega(\mathbb R)$, the countable axiom of choice for sets of real numbers.
Assume that every collection of subsets of $\mathbb Q$ which covers $\mathbb Q$ has a countable subcover. Let $(X_n:n\in\mathbb N)$ be a family of nonempty subsets of $\mathbb R$; I will show that the Cartesian product $\prod_{n\in\mathbb N}X_n$ is nonempty.
For each $x\in\mathbb R,$ let
$$L_x=(\mathbb Q\setminus\mathbb N)\cap(-\infty,x).$$
Now define
$$\mathcal U=\{\mathbb Q\setminus\mathbb N\}\cup\{\{n\}\cup L_x:n\in\mathbb N,\ x\in X_n\}.$$
Since $\bigcup\mathcal U=\mathbb Q$, there is a countable subfamily $\mathcal U'$ of $\mathcal U$ which also covers $\mathbb Q.$ For each $n\in\mathbb N,$ let $U_n$ be the first element of $\mathcal U'$ (relative to some fixed enumeration) which covers $n.$ Then $U_n=\{n\}\cup L_x$ for some $x\in X_n.$ Thus we can define $x_n=\sup(U_n\setminus\{n\})\in X_n$ and we will have $(x_n:n\in\mathbb N)\in\prod_{n\in\mathbb N}X_n.$
Comment: Very interesting alternate way of proving one implication, I'd say easier than Asaf's. Still, I keep his answer as accepted because it is complete :). +1 anyway.
Answer: Let $\mathcal B$ be the countable base of $X$. Then for any open cover $\mathcal U=\{U_\alpha:\alpha \in \Omega\}$, then for any $x\in X$ and $x \in U_\alpha$, there exists $B_x\in \mathcal B$ such that $x\in B_x \subset U_\alpha$. Then $\{B_x:x\in X\}$ is the subcover and countable.
Comment: I have the impression this is merely a proof that second countable implies Lindelöf. I am not asking for this proof. I am asking how it can be proved that the proposition "second countable implies Lindelöf" is equivalent to countable choice for subset of the reals, or in short $\mathsf{CC}(\mathbb{R})$, which is what @BrianMScott stated in the comment I linked to in teh question.