what will happen to the uniform matroid $U_{2,m}$ if we remove an element from it?

Question: I am trying to figure out what will happen to the uniform matroid $U_{2,m}$ if we remove an element e from it, where e is neither a coloop nor a loop. I am guessing that it will become disconnected but I am not sure from this.
A uniform matroid is defined as: If m and n are non-negative integers with $m \leq n.$ Let $E$ be an $n$-element set and $\mathcal{B}$ be the collection of $m$-element subsets of $E.$ Then it is easy to check that $\mathcal{B}$ is the set of bases of a matroid on $E.$  We denote this matroid by $U_{m,n}$ and call it the uniform matroid of rank $m$ on an $n$-element set.
I also know that the drawing of a $U_{2,5}$ matroid is just a line segment with 5 dots on it representing the vertices from a picture online, is this always the drawing of a uniform matroid $U_{2,m}$ matroid?
Any clarification will be greatly appreciated!
Answer: First we should note that $U_{2, n}$ has no loops, since the rank of any singleton is 1. If $n\geq 3$, $U_{2, n}$ has no coloops, since every element is in a circuit (any 3 element set containing said element). Thus, the condition of $e$ not being a loop or coloop is irrelevant unless $n=2$, in which case both elements are coloops. So let $n\geq 3$.
Now, recall that given a matroid $M$ with elements $E$ and an element $e\in E$, the matroid $M\backslash e$ has for independent sets those of $M$ contained in $E-e$, or equivalently, the bases of $M\backslash e$ are the bases of $M$ contained in $E-e$. Hence, $U_{2, n}$ minus an element is isomorphic to $U_{2, n-1}$. Hence, the resulting matroid is not connected if and only if $n=3$. In general, $U_{m,n}$ is connected unless $m\in \{0,n\}$.
Now, if you were to delete more than one element, you are bound to decrease the rank of the uniform matroid at some point, as you at some point will not have enough elements to keep the rank up. In general, for the uniform matroid $U_{m, n}$ and a set $T$ of $t$ elements,
$$
U_{m, n}\backslash T \cong \begin{cases}U_{n-t, n-t}, & \text{if } n-m\leq t\leq n,\\ U_{m, n-t}, & \text{if } t<n-m.
\end{cases}
$$
For instance, if we delete an element from $U_{2,2}$ (which is necessarily a coloop) we obtain $U_{1,1}$.
Indeed, the drawing of $U_{2, m}$ is in general a line with $m$ points. Lines in such matroid drawings are rank 2 flats.
Comment: Why the drawing is just a line?
Comment: This is just convention for how we draw matroids. Matroids of rank at most four are drawn as follows: you put a point for each non-loop element, parallel elements are drawn next to each other, three elements forming a circuit are on a line, and four elements forming a circuit are on a plane. Loop elements are drawn somewhere to the side of the figure, usually in a box, indicating these are loops. It is harder to do this with higher ranks, because it is hard to draw in dimension four or higher. James Oxley's book describes this process with some examples.
Comment: I did not quite well understand why the figure is a line? Is it because our bases are always  consisting of 2 points in $U_{2,m}$?
Comment: oh I got you because any set of 3 elements or more is a circuit in our matroid, right?
Comment: Yes. Any three points form a circuit, so must be on a line. You can try drawing this for yourself, but the only way to do this is to put them all on a single line.
Comment: what will happen if we contract an element that is nether a loop nor a coloop? Will the matroid become containing a loop?
Comment: But fig. 1.8 in Oxley has a loop in it and it is a geometric representation of a rank 2 matroid, can you clarify this please?
Comment: @Hope I think at this point you ought to make a new post with your new questions (mainly so that people can actually find this information if they are looking for it).
Comment: but my last question is very related to the first line of your answer here, should I still post a new question?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/150503/discussion-between-mathieu-rundstrom-and-hope).


Console Edge? Existe?

Question: Existe console no Edge? Como abrir e usar?
Tem algumas coisas que preciso consertar no CSS do site no Edge e sem console não consigo saber.
Comment: Acredito que seja o mesmo do IE, F12.
Comment: Obrigado, não tinha testado, deu certo!!
Answer: Existe sim, a tecla de atalho seria o F12.
Veja a documentação sobre o funcionamento.
Comment: Veja [essa](https://pt.stackoverflow.com/questions/79964/quais-prefixos-de-propriedades-css-s%C3%A3o-compat%C3%ADveis-com-o-edge) resposta sobre os prefixos no Edge.
Comment: E qual o prefixo do Microssoft Edge? Continua sendo o -ms do internet explorer?

Console Edge? Existe?


Interpreting nm output after rejected app

Question: my app was rejected by Apple, because somehow my app uses private API's.
Apple said that my app uses
framework: '/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation': CFHashBytes
I couldn't find anything in the code, so I searched stackoverflow and fout out that I can use otool or strings.
With string I find two "hash" calls (wherever they are) and using nm, I get the following output:
nm Sporty\ Architect | grep hash
0000000100077490 T __TFO16Sporty_Architect12ActivityTypeg9hashValueSi
0000000100056240 T __TFO16Sporty_Architect12RotationModeg9hashValueSi
0000000100064480 T __TFO16Sporty_Architect13DraggedSliderg9hashValueSi
000000010003e3a0 T __TFO16Sporty_Architect8FileTypeg9hashValueSi
000000010003d910 T __TFO16Sporty_Architect9DateRangeg9hashValueSi
0000000100021360 T __TFO16Sporty_Architect9ModelModeg9hashValueSi
                 U __TFSig9hashValueSi
00000001000777b0 T __TTWO16Sporty_Architect12ActivityTypes8HashableS_FS1_g9hashValueSi
00000001000562e0 T __TTWO16Sporty_Architect12RotationModes8HashableS_FS1_g9hashValueSi
0000000100064500 T __TTWO16Sporty_Architect13DraggedSliders8HashableS_FS1_g9hashValueSi
000000010003e9d0 T __TTWO16Sporty_Architect8FileTypes8HashableS_FS1_g9hashValueSi
000000010003e080 T __TTWO16Sporty_Architect9DateRanges8HashableS_FS1_g9hashValueSi
0000000100021500 T __TTWO16Sporty_Architect9ModelModes8HashableS_FS1_g9hashValueSi
I think the U __TFSig9hashValueSi is it, isn't it? But now the question...how can i narrow this down any further?
It is beyond me, why Apple offers a validate button that shows that everything is OK and once the app is in review, it gets rejected for something, that could clearly be detected at compile time (or at least when it is submitted).
Answer: If you don't use any external API or framework, CFHashBytes is present only in Swift framework.
I had this issue with two Apps. I have sent this message to the Resolution Center and now both have been approved:
"Hello,
I think that there is an error. The only file that contains that non-public API is libswiftFoundation.dylib, framework used in Swift Apps. Xcode uses it automatically. Please, check it again.
Many thanks."
I hope this helps you.
Comment: Hello, thank you for your answer. I saw that I had a method that used the same (and an additional parameter) parameters than the CFHasBytes one. The Mrthod was called getBytes(bytes:length:index:). I can see why an automated test fould fail at this. I renamed the method and will submit again, if it fails again, I will add your comment. Thanks.


Postfix - How to prevent external clients from using my server as a relay?

Question: I have a postfix server installed on Ubuntu 14.04. A PHP script running on the machine uses it to send outgoing email. Additionally, I use postfix to receive mail sent to a local account, which is then forwarded to my personal gmail.
However, this means that anyone can connect to my server and use it as an open relay for spam. How can I  prevent remote connections from relaying email?
This is my main.cf:
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = aviacao.pt
virtual_alias_maps = hash:/etc/postfix/virtual
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = aviacao.pt, localhost.localdomain, localhost
relayhost =
mynetworks = 0.0.0.0/0
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4

If I change mynetworks to 127.0.0.0/8 then people won't be able to send email to the local account.
Comment: Go to http://postfix.org and look at the Documentation link. If you are putting a mailserver on the internet, you need to actually know how it works, not just follow instructions on a QA site.
Answer: Your smtpd_relay_restrictions should prevent that anyone can connect to my server and use it as an open relay for spam.
The value of mynetworks does not determine if others can email you.  127.0.0.0/8 is a correct value 0.0.0.0/0 is not.
What determines if email for your account email@example.com is accepted is determined by the settings that inform postfix that it should accept email for the example.com domainname, such as mydestination
Answer: the setting of smtpd_relay_restrictions you have is correct except that you defined your mynetworks wide open (shown below from your main.cf)
mynetworks = 0.0.0.0/0

Just remove mynetworks; the default value should restrict relay access. For example, mine comes out as shown below with default.
postconf -d |grep mynetworks
mynetworks = 127.0.0.0/8 192.168.1.0/24

You should really test your server to ensure that is not an open relay. There are lot of online tools available ex: http://www.mydnstools.info/smtprelay
Ref: http://www.postfix.org/SMTPD_ACCESS_README.html


ListView no AsyncTask

Question: Meu código não carrega os dados para list view quando ta dentro do AsyncTask, mas se for colocado no onCreateView funciona perfeitamente.
public class Tab_os_Fechadas extends Fragment {

    private String url ="http://redeml.no-ip.info/controleos/mobile/list_os_fechadas.php";
    private String parametros ="";
    private  ListView listOSFechadas;
    private int i;

    private LayoutInflater inflater;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

       View x =  inflater.inflate(R.layout.tab_os_fechada,null);

        new SolicitarDados().execute(url);
        return x;

    }

    private  class SolicitarDados extends AsyncTask<String, Void,String > {

        View view;

        @Override
        protected String doInBackground(String... urls) {
            return ConexaoDB.postDados(urls[0], parametros);
        }

        @Override
        protected void onPostExecute(String result) {

            try {
                JSONArray jsonarray = new JSONArray(result);
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject jsonobject = jsonarray.getJSONObject(i);

                }

                ArrayList<ItemOSFechadas> listaFechada = new ArrayList<ItemOSFechadas>();

                ItemOSFechadas a = new ItemOSFechadas("g1","ffff");
                ItemOSFechadas b = new ItemOSFechadas("g1","ffff");
                ItemOSFechadas c = new ItemOSFechadas("g1","ffff");
                ItemOSFechadas d = new ItemOSFechadas("g1","ffff");
                listaFechada.add(a);
                listaFechada.add(b);
                listaFechada.add(c);
                listaFechada.add(d);

                ListAdapterOSFechadas adapterOSFechadas = new ListAdapterOSFechadas(getContext(),listaFechada);
                listOSFechadas = (ListView)view.findViewById(listFechadasOS);
                listOSFechadas.setAdapter(adapterOSFechadas);
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}

Minha intenção é fazer meu retorno JSON e montar todo meu list view.
Answer: Não posso executar seu código por isso não tenho certeza, mas acho que seu problema esta relacionado com seu id de sua ListView.
listOSFechadas = (ListView)view.findViewById(listFechadasOS);

Não entendo o porque de listFechadasOs
como id, já que não existe nenhum integer(int) com este valor.
Há também algums erros com o View.
Tente editar seu código da seguinte forma:
//Criando variável view
private View view;
//Remova sua LitView da AsyncTask e defina em onCreateView.
@Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (view == null) {
        view = inflater.inflate(R.layout.tab_os_fechada,null);
       listOSFechadas = (ListView)view.findViewById(R.id.id_da_listview);
       new SolicitarDados().execute(url);
       }
       return view;
 }

Comment: Tentei dessa forma e não deu certo.. a minha listview não aparece os dados que crio, a minha função SolicitaDados é exeucutada normalmente, mas nao mosta os dados da listview
Comment: conseguir acertar, e ta funcionando ok , mas fui testar no celular e o listview nao carregou, mas no emulador do android studio carregou, como posso identificar o problema ?
Comment: E bem difícil te dizer somente olhando para este pedaço de código. Tente enviar seu projeto para o github e forneça o link para que eu possa tentar identificar seu problema.

ListView no AsyncTask


How to resend verification email django restframework?

Question: I can send a verification email upon registering the user so that the account can be activated. But how would one go about resending another verification email on an API? Here, I am making an activation link with a token in it and when the user opens the link it takes the token and verifies the user.
But how would resending the verification email work?
class RegisterUser(APIView):
    serialzer_class = RegisterSerialzer
    def post(self, request):
        user = request.data
        serializer = self.serialzer_class(data = user)
        serializer.is_valid(raise_exception = True)
        serializer.save()
        user_data = serializer.data
        # user = User.objects.get(username=serializer.data['username'])
        # print(user.id)
        # token = Token.objects.create(user=user)
        user = User.objects.get(email = user_data['email'])
        token = RefreshToken.for_user(user).access_token
        current_site = get_current_site(request).domain
        relativeLink = reverse('email-verify')

        absurl = 'http://'+current_site+relativeLink+"?token="+str(token)
        email_body = 'Hi '+ user.username + 'user the link below to verify your email \n' + absurl

        data = {'email_body':email_body,'to_email':user.email,
                'email_subject':'Verify your email'}
        Util.send_email(data)

class VerifyEmail(APIView):
    def get(self, request):
        token = request.GET.get('token')
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
            user = User.objects.get(id=payload['user_id'])
            user.is_verified = True
            # user.is_authenticated = True
            user.is_active = True
            # if not user.is_verified:
            user.save()
            return Response({'email':'successfuly activated'}, status=status.HTTP_200_OK)
        # except jwt.ExpiredSignatureError as identifier:
        except jwt.ExpiredSignatureError:
            return Response({'error':'Activation Expired expired'}, status=status.HTTP_400_BAD_REQUEST)
        # except jwt.exceptions.DecodeError as identifier:
        except jwt.exceptions.DecodeError:
            return Response({'error':'invalid token'}, status=status.HTTP_400_BAD_REQUEST)

Answer: My work around is asking for the email from the user or frontend, and then query the user to get email address and send it to the email.
class ResendVerifyEmail(APIView):
    serializer_class = RegisterSerialzer
    def post(self, request):
        data = request.data
        # email = data.get('email')
        email = data['email']
        print(email)
        try:
            user = User.objects.get(email=email)

            print('hello')
            if user.is_verified:
                return Response({'msg':'User is already verified'})
            print (user.username)
            token = RefreshToken.for_user(user).access_token
            current_site= get_current_site(request).domain
            relativeLink = reverse('email-verify')

            absurl = 'http://'+current_site+relativeLink+"?token="+str(token)
            email_body = 'Hi '+ user.username + ' this is the resent link to verify your email \n' + absurl

            data = {'email_body':email_body,'to_email':user.email,
                    'email_subject':'Verify your email'}
            Util.send_email(data)
            return Response({'msg':'The verification email has been sent'}, status=status.HTTP_201_CREATED)
        except User.DoesNotExist:
            return Response({'msg':'No such user, register first'})

Answer: If you are using allauth, this solution might work for you
from allauth.account.models import EmailConfirmationHMAC, EmailAddress
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

class ResendVerifyEmail(APIView):

    def post(self, request):
        data = request.data
        email = data['email']
        try:
            email_address = EmailAddress.objects.get(email=email)
            emac = EmailConfirmationHMAC(email_address=email_address)
            emac.send(request, signup=True)

            return Response({'msg': 'The verification email has been sent'}, status=status.HTTP_201_CREATED)
        except EmailAddress.DoesNotExist:
            return Response({'msg': 'No such user, register first'})


Can't receive RTSP live stream from an IP cam

Question: I want to receive live streaming from an IP camera using RTSP, I'm getting 'Can't play this video', and the following Exception:
07-16 14:06:26.945: D/MediaPlayer(19411): setDataSource IOException happend :
07-16 14:06:26.945: D/MediaPlayer(19411): java.io.FileNotFoundException: No content provider: rtsp://192.168.30.108:554
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1052)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:907)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:834)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.media.MediaPlayer.setDataSource(MediaPlayer.java:973)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.widget.VideoView.openVideo(VideoView.java:337)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.widget.VideoView.setVideoURI(VideoView.java:247)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.widget.VideoView.setVideoURI(VideoView.java:237)
07-16 14:06:26.945: D/MediaPlayer(19411):   at com.example.video_rtsp.MainActivity$2.run(MainActivity.java:59)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.os.Handler.handleCallback(Handler.java:733)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.os.Handler.dispatchMessage(Handler.java:95)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.os.Looper.loop(Looper.java:157)
07-16 14:06:26.945: D/MediaPlayer(19411):   at android.app.ActivityThread.main(ActivityThread.java:5293)
07-16 14:06:26.945: D/MediaPlayer(19411):   at java.lang.reflect.Method.invokeNative(Native Method)
07-16 14:06:26.945: D/MediaPlayer(19411):   at java.lang.reflect.Method.invoke(Method.java:515)
07-16 14:06:26.945: D/MediaPlayer(19411):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-16 14:06:26.945: D/MediaPlayer(19411):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-16 14:06:26.945: D/MediaPlayer(19411):   at dalvik.system.NativeStart.main(Native Method)
07-16 14:06:26.945: D/MediaPlayer(19411): Couldn't open file on client side, trying server side
07-16 14:06:26.955: V/MediaPlayer(19411): setVideoSurfaceTexture
07-16 14:06:26.955: V/MediaPlayer-JNI(19411): setAudioStreamType: 3
07-16 14:06:26.955: V/MediaPlayer(19411): MediaPlayer::setAudioStreamType
07-16 14:06:26.955: V/MediaPlayer(19411): setVideoSurfaceTexture
07-16 14:06:26.955: V/MediaPlayer(19411): prepareAsync
07-16 14:06:26.965: D/ProgressBar(19411): setProgressDrawable drawableHeight = 48
07-16 14:06:26.985: D/AbsSeekBar(19411): AbsSeekBar Constructor: misSeebarAnimationAvailable = true

