text:
Q: What is the derivative of $ \|X^TW-Y\|_{2,1}$ w.r.t. $W$? How to compute it? $W$ is a variable. $\|X^TW-Y\|_{2,1}$  is not smooth due to the $\|\cdot\|_{2,1}$-norm. In order to be differentiable, $\|X^TW-Y\|_{2,1}$  is relaxed to $2\operatorname{Tr}((X^TW-Y)^TD(X^TW-Y))$, where
$$D_{ii} = \frac{1}{2\|(X^TW-Y)_i\|_2+\varepsilon}$$
and $\varepsilon$ denotes a small constant. $X \in \mathbb{R}^{d \times n}$, $Y \in \mathbb{R}^{n \times l}$ and $W \in \mathbb{R}^{d\times l}$.
Note that: the norm $\|\cdot\|_{2,1}$ of a matrix $W \in \mathbb{R}^{d \times l}$ is defined as
$$
\Vert W \Vert_{2,1}
= \sum_{i=1}^d \Vert w^{i} \Vert_2
= \sum_{i=1}^d \left( \sum_{j=1}^l |w_{ij}|^2 \right)^{1/2}
$$
where $w^i$ denotes $i^\text{th}$ row of $W$, $w_{ij}$ denotes a element of $W$.
Some papers as follows:
Multi-Label Informed Feature Selection
Efficient and Robust Feature Selection via Joint $l_{2,1}$-Norms Minimization

A: Based on this answer you can write
$$
G_A
 \,=\, \frac{\partial \|A\|_{2,1}}{\partial A}
 \;=\; A\odot\Big[(A\odot A)\,{\tt\large 1}\Big]^{\odot -1/2}
$$
where $(\odot)$ is used to indicate element-wise multiplication and exponentiation.
So the subdifferential of your expression, after setting $A=(X^TW-Y),\,$ becomes
$$\eqalign{
\phi &= \|A\|_{2,1} \\
d\phi
 &= G_A:dA \;= G_A:X^TdW \;= XG_A:dW \\
\frac{\partial\phi}{\partial W} &= XG_A \\
}$$


text:
Q: Spring Security cannot retreieve Currently authenticated user I am working on a Spring-MVC application which uses Spring-Security. In that I need to get the currently authenticated user's object so I can use setUser() method. However the method returns null, the program seems to crash with a null pointer exception. Kindly have a look at the code. I already debugged+try-catch it and it doesn't return the user.
The call getCurrentlyAuthenticatedUser() throws exception. When I check, it says authentication is null.
I have implemented Spring-Security by implementing the interface UserDetails and UserDetailsService.
Person Class :
@Entity
@Table(name="person")
public class Person implements UserDetails{

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

 @Transient
    private final String PERMISSION_PREFIX = "ROLE_USER";
    @Transient
    private List<GrantedAuthority> authorities;

    @Transient
    private String role;

@OneToMany(cascade = CascadeType.ALL,mappedBy = "person1")
  private Set<Notes> notes1;

    public Set<Notes> getNotes1() {
        return notes1;
    }

    public void setNotes1(Set<Notes> notes1) {
        this.notes1 = notes1;
    }
}

LoginServiceImpl :
@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{

    @Autowired private PersonDAO personDAO;
    @Autowired private Assembler assembler;

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
        Person person = personDAO.findPersonByUsername(username);

        return assembler.buildUserFromUserEntity(person);
    }
}

Assembler class :
@Service("assembler")
public class Assembler {
    @Transactional(readOnly = true)
    User buildUserFromUserEntity(Person userEntity){
        String username = userEntity.getUsername();
        String password = userEntity.getPassword();

        // Long id = userEntity.getId();
        boolean enabled = userEntity.isActive();
        boolean accountNonExpired = userEntity.isAccountNonExpired();
        boolean credentialsNonExpired = userEntity.isCredentialsNonExpired();
        boolean accountNonLocked = userEntity.isAccountNonLocked();

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        User user = new User(username,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
        return  user;
        }
}

// I get error in below method at getPrincipal
PersonServiceImpl :
@Service
public class PersonServiceImpl implements PersonService {

    private PersonDAO personDAO;
 @Override
    public Person getCurrentlyAuthenticatedUser() throws Exception{
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        Person currentUser = (Person) a.getPrincipal();
        if(currentUser == null){
            throw new Exception("No authenticated user retrieved");
        }else {
            System.out.println("We have currently authenticated user");
            return currentUser;
        }
    }

Spring Security-xml
    <import resource="servlet-context.xml" />

    <!-- Global Security settings -->
    <security:global-method-security pre-post-annotations="enabled" />

    <security:http pattern="/" security="none" />

    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
         <security:port-mappings>
        <security:port-mapping http="80" https="443"/>

    </security:port-mappings>
           <security:session-management session-fixation-protection="migrateSession" invalid-session-url="/invalidSession.html">
            <security:concurrency-control max-sessions="3" error-if-maximum-exceeded="true" expired-url="/sessionExpired.html"/>
        </security:session-management>
           <security:form-login login-page="/login" default-target-url="/note/add" always-use-default-target="true" authentication-failure-url="/login?error"/>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl" />

    </security:authentication-manager>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
    </beans:bean>

</beans>

A: It is not still a real answer, but too long to fit in a comment.
You never test if objects returned from other methods are not null before using them. I think that the most probable error is that SecurityContextHolder.getContext().getAuthentication(); returns null causing the NPE on next line. If that's true, that mean that your problem is in the configuration of Spring security. But it is not possible to say more without seeing the bean userDetailsService. You say you implemented userDetail and UserDetailsService but do not show how.
I advice your to remove remember_me as long as you do not have a working basic configuration, that is one where :

*

*you have to login before accessing protected pages

*you can find the logged user in SecurityContextHolder.getContext().getAuthentication()
You will add more functionnalities once this works. If not, it will be very hard to find the causes of your problems.
Edit:
You say the error occurs on line  Person currentUser = (Person) a.getPrincipal();. It is now clear that in previous line
Authentication a = SecurityContextHolder.getContext().getAuthentication();

getAuthentication() returned null. It means that for Spring security, there is no currently authenticated user.

redpajama_set_name: RedPajamaStackExchange


text:
Q: python stub property "Unresolved Attribute Reference" in Class Implementation I made a Class Interface in my pyi module (scheme.pyi):
class Catalog:

    @property
    def elements(self) -> List[Element]: ...

and in my scheme.py I implemented the class like this:
class Catalog:

    def __init__(self, element_collection):
        self.__elements = element_collection

    @property
    def elements(self):
        return self.__elements

PyCharm says "Unresolved Attribute Reference "__elements" for class Catalog"

A: I think it will work if you make Class Interface like so:
class Catalog:

    def __init__(self, element_collection) -> None:
        self.__elements: List[Element]

    @property
    def elements(self) -> List[Element]:

or you can optionally declare instance variables in the class body like so:
class Catalog:

    self.__elements: List[Element]