I'm using the following way:
VideoView videoView = (VideoView) ((Activity) ctx).findViewById(R.id.videoView);

//add controls to a MediaPlayer like play, pause.
MediaController mc = new MediaController(ctx);
videoView.setMediaController(mc);

//Set the path of Video or URI
videoView.setVideoURI(Uri.parse("rtsp://192.168.30.108:554"));

//Set the focus
videoView.requestFocus();

can't say I'm sure this is the problem, but I think it's because this camera software needs authentication, but if so, I don't know how to provide the authentication to it.

After using MediaPlayer with setDataSource, I'm getting the following Exception:
07-21 12:04:11.677: W/System.err(17714): java.io.IOException: Prepare failed.: status=0x1
07-21 12:04:11.677: W/System.err(17714):    at android.media.MediaPlayer.prepare(Native Method)

I'm not sure if that related to a wrong way in setting the headers or not :
Uri uri = Uri.parse("rtsp://192.168.30.108:554");
Map<String , String> headres = new HashMap<String, String>();
headres.put("Authorization", "Basic ce0ca0f0864513c28c7be98f0f929be7b1f5db79"); //Also tried it without "Basic"
headres.put("encryption", "Default");
headres.put("mac", "9002A9D89200");
headres.put("random", "1715377261");
headres.put("realm", "Login to 90:02:a9:d8:92:00");

mediaPlayer.setDataSource(getApplicationContext(), uri, headres);

and this is a screenshots of login process headers and json data using firebug:
Comment: Try to play the stream on the same machine using another player like VLC
Comment: Did you try to put the authentication into the URI (in VLC as well) like @aergistal mentioned in his first comment?
In your example using `rtsp://username:email@example.com:554` instead of `rtsp://192.168.30.108:554`
Comment: Have you tried basic authentication `rtsp://username:firstname.lastname@example.com:554`? You may need a stream name too `rtsp://username:email@example.com:554/stream_name`
Comment: @aergistal yea I tried it and nothing new
Comment: @aergistal I tried that on VLC, and once I pressed play it popped up a dialog for user and password and once I entered them the stream played without problems
Comment: @Levit putting authentication into the URI of (VLC) works efficiently.
Comment: I'm not sure about that base64 encoding. How did you obtain it?
Comment: I don't know how, I didn't obtain it, I captured it when the login process completed successfully in the web service of the camera
Comment: @MuhammedRefaat: Have you found a solution? I got the same exception when trying to connect to a DLink IP Camera.
Comment: @Christopher unfortunately no
Answer: If the authentication mechanism is HTTP basic authentication then there might be way to set the required HTTP header: the MediaPlayer class has a method setDataSource taking a Map parameter for headers:
public void setDataSource (Context context, Uri uri, Map<String, String> headers)
You must set the Authorization header:
Authorization: Basic _credentials_
_credentials_ is the RFC2045-MIME Base64 encoding of the username:password string.
Comment: Thanks for your answer, kindly have a look at my updates
Comment: also when I performed decoding it gives me a binary data file not a specific words combination, and when encoding the username:password manually it doesn't give me the above code


Name of guy who teachs famous training technique for beginner drummers

Question: My teacher is bad at English and he couldn't pronounce the name of the guy who teaches a famous technique that he feels will really help me.  My teacher suggested that I should  train everyday using this technique:
<code>By legend
P - plant (Shaft)
C - cutting edge (tip of the drumstick)
</code>
On hi-hat, you use your drumstick and hit it in this sequence C-P-C-P. But you have to raise your wrist above the hi-hat when you do Cutting Edge.
Whats the name of the guy who teaches this technique?  If I know his name I can find him on-line.  In addition to this technique - he may teach others as well that myself or other beginning drummers may find helpful.
I'm not familiar with technical names...
Comment: Speaking as a _user_, not as a moderator, I don't see a problem with this kind of question beyond the title needing minor improvement.
Comment: Welcome to Music Practice and Theory SE. Unfortunately, questions that ask to identify specific techniques are off-topic. Please see here for a full list: http://music.stackexchange.com/help/on-topic
Comment: Hmmm - I'm not sure. I really can't understand what the question is asking.
Comment: @DrMayhem Check out my edits.  I think I figured out what he meant and made it more understandable.  Apparently fsi  is not a native English Speaker - but I trying to help ;)  PS: I took the liberty of trying to improve the question as well.
Comment: Yes, Im not native speaker, but the question is not only the name of the guy, but the technique too.
Comment: See my answer below and let me know if this is the technique you are looking for.
Answer: Here is a technique that appears similar to what you are asking about.  The person who originated the technique is Sanford Moeller and it is now known as the Moeller Technique.  It has been extensively taught by a drum teacher named Jim Chapin.
You will find many YouTube videos on using the Moeller Technique.
Here is a video of someone demonstrating the technique on the high hat with the raising of the wrist above the cymbal (as described in your question) and letting the tip of the stick fall back on it.
Moeller Down & Up stroke
He starts to demonstrate the technique you described at about 0:27 in the video.  Hope this helps.
Comment: Its not him. But I found out with another teacher I meet up.
Comment: Glad you found out.  What is name of technique?
Comment: Looking up on the internet, this teacher(he's not a drummer) doesn't know the name. But he already seen this method before.
Answer: The name I was looking for is Gary Chester, and its not a technique, its a method of trainning on hit-hat.
Comment: fsi -- If you fleshed this out a bit more it would be a good answer.
Comment: Can you give me advice what I could improve my answer?


Ordenar array de objetos

Question: Tenho como resultado de uma consulta ao banco de dados os seguintes dados:
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [nome] => Pizzaria 1
            [latitude] => -8.12044775643893
            [longitude] => -35.025825550000036
            [distancia] => 3800
        )

    [1] => stdClass Object
        (
            [id] => 2
            [nome] => Pizzaria 2
            [latitude] => -7.90856162499827
            [longitude] => -34.91269575000001
            [distancia] => 1500
        )

    [2] => stdClass Object
        (
            [id] => 3
            [nome] => Pizzaria 3
            [latitude] => -8.12044775643893
            [longitude] => -35.025825550000036
            [distancia] => 2000
        )
)

Só que estou adicionando a entrada distancia depois, pois ela não existe no banco. Ela serve para guardar o valor de um cálculo de distância, em metros, feito quando o usuário entra na pagina para que seja ordenado do mais próximo para o mais distante.
Minha dúvida é como eu faço para ordenar esse array de objetos para que a distância fique em ordem crescente?
Answer: Para esses e outros casos, usort() é quem você procura.
Porém, ligeiramente diferente dos exemplos do manual, você deve informar as propriedades que serão usadas como base para comparação.
Não é lá muito diferente do primeiro exemplo, veja:
usort(

    $data,

     function( $a, $b ) {

         if( $a -> distancia == $b -> distancia ) return 0;

         return ( ( $a  -> distancia < $b  -> distancia ) ? -1 : 1 );
     }
);

A saída, como esperado:
Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [nome] => Pizzaria 2
            [latitude] => -7.9085616249983
            [longitude] => -34.91269575
            [distancia] => 1500
        )

    [1] => stdClass Object
        (
            [id] => 3
            [nome] => Pizzaria 3
            [latitude] => -8.1204477564389
            [longitude] => -35.02582555
            [distancia] => 2000
        )

    [2] => stdClass Object
        (
            [id] => 1
            [nome] => Pizzaria 1
            [latitude] => -8.1204477564389
            [longitude] => -35.02582555
            [distancia] => 3800
        )

)

Comment: Antiga, mas muito útil.

Ordenar array de objetos


Why C(m+n, k) can be classified into k+1 types, not k types?

Question:
Source: A Path to Combinatorics for Undergraduates: Counting Strategies by Titu Andreescu,Zuming Feng
I don't understand the explanation in the part that there are C(m+n, k) ways to do and C(m+n, k) can be classified into k+1 types, which is followed by the explanation there are C(m, i)C(n, k-i) $i^{th}$ type  for $0≤i≤k$, not for $0≤i≤k+1$.
Is it just the author's fault of mistyping "k+1 types" instead of k types?
Or where's the type for k+1?
Answer: There are $k+1$ integers from $0$ to $k$, inclusive. It is possible to examine $0$ male dorms, $1$ male dorm, $2$ male dorms, and so on up to $k$ male dorms, a total of $k+1$ possibilities.
Remark: If $k\gt m$, one cannot actually examine $k$ male dorms, but that is taken care of by the convention that $\binom{a}{b}=0$ if $b\gt a$.


How to scan for log4j on Windows Server

Question: I have a Windows Server 2012 R2 machine. What is the best way to search for log4j. Is it enough with a simple file search or can these files be used from inside a container. I have done a file search like this in power shell
<code>Get-childitem -Path c:\ -Include log4j*.jar -File -Recurse -ErrorAction SilentlyContinue | select Lastwritetime, directory, name | export-csv -append -notypeinformation c.csv
</code>
Answer: That is definitely insufficient. You need something to open up war/jar/etc files and inspect inside there. Further, depending on the filename to match isn't guaranteed to work. Finally, you're not checking on the version with that, so you'd also need to determine if you're running a vulnerable version.
This page has a link to a github project that does claim to do these things.
Answer: Syft creates a software bill of materials, which you can in turn search for log4j occurrences.

How to scan for log4j on Windows Server


In Scikit, How Do You Fix Value Error When Predicting?

Question: The following code gives me the following error: ValueError: Found array with 0 sample(s) (shape=(0, 3)) while a minimum of 1 is required.
The error is produced in line where prediction is invoked. I am assuming there's something wrong about the shape of the dataframe, 'obs_to_pred.' I checked the shape, which is (1046, 3).
What do you recommend so I can fix this and run the prediction?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm

from patsy import dmatrices
from sklearn.linear_model import LogisticRegression
import scipy.stats as stats
from sklearn import linear_model

# Import Titanic Data
train_loc = 'C:/Users/Young/Desktop/Kaggle/Titanic/train.csv'
test_loc = 'C:/Users/Young/Desktop/Kaggle/Titanic/test.csv'
train = pd.read_csv(train_loc)
test = pd.read_csv(test_loc)

# Predict Missing Age Values Based on Factors Pclass, SibSp, and Parch.
# In the function, combine train and test data.
def regressionPred (traindata,testdata):

    allobs = pd.concat([traindata, testdata])
    allobs = allobs[~allobs.Age.isnull()]
    y = allobs.Age

    y, X = dmatrices('y ~ Pclass + SibSp + Parch', data = allobs, return_type = 'dataframe')
    mod = sm.OLS(y,X)
    res = mod.fit()

    predictors = ['Pclass', 'SibSp', 'Parch']
    regr = linear_model.LinearRegression()
    regr.fit(allobs.ix[:,predictors], y)

    obs_to_pred = allobs[allobs.Age.isnull()].ix[:,predictors]
    prediction = regr.predict( obs_to_pred ) # Error Produced in This Line ***

    return res.summary(), prediction

regressionPred(train,test)

In case you may want to look at the dataset, the link will take you there: https://www.kaggle.com/c/titanic/data
Answer: In the line
allobs = allobs[~allobs.Age.isnull()]

you define allobs as all the cases with no NaN in Age column.
Later, with:
obs_to_pred = allobs[allobs.Age.isnull()].ix[:,predictors]

you do not have any case to predict on as all allobs.Age.isnull() will be evaluated to False and you'll get an empty obs_to_pred. Thus your error:

array with 0 sample(s) (shape=(0, 3)) while a minimum of 1 is required.

Check the logic what you want with your predictions.


pyqtgraph facilities to pcolor plot llike matplotlib

Question: Is there any possibility to plot pcolor in pyqtplot, like the ones matplotlib can ?
and  Is there any good example ?
How we can add axis to pyqtgraph plot?
Answer: Try this to get started:
import pyqtgraph as pg
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
pg.plot(x, y, title="Simple Example", labels={'left': 'Here is the y-axis', 'bottom': 'Here is the x-axis'})

I looked at the documentation here to construct that example.
You can also try:
import pyqtgraph.examples
pyqtgraph.examples.run()

to see more examples
Also see this google groups question.
Comment: there exists many good features i searched for in the mentioned google group. it have many features match my problem. thanks
Answer: There is a support of plotting Image in pyqtgraph. You can checkout the imageAnalysis.py, ImageItem.py and ImageView.py examples under pyqtgraph examples.
The documentation for ImageItem is here
Here is the simple example function:
def plot_image(data):
    """
    Plot array as an image.
    :param data: 2-D array
    """
    pl = pg.plot()
    image = pg.ImageItem()

    pl.addItem(image)

    hist = pg.HistogramLUTItem()
    # Contrast/color control
    hist.setImageItem(image)
    # pl.addItem(hist)

    image.setImage(data)
    pos = np.array([0., 1., 0.5, 0.25, 0.75])
    color = np.array([[0, 0, 255, 255], [255, 0, 0, 255], [0, 255, 0, 255], (0, 255, 255, 255), (255, 255, 0, 255)],
                 dtype=np.ubyte)
    cmap = pg.ColorMap(pos, color)
    lut = cmap.getLookupTable(0.0, 1.0, 256)
    image.setLookupTable(lut)

    hist.gradient.setColorMap(cmap)
    pl.autoRange()


Unit root test specification with a structural break

Question: I am puzzled as to what specification I should include in my unit root tests of the following data: .
I will use ADF, KPSS and ZA tests. I can see there is a break in trend at observation 9. However, for the former two tests, especially for ADF, I do not know what to choose as a final specification.
Comment: You can perform unit root (or trend stationarity) test in the presence of break. There are plethora of such tests. You might want to read section 5 of following review article to choose the one  http://sws1.bu.edu/perron/papers/dealing.pdf. I think most of them are readily available in `R`.
Comment: Check this page http://people.bu.edu/perron/ he has many methods for dealing with unit roots and structural breaks (both level and trend breaks), plus there is some code in Matlab for testing that...
Answer: ADF test is pointless in this case. It's not going to give you a meaningful result.
The trend stationary is not going to detect this "break". All it looks at is whether the end is far enough from the start. The same with the drift: your start is not far from end in comparison to how much it went down first.
I bet you suspect that there was a trend down, then up. So, you have to test this hypothesis. For instance, run ADF test on first and second halves separately to establish there is a trend. Then run Chow test to detect the break. This will support the "obvious" graphical evidence of what I just wrote. Basically, you don't need any tests in this case.
Comment: Even if your ADF test shows no unit root in sample 1 and 2 respectively this does not mean that you can reject the unit root hypothesis for the entire sample. The correct approach would be to use a unit root test which can accommodate structural breaks. That being said this sample is probably to small to give any reasonable results.
Answer: On the ADF test, there is a "rule of thumb" to selection of $p_{\text{max}}$ (highest $p$).
The $p_{\text{max}}$ is given as $12\cdot \left(\frac{T}{100}\right)^{0.25}$, by Schwert (1989), try this and move downwards from this $p$, and check for serial correlation of the residuals until you're happy with your results.
Comment: Dear @user21240, many thanks for your answer. I am looking for your views about the specification for the unit root tests. should I include trend in the final specification?
Comment: From the plot, it doesn't really look like a trend, but there is a constant which should be included in the test, that is case II.
Comment: Many thanks @user21240, do you think I should include a trend break dummy in the regression model as there seems to be a break at time 9?