    @property
    def elements(self) -> List[Element]:


text:
Q: Problema para dividir variáveis em PHP Estou tendo problema com uma página em php. Sempre que eu coloco o seguinte código para fazer a divisão de duas variáveis armazenadas em arrays
$dj_cv_at[percentual][$i] = ($dj_cv_at[concluida_c_imp_total][$i] / $dj_cv_at[concluida_total][$i]) * 100;

Como resultado a página deixa de funcionar corretamente.
Isto só acontece quando eu coloco o operador de divisão. Com os demais operadores o código roda perfeitamente.

A: Após análise descobri que o problema estava relacionado a divisão de 0. Então para resolver isso fiz o seguinte:
if ($dj_cv_at[concluida_c_imp_total][$i] == 0){
$dj_cv_at[percentual][$i] = 0; }
else {$dj_cv_at[percentual][$i] =($dj_cv_at[concluida_c_imp_total][$i]
/ $dj_cv_at[concluida_total][$i]) * 100;}


text:
Q: How to modify this regular expression to not match a non-breaking space? I'm using John Gruber's regular expression to try to match URLs in a document.
I've represented the regular expression in Python like this:
URL_PATTERN = re.compile(ur'(?i)\b((?:https?://)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))')

This is a modified version of a version found here.
This works well in most cases except for documents which contain non-breaking spaces. In Python I see this represented as \xc2\xa0.
Here is an example string that I'm attempting to parse; hopefully the characters will paste in tact:
Go to https://example.com to log in.

If I print just that string in Python, I get:
In [100]: string
Out[100]: 'Go to\xc3\x82\xc2\xa0https://example.com\xc3\x82\xc2\xa0to log in.'
In [101]: URL_PATTERN.search(string).groups()
Out[102]: ('https://example.com\xc3\x82\xc2\xa0to', None, None, None, None)

The string that I am attempting to match against is an str, not unicode.
How can I modify this regular expression to not match this character? I've tried putting \xc2\xa0 into the ^ negated character class near the end of the regex, but it still matches the URL with the space characters.

A: To avoid matching URLs with non-breaking spaces you need to add \u00A0  to the negated character classes [^\s] and pass the re.U flag when compiling the pattern:
URL_PATTERN = re.compile(ur'(?i)\b(https?://(?:[^\u00A0\s()<>]+|\(([^\u00A0\s()<>]+|(\([^\u00A0\s()<>]+\)))*\))+(?:\(([^\u00A0\s()<>]+|(\([^\u00A0\s()<>]+\)))*\)|[^\u00A0\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))', re.U)
                                                 ^^^^^^              ^^^^^^              ^^^^^^                           ^^^^^^            ^^^^^^                  ^^^^^^                                                            ^^^^


text:
Q: NodeJS - Returning object from function overwrites previous declaration of that object I have object in my main.js:
var Status={
   prop1:'',
   prop2:'',
   prop3:'',
   prop4:''
};

Then I have a function (in another .js file) that calculates prop2, prop3 and prop4 like so:
function CalculateProperties() {
   var returnToMain={
      prop2:'',    //note that props in returnToMain have same names as in Status
      prop3:'',
      prop4:''
       };
   returnToMain.prop2=**some_calculations**;
   returnToMain.prop3=**some_calculations**;
   returnToMain.prop4=**some_calculations**;

   return returnToMain;

}

module.exports = CalculateProperties;

From main.js I call it like this:
Status = CalculateProperties();

I would expect that it leaves prop1 alone and it overwrites prop2, prop3 and prop4, but it overwrites the objest as a whole, so after I run it I end up with:
Status={
   prop2: 'Calculated_Value',
   prop3: 'Calculated_Value',
   prop4: 'Calculated_Value'
};

instead of:
Status={
   prop1: 'Original_Value',
   prop2: 'Calculated_Value',
   prop3: 'Calculated_Value',
   prop4: 'Calculated_Value'
};

How do I make it so it overwrites only properties with same names and leaves others alone? Thanks.

A: You are creating a new object in CalculateProperties and returning it.
In your main.js you are assigning this returned value to Status which is a different object.
Hence now Status points to the new object which doesn't know anything of the older properties.
You have three options:
a. Pass the Status object to CalculateProperties and update it.
b. Assign it to new variable say CalculatedValues  and copy over relevant properties to Status
c. Merge the objects using Object.assign() or lodash.merge().

A: You should merge your objects using Object.assign
Status = Object.assign(Status, CalculateProperties());

es6 analogue
Status = {...Status, ...CalculateProperties()}


text:
Q: Pricing table query In MYSQL I've 3 tables in MYSQL one is pricing, transactions and billing. I've 100 Customers, 10 out of them having special rates. Remaining 90 customers having same pricing structure. While billing i want to get the prices accordingly.
Ex
Pricing Table
Cust   prod   price   fromdate    todate
001    apple   5.25   01-09-2015  31-12-9999
002    apple   4.25   01-09-2015  31-12-9999
999    apple   6.00   01-09-2015  31-12-9999 default value
001    Orange  8.25   01-09-2015  31-12-9999
999    Orange  9.00   01-09-2015  31-12-9999 default value

Trans Table
Date        cust   prod      qty
10-09-2015  001    apple     2.0
10-09-2015  002    apple     3.0
10-09-2015  002    Orange    3.0
10-09-2015  050    apple     3.0
10-09-2015  050    Orange    2.0
10-09-2015  001    Orange    2.0

Third result table.
**Bill table **
Date        cust   prod    price   qty  amount

10-09-2015  002    apple    4.25   3.0   12.75 Which is present in PriceTbl

10-09-2015  002    Orange   9.00   3.0   27.00 Default Price Orange

10-09-2015  050    apple    6.00   3.0   18.00 Default Price Apple

10-09-2015  050    Orange   9.00   2.0   18.00 Default Price Orange

How to get the default values for customer number 050 for all products and
for customer number 002 for Oranges.

A: I think, something like this should work:
SELECT
  `Trans`.`Date`,
  `Trans`.`cust`,
  `Trans`.`prod`,
  IF(ISNULL(`Pricing`.`price`, `DefPrices`.`price`, `Pricing`.`price`)) AS `price`,
  `Trans`.`qty`,
  IF(ISNULL(`Pricing`.`price`, `DefPrices`.`price`, `Pricing`.`price`)) * `Trans`.`qty` AS `amount`
FROM `Trans`
LEFT JOIN `Pricing` ON `Pricing`.`Cust` = `Trans`.`cust` AND `Trans`.`prod` = `Pricing`.`prod`
LEFT JOIN `Pricing` AS `DefPrices` ON `DefPrices`.`prod` = `Trans`.`prod` AND `DefPrices`.`Cust` = '999'
WHERE `Trans`.`cust` IN ('002','050')


text:
Q: Wolfram Cloud not working in any browser I am using Ubuntu 18.04, and Firefox and Chrome with extensions UBlock Origin, HTTPS Everywhere and Privacy Badger. Whenever I want to open code on Wolfram Alpha or just create a notebook on Wolfram Cloud, the page loads indefinitly and never does what it should. I tried disabling UBlock but it changed nothing. Where can the problem come from ?

A: I had the same issue. It has been solved when I accepted the cookies. Button is on the lower right of the page, easy to miss.
If you have a link to a workbook and the button does not appear (only a white page or similar), then first try to visit https://develop.open.wolframcloud.com, accept the cookies and reload the workbook.
wolfram cloud cookie accept button


text:
Q: Randomly choose track from jquery html5 audio playlist on page refresh I'm building an audio player for a web experience, that has a list of tracks. Here is the code controlling the audio player.
$( document ).ready(function() {
jQuery(function($) {
            var supportsAudio = !!document.createElement('audio').canPlayType;
            if(supportsAudio) {
                var index = 0,
                playing = false;
                mediaPath = 'audio/',
                extension = '',
                tracks = [
                    {"track":1,"name":"track1","length":"00:55","file":"track1"},
                    {"track":2,"name":"track2","length":"00:55","file":"track2"},
                    {"track":3,"name":"track3","length":"00:55","file":"track3"},
                    {"track":4,"name":"track4","length":"00:55","file":"track4"},
                    {"track":5,"name":"track5","length":"00:55","file":"track5"}
                ],
                trackCount = tracks.length,
                npAction = $('#npAction'),
                npTitle = $('#npTitle'),
                audio = $('#audio1').bind('play', function() {
                    playing = true;
                    npAction.text('Now Playing:');
                }).bind('pause', function() {
                    playing = false;
                    npAction.text('Paused:');
                }).bind('ended', function() {
                    npAction.text('Paused:');
                    if((index + 1) < trackCount) {
                        index++;
                        loadTrack(index);
                        audio.play();
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }).get(0),
                li = $('#plUL li').click(function() {
                    var id = parseInt($(this).index());
                    if(id !== index) {
                        playTrack(id);
                    }
                }),
                loadTrack = function(id) {
                    $('.plSel').removeClass('plSel');
                    $('#plUL li:eq(' + id + ')').addClass('plSel');
                    npTitle.text(tracks[id].name);
                    index = id;
                    audio.src = mediaPath + tracks[id].file + extension;
                },
                playTrack = function(id) {
                    loadTrack(id);
                    audio.play();
                };

                extension = audio.canPlayType('audio/mpeg') ? '.mp3' : audio.canPlayType('audio/ogg') ? '.ogg' : '';
                loadTrack(index);
            }

});
});

Is there a way to reorder the list inside of the variable named tracks? Generating the list of 1 through 5 in a random pull? for example, the items named track2 track3 track4 ect. could potentially be played first? I'm looking for that to be random on a page refresh.
Thanks for the help!

A: You could add a playOrder field to the tracks variable, and have a function go through each on on load and assign it a random unused playOrder number.


text:
Q: GridSearch CV multiple metrics result in same score values I'm tuning my models with GridSearchCV. There are multiple scoring metrics used - precision, recall and accuracy. However, when I inspect the cv_results_, all 3 metrics give the same score values.
Here is my code.
model = RandomForestClassifier(random_state=0)

param_grid = {
    'max_depth': range(5, 11, 1),
    'max_features': range(10, 21, 1),
    'n_estimators': [10, 100],
    'min_samples_leaf':[0.1, 0.2, 0.3]
}

scorers = {
    'precision_score': make_scorer(precision_score, average='micro'),
    'recall_score': make_scorer(recall_score, average='micro'),
    'accuracy_score': make_scorer(accuracy_score)
}

grid_search = GridSearchCV(model, param_grid = param_grid,
                           scoring=scorers, refit='precision_score', return_train_score=True,
                          cv = 3, n_jobs = -1, verbose = 3)

grid_search.fit(X,y)

The scores returned by cv_results:
pd.DataFrame(grid_search.cv_results_)[['mean_test_precision_score', 'mean_test_recall_score', 'mean_test_accuracy_score']].head(10)

The way I made my X and y (if that matters):
X = data_merge.drop('label', axis=1)
le = preprocessing.LabelEncoder()
y = le.fit_transform(data_merge['label'])

I'm running Scikit Learn 0.24.2 and Python 3.8.10


text:
Q: Converting binary decision diagram to truth table Given a binary decision diagram, how do I convert it into a truth table?  What is the exact algorithm for it ? I have been trying this for a long time. Here is an example which one can follow:

Source: Wikipedia.
(The dotted edges represent 0; solid edges, 1.)

A: Beginning at the root node, traverse tree in depth-first manner.
For each leaf node reached, record an entry in truth table as follows:

*

*x1 is 0 if you descended the dashed edge from node x1; 1 otherwise.

*x2 is 0 if you descended the dashed edge from node x2; 1 otherwise.

*x3 is 0 if you descended the dashed edge from node x3; 1 otherwise.

*f is value of the leaf node.


text:
Q: bdutil socksproxy doesn't work I created an hadoop cluster on Google Compute engine (E.g., like this). I can ssh in with bdutil shell without any problems, but when I run bdutil socksproxy, it says it is running, but whenever I connect with a browser, it says that the proxy is refusing connections. I have installed necessary browser add-ons and this has worked for me without problems last year.
How do I debug this? There are no error messages of any kind in the bdutil socksproxy terminal window.
Thanks,
Mike

A: OK. Figured it out. I'm going to answer my own question in case it helps anyone else. You may have to use ssh-keygen or the proxy rejects request. (Running the gcloud compute ssh command manually will print out a message with the proper ssh-keygen command to use).


text:
Q: Deleting your comment appears to trigger the 5-second rule
Possible Duplicate:
Deleting a comment (mine) shouldn't count as a comment vote

After I submitted a comment to a question I discovered a couple of other comments had been posted before mine. One of those made much the same point so I deleted my comment and tried to upvote the other. When I tried to upvote I got the message "You can only upvote a comment every 5 seconds" or something to that effect.
I don't think deleting my own comment should trigger the 5-second timer.


text:
Q: Has anyone installed 16.04 LTS on NUC6i5SYH or NUC5i5RYH and it worked OTB? I am thinking of getting one but keep reading mixed reviews on 16.04 LTS on them. Some say video driver issues. I cannot tell.
Thought I would check here if anyone has installed on these NUCs.

A: I use Lubuntu (14.04 and 15.10) on a NUC5i7RYH with an M.2 SSD and it works like a charm. No issues at all, and it runs lightning fast! I haven't installed the 16.04 yet, but I am sure it won't do worse.


text:
Q: Use data from js library internal cache I use fullcalendar.io.
I see on official site documentation:

lazyFetching

Determines when event fetching should occur.
Boolean, default: true When set to true (the default), the calendar
  will only fetch events when it absolutely needs to, minimizing AJAX
  calls. For example, say your calendar starts out in month view, in
  February. FullCalendar will fetch events for the entire month of
  February and store them in its internal cache. Then, say the user
  switches to week view and begins browsing the weeks in February. The
  calendar will avoid fetching events because it already has this
  information stored.
When set to false, the calendar will fetch events any time the view is
  switched, or any time the current date changes (for example, as a
  result of the user clicking prev/next).

Now I want to know how I can use internal cache to use that data for other things at web page (etc. draw graph and similar)
I also can select data for month I need to why to do that when I already have selected in library cache?
But how I can use it? Where to find it?

A: The internal events of the fullCalendar can be accessed via the property clientEvents.  ClientEvents returns an array of event objects structured like the JSON event feed except that any dates supplied as strings have been converted to instances of the moment.js object.  You can loop through this array and operate on each event in any manner you please.  Here is an example code fragment from some code I recently implemented showing the syntax to refer to the array:
$('#calendar').fullCalendar('clientEvents');


text:
Q: If $E$ and $P$ don't commute, why could we have an $E$-$K$ diagram? If $E$ (energy) and $P$ (momentum) only commute in constant potential, how could we have an $E$-$K$ diagram in a solid material?
$[E,p] \neq 0$. Then we cannot prepare electrons whose $E$ and $P$ are both very specified.
However, in solid state material, we often have $E$-$K$ diagram, where every point is a pair of specified $E$ and $P$.
The potential in a solid is definitely not a constant, so can somebody explain this?

A: In the band diagrams you refer to, $K$ is not actually momentum; instead, it is something called crystal momentum (also often 'quasimomentum'; for more details and its relationship to real momentum see this, this, this and this questions, among many others on this site).
In short, $\hat H$ does not commute with $\hat p$, but it does commute with a restricted subset of operators which are functions of $\hat p$. In particular, it can be seen that the operator
$$
\hat U(a) = e^{i\hat p a/\hbar}
$$
produces a translation by $a$ in position space by the displacement $a$. If the hamiltonian has the form
$$
\hat H = \frac{1}{2m} \hat p^2 + V(\hat x)
$$
where $V(x+a)=V(x)$ is a periodic potential, then generically $\hat H$ will not commute with arbitrary displacements, i.e. $[\hat H, e^{i\hat p \tilde a/\hbar}] \neq 0$ for arbitrary $\tilde a$, but it will commute with $e^{i\hat p \tilde a/\hbar}$ when $\tilde a = a$, i.e. when the displacement length matches the period of the potential.
Thus, we have
$$
[\hat H, e^{i\hat p \tilde a/\hbar}] = 0,
$$
which means that $\hat H$ and $e^{i\hat p \tilde a/\hbar}$ admit a common eigenbasis. Moreover, $\hat U(a) = e^{i\hat p a/\hbar}$ is a unitary operator, which means that all of its eigenvalues must have unit modulus and it is always possible to write them as $u = e^{ik a/\hbar}$, where $k$ is only ever defined up to a multiple of $2\pi\hbar/a$; to remove this ambiguity, we restrict ourselves only to $k$'s in the interval $(-\pi\hbar/a, \pi \hbar/a]$.
This $k$ is the crystal momentum that's used in the band diagrams you're bothered by. While it does have a nontrivial relationship with physical momentum, it is not the same thing.

A: This is not an answer to your question, but rather a response to the premise you wrote, to clear up a misconception: Energy and momentum can commute in a non-constant potential, it just depends what the potential is. You'd have to check it explicitly for a given potential by acting the momentum operator on the potential on a test function.
In general, in any closed system (so no external potential), momentum is conserved, which means we must have
$$[H,p_i]=0$$
Why should they commute? A conserved quantity commutes with $H$ so that its time evolution is unaffected, thus it is conserved:
$$P(t)=e^{-itH} P e^{itH}=P e^{-itH} e^{itH}=P$$
Edit: In the comments it was suggested that the claim above was false. So as an important example, below is a proof of this for the coulomb potential of two charge particles of mass $m$. Note that the conserved quantity is the summed (total) momentum of both particles, $\vec{p}_1+\vec{p}_2$. The individual momenta are not conserved and do not commute with $H$.
$$[H,p]$$
$$=[p_1^2/2m +p_2^2/2m+V(x_1,x_2), p_1 +p_2]$$
The first two terms of the hamiltonian commute with the total momentum so they vanish.
$$=[V(x_1,x_2), p_1 + p_2]$$
$$=[V(x_1,x_2), p_1]+[V(x_1,x_2),p_2]$$
Consider the first commutator, for $p_1$. Use the notation $\partial_{x1}\equiv \frac{\partial}{\partial x_1}$.
$$[V(x_1,x_2), p_1]$$
$$=-i\hbar[V(x_1,x_2), \partial_{x1}]$$
where $V(x_1, x_2)=\frac{-k}{|x_2-x_1|}$
Let's find this commutator. Consider on some test function $\psi(x_1, x_2)$
$$\partial_{x1} (V(x_1, x_2) \psi)=V(x_1, x_2) \partial_{x1}\psi + \partial_{x1}V(x_1, x_2) \psi$$
$$\implies V(x_1, x_2) \partial_{x1}\psi-\partial_{x1} (V(x_1, x_2) \psi)=[V,\partial_{x1}]\psi=-\partial_{x1}V(x_1, x_2) \psi$$
The derivative of the potential is
$$\partial_{x1}V(x_1, x_2)=\frac{k(x_2-x_1)}{|x_2-x_1|^3}$$
Therefore $[V(x_1, x_2),\partial_{x1}]=\frac{k(x_2-x_1)}{|x_2-x_1|^3}$. This gives
$$[V(x_1, x_2),p_1]=-i\hbar\frac{k(x_2-x_1)}{|x_2-x_1|^3}$$
$$[V(x_1, x_2),p_2]=+i\hbar\frac{k(x_2-x_1)}{|x_2-x_1|^3}$$
..where the second commutator came from exchanging $x_1 \leftrightarrow x_2$. These commutators are negatives of each other, so adding them gives
$$[V(x_1, x_2),p_1+p_2]=[V(x_1, x_2),p]=0$$
$$\implies [H,p]=0$$
This is a proof in one spacial dimension. The same proof works for the Coulomb potential in three spacial dimensions, where the generalized result is $[H,p_i]=0$ for all three components of the momentum.


text:
Q: Python: problem with tiny script to delete files I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files.
It's a little too big to do it by hand, so I decided to write a python script to do it. But it isn't working.
def cleandir(dir_path):
    print "Cleaning %s\n" % dir_path
    toDelete = []
    files = os.listdir(dir_path)
    for filedir in files:
        print "considering %s" % filedir
        # continue
        if filedir == '.' or filedir == '..':
            print "skipping %s" % filedir
            continue
        path = dir_path + os.sep + filedir
        if os.path.isdir(path):
            cleandir(path)
        else:
            print "not dir: %s" % path

        if 'svn' in filedir:
            toDelete.append(path)

    print "Files to be deleted:"
    for candidate in toDelete:
        print candidate
    print "Delete all? [y|n]"

    choice = raw_input()

    if choice == 'y':
        for filedir in toDelete:
            if os.path.isdir(filedir):
                os.rmdir(filedir)
            else:
                os.unlink(filedir)

    exit()

if __name__ == "__main__":
    cleandir(dir)

The print statements show that it's only "considering" the filedirs whose names start with ".". However, if I uncomment the continue statement, all the filedirs are "considered". Why is this?
Or is there some other utility that already exists to recursively de-SVN-ify a directory tree?

A: At the very least you should not re-invent the wheel for recursive directory traversal and just use os.walk.

A: This doesn't answer your Python question, but there's an easier way to do what you want: svn export will write your tree of files some place new without all the .svn directories.

A: The reason 'continue' shows all the folders being considered is because exit() is being called at the end of the function. The call to exit() will exit Python after the first directory is searched. If you change it to 'return' your function will be called recursively.
Also os.listdir does not return '.' or '..' so you don't need a check or any continue statements.
:-)
Davy

A:
I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files.

Not to side step your question here (and I know it's been answered, correctly no less) but if you want to export your source from Mercurial, you should use the 'export' command of SVN.... You don't need to manually (or pragmatically) remove all of the .svn folders....
(This is mainly for others' that come up this post looking how to do this)
Also, there are SVN to Mercurial importers....


text:
Q: a problem in grub bootloader I'm a new Linux user and I'm facing an annoying problem with my customized grub boot-loader, suddenly after running the OS for a while -maybe two days or a week- my PC stack in keep repeating this screen which containing the manufacturer logo -sorry that i don't know it's name- and don't display the grub menu to choose between Ubuntu or windows but when I try to boot from my external hard drive that contain backups for the whole PC the grub menu appears and I can then boot the OS. this problem faced me about 6 times and what i do is recovering the nearest backup data but this cause me to loose all my new data. I always try to run the command  ($sudo update-grub) but nothing changes. could you help me please?
I'm still not familiar with Linux commands and consents so please give me some details.


text:
Q: Getting: "rsync: could not open password file" in cygwin Running in cygwin
rsync -vrtz --password-file=c:\cygwin\secret --delete /cygdrive/d/Data user@xx.xx.xx.xx::modulename

But getting
rsync: could not open password file c:cygwinsecret: No such file or directory (2)
rsync error: syntax or usage error (code 1) at /home/lapo/package/rsync-3.0.9-1/src/rsync-3.0.9/authenticate.c(166) [sender=3.0.9]

I have tried 'chmod 600 secret' and changing the owner/group in many ways but rsync still cannot seem to see this file. Any ideas?

A: The correct path in cygwin is /cygdrive/c for C:. But you already used it in the same line.
Correct this and try again.


text:
Q: Access denied for user 'root'@'localhost' (using password: YES) despite granted privileges I can access mysql from the command line, and can also access via phpmyadmin. I've granted all privileges both via command line and via phpmyadmin but when i try to access locally, it runs the same access denied.
+----------------------------------------------------+
| Grants for root@localhost|
+----------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD 'HASHED' WITH GRANT OPTION |
| GRANT ALL PRIVILEGES ON `table`.* TO 'root'@'localhost' WITH GRANT OPTION                                                                                |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION                                                                                |
+----------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)

I realise this question has been asked multiple times but all solutions provided thus far have come up fruitless. Any help will be hugely appreciated, because I have to commit my code and pull it to a server every time I want to make a change to the db (which gives an embarrassing amount of commits).
EDIT (to clarify): This error only happens whenever I have to do something on my local development machine. Whenever I try and run artisan migrate, or login to the authentication system I've integrated into my app.
Thanks.

A: Please,check up a "--skip-name-resolve" variable value.  Is it "On" or "Off" ?
  You may do it from mysql command promt>: show variables like '%skip%';

A: I have no idea why this issue arose but I had to change my config.inc.php file to include the MySQL username and password. I think it must have been an issue with the installation of MySQL. The file is located MAMP\bin\phpMyAdmin


text:
Q: How to bind Image Button command from a DataTemplate Selector to a ViewModel? I am working with SyncFusion's TreeView. I have a TreeView with three separate DataTemplate/Custom View Cells. In my main XAML, I have the following tree view code below which binds to my DataTemplates.
SamplePage.xaml
<syncfusion:SfTreeView x:Name="treeView"
       QueryNodeSize="TreeView_QueryNodeSize"
       NodeSizeMode="Dynamic"
       AutoExpandMode="RootNodesExpanded"
       ChildPropertyName="SubFiles"
       ItemsSource="{Binding ImageNodeInfo}" Indentation="0"
       ItemTemplate="{StaticResource TemplateSelector}">
</syncfusion:SfTreeView>

I am now trying to bind my command from one of my data templates (code below) to my view model connected to my page but I can't seem to connect my data bindings. Most examples online shows the data template on the same xaml page of the view / viewModel. However, my code is using a data template selector which gives me a harder route to bind.
SampleTemplate.xaml
<ViewCell.BindingContext>
    <local:SamplePage x:Key="SamplePage">
    </local:SamplePage>
</ViewCell.BindingContext>

   <ImageButton Aspect="AspectFill"
      Grid.Row="0" Grid.Column="3"
      HorizontalOptions="End"
      WidthRequest="90" HeightRequest="90"
      Source="{xaml:ImageResource plus_Icon}"
      Command="{Binding Path=BindingContext.AddAsJobClickedCommand}, Source={x:Reference SamplePage}"
      CommandParameter="{Binding treeView}"
                                 />

A: Try this, probably you are missing the x:Reference for the command:
<ImageButton Aspect="AspectFill"
             Grid.Row="0" Grid.Column="3"
             HorizontalOptions="End"
             WidthRequest="90" HeightRequest="90"
             Source="{xaml:ImageResource plus_Icon}"
             Command="{Binding Path=BindingContext.AddAsJobClickedCommand, Source={x:Reference treeView}}"
             CommandParameter="{x:Reference treeView}"/>

Note: Here treeView is the x:Name of SfTreeView
Find Reference here

A: You have probably wanted code from your list data templates to call commands from your view model directly and pass the current item to the view model to perform necessary actions, I suggest you can take a look:
https://doumer.me/xamarin-forms-listview-advanced-guide-with-mvvm/
1.We need to create properties in the list data templates. These properties will contain their's parent view's BindingContext and commands will be gotten from them.
2.Pass the Binding context from xaml to the data template
3.Receive the binding context in the data template, bind commands and pass the current item as the command's parameter.


text:
Q: How to make a runnable .jar file? for school i have to make a game, together with 2 classmates.
our group had to make something in Java, a language we never used before.
we got ourselfs a little game now, but we can't seem to get it into a working .jar file nor a runnable jar.
We use eclipse, but the .jar file created through export => jar file doesn't work. it doesn't do anything. (manifest file is totally empty)
the runnable jar file is even worse, it says there is no main class selected, but when i try to set 'Main.class' as main class, then it's not in the list. (at advanced options for creating a runnable jar in Eclipse)
i tried through cmd too, but then it couldn't find a manifest attribute...
any help?
my maps:
-Smash'em All
    -.settings
    - bin
         -data (all my images and such)
         -Smash (all the .class files)
         -java.policy.applet
    - src
         -data (some old pictures, not the same as in the other data map)
         -Smash (all the .java files)
    - .classpath
    - .project
any idea how to make a runnable jar?
and if i want to implement it in HTML, do i need a runnable or just a .jar file?
EDIT:
my lay-out doesn't seem saved? :( sorry, is my first post ever herer :(

A: To add to Césars' comment, have you tried:
jar cvf YourApplication.jar *.class

From "Java How to Program" :

That should jar up your classes which creates in the current directory
  a JAR file named YourApplication.jar containing the applet's .class
  files. If the program had other resources, you'd simply add the file
  names or the folder names in which those resources are stored to the
  end of the preceding command. The letters cvf are command-line options
  to the jar command. The c option indicates that the command should
  create a new JAR file. The v option indicates that the command should
  produce verbose output so you can see the list of files and
  directories being included in the JAR file. The f option indicates
  that the next argument in the command line (YourApplication.jar) is
  the new JAR file's name.

As per one of your questions, you asked "if i want to implement it in HTML, do i need a runnable or just a .jar file". No, you can just run the class file, if you want.
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <applet code = "YourApplication.class" width = "300" height = "45">
        </applet>
    </body>
</html>

A: If you want some that can run with "java -jar" you need to specify the main class in the JAR manifest.

A: To run you jar using the java -jar command or double click your jar you need to indicate the main class to run, you do it adding the Main-Class in the META-INF/Manifest.MF of your jar, in this link you can see how to setup the main class

A: you can make use of exe4j tool, which takes your classes in jar and produce exe for you.
try this http://www.ej-technologies.com/products/exe4j/overview.html


text:
Q: How extract iWorks suite mimetype with Exiftool I need to extract mimetype with magic number from iWork suite.
How do? Exiftool see ".pages" etc. as "application/zip". But the real mimetype isn't this.
How can i extract the correct mime?
I can use an validation with python tool if needed.
"Apline for docker".
Thanks for help.

A: Phil Harvey has "Improved identification of Apple iWork files" in exiftool version 10.96.  Check to see if that works for you.


text:
Q: How do I add two 16bit Decimal numbers in Dosbox Debug? Without experience or even a lecture whatsoever in assembly language our professor told us to add & subtract 16bit decimal numbers in Dosbox Debug, we only know handful of syntax that can work in debug. After a week of trying i only manage to this line of codes to convert my hexa inputs to decimal output but only a 4bit number.
mov al,9
mov bl,8
add al,bl
daa
int 21
int 20


text:
Q: C Program Gives Results After I Stop It So, right now I've been learning function pointers and the code I've written for it is below
#include <stdio.h>
#include <stdlib.h>

void addition(int a, int b) {
    printf("%d", a + b);
}
void subtraction(int a, int b) {
    printf("%d", a - b);
}
void multiplication(int a, int b) {
    printf("%d", a * b);
}
void division(int a, int b) {
    printf("%d", a / b);
}

int main() {
    void (*functionPTR_ARR[])(int, int) = { addition, subtraction, multiplication, division };
    unsigned int ch, a = 15, b = 10;

    printf("Enter a Array Number: ");
    scanf("%d\n", &ch);

    (*functionPTR_ARR[ch])(a, b);
}

When I run the program and give it input, let's say 2, for the multiplication function. It'll run but it won't give the results while running, it will only give them when I stop it. Is there a reason why this is happening?


text:
Q: Azure Python SDK ClientSecretCredential fetch the values from Azure keyvault Unable to get the values of tenant_id, client_id,client_secret which are stored in Azure Keyvault, by using library from azure.identity import ClientSecretCredential. I have installed and imported the modules azure-keyvault-secrets azure-identity but for some reason its not working. i don't want to use import DefaultCredentials. Below is my python script
from azure.identity import ClientSecretCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.keyvault.secrets import SecretClient

credential = ClientSecretCredential(
    tenant_id='xxxxx',
    client_id='xxxxx',   ##the secret id's values should pick from Keyvault #
    client_secret='xxxxx'
)
subscription_id = "xxxxx"
compute_client = ComputeManagementClient(credential, subscription_id)
`````
Assist me to solve this


text:
Q: How to solve exact equations by integrating factors? I know how to solve an exact equation like
$$M(x,y) + N(x,y)y=0 $$
We just check $$\frac{\partial M}{\partial y} =\frac{\partial N}{\partial x} $$
If so, then it's just a little bit of algebra, taking anti-derivative and solve, such that $f = f(x,y) = c$, where we can obtain $f$ by just taking integal w.r.t. $x$ etc.
But now I'm stuck with integrating factors. I can do it if the integrating factor $\mu=\mu(x)$ depends only on one variable. But now I want to do another exercise, which uses a function of the form $\mu(x+y)$.
How can I solve $$(7x^3+3x^2y+4y) +(4x^3+x+5y)y'=0 $$ I'm given a hint that I should use a function of the form $\mu(x+y)$.
I guess I should just multiply by $(x+y)^m$ for an arbitrary $m$, but I don't know how to do the algebra after I multiplied...
I guess something like this  :
$$\frac{\partial (M \mu)}{\partial y}= m(x+y)^{m-1}(7x^3+3x^2y+4y) + (x+y)^m(3x^2+4) =$$
$$\frac{\partial (N\mu)}{\partial x} = m(x+y)^{m-1}(4x^3+x+5y) + (x+y)^m(12x^2+1) $$
How solve for $\mu$ ?

A: Your integrating factor is
$$
\mu(x+y)=(x+y)^3.
$$
To find it you use the usual strategy expressing
$$
\mu_yM-\mu_xN=\mu(N_x-M_y).\tag{1}
$$
After some simplification you can find that
$$
\frac{N_x-M_y}{M-N}=\frac{3}{x+y}.
$$
Hence, if $\mu(x,y)=\mu(x+y)$ $(1)$ simplifies to
$$
\mu'_w=\frac{3\mu}{w},\quad w=x+y,
$$
from which you find your integrating factor.

A: Hint: Let you have an OE like $$M(x,y)dx+N(x,y)dy=0$$ and let $\mu=\mu(z(x,y))$ be an integrating factor for it. If $$\frac{M_y-N_x}{Nz_x-Mz_y}$$ be a function respect to $z$ then $$\mu=\exp\left(\int\frac{M_y-N_x}{Nz_x-Mz_y}dz\right)$$. Here $z=x+y$, so $z_x=1,z_y=1$ and therefore your integrating factor is $\mu=\exp\left(\int\frac{M_y-N_x}{N-M}dz\right)$. You can easily find $\mu$ by doing $$(\mu M)_y=(\mu N)_x$$ as well. For thsi problem $$\mu=\exp\left(\int\frac{3x^2+4-12x^2-1}{4x^3+x+5y-7x^3-3x^2y-4y}dz\right)=\exp\left(\int\frac{3(1-3x^2)}{(x+y)(1-3x^2)}dz\right)$$ which if $3x^2-1\neq0$ then $$\mu=\exp\left(\int\frac{3}{x+y}dz\right)=\exp\left(\int\frac{3}{z}dz\right)$$ I think you can do the rest.


text:
Q: Jquery being loaded after AJAX in a loop I have this code:
document.addEventListener('DOMContentLoaded', function PostLinkHome() {
    jQuery(function($) {
        $('.post-link-home').find('.elementor-post').each(function() {
            let link = $(this).find('a').attr('href');
            $(this).wrapAll(document.createElement('a'));
            $(this).closest('a').attr('href', link);
        });
        jQuery(document).ajaxComplete(function() {
            PostLinkHome();
        });
    });
});

Which is suppose to run the Jquery function PostLinkHome() before and after Ajax has been loaded.
I have tried to do this:
jQuery(document).bind('ready ajaxComplete', function($) {
    $('.post-link-home').find('.elementor-post').each(function() {
        let link = $(this).find('a').attr('href');
        $(this).wrapAll(document.createElement('a'));
        $(this).closest('a').attr('href', link);
    });
});

Source
But this didn't work.
The problem is that the code works but once the Ajax is loaded, it loads the jQuery again, to the previous items in the loop which already had the function applied to them before the Ajax loading more things.
This results in the Ajax items having the jQuery applied to them but the old items on the page get the same script applied to them twice which is a problem.

A: Just define the code you want to run in a function. Call it on document ready and bind it to the Ajax call. (Side note: seems odd you would run this code on every Ajax call and not just the one you make that returns the content)
function PostLinkHome() {
  $('.post-link-home .elementor-post').each(function() {
    const elem = $(this);

    // if parent is already a link, just exit out
    if(elem.parent().is('a')) return;

    const link = elem.find('a').attr('href');
    elem.wrapAll(document.createElement('a'));
    elem.closest('a').attr('href', link);
  });
}

// Then bind the event and call the function

jQuery(function () {
  jQuery(document).ajaxComplete(PostLinkHome);
  PostLinkHome();
});

Seems odd because this code would put a link in a link? My guess you would want to unwrap the initial link.
const linkElem = elem.find('a');
const link = linkElem.attr('href');
linkElem.children().unwrap();


text:
Q: Call javascript function after CSS change I want to call a function after the css has been changed. For Example something like this
$("#ContentDiv").css('height','500px').change(function(){
    alert('changed');
});

Call function immediately after above css change. I cannot use setTimeout or other timeouts. Actually i have applied some css animation for 1 sec which cause contentdiv to resize for 1 sec and that's why if i call a function immediately like this
$("#ContentDiv").css('height','500px');
myfunction();

myfunction() will start executing while the height is still not changed.
Thanks to John Smith for correcting my question, he suggested good but i could not find to accept his changes.

A: There is a DOMAttrModified event that is fired on some browsers that you could catch to detect this. You can probably use PropertyChanged on IE, but DOMAttrModified should work on Chrome/Firefox etc.
Something like this:
document.documentElement.addEventListener('DOMAttrModified', function(evt){
  if (evt.attrName === 'class') {
          // Code
  }
}, false);

EDIT: Based on your update, if you just want to call code after the animation is done, and you are using jQuery to do the animation, you can chain a callback function to the animation, please refer to the documentation: http://api.jquery.com/animate/

A: Just call the function.
$("#ContentDiv").css('height','500px');
myFunction();


text:
Q: How to secure connection string in Azure I have enabled MSI and added it to secure key vault. I want to retrieve the password from Key Vault and pass it to the connection string in application settings of app service.
How can I do that?


text:
Q: how to set event to native calendar dynamically in android? I need to set the event to the native calendar.and date and time will be provided by the user input.How can I pass the date and time values to the native calendar?
I tried a lot and Calendar.getInstance() will be helpful in setting the current date and time.
But I want to set the event for user provided dates and time.Can anybody help me in this regard?
I want the particular code.

A: Try this
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", startTime);
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", endTime);
intent.putExtra("title", "title");
startActivity(intent);

start Time and endTime are the Time values

A: package com.example.calendar_four_one;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

Button click;
EditText date,time;
int years,months,days,hours,mins,seconds;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    date=(EditText) findViewById(R.id.editTextDate);
    time=(EditText) findViewById(R.id.editTextTime);

    click=(Button) findViewById(R.id.button1);

    click.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            String d=date.getText().toString();

            String t=time.getText().toString();

            List <String> dateTime = new ArrayList<String>();
            dateTime = getDateAndTime(d,t);
            //String str[] = new String[dateTime.size()];

            years = Integer.parseInt(dateTime.get(0));
            months = Integer.parseInt(dateTime.get(1));
            days = Integer.parseInt(dateTime.get(2));
            hours = Integer.parseInt(dateTime.get(3));
            mins = Integer.parseInt(dateTime.get(4));
            seconds = Integer.parseInt(dateTime.get(5));

            Toast.makeText(getApplicationContext(), ""+years, Toast.LENGTH_LONG).show();

            //SimpleDateFormat formatter=new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");

            Intent calIntent = new Intent(Intent.ACTION_INSERT);
            calIntent.setData(Events.CONTENT_URI);
            calIntent.putExtra(Events.TITLE, "Google IO Afterparty");
            calIntent.putExtra(Events.EVENT_LOCATION, "The W Hotel Bar on Third Street");
            calIntent.putExtra(Events.DESCRIPTION, "Hang out after Google IO for a drink and geeky conversation.");
            Calendar startTime = Calendar.getInstance();
            startTime.set(years, months-1, days, hours, mins,seconds); // (Year-2013)(Day-Wed [i.e:-3rd DOW]) (Date-16th) 15:50
            Calendar endTime = Calendar.getInstance();
            endTime.set(years, months-1, days, hours, mins+30,seconds); // 18:30
            calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
            startTime.getTimeInMillis());
            calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
            endTime.getTimeInMillis());
            startActivity(calIntent);

            Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();

        }
    });
}

public List<String> getDateAndTime(String date,String time)
{

    List<String> list = new ArrayList<String>();

    String[] dateStr = date.split("/");
    String[] timeStr = time.split(":");

    for(String str:dateStr)
        list.add(str);

    for(String str:timeStr)
        list.add(str);

    return list;

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

package com.example.calendar_four_one;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.widget.Toast;

public class ReminderReceiver extends BroadcastReceiver {
// Vibrator object
public Vibrator vibrator;
long[] pattern = { 0L, 250L, 200L, 250L, 200L, 250L, 200L, 250L, 200L,
    250L, 200L, 250L, 200L, 250L, 200L };
// Ringtone object
Uri ringT;
Ringtone ringTone;

@Override
public void onReceive(Context context, Intent intent) {
String remindText = intent.getStringExtra("text");
//Unique notification id for every alarm
int receiverID = intent.getIntExtra("AlrmId", 0);
// Notification creation
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
        context).setSmallIcon(android.R.drawable.ic_popup_reminder)
        .setContentTitle("Reminder").setContentText(remindText);

// Create vibrator pattern
vibrator = (Vibrator) context
        .getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, -1);// No repetition

// Notification tone creation and play
ringT = RingtoneManager
        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
ringTone = RingtoneManager.getRingtone(context, ringT);
ringTone.play();
// Create toast and show on center of the screen
Toast toast = Toast.makeText(context, remindText, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
// end of toast...

// Show status bar notification
NotificationManager mNotificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(receiverID, mBuilder.build());

}
    }
This code finally worked for me..


text:
Q: Principal Component Analysis and Time Series I'm a PhD student with a very superficial knowledge of statistics and econometrics. I am trying to build an index representing the intensity of rental regulation in my country from 1915 to the present. This index should "summarize" different detailed (numerical) indicators, each representing a very specific feature of the regulation (most of them will be dummies).
I have read something about weighted indices, built through a Principal Component Analysis, but:
- I wasn't able to understand if this method can be used with time series; the papers I read only used it with cross-sectional datasets.
- Because of my very lacking knowledge of statistics, I'm not even sure this method would lead me to the index I am trying to build!
Is there anyone who could help me? I appreciate every suggestion, warning or advice for further readings. If you need more info about the data and research question,just ask :)
Thanks a lot!


text:
Q: Get nested keys hstore postgres I'm trying to get the nested key's of the following 2 strings, saved as hstore in an postgresdb:
{"values"=>"{\"60\"=>[\"hallo\"], \"63\"=>[\"9\"], \"62\"=>[\"Nein\", \"Vielleicht\"], \"61\"=>[\"Ja\"]}", "comment"=>"[\"hmm\"]"}"},
{"values"=>"{\"60\"=>[\"test?\"], \"63\"=>[\"9\"], \"62\"=>[\"Ja\", \"Nein\"], \"61\"=>[\"Ja\"]}", "comment"=>"[\"kommentar23\"]"}"}

to be clear, how can I get all the keys/numbers in sql?
I tried the akeys function and get "values", thats fine, thats the first key, but I don't know how to get the nested keys?
I tried with subqueries with no success.
any advice?
Thanks, Patrick

A: I'd say your hstore looks more like twisted JSON. You can try to replace => with : and parse it, for example, with python json module or, if you're using 9.3, with native json methods.
Or you can get skeys, convert it to hstore again and get values.


text:
Q: SPRING MVC database error jdbc Thanks for your time
I am getting an error as my project is having 2 modules add driver and add truck for which i am executing the sql query for both but when i execute the query for addDriver module the database exception is throwing stating
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO truck(TRegnNo,VendorName,PurchaseDate,Price,RepairDate,InvoiceNo,RepairCost) VALUES(?,?,?,?,?,?,?)]; Column 'TRegnNo' cannot be null; nested exception is com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'TRegnNo' cannot be null
    org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:101)

driver insert sql statement                                                public void insertData(Driver driver)
    {
        String sql = "INSERT INTO driver" + "(DLNo,DName,Age,Experience) VALUES (?,?,?,?)";
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.update(sql, new Object[] {driver.getLicenseNumber(),driver.getDriverName(),driver.getAge(),driver.getExperience()});
}                                                          Truck Insert code                                                                 public void insertData(Truck truck)
{
    String sql = "INSERT INTO truck" + "(TRegnNo,VendorName,PurchaseDate,Price,RepairDate,InvoiceNo,RepairCost) VALUES(?,?,?,?,?,?,?)";
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.update(sql , new Object[] {truck.getTregNo(),truck.getVendorName(),truck.getPurchaseDate(),truck.getPrice(),truck.getRepairDate(),truck.getInvoiceNo(),truck.getRepairCost()});

}

A: Column TRegnNo can not be null. You have to assign a (unique) value to this row.

A: Check out with this :
StackTrace contains Column 'TRegnNo' cannot be null pointing to constraints in Truck table, like primary key or foreign key etc..


text:
Q: Holomorphic maps of the Riemann sphere I'm trying to understand a proof that the holomorphic maps of the Riemann sphere are the rational functions from this book:

All rational maps are analytic from the extended plane to itself. For the converse, suppose $f(z) \in \mathbb{C}$ for all $z \in \mathbb{C}_\infty$. Then $f$ is entire and bounded and thus constant. We can therefore assume that $f(z_0) = \infty$ for some $z_0 \in \mathbb{C}$ (consider $f(1/z)$ if necessary). By continuity of $f$ the point $z_0$ cannot be an essential singularity of $f$. In other words, $z_0$ is a removable singularity or a pole. By the uniqueness theorem, the poles cannot accumulate in $\mathbb{C}_\infty$. Since the latter is compact, there can thus only be finitely many poles. Hence, after subtracting the principal part of the Laurent series of $f$ around each pole in $\mathbb{C}$ from $f$, we obtain an entire function which grows at most like a polynomial. By Liouville's theorem, such a function must be a polynomial and we are done.

I have a few questions regarding this:

*

*Using the continuity argument can we also conclude that $z_0$ must be a pole?

*Why does the uniqueness theorem imply the poles cannot accumulate in $\mathbb{C}_\infty$?

*Perhaps slightly less relevant to this proof, does $f : \mathbb{C}_\infty \to \mathbb{C}_\infty$ holomorphic imply $f$ is meromorphic? I'm using Conway's definition that $f$ is meromorphic iff it is analytic except for poles.

A: *

*Yes. It must be either a pole or an essential singularity, and essential singularities were ruled out. Though to be exact, we also have to show that it is isolated, first, which is done in the next step.

*If they did accumulate, then their accumulation point would be an accumulation point of points on the domain where $f$ is $\infty$. The function which is $\infty$ everywhere is a holomorphic function with such an accumulation point, and since it is unique, $f$ must be this same constant function. This would make $z_0$ neither a pole, nor removable, nor essential, by the way. But it would make $f$ rational, depending on how you define rational. But I admit that this could have been communicated better by the author.

*No, meromorphic functions make a distinction between $\infty$ and other points, while holomorphic ones do not. The function which is a constant $\infty$ is not meromorphic because the singularities are not isolated, for instance, but it is holomorphic as a function $\mathbb C^\infty\to\mathbb C^\infty$.


text:
Q: Explicit and safe git pull in Intellij IDEA Is it possible to do "git pull" safely in Intellij IDEA 9?
Now I am using Git -> Pull Changes... and then I have to select branch explicitly - this is source of error if I pull from not current branch by error. This is completely unsafe. I wonder if there is a safer way to do "git pull" in IDEA through standard UI.
Use git pull in command line is not a good option, because we have IDE to increase productivity and convenience and part of functions is already implemented well for git.
Another major case is when you want to pull changes from tracking branch. For example your have created newfeature branch from master on local master and want to update it from master.

A: Vladimir, you may use the Update Project action.
It performs git pull for the tracked branch.

A: I'd recommend to use an external Git client for such tasks and the internal one for compare or commit tasks.


text:
Q: Differential Equation power spectra ε = .1; A = 0; ω0 = 1; ωf = 0;
data =
  NDSolve[
    {x''[t] == ε (1 - x[t]^2) x'[t] - ω0^2*x[t] + A*Cos[ωf*t], x[0] == 1, x'[0] == 0},
    {t, 0, 100}];
Periodogram[data, ScalingFunctions -> "Absolute", PlotRange -> All]

How would I create a suitable Power spectrum of the frequencies that this system has. For these set of values (at the top), there should ideally be only one unique frequency (ω0) since the other one is not in play.
Mathematica's example of power spectra utilizes the periodogram funcition, although I don't really understand what it does mathematically, so there is room for using another type of graph.

A: ε = 1/10; A = 0; ω0 = 1; ωf = 0;
sol = NDSolve[{x''[
      t] == ε*(1 - x[t]^2) x'[t] - ω0^2*x[t] +
      A*Cos[ωf*t], x[0] == 1, x'[0] == 0},
   x[t], {t, -100, 100}];
Plot[x[t] /. sol, {t, -100, 100}]

Periodogram[Flatten[Table[x[t] /. sol, {t, -100, 100, 0.5}]],PlotRange -> All]

A: Here's my shot at it:
ε = .1; A = 0; ω0 = 1; ωf = 0;

sol = First[NDSolve[
    {x''[t] == ε (1 - x[t]^2) x'[t] - ω0^2*x[t] + A*Cos[ωf*t], x[0] == 1, x'[0] == 0},
    x, {t, 0, 100}]];
f = x /. sol;
data = Table[f[t], {t, 0, 100}];

Periodogram[data, ScalingFunctions -> "Absolute"]

A: Consider the equation: $$\ddot{x} = (x,\dot{x},t)$$
The numerical solution generates a sequence of values of x at discrete values of t. This sequence is known as time series. Plotting x pk t might seem random or noisy, but often it contains harmonics at certain frequencies. Dominant frequencies in time series data can be investigated using the Discrete Fourier transform. For example we take N equally spaced values from the time series - $$x = x_{0},x_{1}, ..., x_{N}$$
The Discrete Fourier transform is defined as follows: $$X_{k}=\frac{1}{\sqrt{N}}\sum_{m=0}^{N}x_{m}e^{\frac{-2\pi ikm}{N}},   (k=0,1,2,...,N-1)$$
Generally $X_{k}$ is a complex number. To analyse the frequency structure we analyse the power spectrum $P(\omega _{k})$ defined by: $$P(\omega _{k})=X_{k}\overline{X_{k}}=\left | X_{k} \right |^{2}$$
ε = .1; A = 0; ω0 = 1; ωf = 0;

ff = x[t] /.
 First[NDSolve[{x''[
    t] == ε (1 - x[t]^2) x'[t] - ω0^2*x[t] +
    A*Cos[ωf*t], x[0] == 1, x'[0] == 0},
 x, {t, 0, 300}]][[1]]

Table[ff, {t, 0, 100}] // Fourier // Abs //
 ListLogPlot[#, PlotRange -> All] &

A: The code that gives me the best results is this.
ε = 3; A = 5; ω0 = 1; ωf = 1.788;
sol = NDSolve[{x''[t] == ε*(1 - x[t]^2) x'[t] - ω0^2*x[t] +
    A*Sin[ωf*t], x[0] == 1, x'[0] == 0}, x[t], {t, 0, 500}, MaxSteps -> Infinity]

Periodogram[Flatten[Table[x[t] /. sol, {t, 0, 500, 1}]],
    PlotRange -> All, ScalingFunctions -> "Absolute"]


text:
Q: Find the rotation symmetries of cube in terms of the four long diagonals. Request to vet the thorough description of the cube's rotations, and help in the second way to represent the rotation symmetries of the cube.
Have the usual way of describing the $24$ non-trivial rotation symmetries of a cube in terms of the eight vertices.
Also, represent the cube in terms of configurations of vertices by describing the two $x-z$ planes in the counter-clockwise direction, starting with farthest point in the $x,$ and $z$ directions.
For the purpose of stating configurations, use two square brackets, each containing $4$ vertices.
Say, the initial configuration as given below is: $[EHCD][FGBA].$
Say, for the below cube, have three non-trivial rotations along each of the $3$ axis, formed by the midpoints of opposite faces, as:
(A). Along the midpoints of faces along the $x-z$ axis, in counter-clockwise direction, i.e. the faces: $EHCD, FGBA$:

*

*$(EHCD)(FGBA),$ final configuration : $[DEHC][AFGB],$

*$(EC)(HD)(FB)(GA),$ final configuration : $[CDEH][BAFG],$

*$(EDCH)(FABG),$ final configuration : $[HCDA][GBAF].$
(B). Along the midpoints of faces along the $x-y$ axis, in counter-clockwise direction, i.e. the faces: $CBGH, DAFE$:

*

*$(CBGH)(DAFE),$ final configuration : $[FGHE][ABCD],$

*$(CG)(BH)(DF)(AE),$ final configuration : $[ABGF][DCHE],$

*$(CHGB)(DEFA),$ final configuration : $[DCBA][EHGF].$
(C). Along the midpoints of faces along the $y-z$ axis, in counter-clockwise direction, i.e. the faces: $CDAB, HEFG$:

*

*$(CDAB)(HEFG),$ final configuration : $[HGBC][EFAD],$

*$(CA)(DB)(HF)(EG),$ final configuration : $[GFAB][HEDC],$

*$(CBAD)(HGEF),$ final configuration : $[FEDA][GHCB].$
Similarly, there are $8$ non-trivial rotations about the diagonally opposite vertices, in $\pm120^o$ counter-clockwise direction.
There are $4$ such vertex pairs.
In the below labelled cube, have:
$E-B, C-F, H-A, D-G.$
The symmetries are given by:
(D). About the vertices $C-F$:

*

*$(HDB)(EAG),$ final configuration : $[GBCH][FADE],$

*$(HBD)(EGA),$ final configuration : $[ADCB][FEHG],$
(E). About the vertices $E-B$:

*

*$(HDF)(CAG),$ final configuration : $[EFGH][DABC],$

*$(HFD)(CGA),$ final configuration : $[EDAF][HCBG],$
(F). About the vertices $H-A$:

*

*$(CEG)(FBD),$ final configuration : $[CHGB][DEFA],$

*$(CGE)(FDB),$ final configuration : $[GHEF][BCDA],$
(G). About the vertices $D-G$:

*

*$(EAC)(HFB),$ final configuration : $[CBAD][HGFE],$

*$(ECA)(HBF),$ final configuration : $[AFED][BGHC],$
Next, there are six non-trivial edge rotations of $180°,$ about the midpoints of diagonally (long) opposite edges.
(H). Axis about the midpoints of the opposite edges: $H-G, D-A$:
$(HG)(DA)(EB)(CF),$ final configuration : $[BGFA][CHED],$
(I). Axis about the midpoints of the opposite edges: $H-C, F-A$:
$(HC)(FA)(EB)(DG),$ final configuration : $[BCHG][ADEF],$
(J). Axis about the midpoints of the opposite edges: $H-E, B-A$:
$(HE)(BA)(DG)(CF),$ final configuration : $[HEFG][CDAB],$
(K). Axis about the midpoints of the opposite edges: $C-D, G-F$:
$(CD)(GF)(EB)(AH),$ final configuration : $[BADC][GFEH],$
(L). Axis about the midpoints of the opposite edges: $C-B, E-F$:
$(CB)(EF)(HA)(DG),$ final configuration : $[FABG][EDCH],$
(M). Axis about the midpoints of the opposite edges: $E-D, B-G$:
$(ED)(BG)(HA)(CF),$ final configuration : $[DAFE][CBGH],$

Next, is the job to represent the $24$ rotation symmetries using the four diagonals.
Let us call the two representations: $Cub_8,$ and $Cub_4$ respectively.
$Cub_8$ is based on the $8$ vertices, and hence a subset of $S_8.$ While $Cub_4$ is based on the $4$ long diagonals, and hence a subset of $S_4.$ In fact, $Cub_4$ is isomorphic to $S_4.$
Let these four diagonals :$EB, HA, CF, DG,$ be named after the first letters :$E, H, C, D,$ respectively. I.e. the long diagonals are named by the vertices in the initial configuration shown below, in the top $x-z$ plane.
The case of $180^o$ rotations about the midpoints of diagonally opposite edges, seems toughest in the second representation.
There are six such rotations, and each should have a unique representation by a single transposition; but cannot prove it.
So, if a proof could also be provided that each of such $6$ symmetries needs just a single transposition of the four diagonals, then better.
Though, also have $4C2=6$ combinations of the four diagonals, taken two for the purpose of a single transposition.
(H). Axis about the midpoints of the opposite edges: $H-G,D-A> (HD),$ i.e. the transposition of the two long diagonals $HA, DG$ occurs.
(L). Axis about the midpoints of the opposite edges: $C-B, E-F> (EC),$
i.e. the transposition of the two long diagonals $EB, CA$ occurs.
Am sure about the above two symmetries, labelled: (H), (L).  But, not about the rest $4$ edge symmetries of $180^o$ rotations, as stated below:
(I). Axis about the midpoints of the opposite edges: $H-C, F-A: ,$
(J). Axis about the midpoints of the opposite edges: $H-E, B-A: ,$
(K). Axis about the midpoints of the opposite edges: $C-D, G-F: ,$
(M). Axis about the midpoints of the opposite edges: $E-D, B-G: ,$
Would be very much helped if some gif as here, be provided.

A: Notation
Label the vertices of the cube as follows:

\begin{array}{cc}
\text{vertex name} & \text{coordinates} \\ \hline
0 & (0,0,0) \\
1 & (0,0,1) \\
2 & (0,1,0) \\
3 & (0,1,1) \\
4 & (1,0,0) \\
5 & (1,0,1) \\
6 & (1,1,0) \\
7 & (1,1,1)
\end{array}
That is, we treat the coordinates as digits of a binary number, also called bits.
Vertices at two ends of an edge have names differing by one bit
(such as the pair $2=010_2$ and $3=011_2$ or the pair $1=001_2$ and $5=101_2$).
Vertices at two ends of a face diagonal have names with just one matching bit
(such as the pair $4=100_2$ and $7=111_2$).
Vertices at two ends of a body diagonal have names with all bits different,
so if one vertex has name $x$ then the other has name $7 - x.$
We can identify each body diagonal by the lower-numbered vertex at an end of the diagonal, so the diagonals are named $0,1,2,3.$
We can describe the "home" orientation of the cube by listing the vertices of the cube by name in increasing numerical order.
We can describe any other orientation by replacing each vertex name with the name of the vertex that now lies at the same point.
Similar to the notation in the question, we can use square brackets to write the vertices in groups of four and omit commas between vertex names.
So the home orientation is $[0123][4567]$ and the result of rotating the face $0123$ so that vertex $0$ moves to the home position of vertex $1$ is $[3012][7456].$
But I will just write the permutations of vertices (eight digits in groups of one or more), since the listing of the orientation can be obtained by permuting the vertices of the home position.
I will also write the permutations of the diagonals as permutations of the digits $0,1,2,3$ which name the diagonals.
Rotations of faces
Take a pair of faces. One face has all $0$s at a particular bit position.
The other has all $1$s at that bit position.
Take the vertices around one face in cyclic order. The non-constant bits on that face cycle through two-bit Gray code.
The permutation of one $90$-degree rotation is simply the cyclic list of four vertices of one face in a cycle, and the other four vertices in a second cycle. Order the second cycle so that if diagonal $m$ transitions to diagonal $n$ on one face then diagonal $m$ rotates to diagonal $n$ on the other face.
The permutation of the body diagonals is just one of the four-cycles with each vertex name translated to its body-diagonal name; that is, if the vertex name is $n$ and $n>3,$ replace $n$ by $7 - n.$
The remaining permutations are just the square and inverse of the first permutation.
For the square we have four two-cycles of vertices; these reduce to two two-cycles of body diagonals when we replace vertex names with their body-diagonal names and eliminate duplicate cycles.
Do this for three pairs of faces.
In the table below, after translating a four-cycle of vertices into the vertices at the opposite ends of the body diagonals, I rewrite the second cycle starting at its lowest-numbered vertex. In later parts of this answer I also rewrite other cycles to start at their lowest-numbered vertex.
\begin{array}{cc}
\text{faces} & \text{vertex permutations} & \text{diagonal permutations} \\ \hline
0123,4567 & (0132)(4576)     & (0132) \\
          & (03)(12)(47)(56) & (03)(12) \\
          & (0231)(4675)     & (0231) \\
0145,2367 & (0154)(2376)     & (0123) \\
          & (05)(14)(27)(36) & (02)(13) \\
          & (0451)(2673)     & (0321) \\
0246,1357 & (0264)(1375)     & (0213) \\
          & (06)(24)(17)(35) & (01)(23) \\
          & (0462)(1573)     & (0312)
\end{array}
Rotations holding vertices fixed
Choose two body-diagonally opposite vertices ($n$ and $7 - n$) to be held fixed.
List the adjacent vertices of one of the fixed vertices.
The permutation of vertices is this list in one three-cycle, the other ends of the body diagonals at these three vertices in a matching cycle (diagonal $m$ transitions to the same diagonal $n$ in both cycles) and two singletons for the remaining vertices.
The permutation of body diagonals is the first three-cycle with vertex names replaced by their body-diagonal names.
The other non-trivial rotation around these vertices is the inverse of the first rotation.
Do this for four pairs of vertices.
\begin{array}{cc}
\text{vertices} & \text{vertex permutations} & \text{diagonal permutations} \\ \hline
0,7 & (0)(124)(365)(7) & (0)(123) \\
    & (0)(142)(356)(7) & (0)(132) \\
1,6 & (035)(1)(274)(6) & (032)(1) \\
    & (053)(1)(247)(6) & (023)(1) \\
2,5 & (036)(174)(2)(5) & (031)(2) \\
    & (063)(147)(2)(5) & (013)(2) \\
3,4 & (056)(172)(3)(4) & (021)(3) \\
    & (065)(127)(3)(4) & (012)(3)
\end{array}
Rotations of edges
Choose an edge and the diagonally opposite edge. The diagonally opposite edge is found by taking the names of the first edge and flipping the two bits that are constant on that edge.
For the permutation of vertices, the (single) rotation of these edges has four two-cycles. Each of the two named edges is a two-cycle, and each of the diagonals that does not have a vertex on these edges is a two-cycle.
For the permutation of body diagonals, take one of the edges and convert its vertex names to body-diagonal names. Those two body diagonals are a two-cycle and the other body diagonals are singletons.
\begin{array}{cc}
\text{edges} & \text{vertex permutations} & \text{diagonal permutations} \\ \hline
01,67 & (01)(25)(34)(67) & (01)(2)(3) \\
23,45 & (07)(16)(23)(45) & (0)(1)(23) \\
02,57 & (02)(16)(34)(57) & (02)(1)(3) \\
13,46 & (07)(13)(25)(46) & (0)(13)(2) \\
04,37 & (04)(16)(25)(37) & (03)(1)(2) \\
15,26 & (07)(15)(26)(34) & (0)(12)(3)
\end{array}
It's all quite mechanical and the permutations can be worked out without diagrams.
The main trick is simply to be able to quickly know which vertices are adjacent to which and which are at opposite ends of a body diagonal.
Any labeling would suffice if you can memorize all these relationships, but the labeling in this answer makes the relationships evident through arithmetic.


text:
Q: Need to checkin a file in TFS Work space Unknowingly i deleted a useraccount from TFS server where he doesn't checkin the checkout file.
Now i am facing the merging issue..
Unable to perform operation on $/ERPONCLOUD/Development/V1.5/Source/Presentation/WebUI/Script/ControlPanel/UserCreation.js. The item $/ERPONCLOUD/Development/V1.5/Source/Presentation/WebUI/Script/ControlPanel/UserCreation.js is locked in workspace NCWS054;Suganth.
Regards
Sundar

A: UPDATE:
Based on Sundaresan's comment below, resolved the issue via create another branch by eliminating the deleted user.

You can try below ways to unlock the file:

*

*tf lock /lock: none Please see Lock Command for details:

To use the lock command, you must have the Lock permission set to
  Allow. Having the Unlock other user's changes permission set to Allow
  is required to remove a lock held by another user if you do not have
  Write permission for that user's workspace

tf lock /lock:none /workspace:workspacename [/recursive][/login:username,[password]] [/collection:TeamProjectCollectionUrl]
UPDATE:
In your case please try below command: (According to the error message,the file is locked in workspace NCWS054 and Suganth, So, you need to unlock in both workspace)
tf lock /lock:none /workspace:NCWS054 $/ERPONCLOUD/Development/V1.5/Source/Presentation/WebUI/Script/ControlPanel/UserCreation.js /login:Domain\user,password /collection:http://servername:8080/tfs/DefaultCollection

*

*tf undo The undo command removes any locks on the items. See Undo command
To unlock individual files run the command below in Visual Studio Command Prompt:
tf undo "file_path" /workspace:workspace_name
e.g.:
tf undo $/ERPONCLOUD/Development/V1.5/Source/Presentation/WebUI/Script/ControlPanel/UserCreation.js /workspace:NCWS054
To unlock the whole folder in one shot:
tf undo $/ERPONCLOUD/Development/V1.5/Source/Presentation/WebUI/Script/ControlPanel/* /workspace:NCWS054
here it will unlock all files which is inside ControlPanel folder.
UPDATE:
In your case, if it is a remote workspace, please try below command:
tf undo /collection:http://servername:8080/tfs/DefaultCollection /workspace:NCWS054;workspaceOwner $/ERPONCLOUD/Development/V1.5/Source/Presentation/WebUI/Script/ControlPanel/UserCreation.js

*

*You can also unlock other users file using TFS Sidekick tools:
It gives you a graphical interface to do all these commands, which makes it much easier to perform these tasks.
You can also reference this thread: How to unlock a file from someone else in Team Foundation Server

A: Team Foundation Sidekicks from Attrice (just Google it) are very helpful here. You can find all workspaces and delete the ones that are locking the files you need.

A: If you install TFS PowerTools for whatever version of TFS you have (e.g. TFS 2015 you should use https://marketplace.visualstudio.com/items?itemName=TFSPowerToolsTeam.MicrosoftVisualStudioTeamFoundationServer2015Power)
It adds many useful things, including ways to do this through the UI.
With Powertools installed:

*

*Open Soruce Control Explorer in Visual Studio

*Right click some file or folder or Team Project and select from the fly-out menu "Find" > "Find by Status..."

*Choose to "Display all checked out" or optionally search for just the files checked out to the deleted user. Then click "Find"

*Choose/Highlight any User/Workspace/File combination desired and Right click and "Undo..."

*Choose OK/Yes to all the prompts confirming you want to do it and informing you what the remote workspace would have to do if you continue.

I've had to use this many times because a developer's machine/hard-drive fails, or a mapped workspace folder was accidentally removed, an unused VM was reclaimed before properly disconnected from TFS, etc. I prefer doing it through the UI vs command line.


text:
Q: Help, I am having difficulty understanding p-groups! Kindest regarts So, I need to memorise this proof for an exam, and it seems to be just checking the subgroup criterion. However, I don't actually understand what p-groups are by the definition at the top! Some illustrative examples would be much appreciated!

In particular, this confuses me.


text:
Q: Keep trying a print command LP until successful I wish to keep sending the printer print command until the print succeeds. If it succeeds printing then it should delete the file.
Below is my script.
until ssh root@45.76.162.227 'lp -d Brother_HL_L2350DW_series $FILE'
do
  echo "Deleting $FILE"
  rm $FILE;
done

The issue is that it deletes the file rm $FILE; even if the print command lp -d Brother_HL_L2350DW_series $FILE fails.
Below is a sample failing print command.
ssh root@remotehost 'lp -d Brother_HL_L2350DW_series /home/system/test8.pdf'

lp: Transport endpoint is not connected

[system@live send4print]$ echo $?
1

Can you please suggest how can I meet my requirement?

A: You are not understanding how iteration works.
Your script says:
Until successful:
  print stuff, and delete files

until ssh root@45.76.162.227 'lp -d Brother_HL_L2350DW_series $FILE'
do
  echo "trying again"
done

echo "Deleting $FILE"
rm $FILE;

There seems to be some other problems:

*

*FILE is in capitals (latent bug: capital letters are reserved and should not be used).

*Quoting problem $FILE will not be expanded.

*It would be a good idea to rate throttle it, put a sleep in there.


text:
Q: YAML - DownloadPipelineArtifact@2 to download files with specific extension I have a YAML file with a task to download the artifact:
- task: DownloadPipelineArtifact@2
  inputs:
    artifact: '$(Build.BuildNumber)_$(BuildConfiguration)'
    path: Service\ProjectName

Logs for this task:
Downloading: D:\a\1\s\Service\ProjectName\Hosts.Console/Hosts.Console.csproj
Downloading: D:\a\1\s\Service\ProjectName\Hosts.Console/bin/Debug/netcoreapp3.1/Hosts.Console.dll
Downloading: D:\a\1\s\Service\ProjectName\Hosts.Console/bin/Debug/netcoreapp3.1/Entities.dll
Downloading: D:\a\1\s\Service\ProjectName\Hosts.Console/bin/Debug/netcoreapp3.1/Hosts.Console.deps.json
Downloading: D:\a\1\s\Service\ProjectName\Hosts.Console/bin/Debug/netcoreapp3.1/Entities.pdb
Downloading: D:\a\1\s\Service\ProjectName\Hosts.Console/bin/Debug/netcoreapp3.1/Hosts.Console.exe

I only want to download files that end with .csproj
How do I update the task to perform that?
- task: DownloadPipelineArtifact@2
  inputs:
    artifact: '$(Build.BuildNumber)_$(BuildConfiguration)'
    #patterns:
    path: Service\ProjectName

A: You can use the patterns argument in the task.
patterns:(Optional) One or more file matching patterns (new line delimited) that limit which files get downloaded. More Information on file matching patterns. Argument aliases: itemPattern
For example: Given the pattern **/*.csproj.


text:
Q: Hadoop error running the file gives the error I have a Hadoop java file for running it in my eclipse IDE and When I run this hadoop to generate the sequence file from Input text file I getting the following error.
   Feb 12, 2013 6:33:02 PM org.apache.hadoop.fs.FileSystem$Cache$Key <init>
   WARNING: uri=file:///

   javax.security.auth.login.LoginException: Login failed: Cannot run program "whoami":        CreateProcess error=2, The system cannot find the file specified
at
                    org.apache.hadoop.security.UnixUserGroupInformation.login(UnixUserGroupInformation.java:250       )
       at org.apache.hadoop.security.UnixUserGroupInformation.login(UnixUserGroupInformation.java:275)
at org.apache.hadoop.security.UnixUserGroupInformation.login(UnixUserGroupInformation.java:257)
at org.apache.hadoop.security.UserGroupInformation.login(UserGroupInformation.java:67)

at org.apache.hadoop.fs.FileSystem$Cache$Key.<init>(FileSystem.java:1438)

at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1376)

at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:215)

at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:120)

at org.apache.hadoop.mapred.JobConf.getWorkingDirectory(JobConf.java:319)

at org.apache.hadoop.mapred.FileInputFormat.addInputPath(FileInputFormat.java:313)

at main.LineIndexer.main(LineIndexer.java:81)

A: Running your IDE on Windows?
Try installing unxutils (unzip it somewhere), and putting the usr/local/wbin folder on your windows $PATH, restart your IDE (or add the path to your IDE runtime path) and try again


text:
Q: Laravel Nova - Scope Relationship Fields Is there a way of adding a scope to the BelongsToMany fields, such that when you attach related models you can only do so from restricted options?
Example:
Post belongsToMany Tags (using Spatie/Laravel-Tags).
Tags belongsToMany Posts.
Tags model has id, name, slug, type and timestamp properties.
On the Detail or Update views, I would like to be able to attach Tags to Post.
Using the default BelongsToMany field (or a third-party package) on the Post resource allows for me to add Tags to Post.
App\Nova\Post.php
public function fields(Request $request)
{
            BelongsToMany::make('Tags'),
}

However, I would like to only be able to add Tags where type = 'Books' to this model.

A: If you're using the Spatie Tags package, I'd suggest using their Nova Tags package. Then you can add the following to your field definitions:
Tags::make('Tags')->type('books'),

This will limit the available tags for that resource to those of type books. See the entry on the Nova Tags package and the base Spatie Tags package


text:
Q: Python interactive console using curses lib getstr() function dosen't wait for user input I'm trying to do an interactive console using the curses lib.
similar to this :
import curses

if __name__ == '__main__':
    stdscr = curses.initscr()
    stdscr.nodelay(False)
    curses.echo()
    curses.nonl()

while True:
    stdscr.addstr('#')
    stdscr.refresh()
    command = stdscr.getstr()

    if not command:
        continue

    if command == b'xys':
        stdscr.addstr('Execute xys block and print result')

    elif command == b'qwe':
        stdscr.addstr('Execute qwe block and print result')

    # ...

But it return this :
#xys
Execute xys block and print result#
#qwe
Execute qwe block and print result#
#
#
#

(after the Execute qwe block and print result# line I pressed the enter key)
The stdscr.getstr() function only wait for input half the time. The other half command = '' without any input. This is why you see the double # sign or the # sign at the end of each output.
The expecting result should be :
#xys
Execute xys block and print result
#qwe
Execute qwe block and print result
#

Any recommendation ?

A: I was using the pyCharm terminal (with the run > edit configurations... > emulate terminal in output console checked) but apparently curses lib and pyCharm are not compatible.
When running the script in the normal terminal, it worked perfectly.
Hope this will help someone!


text:
Q: Its there a way to use Firebird/Ibase with Doctrine in Zend Framework 2? Configuration of doctrine in Zend Framework:
This is the configuration to use mysql driver but i want tu use the PDO database driver for ibase.
   <?php
    return array(
       'doctrine' => array(
            'connection' => array(
                'orm_default' => array(
                    'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                    'params' => array(
                            'driver_options' => array(
                                  PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
                            ),
                    ),

                ),
            )
    ));
    ?>

A: Dbal Doctrine driver for firebird is a work in progress not yet merged on github
http://www.doctrine-project.org/jira/browse/DBAL-95
I have requested the patch and it will be integrated soon
On the Zend Framework side it should be possible to use the pdo addapter without dbal (unsupported yet)
https://zf2.readthedocs.org/en/latest/modules/zend.db.adapter.html#zend-db-adapter

A: Thanks!

Looks like meanwhile i can use the PDO for Ibase with a Zend Adapter

return array(
    'db' => array(
        'driver' => 'PDO_FIREBIRD',
        'database' => 'localhost:C:\Base.FDB',
        'username' => 'SYSDBA',
        'password' => 'masterkey',
    ),
);


text:
Q: Merge timepoints that occur on next row I have a large start end time-series database and want to merge any time entries that "end"(third column) at "00:00:00" and "start"(second column) at "00:00:00" in next row.
Current attempts delete the additional "00:00:00" in the end column that is correct there.
#Before
df<-data.frame(id=1,start=c("17/07/2017 19:30","17/07/2017 22:30",
                            "18/07/2017 00:30","18/07/2017 19:00","18/07/2017 21:30",
                            "19/07/2017 00:00","19/07/2017 02:30","19/07/2017 21:00",
                            "19/07/2017 22:30","20/07/2017 00:00",
                            "20/07/2017 03:00","20/07/2017 22:00","20/07/2017 23:00",
                            "21/07/2017 00:00","21/07/2017 01:30"),
               end=c("17/07/2017 22:00","18/07/2017 00:00","18/07/2017 02:30",
                     "18/07/2017 21:00","19/07/2017 00:00",
                     "19/07/2017 02:00","19/07/2017 04:30","19/07/2017 21:30",
                     "20/07/2017 00:00","20/07/2017 02:00",
                     "20/07/2017 04:00","20/07/2017 22:30","21/07/2017 00:00",
                     "21/07/2017 01:00","21/07/2017 02:00"))

#After
dfoutput<-data.frame(id=1,start=c("17/07/2017 19:30","17/07/2017 22:30",
                                  "18/07/2017 00:30","18/07/2017 19:00","18/07/2017 21:30",
                                  "19/07/2017 02:30","19/07/2017 21:00",
                                  "19/07/2017 22:30","20/07/2017 03:00","20/07/2017 22:00",
                                  "20/07/2017 23:00","21/07/2017 01:30"),
                     end=c("17/07/2017 22:00","18/07/2017 00:00",
                           "18/07/2017 02:30","18/07/2017 21:00","19/07/2017 02:00",
                           "19/07/2017 04:30","19/07/2017 21:30",
                           "20/07/2017 02:00","20/07/2017 04:00","20/07/2017 22:30",
                           "21/07/2017 01:00","21/07/2017 02:00"))

Current ifelse results delete "00:00:00" in end row that is correct.

A: I came up with two solutions in dplyr:
df %>%
  group_by(id) %>%
  mutate(index = (substr(start,12,16) == "00:00" &
                  substr(lag(end),12,16) == "00:00"),
         start2 = if_else(index, lag(start), start),
         end2 = if_else(lead(index), lead(end), end)) %>%
  mutate(start = if_else(is.na(start2), start, start2),
         end = if_else(is.na(end2), end, end2)) %>%
  filter(!index) %>%
  select(-index, -start2, -end2)

or
df %>%
  group_by(id) %>%
  arrange(start, end) %>%
  mutate(index1 = ((substr(start,12,16) == "00:00" &
                     substr(lag(end),12,16) == "00:00") |
                    (substr(lead(start),12,16) == "00:00" &
                       substr(end,12,16) == "00:00")),
         index2 = cumsum(index1 != c(F, lag(index1)[-1]))) %>%
  group_by(id, index2) %>%
  mutate(start = if_else(index1, first(start), start),
           end = if_else(index1, last(end), end)) %>%
  ungroup %>%
  select(-index1, -index2) %>%
  unique()

both give:
#> # A tibble: 12 x 3
#>       id start            end
#>    <dbl> <fct>            <fct>
#>  1     1 17/07/2017 19:30 17/07/2017 22:00
#>  2     1 17/07/2017 22:30 18/07/2017 00:00
#>  3     1 18/07/2017 00:30 18/07/2017 02:30
#>  4     1 18/07/2017 19:00 18/07/2017 21:00
#>  5     1 18/07/2017 21:30 19/07/2017 02:00
#>  6     1 19/07/2017 02:30 19/07/2017 04:30
#>  7     1 19/07/2017 21:00 19/07/2017 21:30
#>  8     1 19/07/2017 22:30 20/07/2017 02:00
#>  9     1 20/07/2017 03:00 20/07/2017 04:00
#> 10     1 20/07/2017 22:00 20/07/2017 22:30
#> 11     1 20/07/2017 23:00 21/07/2017 01:00
#> 12     1 21/07/2017 01:30 21/07/2017 02:00


text:
Q: What are benefits of C# interfaces I have done demo implementation using interface:
class Program
{
    static void Main(string[] args)
    {

        #region Calling method without interface
        GreaterThanZeroTest objGreaterThanZeroTest = new GreaterThanZeroTest { SomeTestVariable = 10 };
        Console.WriteLine(objGreaterThanZeroTest.SomeTestMethod().ToString());

        LessThanZeroTest objLessThanZeroTest = new LessThanZeroTest { SomeTestVariable = -1 };
        Console.WriteLine(objLessThanZeroTest.SomeTestMethod().ToString());
        #endregion

        #region Calling using interface
        runTest(new GreaterThanZeroTest() { SomeTestVariable = 10 });
        runTest(new LessThanZeroTest() { SomeTestVariable = 10 });
        #endregion

        Console.ReadKey();
    }

    public static bool runTest(ITest test)
    {
        return test.SomeTestMethod();
    }
}

public interface ITest
{
    int SomeTestVariable { get; set; }

    bool SomeTestMethod();
}

// Determines whether an int is greater than zero
public class GreaterThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable > 0;
    }
}

// Determines whether an int is less than zero
public class LessThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable < 0;
    }
}

I see two benefit from the above implementation:

*

*Code will look clean.

*It will save one line of code.

What are the other benefits that we will get from such implementation and when we should consider interface in the application architecture?

A: IMHO, the most important thing for me is it allows you to

*

*Mock some function for unit testing purpose.

*It allows the implementation of "Inversion of Control" or IoC

There are plenty of reasons in the universe you can just search it though but these are what I think are important


text:
Q: Are $\mathbb{R}$ and $\mathbb{R}^{\infty}$ isomorphic as groups under addition? The title says it all:
Are $\mathbb{R}$ and $\mathbb{R}^{\infty}$ isomorphic as groups under addition?
(By $\mathbb{R}^{\infty}$ I mean the cartesian product of countably-infinitely many copies of $\mathbb{R}$)

A: Yes. To see that, note that $\Bbb{R}$ and $\Bbb{R}^\infty$ are isomorphic as $\Bbb{Q}$-vector spaces. Indeed, they are isomorphic iff they have the same $\Bbb{Q}$-dimension, and they have the same $\Bbb{Q}$-dimension because they have the same cardinality.
Isomorphic vector spaces are, in particular, isomorphic as abelian groups. So $\Bbb{R} \cong \Bbb{R}^\infty$.

A: $\mathbb{R}$ and $\mathbb{R}^\infty$ both have cardinality $\mathfrak{c}$, and are vector spaces over $\mathbb{Q}$.
The following lemma may be helpful:
Lemma. Let $X, Y$ be vector spaces over a field $F$. If $|X| = |Y| > |F| \ge \aleph_0$, then $X, Y$ are isomorphic as vector spaces.
Proof. Let $I$ be an index set for a basis of $X$ over $F$. We have that
$$
|X| =
\sum_{i \in \mathbb{N}} \left|{I \choose i}\right| |F \setminus \{0\}|^i.
$$
Since $F$ is infinite, $|F \setminus \{0\}|^i = |F|$.
If $I$ were finite, we would have $\left|{I \choose i}\right| < \aleph_0$,
$|X| \le \aleph_0^2 |F| = |F|$, contradicting our assumption that $|X| > |F|$.
So $I$ is infinite, so $\left|{I \choose i}\right| = |I|$.
So $|X| = \aleph_0 |I| |F| = |I|$.
Similarly, let $J$ be an index set for a basis of $Y$ over $F$, and we have
$|Y| = |J|$.
Therefore we conclude $|I| = |J|$; then there is a bijection $f: I \to J$.
Mapping each basis element $\alpha_i$ of $X$ to the basis element $\beta_{f(i)}$ of $Y$ we have an isomorphism of $X$ and $Y$.
$\square$
Now note that isomorphic vector spaces are in particular isomorphic as abelian groups.


text:
Q: Need solution for this CB BJT circuit How can I solve this circuit?

simulate this circuit – Schematic created using CircuitLab
This capacitor confuses me when I tried to do DC biasing.
Also when I draw small signal equivalent circuit( T model ) to find the equation for Rin (=re) and Rout(=R1) but not Av ( voltage gain ) and Ai (current gain ).
here is my small signal equivalent circuit:

simulate this circuit

A: As always, it's helpful to first draw the DC and AC circuits.
DC circuit:

simulate this circuit – Schematic created using CircuitLab
The operating point is evident by inspection:
$$I_C = \frac{\beta}{1 + \beta}I_2  = \alpha I_2 $$
$$V_C = I_C(\frac{75\Omega}{\alpha} + \frac{100k\Omega}{\beta}) + V_{BE} $$

Update to address comment:

I can't perfectly grasp your equation for Vcc.I think understand you
  divide resistance with beta and alpha to make them equivalent
  resistance looking through C.

Assuming you meant \$V_C\$ rather than \$V_{CC}\$, by KVL we have
$$V_C = V_E + V_{BE} + V_{R1}$$
We have
$$V_E = I_E R_S = \frac{I_C}{\alpha}R_S $$
and
$$V_{R1} = I_B R_1 = \frac{I_C}{\beta}R_1$$
Thus
$$V_C = I_C(\frac{R_S}{\alpha} + \frac{R_1}{\beta}) + V_{BE} $$

AC circuit:

simulate this circuit
The small-signal circuit is thus

simulate this circuit
This is a straightforward circuit to solve.  What have you tried so far?

A: In small signal, your Vs becomes a short.
Make sure you're not confusing the T and pi models. Here's a good reference:
http://www.ittc.ku.edu/~jstiles/412/handouts/5.6%20Small%20Signal%20Operation%20and%20Models/The%20Hybrid%20Pi%20and%20T%20Models%20lecture.pdf
Lastly, determine what Vout/Vin is (Av) and Iout/Iin (Ai).
Also, I doubt your Rin and Rout are so simple. To obtain those, you'll need to apply a test voltage or test current to the input and solve for the other one. Then you'll have Vin/Iin = Rin and Vout/Iout = Rout. When dealing with voltage dependent current sources like you have, you almost always need to factor that into the problem which is why you need to solve using test voltages/currents.


text:
Q: What is special about a function being elementary? Functions such as $ \sin(x) $ are considered to be elementary, however functions like $ \text{erf}(x) $ are considered to be non-elementary.
What makes elementary functions different from non-elementary functions, both $ \sin(x) $ and $ \text{erf}(x) $ can only be expressed as an infinite sum containing the 4 basic operations, division, multiplication, addition, and subtraction. Is what makes a function elementary a purely arbitrary decision?