Leitura de XML Java

Question: Estou tentando fazer a leitura de um XML em Java para pegar dados de uma NF-e.
Tentei assim para tentar pegar só o código do produto pra testar mais sem sucesso:
 public void testeaa(String xml) throws DocumentException {

    Document document = getDocumento(xml);
    Element root = document.getRootElement();

    Iterator<Element> i = root.elementIterator();

    i.forEachRemaining(element -> {

        if (element.getQualifiedName().equals("det nItem")) {
            System.out.println("COdProd: " + element.getText());
        }

    });
}

public Document getDocumento(String xml) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(xml);
    return document;
}

Exemplo XML:
<?xml version="1.0" encoding="UTF-8"?>
<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="3.10">
   <NFe>
      <infNFe Id="NFe41180710930674000149550010000005561136042494" versao="3.10">
         <ide>
            <cUF>41</cUF>
            <cNF>13604249</cNF>
            <natOp>Venda</natOp>
            <indPag>0</indPag>
            <mod>55</mod>
            <serie>1</serie>
            <nNF>556</nNF>
            <dhEmi>2018-07-31T15:04:00-03:00</dhEmi>
            <dhSaiEnt>2018-07-31T15:04:00-03:00</dhSaiEnt>
            <tpNF>1</tpNF>
            <idDest>1</idDest>
            <cMunFG>4115002</cMunFG>
            <tpImp>1</tpImp>
            <tpEmis>1</tpEmis>
            <cDV>4</cDV>
            <tpAmb>1</tpAmb>
            <finNFe>1</finNFe>
            <indFinal>1</indFinal>
            <indPres>1</indPres>
            <procEmi>0</procEmi>
            <verProc>0.0.1</verProc>
         </ide>
         <emit>
            <CNPJ>10930674000149</CNPJ>
            <xNome>COMERCIO DE PRODUTOS AGROPECUARIOS JSM EIRELI</xNome>
            <xFant>CASA DO AGRICULTOR</xFant>
            <enderEmit>
               <xLgr>AV PARANA</xLgr>
               <nro>996</nro>
               <xBairro>CENTRO</xBairro>
               <cMun>4115002</cMun>
               <xMun>MARILENA</xMun>
               <UF>PR</UF>
               <CEP>87960000</CEP>
               <cPais>1058</cPais>
               <xPais>BRASIL</xPais>
               <fone>4434481934</fone>
            </enderEmit>
            <IE>9048560455</IE>
            <CRT>1</CRT>
         </emit>
         <dest>
            <CPF>82726647987</CPF>
            <xNome>LUIS CARLOS BONOME</xNome>
            <enderDest>
               <xLgr>SITIO SAO PAULO</xLgr>
               <nro>S/N</nro>
               <xBairro>SEIS CASAS</xBairro>
               <cMun>4111308</cMun>
               <xMun>ITAUNA DO SUL</xMun>
               <UF>PR</UF>
               <CEP>87980000</CEP>
               <cPais>1058</cPais>
               <xPais>BRASIL</xPais>
               <fone>4488326605</fone>
            </enderDest>
            <indIEDest>9</indIEDest>
         </dest>
         <det nItem="1">
            <prod>
               <cProd>5409</cProd>
               <cEAN />
               <xProd>BRUCELINA B-19 30 ML (15 DOSES)</xProd>
               <NCM>30023080</NCM>
               <CFOP>5102</CFOP>
               <uCom>uni</uCom>
               <qCom>1.0000</qCom>
               <vUnCom>18.200000</vUnCom>
               <vProd>18.20</vProd>
               <cEANTrib />
               <uTrib>uni</uTrib>
               <qTrib>1.0000</qTrib>
               <vUnTrib>18.200000</vUnTrib>
               <indTot>1</indTot>
            </prod>
            <imposto>
               <vTotTrib>0.76</vTotTrib>
               <ICMS>
                  <ICMSSN102>
                     <orig>0</orig>
                     <CSOSN>103</CSOSN>
                  </ICMSSN102>
               </ICMS>
               <IPI>
                  <cEnq>301</cEnq>
                  <IPINT>
                     <CST>52</CST>
                  </IPINT>
               </IPI>
               <PIS>
                  <PISNT>
                     <CST>07</CST>
                  </PISNT>
               </PIS>
               <COFINS>
                  <COFINSNT>
                     <CST>07</CST>
                  </COFINSNT>
               </COFINS>
            </imposto>
         </det>
         <det nItem="2">
            <prod>
               <cProd>3997</cProd>
               <cEAN />
               <xProd>BRUSKY ADULTO  15KG</xProd>
               <NCM>23091000</NCM>
               <CFOP>5102</CFOP>
               <uCom>uni</uCom>
               <qCom>1.0000</qCom>
               <vUnCom>39.900000</vUnCom>
               <vProd>39.90</vProd>
               <cEANTrib />
               <uTrib>uni</uTrib>
               <qTrib>1.0000</qTrib>
               <vUnTrib>39.900000</vUnTrib>
               <indTot>1</indTot>
            </prod>
            <imposto>
               <vTotTrib>3.63</vTotTrib>
               <ICMS>
                  <ICMSSN102>
                     <orig>0</orig>
                     <CSOSN>103</CSOSN>
                  </ICMSSN102>
               </ICMS>
               <IPI>
                  <cEnq>301</cEnq>
                  <IPINT>
                     <CST>52</CST>
                  </IPINT>
               </IPI>
               <PIS>
                  <PISNT>
                     <CST>07</CST>
                  </PISNT>
               </PIS>
               <COFINS>
                  <COFINSNT>
                     <CST>07</CST>
                  </COFINSNT>
               </COFINS>
            </imposto>
         </det>
         <det nItem="3">
            <prod>
               <cProd>4544</cProd>
               <cEAN />
               <xProd>BAYTICOL POUR-ON 1L</xProd>
               <NCM>38089999</NCM>
               <CFOP>5102</CFOP>
               <uCom>uni</uCom>
               <qCom>1.0000</qCom>
               <vUnCom>98.000000</vUnCom>
               <vProd>98.00</vProd>
               <cEANTrib />
               <uTrib>uni</uTrib>
               <qTrib>1.0000</qTrib>
               <vUnTrib>98.000000</vUnTrib>
               <indTot>1</indTot>
            </prod>
            <imposto>
               <vTotTrib>4.12</vTotTrib>
               <ICMS>
                  <ICMSSN102>
                     <orig>0</orig>
                     <CSOSN>103</CSOSN>
                  </ICMSSN102>
               </ICMS>
               <IPI>
                  <cEnq>301</cEnq>
                  <IPINT>
                     <CST>52</CST>
                  </IPINT>
               </IPI>
               <PIS>
                  <PISNT>
                     <CST>07</CST>
                  </PISNT>
               </PIS>
               <COFINS>
                  <COFINSNT>
                     <CST>07</CST>
                  </COFINSNT>
               </COFINS>
            </imposto>
         </det>
         <total>
            <ICMSTot>
               <vBC>0.00</vBC>
               <vICMS>0.00</vICMS>
               <vICMSDeson>0.00</vICMSDeson>
               <vBCST>0.00</vBCST>
               <vST>0.00</vST>
               <vProd>156.10</vProd>
               <vFrete>0.00</vFrete>
               <vSeg>0.00</vSeg>
               <vDesc>0.00</vDesc>
               <vII>0.00</vII>
               <vIPI>0.00</vIPI>
               <vPIS>0.00</vPIS>
               <vCOFINS>0.00</vCOFINS>
               <vOutro>0.00</vOutro>
               <vNF>156.10</vNF>
               <vTotTrib>8.51</vTotTrib>
            </ICMSTot>
         </total>
         <transp>
            <modFrete>1</modFrete>
         </transp>
         <cobr>
            <dup>
               <nDup>1</nDup>
               <dVenc>2018-08-24</dVenc>
               <vDup>156.10</vDup>
            </dup>
         </cobr>
      </infNFe>
      <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
         <SignedInfo>
            <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
            <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
            <Reference URI="#NFe41180710930674000149550010000005561136042494">
               <Transforms>
                  <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                  <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
               </Transforms>
               <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
               <DigestValue>eBgQo1KZj/0m4GrTiqMZ3KPmM1k=</DigestValue>
            </Reference>
         </SignedInfo>
         <SignatureValue>XEPqu9honydrDj0LYZFnJbhGAx4CIhxZPyNh/9iyZzp4UD3zPP3oSh6y6tj9hD9Hltitv3tpK3VqtUgUddfTY2GFKQ9q0xrAm82bGhNzk2tGDed1HIMOb7uLaIOdb59oFkwnmoG4q4XgWuD1h8JZ1wscYo4gyBvUPyHV0QmwscszGivGYamqh0opEgpDaB8Gk/MyO1GWODCdmnETIGZULxS3XYw1PNZAnKfOCW8d6WkY3l8owQNR1WipA0HbTH95DBU0HYjl9/h/6fyvUc4ekEoWiUkAaVbm+XNIdjkbY+9nQAOoNlA7GKzava9J9cHPVuikFoAv+rjP6EGPZYua3g==</SignatureValue>
         <KeyInfo>
            <X509Data>
               <X509Certificate>MIIIEDCCBfigAwIBAgIQF58IxhG5SzlAAG/hGgt0lzANBgkqhkiG9w0BAQsFADB4MQswCQYDVQQGEwJCUjETMBEGA1UEChMKSUNQLUJyYXNpbDE2MDQGA1UECxMtU2VjcmV0YXJpYSBkYSBSZWNlaXRhIEZlZGVyYWwgZG8gQnJhc2lsIC0gUkZCMRwwGgYDVQQDExNBQyBDZXJ0aXNpZ24gUkZCIEc1MB4XDTE3MTAyNDEwMDcwM1oXDTE4MTAyNDEwMDcwM1owggEAMQswCQYDVQQGEwJCUjETMBEGA1UECgwKSUNQLUJyYXNpbDELMAkGA1UECAwCUFIxETAPBgNVBAcMCE1hcmlsZW5hMTYwNAYDVQQLDC1TZWNyZXRhcmlhIGRhIFJlY2VpdGEgRmVkZXJhbCBkbyBCcmFzaWwgLSBSRkIxFjAUBgNVBAsMDVJGQiBlLUNOUEogQTExIjAgBgNVBAsMGUF1dGVudGljYWRvIHBvciBBUiBGQUNJQVAxSDBGBgNVBAMMP0NPTUVSQ0lPIERFIFBST0RVVE9TIEFHUk9QRUNVQVJJT1MgSlNNIEVJUkVMSSBNRToxMDkzMDY3NDAwMDE0OTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBA4kdurgnIHUkt08DVhLumBuwqGDnkqH7SAND4terSn+uIau2TeElvTEMv3g+MFgfc92lrYcUwSsyEI5TJWBHKRYISSO143bpMw/Y0Zu8f2Uf74xPWOFvbH7g+5zRt3f/hVo8AmtDeBLYsEkJPmPgPa5rx6BBvR5uF4ujFUeiK/cIyaKcLLYa3uhMf/VqnioRwbNi69wC5bH80jm0xQJvG7mCpYuuDbfZJrewECY8G/uQ2C+lV4GSkF9T2DvcwAtdPDEa9Mywblc3Ximlk4kZ1WH3okNCmU7llbsJ4+MXb/Krxp07HJEHf7CdCqaXKvQylQFASu4H9xOgbdt/uUKkCAwEAAaOCAwowggMGMIG5BgNVHREEgbEwga6gPgYFYEwBAwSgNQQzMTIxMDE5ODUwNTQ3Njg2NTk1MDAwMDAwMDAwMDAwMDAwMDAwMDg3MDExNTQyU0VTUFBSoB0GBWBMAQMCoBQEEkpPSUNFIFNPQVJFUyBNQUpPUqAZBgVgTAEDA6AQBA4xMDkzMDY3NDAwMDE0OaAXBgVgTAEDB6AOBAwwMDAwMDAwMDAwMDCBGWhpZ29yX25vcnRlaW9AaG90bWFpbC5jb20wCQYDVR0TBAIwADAfBgNVHSMEGDAWgBRTfX+dvtFh0CC62p/jiacTc1jNQjB/BgNVHSAEeDB2MHQGBmBMAQIBDDBqMGgGCCsGAQUFBwIBFlxodHRwOi8vaWNwLWJyYXNpbC5jZXJ0aXNpZ24uY29tLmJyL3JlcG9zaXRvcmlvL2RwYy9BQ19DZXJ0aXNpZ25fUkZCL0RQQ19BQ19DZXJ0aXNpZ25fUkZCLnBkZjCBvAYDVR0fBIG0MIGxMFegVaBThlFodHRwOi8vaWNwLWJyYXNpbC5jZXJ0aXNpZ24uY29tLmJyL3JlcG9zaXRvcmlvL2xjci9BQ0NlcnRpc2lnblJGQkc1L0xhdGVzdENSTC5jcmwwVqBUoFKGUGh0dHA6Ly9pY3AtYnJhc2lsLm91dHJhbGNyLmNvbS5ici9yZXBvc2l0b3Jpby9sY3IvQUNDZXJ0aXNpZ25SRkJHNS9MYXRlc3RDUkwuY3JsMA4GA1UdDwEB/wQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwgawGCCsGAQUFBwEBBIGfMIGcMF8GCCsGAQUFBzAChlNodHRwOi8vaWNwLWJyYXNpbC5jZXJ0aXNpZ24uY29tLmJyL3JlcG9zaXRvcmlvL2NlcnRpZmljYWRvcy9BQ19DZXJ0aXNpZ25fUkZCX0c1LnA3YzA5BggrBgEFBQcwAYYtaHR0cDovL29jc3AtYWMtY2VydGlzaWduLXJmYi5jZXJ0aXNpZ24uY29tLmJyMA0GCSqGSIb3DQEBCwUAA4ICAQBJpwXw79VQqU7raW5b+JoCYJnLT6W8xL+jzBrS3LDZ+TcqavyzMkVT4NTmkqnPl7I+Y52ILURhg50KXCSXLw8PhZ9fY6uHZcRSVpNvIOnqQyc0UXqY6YESKmdAbUs5PVEtfb5i2koFOcU8M8zK+LBhARP+BFbv/DfKOeiw7pYc3niBc6Jn2Yc1WnSlsoT1/+UzLbHvE+WMSEzvUcgm028+LfqcYf+KKc/YJfMPG29y2/LWfRYp6qHaLj0Solgrfh5gvyo0e6kxLX9JCc4o0XBmiPT51awolkcvnDkR7F1D87iQo4g7F4m43VO5dqBqePw/syMQrWFvndlwHlWujECy2QuE/2j9Xrgn5JKwViGVSvaf50a+KvT98s/KZuQYk//gXzzlQ1GqwzhQPMYt7SUXpQ4Du2bBTUSvbMxI42iN/Py/jgd26U/BKVPgtP7o3us8K71iiMh6IOp/AtCMMnMcZ5nm+XoQI8ciuMykd6dTMBBKbg8U3sZ1rXxX8hxLw/ux0BhnT5aWM5/zYgkUFz4vvDMgFsSoswSMARgUuS+C7K+2Y4RgQCxxtk1S8ecGbOD0OrExgv1StEChKx/PjhtqWkoKQY1y/302COeozJAhmeD1oOnZDyrIAtbW6Qz2sUYh2fEuH6LDuLRfAwFyIP0PwRHkdVO7KC7qZTUNSIaRRw==</X509Certificate>
            </X509Data>
         </KeyInfo>
      </Signature>
   </NFe>
   <protNFe versao="3.10">
      <infProt>
         <tpAmb>1</tpAmb>
         <verAplic>PR-v3_9_5</verAplic>
         <chNFe>41180710930674000149550010000005561136042494</chNFe>
         <dhRecbto>2018-07-31T15:04:04-03:00</dhRecbto>
         <nProt>141180128267723</nProt>
         <digVal>eBgQo1KZj/0m4GrTiqMZ3KPmM1k=</digVal>
         <cStat>100</cStat>
         <xMotivo>Autorizado o uso da NF-e</xMotivo>
      </infProt>
   </protNFe>
</nfeProc>

Teriam alguma ideia?
Comment: Você teria um XML de exemplo para que outras pessoas possam testar o seu código e as modificações que nele quiserem fazer?
Comment: Inseri na pergunta, é um xml de uma nfe, preciso dos dados e percorrer os produtos.
Answer: Primeiro, o método SAXReader.read(String) que você está usando no getDocumento espera uma URL ou um nome de um arquivo (https://dom4j.github.io/javadoc/2.0.1/org/dom4j/io/SAXReader.html#read-java.lang.String-), sendo assim acontecerá um erro se você passar o XML direto (pelo menos foi isso que aconteceu ao tentar executar seu código).
Para corrigir isso, você pode usar o método o método SAXReader.read(Reader) passando um StringReader contendo o XML.
Exemplo de como ficaria:
public static Document getDocumento(String xml) throws DocumentException {
  SAXReader reader = new SAXReader();
  Document document = reader.read(new StringReader(xml));
  return document;
}

Agora, para pegar o código do produto:
Supondo que o código do produto seja o que está dentro da tag <cProd> (não tenho certeza, pois não conheço a estrutura de uma NFE), você pode usar o seguinte código:
Document document = getDocumento(xml);
Element root = document.getRootElement();

root.accept(new VisitorSupport() {
  @Override
  public void visit(Element node) {
    if (node.getQualifiedName().equals("cProd")) {
      System.out.println(node.getText());
    }
  }
});

E isso irá mostrar:
5409
3997
4544

Você também pode pegar o <det>, com isso você consegue acessar cada elemento filho separadamente: (Útil para caso você precise acessar não apenas o cProd)
root.accept(new VisitorSupport() {
  @Override
  public void visit(Element node) {
    if (node.getQualifiedName().equals("det")) {
      String attributoNItem = node.attributeValue("nItem");

      System.out.println("Item " + attributoNItem);

      Element prodNode = (Element) node.element("prod");
      System.out.println("Código: " + prodNode.element("cProd").getText());
    }
  }
});

Saída:
Item 1
Código: 5409
Item 2
Código: 3997
Item 3
Código: 4544

Comment: Exatamente isso que eu precisava, obrigado :D

Leitura de XML Java


Where does the number "12" comes from in Kruskal Wallis formula?

Question: I just want to know.. Where does the "12" in the Kruskal Wallis formula comes from?
I hope someone can give me a very good explanation.
Comment: $12$ comes from the fact that $\sum_{i=1}^N (i - \frac{N+1}{2})^2 = \frac{(N-1) N (N + 1)}{12}$, so it occurs naturally in the expression for the sample variance of the ranks of the outcomes which is (deterministically) equal to $\frac{N (N + 1)}{12}$.
Answer: "The sum of the first N integers is 1/2*N(N+ 1) and the sum of their squares is 1/6*N(N+ 1)(2N+ 1). It follows that the mean and variance of the first N integers are 1/2(N+1) and 1/12*(N^2-1)."
This is where the 12 appears first in William H. Kruskal and W. Allen Wallis: Use of Ranks in One-Criterion Variance Analysis, Journal of the American Statistical Association, Vol. 47, No. 260 (Dec., 1952), pp. 583-621
I suppose you read more on that in http://www.jstor.org/stable/pdf/2280779.pdf


Creating a job system in Drupal 7

Question: I want to create a job system in drupal 7 with the following workflow.

Administrator can add the jobs.
A for jobs listing.
On detail job there should a link of apply for this job.
The form will contain the fields and upload application form.
The back end must have trackers such as Response received at, action trackers: 'Candidate contacted, Candidate data transferred to HR', Vacany filled.

I have tried it with the views and the webform module.
Created a view for job listing. and use webform for apply form. But what should I do with the trackers in point 5. I have no idea about this.
Please guide me in this situation or any module for this requirement which should use?
Answer: There are various distributions available in Drupal.org
You can check it out Drupal jobs and Recruiter. both are well maintained.
Take these distributions as base and develop your project. They almost support all of your usecases.
Comment: but you can see the modules/features from this site and use it
Comment: I needs a small module not a distribution.
Comment: http://www.creativebloq.com/web-design/build-job-listings-website-drupal-9134658

Creating a job system in Drupal 7


Ncurses bug mouse coordinates to beyond 222 width or height terminal

Question: I am coding an user interface with ncurses.
I have a problem when my terminal width or height is beyond to 222 characters/rows, mouses coordinates return the -33 value, so when i click to beyond 222 characters mouse_x = -33
when i click to beyond 222 rows mouse_y = -33
Would it be possible to tell ncurses no to stop mouses events beyond 222 characters/rows ?
This bug also occurs in vim, when you move the :vs separation bar beyond 222 characters, it goes back to x=0.
Maybe this bug has already been fixed ?
  1 #include <ncurses.h>
  2
  3 void    treat_mouse(MEVENT* event);
  4
  5 int     main(void)
  6 {
  7         bool    run;
  8         int     key;
  9         MEVENT  event;
 10
 11         run = true;
 12         initscr();
 13         noecho();
 14         keypad(stdscr, TRUE);
 15         mousemask(BUTTON1_PRESSED, NULL);
 16         while (run == true)
 17         {
 18                 key = getch();
 19                 switch  (key)
 20                 {
 21                         case    'q':
 22                                 run = false;
 23                                 break;
 24                         case    KEY_MOUSE:
 25                                 treat_mouse(&event);
 26                                 break;
 27                         default:
 28                                 break;
 29                 }
 30         }
 31         endwin();
 32         return 0;
 33 }
 34
 35 void    treat_mouse(MEVENT* event)
 36 {
 37         if (getmouse(event) == OK)
 38                 mvwprintw(stdscr, 0, 0, "click: x = %d, y = %d\n", event->x, event->y);
 39 }

.
.
========================    EDIT   =======================
.
.
Ok i have found.
I have downloaded ncurses code source here http://ftp.gnu.org/pub/gnu/ncurses/
And i have taken this link ncurses-5.9.tar.gz      04-Apr-2011 19:12  2.7M
I have searched getch().
getch() call wgetch().
wgetch() call _nc_wgetch().
_nc_wgetch() call _mouse_inline().
_mouse_inline() is a function pointer in struct screen who call _nc_mouse_inline() or no_mouse_inline() who is an empty function (when no mouse i think).
you can see _nc_mouse_inline() function in ncurses-5.9/ncurses/base/lib_mouse.c
She use unsigned char to calcul mouse coordinates, to see this litle example:
821 static bool
822 _nc_mouse_inline(SCREEN *sp)
823 /* mouse report received in the keyboard stream -- parse its info */
824 {
.
.
.
832         unsigned char kbuf[4];
.
.
.
970         eventp->x = (kbuf[1] - ' ') - 1;
971         eventp->y = (kbuf[2] - ' ') - 1;
.
.
.
984     return (result);
985 }

Finally I'll do anything.
Comment: This answers your question: [How to Build Curses Program That Supports More Than 223 Columns of Mouse Input](https://stackoverflow.com/questions/47256750/how-to-build-curses-program-that-supports-more-than-223-columns-of-mouse-input)
Answer: I think you've found the answer to your question.
unsigned char kbuf[4];
eventp->x = (kbuf[1] - ' ') - 1;
eventp->y = (kbuf[2] - ' ') - 1;

The mouse x and y are been received as unsigned char, so the maximum value they can hold is 255. ' ' (space) is ASCII 32, so the maximum value possible is 255 - 32 - 1 which equals 222.
The value then wraps to 0 giving 0 - 32 -1 which equals -33.
Comment: This is a limitation of the xterm mouse protocol. There is an extension (SGR 1006), but the latest news about its support in ncurses were just: https://lists.gnu.org/archive/html/bug-ncurses/2013-01/msg00014.html


Show "Does it affect?" with hypothesis test

Question: I am trying to learn ttest and ANOVA for my project. I need to know that my subjects answers "effected" by the feedback they get from the first question.
What should I use to show "sth did effect or not sth"?
ANOVA or ttest?
Thanks in advance.
My data is:
A person answers a question and receives a feedback as "good/bad" than he/she answers another question. Does the second answer effected by the feedback or not? That is what i want to learn.
Comment: Can you describe the data more clearly? ANOVA is a generalization of a two-sample t-test for more than two groups, so it is a matter of any of the two only if you want to compare the means of two or more groups (or means of a metric variable for two or more levels levels of a categorical variable). But a t-test can also be used with a single sample or a paired sample, so we need more info what it is you actually want to check and how your problem looks like.
Comment: If these are experimental data with randomly assigned conditions, I would be comfortable with using (causal) language like "X affects Y". But if these are data from surveys, you should really use more associative language.
Comment: Thanks for the clarification. For the second answer, does the answer of the person get measured in a metric sense? E.g., is it response time or a freely assigned number of performance (say 0 to 100) or something like that, or are you recording if the person gets it correct/wrong the second time. And would you like to say something about each individual person or about all persons "on average"?
Comment: "*sth*"? Please expand your abbreviations. You don't have a 140-character limit. Please also be consistent with use of affect/effect
Answer: An ANOVA comparing 2 groups is exactly equal to a 2-sample pooled t-test with 2-tailed alternative.  So it may not matter which you use.
Some advantages to using the t-test: you can do a 1-tailed test, you can do an approximation if you believe that the variances of the 2 groups differ.  A confidence interval is more straight forward (automatic in some software).
Some advantages to using ANOVA: can compare more than 2 groups.


Downsampling text documents

Question: I have two classes with 1000 documents in class one and 40000 documents in class two. The documents consist of texts.
I want to use these texts in a neural network. But of course there is a unbalanced-dataset-problem. Each classifier would through all documents into class two and say "I have a great accuracy of 97.5%.
Do you know if there are any implementations that check the document-similarities in class two and kind of clusters them and then just drops documents of each cluster proportional to its cluster size?
Or do you know similar approaches with the same target?
Comment: If you have the time, a simple way to address this concern would be to use a random, say 700 docs from class1 and a random 700 from class 2. Train a bunch of networks on *different* randomly sub-sampled docs, and compare the hidden activations. If they're similar, you're in business. If they're not, you need a principled way of assessing the classes -- maybe by keyword like you mention -- to do the sub-sampling.
Comment: You need to provide a lot more details.  What does your classifier do?  Are you classifying by sentiment, topic modeling, emotion, document type such as news or blogs, phrases, etc.?  Are you looking for specific words?
Comment: My classifier should classify by sentiment. Currently I'm using a CNN.
The documents have pretty long texts, so currently I'm looking for common keywords in all documents of one class (just testing approaches like correlated pattern/sequence mining, simple document-frequency approaches etc.) and then filtering the sentences that contain at least one of these keywords. I'm using these filtered sentences as input for the CNN.
Comment: It sounds like you want N-Grams.  Have you tried using them?
Answer: My understanding from your comments is that you have 50k documents labeled as either positive or negative in sentiment. You would like to reduce the larger class from 40k to 10k by clustering the documents and selecting a fraction of documents from each cluster.
If that's right, the following approach ought to do what you want?

Produce TF-IDF representations for the 40k documents. (You can make the TF-IDF representations from the keyword sets you already identified.)
Apply an agglomerative hierarchical clustering technique until you have only 10k branches remaining. You can use cosine similarity between TF-IDF vectors as your similarity metric, and use the centroid as the TF-IDF vector for a document group. (If implementing yourself: remember that you can retain almost all of your pairwise similarity calculations between rounds, or you will do a lot of unnecessary recalculation!)
From each cluster containing multiple documents, choose one document to retain.

That said, I agree with gerowam that a random downsampling strategy would likely be easier, faster, and likely just as effective, but you're welcome to try it and report back.

Downsampling text documents


sql server 2008 r2 can connect with connection manager but noway else

Question: I have installed (3 times on 3 machines) sql server 2008 r2 can connect with connection manager but other program cannot connect.
I can connect to remote sql servers with heidisql or with my dbcontroles in visal studio or embarcadero delphi xe2. But non of those can connect to te sql server whlie the connection-manager can.
What settings may be involved?
-My firewall is open for SQL server.
-I use the same port numer everywhere
Any suggestions?
Comment: Are you connecting to a default instance, or a named instance?
Answer: I don't know what connection manager is, but I'm assuming you mean SQL Server Management Studio. If I'm not mistaken, SQL Server since SQL Server 2005 installs with only the Shared Memory protocol enabled and all network protocols disabled. You're able to connect via SSMS on the server to the SQL Server database engine instance on the server because it's connecting via Shared Memory protocol. In order to connect to it from another host on the network you'll need to enable the appropriate network protocol; Named Pipes or TCP/IP, whichever suits your need.
http://msdn.microsoft.com/en-us/library/ms187892.aspx


There's something terribly wrong with the CKEditor, and I can't remove it

Question: Although I have advanced knowledge in HTML, JS, and CSS, I have some co-workers who do not. For that reason, I have installed the CKEditor module, which they love.
I, on the other hand, have had nothing but grief with this module. . . Let me explain.
I have been making and editing "templates" in Notepad++, copying them, and pasting them into the CKEditor through the "plain text" option.
This usually works, kinda... At least it only screws things up in a way I can work around, usually.
Right now, it is screwing things up in a way that I cannot work around.
So, lets say I enter a block like this one:

This is almost exactly what I am entering
And what I get instead is this:

I've tested this in multple different browsers and I am getting the same result. What am I doing wrong? Is this a known issue? Is there a different Wysiwyg editor I can use that doesn't have this issue? Thanks everyone!
Comment: Any reason you can't create another text format like your wysiwyg text format without the wysiwyg on?
Comment: ? Slightly confused by what you mean @Jance . Could you explain further? This sounds promising. Maybe something that I hadn't thought of.
Comment: check out my answer. You may need to install a new module, and I've only done it with tineyMCE, but the module should work with CKeditor as well.
Comment: Yet a terrible place for this, but whatever, I'm in desperate need. Hey @Jance , your quite helpfull, [could you help me out?](http://drupal.stackexchange.com/questions/141291/what-happened-to-my-new-block-region)
Answer: CKEditor does this intentionally because your inline tags should not contain block level tags.... an easy work around is to change your divs to spans and add a class that makes the span display block.
If it is your preference to use invalid html (I have needed to before) another option is to add this line:
CKEDITOR.dtd.a.div = 1;
I wouldn't recommend this unless absolutely necessary since changing the dtd can have unexpected results.
Comment: What exactly does adding that line to the CKEditor do?
Comment: "Each element in the DTD is represented by a property in this object. Each property contains the list of elements that can be contained by the element. Text is represented by the # property." - [CKEditor Docs](http://docs.ckeditor.com/#!/api/CKEDITOR.dtd)
Comment: so it basically tells CKEditor that div tags are allowed in a tags
Answer: So drupal allows admins to create text formats (see at /admin/config/content/formats). There you can create multiple different text formats (like an html format, plain text, etc, etc.)
You could duplicate the Full Html, name it something like "Full HTML (No Wysiwyg)." If you download the WYSIWYG module, I think you should be able to use that to tell ckeditor what text formats to be used on. So if you download and install that module, you should be able to control what text formats ckeditor shows up on at /admin/config/content/wysiwyg.
Answer: I found the answer I needed (not quite the one I was looking for) thanks to @Trey for pointing me in the right direction. My issue was with the CKEditor DTD.
I simply had to remove the
 element for my block to work:


Reload Document Ready after Ajax Response Injection to the DOM?

Question: I have a form that uses a color picker, this is defined in the Document Ready with the form select input tags. But I require to access some data trough AJAX in another page and have the response replace that form. When I do this, the jquery colorpicker stops working. I guess it would be cool to reload the Document Ready or something.
Otherwise I think my only option is JSON to pass the variables from PHP output to jquery and then back to html, right?
Comment: Do you have a live demo? There should be an easier way. I'm thinking show/hide the color picker when it's needed. jQuery is picky about event handlers on dynamic content but if it's in the page the whole time you should be good.
Answer: There are two basic ways to accomplish this.  The first is to make the function which initializes your color picker callable from other code.  The other is to manually retrigger the document's ready event.  The former requires a small modification to your color picker code, but the latter will re-execute all functions bound to document.ready!  Be sure that's what you want before you do it.  :-)
// option one

function setupColorPicker() {
    // do color picking magic
}

$(document).ready(setupDatePicker);

$.ajax(options).done(setupColorPicker);

// option two

$(document).ready(function() {
    // do color picking magic
});

$.ajax(options).done(function() {
    $(document).trigger("ready"); // probably has unintended side-effects!
});

Answer: You could make the color picker initializing script run from it's own function and call that once in document ready and again in the callback of your ajax call.
Answer: You should register the events using the live or the delegate method:

http://api.jquery.com/live/
http://api.jquery.com/delegate/
Answer: Passing back the data from server as JSON will not only accomplish your goal but will also boost the performance(SPEED) of the application and also save you bytes of bandwidth. If you still want to inject response as plain html simply initialiZe the color picker plugin in a function and call the function after your ajax success callback.
$(document).ready(function(){
    //page is ready

    function colorpicker(){
      //initialize your color picker

    }

    $.ajax({
      url: 'serverpage.cshtml', //whatever server page
      data: {data1: data1},
      success: function(){
        //append the response into the designated form or div
        colorpicker(); //fire the color picker function to refresh
      }
    });
});


Best practice on hot-swapping disk

Question: I've been putting myself to find an learn more about the product before posting a question. Well, I've tried my luck and didn't got a proper answer to my questions. So I'm posting it here.
Had an issue with the RAID due to a disk failure, replaced it and the Array configuration utility showed that is ok now. However, it later showed that slot 11 is rebuilding, so does the overall array. So I kept the server for two days to rebuild, but at the end of the process it simply said; "interim recovery failed". Knowing that I've ordered another two disk so that I can get it replaced.
Having said that; I've couple of questions to clear;

One of the disks that I have is a seagate raw SCSI disk which matches the same model number as the server currently has? Will it work if I hot-swap it by putting it into the disk cage (cage I've took from previously removed disk)?
When I check the array through ACU offline utility, I see an option to erase each drives. Can I try erasing drive in slot 11, remove it and replace it or any ways to rebuild.
Meanwhile, I do have the existing drive which I replaced on slot 1 as said above, can I replace it atleast. ADU report is attached for further understanding.

I've set-up iLO management but I don't see anything related to the raid controller its just the basic. What can I do about it?
Our ESXi is not been obtained by HP. So I can't even see the array using CLI also it doesn't show on vSphere too. What can be the cause to this "interim recovery failed" error. I'm totally lost with this & its pretty difficult to search for proper article on HP site. Part number for the disk in the server is: 461289 - 001 (1TB SAS disk).
Please advise on this.

EDIT
HP Model:  HP Proliant DL180 G6 // RAID 6 // P410 Smart Array
Where you see interim failure: I booted the server using HP's ACU to check the raid with more expanded information. It showed that it was rebuilding on slot 11. Therefore, I kept the server for two days on it without giving the server any more hassle. Once it was 100%, it suddenly showed that its failed & interim recovery failure on the array of the said disk. Refer this post to see the attached adu report as I don't any option to attach here.
ESXi Version: 5.0.0 // Build, 469512
Comment: Voted to close as "I am a newbie" translates into "that really does not know what I am doing" (as shown in the rest of the question) and while this is a common scenario that is described - this type of question is off topic as per FAQ.
Comment: @TomTom My bad. I've tried my best to search for similar scenarios but couldn't find any informative answer. Just seeking for an advise that would help me on.
Comment: Please provide the model of the servers and version of ESXi? What RAID level is this? RAID5? RAID 1+0? Also, where did you see the "Interim Recovery Error"?
Comment: @ewwhite Added the info as requested.
Comment: Hi @ewwhite! I've added an image of the utility report which was different to what I showed.. this says **disk 11 - has physically failed**. This what I was talking about before which showed later as interim failure
Comment: This isn't a best-practice question. This is a pretty specific question for a pretty specific situation. However, you just need to replace two bad disks. That's all.
Comment: @ewwhite - Thank you for your advise! I've replaced the raw seagate drive and the array took it.. waiting until it rebuilds.. Once done, I will also replace the other.. thank you.
Answer: This is from your Array Diagnostics Utility report...

You have one disk being rebuilt. Another disk is in prefailure mode. You can attempt to rebuild again by just reinserting disk 11 and letting it try once more. Are you absolutely sure this is RAID 6 (ADG)? You didn't mention "ADG", and I wanted to clarify.
Comment: Yes, it is an ADG according to the array utility and it's on a RAID 6.. the disk 11 you said, I'm planning on changing hot-swapping the disk. But its a raw seagate disk with same part number.. So, I placed the raw seagate disk into the the disk cage which I removed previously  from the server. will that work out?
Comment: You can try, but understand that the disk with the prefailure is probably making the recovery effort more difficult. In the end, you need to replace TWO disks.
Comment: Yes!! I'm going to the seagate now. If it doesn't take on, then I will replace the newly bought HP disk... Will keep you posted in few mins.

Best practice on hot-swapping disk


Generating a dict from a list of tuples using dict() builtin

Question: I was surprised that both examples in the code block below return the same value. How does the dict() builtin accept the second syntax (the one that is not a generator expression)? Is this handled by the parser?
>>> words = ['cat','dog','frog']
>>> dict([(word, True) for word in words])
{'dog': True, 'frog': True, 'cat': True}
>>> dict((word, True) for word in words)
{'dog': True, 'frog': True, 'cat': True}

Comment: The second syntax _is_ a [generator expression](http://www.python.org/dev/peps/pep-0289/).  The first is a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions).
Answer: The second syntax is, in fact, a generator expression.
See PEP-289. It even includes the following example:
d = dict( (k, func(k)) for k in keylist)

which is almost exactly what you've got.
The first syntax is a list comprehension, a somewhat similar but distinct construct.
One key difference as applied to your example is that the first version creates and discards a temporary list, whereas the second doesn't.
Answer: Both examples are iterables, so you could write it "long-hand" the same way:
Generator:
generator_construct = ((word, True) for word in words)
d = {}
for key, value in generator_construct:
    d[key] = value

List comprehension:
list_construct = [(word, True) for word in words]
d = {}
for key, value in list_construct:
    d[key] = value

Both can be iterated the same way. The only difference is the list comprehension builds a real list, and the generator yields values one at a time. For a large number of items, the list comprehension will have more overhead because of the extra storage.
A third option given as comment by @JonClements:
d = dict.fromkeys(words, True)

Of the two, this is closest to the generator in that it doesn't build a key/value list, but it works directly over the words iterable.
Comment: In the OP's question, for non mutable values, it might be worth adding the best way would be: `dict.fromkeys(words, True)`


In data compression this equation describes the 'average length' of the code. Can someone please explain?

Question:
$$\bar{l}(\mathcal{P},\mathcal{L}) = \sum_{j=1}^n p_j l_j$$
I have just started studying this module and it describes the equation as the the average length of the code.
Can you please break down what each part of the equation means?
Comment: Thank you Achille Hui for editing the question.
Answer: $l_j$ is the length (say, in bits) of code word $j$.  $p_j$ is the probability that word $j$ occurs.  There is nothing magic about data compression here, it is the usual way of taking a weighted average.


Visual Studio Setup Project Installer Prerequisite for SQL Server CE

Question: I have a Setup Project in my solution in Visual Studio 2008 SP1.  The application installs fine but it is not loading my prerequisite of SQL Server CE.
I have the following configurations set:
alt text http://img6.imageshack.us/img6/317/msiq.png
Do I need to do anything else, like with a Custom Action or anything like that? Thanks.
Answer: I would suggest that you try private file–based deployment (deploying the SQL Server Compact 3.5 DLLs as part of the project) instead.
If you deploy this way you will circumvent this problem and also

Users do not need administrative credentials to install the application.
Can also use ClickOnce deployment

Another upside (or in some rare cases downside) will be that the deployment will not be serviced by the Microsoft Update...
Comment: Thanks for the reply.  I have seen this and do not want to use ClickOnce at this time.
Comment: Although I used this type of deployment only with ClickOnce thus far it is my understanding that it doesn't have to be a ClickOnce deployment... it is just a matter of including the dll files in your project instead of using the Windows Installer to install the SQL Server CE to a host machine. As long as you don't **have to** deploy to GAC this should work just fine...
Comment: I'd really like to know why using the prerequisite does not work, but I did get it to work with the file–based deployment.  +1 for a workaround, but hopefully someone can advise on what is wrong with the prereq method.
Answer: Choose prerequisites from the same location.


How do I get the angle requested in the figure?

Question: I have this problem:

I have not managed to solve the exercise, but this is my breakthrough:

How can I continue to find it?
Answer: An easy, general way to solve these problems is to draw a circle around them. Then by symmetry, each of the 6 arcs has a measure of $360^\circ/6=60^\circ$. The angle intercepts two arcs on one side and on arc on the other, resulting in $\frac{120^\circ+60^\circ}{2}=90^\circ$.
In the circle below arc $DCB$ measures $120^\circ$ and $EF$ measures $60^\circ$, so by an angle-intercepting-arc theorem, the angle is the average of the intercepted arcs: $90^\circ$.
Comment: Good answer ,thanks :)
Answer: Hint:   draw the segments to the center of the circle, and recognize a rhombus there formed by two equilateral triangles with a common base.
Answer: As noted one of the angle is $30^{\circ}$. Also note that the longer diagonal bisects the $120^{\circ}$ angle. Hence the angles in the top triangle are $30^{\circ}$ and $60^{\circ}$, so the the angle complement to $x$ is $90^{\circ}$, so we must have that $x = 90^{\circ}$
Comment: Exactly, that was what he had thought. But they never tell me it's diagonal, so how do you claim that?
Comment: @Mattiu A segment connecting two non-adjacent vertices in a polygon is by definition a diagonal, right?
Comment: True, but how do you ensure that it is just in the angle and not very close to it? That is my question, I believe that visual appreciation is not a demonstration of that.
Comment: @Mattiu If you wan't to be rigorous then we can't be sure about the other diagonal too. Indeed we have to make that assumption, as otherwise I don't believe that $x$ can be found.
Comment: Then, the exercise must have said that it is diagonal? To be rigorous?
Comment: It should have said, but as I said in this kind of problems it's usually assumed to be true from the picture.
Comment: Many thanks Stefan4024 :D
Answer: By using the symmetry of the figure.
Answer: $$x = 360^\circ - 90^\circ - 120^\circ - 60^\circ = 90^\circ$$
Comment: @Mattiu would be a stupid question if the line didn't touch the vertex...
Comment: Is because is a quadrilateral?
Comment: Yes.${} {} {} {}$
Comment: How do you assume it's diagonal? How do you know if it is exactly at the vertex?


How can I iterate starting at a particular key in a LinkedHashMap?

Question: If I have a data structure
Stock
{
  String Symbol;
  LinkedHashMap<Date,Double> DateForPrice;
}

I know in the LinkedHashMap, I can get the stock price of specific date without traversing the whole list.
However, if I want to iterate through the LinkedHashMap of DateForPrice starting from a specific date, are there any way to do it without traversing the whole list?
Comment: Even if you can jump to a particular place, the iteration order of a `LinkedHashMap` will be the *insertion-order*, not the natural ordering of the keys; is that what you want?
Comment: Yes, that's what I want. The the stock price will be inserted in the order of date.
Answer: LinkedHashMap doesn't offer a way to start iterating in the middle of its ordered view of the map's data. Supposing your use case is really that you want all dates after some Date d and to iterate those, then you should probably store your map as a TreeMap. An important distinction here is that LinkedHashMap's ordering is the insertion-order, and our supposed use-case here is that you want the natural key-order. TreeMaps maintain such a view, sorting the contents of the map by the map's key.
TreeMaps have the additional benefit of allowing you to create slices of the map based on the key, so you can call tailMap(K k), to return the map with all keys occurring after k. In this case, you can call tailMap with your starting point, d.
e.g.:
TreeMap<Date, Double> dateForPrice;

// load up dateForPrice

Date start = // the point to start your iteration

for(Entry<Date, Double> entry : dateForPrice.tailMap(start).entrySet()){
    // loop code
}

tailMap method returns SortedMap, which is not iterable. But it has entrySet method returning Set, which is subinterface of Iterable.
Conveniently, if you want to keep storing your data in a LinkedHashMap you can simply load up a TreeMap with your current instance (with some performance tradeoff, of course):
TreeMap<Date, Double> dateSortedDateForPrice = new TreeMap<Date, Double>(dateForPrice);

Comment: +1: Worth mentioning that what you really want is any NavigableMap e.g. TreeMap.
Comment: in addition to tailMap() you can use subMap(Object fromKey, Object toKey), if you want to bound the new map you are creating. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeMap.html
Answer: I'd suggest to use TreeMap instead - it will be sorted by date and you can use tailMap to get the required portion


No Such Element Exception With Loop

Question: I am using this code, and for some reason, I'm getting a No Such Element Exception...
numCompanies is being imported from the keyboard and is showing up right and portfolio is an array with [numCompanies][4].
Can anyone figure out why?
for(int i = 0; i < numCompanies; i++)
{
    System.out.print("Stock #" + (i+1) + ": ");
    String stockData = kbReader.nextLine();
    System.out.print("\n\n hi" + stockData);
    Scanner stockLine = new Scanner(stockData);
    for(int j = 0; j < 4; j++)
    {
        portfolio[i][j] = stockLine.next();
    }
}

Comment: Looks like `stockData` doesn't always have 4 substrings separated by an space.
Comment: Yeah, for some reason nextLine would always skip stock #1 and I created another Scanner object and it fixed the problem
Answer: I have not tested this but probably stockLine.next(); is called even though there is no element left. So maybe this could help:
for(int j = 0; j < 4; j++)
{
    if( stockLine.hasNext() ) {
        portfolio[i][j] = stockLine.next();
    }
    else
    {
        portfolio[i][j] = 0; // or whatever you want it to be by default
    }
}

This will solve the error message but not the fault.
Comment: You should use `hasNext()`, not catching the exeception
Answer: You're passing a single string to a Scanner object, but I would say there's a better way of doing this.
If you want to simply read in the input for each value in the string, separated by spaces, then use split():
String stockData = kbReader.nextLine();
String[] data = stockData.split(" ");
if (data.length != 4) {
    System.err.println("Bad data value found!");
} else {
    //run your loop
}

No Such Element Exception With Loop


Which Notes to Balance for Bansuri Practice

Question: One tutorial (at end of post) shows instructor balancing all notes on Sa, i.e.
starting from low octave ...
'pa Sa
'da Sa
through the middle octave ...
Re Sa
Ga Sa
and finally high octave, the only note
PA Sa
There are total of 15 notes (forget half notes right now). He is balancing 14 notes on Sa
Wouldn't it be good practice to balance all notes on each 15 notes?
So if we start with low octave 'pa, we balance remaining notes on it.
The we proceed to 'da, the continue to middle notes and finally high octave of PA
Do people actually practice this way? While it seems fascinating, there are a total of 15 x 14 balancing pairs to play, i.e. 15 x 14 = 210!
And let's say you want to go in reverse, i.e.
PA Ma
PA Ga
all the way down to
PA 'pa
And the continuing with Ma, i.e.
Ma PA
Ma Ga
etc, this would be 210 x 2 balancing pairs = 420
Playing 420 balancing pairs seems rather overwhelming? Or is this a wonderful goal to eventually play the notes faster and clearer?
Because some note transitions give me difficulties right now, it from Ga to 'da it sounds like a whosh of air.
What are recommendations?
Comment: For those from other cultures, please explain what it means in this context to **balance.**  Matching something across two notes? Loudness? Legato, to use an archaic Italian term? Something else?
Comment: @CamilleGoudeseune I posted original tutorial video. The instructor uses "balance", hence I thought that is the terminology.
Answer: I'm not sure what you mean by 'balancing'. I assume you mean ensuring that both notes have the same tone quality and dynamics, and that you get a smooth transition between them.
Yes, that's 420 pairs of notes to consider, but only very few of them will be difficult. Ignore the easy ones (revisit them later) and concentrate on the difficult ones. Do all the pairs in both directions, up and down.
Comment: this is the original tutorial where instructor uses balance. He usually shows more than explains (probably due to English as 2nd language), https://www.youtube.com/watch?v=SpGHg0Yps_k
Comment: Yes! Smooth transition between notes.


Variance of product of 2 independent random vector

Question: This should be a fairly straight forward but I still couldn't quite get it.
Let $X$ be $n$ by $1$ random vector, $Y$ be another $n$ by $1$ and that $X$ and $Y$ are independent.
What is $Var(X^tY)=:V_{XY}$?
I tried generalizing this formula from the univariate case
$Var(xy)=E(x)^2Var(y)+E(y)^2Var(x)+Var(x)Var(y)$
except I hit a bit of a roadblock for the 3rd term above. That is, I get
$$
V_{XY}=X^tV_YX+Y^tV_XY\\+E[(X^t-\mu_X^t)(Y-\mu_Y)(Y^t-\mu_Y^t)(X-\mu_X)]
$$
So... what is it?
Comment: How do you define $XY$ in $Var(XY)$? Is that an inner product?
Comment: @Stat It should be $X^t$ (X transposed) times Y. Updated the question. Thanks.
Answer: This answer supposes that $X^TY$ (where $X$ and $Y$ are $n\times 1$ vectors) is a $1\times 1$ vector or scalar $\sum_i X_iY_i$ and so we need to consider the
variance of a single random variable that is this sum of products.  Since $X$
and $Y$ are independent random vectors, we note that $X_1, Y_1$ are independent
random variables as are $X_2, Y_2$. Also, $(X_1, X_2)$ is independent of
$(Y_1, Y_2)$.
Since $\operatorname{var}(Z_1+Z_2) = \operatorname{var}(Z_1) + \operatorname{var}(Z_2) + 2\operatorname{cov}(Z_1,Z_2)$, we get that
$$\begin{align}
\operatorname{var}(X_1Y_1+X_2Y_2) &= \operatorname{var}(X_1Y_1)+
\operatorname{var}(X_2Y_2) + 2\operatorname{cov}(X_1Y_1, X_2Y_2)\\
\end{align}$$
The first two terms are the variances of the products of independent
random variables, and the OP knows the formula for handling these.
Turning to the covariance, we have that
$$\begin{align}
\operatorname{cov}(X_1Y_1, X_2Y_2) &=
E[X_1Y_1X_2Y_2] - E[X_1Y_1]E[X_2Y_2]\\
&= E[X_1X_2]E[Y_1Y_2] - E[X_1]E[Y_1]E[X_2]E[Y_2]\\
&= \left(\operatorname{cov}(X_1, X_2)+E[X_1]E[X_2]\right)\left(\operatorname{cov}(Y_1, Y_2)+E[Y_1]E[Y_2]\right)\\
& \qquad \qquad - E[X_1]E[Y_1]E[X_2]E[Y_2]\\
\end{align}$$
which simplifies to
$$
\operatorname{cov}(X_1Y_1, X_2Y_2) =
\operatorname{cov}(X_1, X_2)E[Y_1]E[Y_2]+ \operatorname{cov}(Y_1, Y_2)E[X_1]E[X_2]\\ + \operatorname{cov}(X_1, X_2)\operatorname{cov}(Y_1, Y_2),\tag{1}$$
a result that is eerily similar to the result
$$\operatorname{var}(X_iY_i) = \operatorname{var}(X_i)(E[Y_i])^2 + \operatorname{var}(Y_i)(E[X_i])^2 + \operatorname{var}(X_i)\operatorname{var}(Y_i) \tag{2}$$
quoted by the OP for independent random variables $X$ and $Y$
Thus we have
$$\operatorname{var}\left(\sum_{i=1}^n X_iY_i\right)
= \sum_{i=1}^n \operatorname{var}(X_iY_i) + 2\sum_{i=1}^{n-1}\sum_{j=i+1}^n
\operatorname{cov}(X_iY_i, X_jY_j)$$
where each term in the first sum on the right is given by $(2)$ and
each term in the double sum on the right is given by $(1)$. Plug and chug and enjoy!
Comment: @Sarwate: looks good, will go through it in more details tmr.
Comment: @Sarwate: Looks like the matrix notation has obscured the calculation this time. Thanks.
Answer: Here's a matrix-notation version that might be more convenient to work with than the plug-and-chug required by Dilip's answer.
$\DeclareMathOperator{\E}{\mathbb E} \DeclareMathOperator{\Var}{Var} \newcommand{\tp}{^\mathsf{T}} \DeclareMathOperator{\Tr}{Tr}$
Let $\mu_X := \E[X]$, $\Sigma_X := \Var[X]$, and similarly for $\mu_Y$, $\Sigma_Y$.
Then,
using trace rotation and independence of $X$ and $Y$, we get
\begin{align}
\Var[X\tp Y]
  &= \E[(X\tp Y)^2] - \E[X\tp Y]^2
\\&= \E\left[ X\tp Y Y\tp X\right] - \left(\E[X]\tp \E[Y]\right)^2
\\&= \E\left[\Tr\left( X X\tp Y Y\tp \right)\right] - \left(\mu_X\tp \mu_Y\right)^2
\\&= \Tr\left( \E[X X\tp] \E[Y Y\tp] \right) - \left(\mu_X\tp \mu_Y\right)^2
\\&= \Tr\left(
        \left( \mu_X \mu_X\tp + \Sigma_X \right)
        \left( \mu_Y \mu_Y\tp + \Sigma_Y \right)
     \right) - \left(\mu_X\tp \mu_Y\right)^2
\\&= \Tr\left( \mu_X \mu_X\tp \mu_Y \mu_Y\tp \right)
   + \Tr\left( \mu_X \mu_X\tp \Sigma_Y \right)
   + \Tr\left( \Sigma_X \mu_Y \mu_Y\tp \right)
   + \Tr\left( \Sigma_X \Sigma_Y \right)
   - \left(\mu_X\tp \mu_Y\right)^2
\\&= \left(\mu_X\tp \mu_Y\right)^2
   + \Tr\left( \mu_X\tp \Sigma_Y \mu_X \right)
   + \Tr\left( \mu_Y\tp \Sigma_X \mu_Y \right)
   + \Tr\left( \Sigma_X \Sigma_Y \right)
   - \left(\mu_X\tp \mu_Y\right)^2
\\&= \mu_X\tp \Sigma_Y \mu_X + \mu_Y\tp \Sigma_X \mu_Y + \Tr(\Sigma_X \Sigma_Y)
.\end{align}