text:
Q: Unsatisfied Link Error BluetoothStackBlueSoleil I'm trying to use bluetooth for a java application, I'm on Windows 7 64bit.
I'm following this example
http://luugiathuy.com/2011/02/android-java-bluetooth/

Turned out I had problem with the bluecove.jar proposed on that site, so I found this thread
http://code.google.com/p/bluecove/issues/detail?id=109

telling me to get this .jar:
http://snapshot.bluecove.org/distribution/download/2.1.1-SNAPSHOT/2.1.1-SNAPSHOT.62/

Alright then!
But now, I'm facing a new error (yaay...):
Exception in thread "Thread-2" java.lang.UnsatisfiedLinkError:     com.intel.bluetooth.BluetoothStackBlueSoleil.getLibraryVersion()I
at com.intel.bluetooth.BluetoothStackBlueSoleil.getLibraryVersion(Native Method)
at com.intel.bluetooth.BlueCoveImpl.setBluetoothStack(BlueCoveImpl.java:964)
at com.intel.bluetooth.BlueCoveImpl.detectStack(BlueCoveImpl.java:502)
at com.intel.bluetooth.BlueCoveImpl.access$500(BlueCoveImpl.java:69)
at com.intel.bluetooth.BlueCoveImpl$1.run(BlueCoveImpl.java:1044)
at java.security.AccessController.doPrivileged(Native Method)
at com.intel.bluetooth.BlueCoveImpl.detectStackPrivileged(BlueCoveImpl.java:1042)
at com.intel.bluetooth.BlueCoveImpl.getBluetoothStack(BlueCoveImpl.java:1035)
at javax.bluetooth.LocalDevice.getLocalDeviceInstance(LocalDevice.java:75)
at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:95)
at BTThread.waitForConnection(BTThread.java:35)
at BTThread.run(BTThread.java:23)
at java.lang.Thread.run(Unknown Source)

So.. would anyone have any idea why?
The BluetoothStackBlueSoleil seems to be in the .jar I downloaded, so I don't get the unstatisfied link error...
Thanks for any help

A: I solved my problem by removing Bluesoleil from my computer and installing different Bluetooth drivers.

A: I think the problem was that there was native methods that you needed to build. You have to compile the native code from the JNI folder using the Android NDK. ndk-build etc
Just in case you see the problem again.


text:
Q: Understanding Independence as measure specific I'm trying to understand the definition of independent events or sets in a sigma algebra on a probability space to be something determined by the probability measure the space is endowed with. However, I have been unable to come up with a good enough example to illustrate this to myself.
For example, would it be possible to have three events $A, B, C$ such that when considered with respect to probability measure $\mu, C$ is independent of $A$ and $C$ independent of $B$ but $C$ not independent of $A \cup B$? However, when considered with respect to some alternative probability measure $\nu$, could we have a situation where each of the events $A$, $B$ and $C$ has strictly positive probability with $\nu$ but are mutually independent?

redpajama_set_name: RedPajamaStackExchange


text:
Q: detect whether app is running on simulator or on device (as3) i've found some solutions for this but no one for as3:
I'm developping an app for ios with AS3, and i'd like to set a variable that detects whether the app is running in the adl simulator or on the real device.
Is that possible with as3? i've searched on adobe doc, this forum and google, and found nothing.
thanks.

A: Usually I create a Boolean for debug and set it true when developing and false when will release

A: As for ADL simulator you can simply check the Capabilities.cpuArchitecture == "ARM" statement. For ADL is false, whilst for iOS sim and iOS or Android device it is true.


text: Q: The concept of flux linkage without coil I know the concept of flux linkage when there's two coils and we talk about the flux lines produced by the first coil entering the second coil, but recently I have been studying the inductance of transmission lines, and their is no coil, just one conductor. So here how do we define the the flux linkage to the conductor due to some external magnetic fields?


text:
Q: How to define custom color for this pie chart? I use this very Highchart Pie in my application. How to set custom color for each slices based on the output?
I use this script before the highchart script to change the color but it seems to have no effect.
Highcharts.theme = {
  colors: ['#000000',
           '#FFFFFF',
           '#FF00FF',
           '#DDDF00',
           '#24CBE5',
           '#64E572',
           '#FF9655',
           '#FFF263',
           '#6AF9C4'],

};
// Apply the theme
Highcharts.setOptions(Highcharts.theme);

This is the highchart:
Highcharts.chart('container', {

title: {
    text: 'GRAFIK PENGADAAN SCG'
},
series: [{
    name                : 'Jumlah',
    colorByPoint        : true,
    type                : 'pie',
    allowPointSelect    : true,
    keys                : ['name', 'y', 'selected', 'sliced'],
    data                : [
                            <?php

                                $arr_act = "";
                                foreach($graph_act as $res_act){

                                    $arr_act .= "['".$res_act['ACT']."',".$res_act['JUMLAH'].",false],";

                                }
                                echo rtrim($arr_act, ',');
                            ?>

                          ]
    }]
});


text:
Q: Multivariable differentiation seems to do nothing? If I have $f(x,t)$ and want to augment this as $f_a(x,t)=f(a^3x,a^5t)$. I want to take $\frac{d}{dt}(f_a(x,t))$.
Do I write $\frac{d}{dt}f(a^3x,a^5t)=f(a^3x,g(t))$ where $g(t) = a^5t$ and sort of chain rule in the right position to obtain:
$$\frac{d}{dt}f_a(x,t) =  \frac{\partial f(a^3x,a^5t)}{\partial t}\cdot a^5,$$
this seem wrong? It feels like I just have $f_t(a^3x,a^5t)=a^5f_t(a^3x,a^5t)$ which is nonsense...

A: If $x$ does not depend on $t$,
$$\frac{d f(x,t)}{dt}=\frac{\partial f(x,t)}{\partial t}.$$
You can "hide" the dependency on $x$ by defining
$$g_x(t):=f(x,t)$$ so that
$$g_x'(t)=\frac{d g_x(t)}{dt}=\frac{d f(x,t)}{dt}=\frac{\partial f(x,t)}{\partial t}.$$
Now by the chain rule
$$\frac{d g_{a^3x}(a^5t)}{dt}=a^5g_{a^3x}'(a^5t)=a^5\left.\frac{\partial f(x,t)}{\partial t}\right|_{x=a^3x,t=a^5t}.$$


text:
Q: Error trying to use global variable from Bottlepy mounted app I got a parent_app in a python file (parent.py) that I'm trying to mount in a child_app in another python file (child.py). The mount seems to work but, when I try to call a route from my parent_app trough the mount in my child_app, this route doesn't seems to be able to use global variable in my parent.py file.
The parent.py file:
from bottle import route
import bottle
import subprocess as sp

global extProc

parent_app = bottle.Bottle()

@parent_app.route('/start')
def start_bazarr():
    global extProc
    extProc = sp.Popen(['python','child.py'])

@parent_app.route('/stop')
def stop_bazarr():
    sp.Popen.terminate(extProc)

@parent_app.route('/restart')
def restart_bazarr():
    stop_bazarr()
    start_bazarr()

if __name__ == '__main__':
    start_bazarr()

The child.py file:
from bottle import route, run
import bottle
from parent import parent_app

child_app = bottle.Bottle()

@child_app.route('/')
def root():
    return u'Lorem Ipsum'

if __name__ == '__main__':
    child_app.mount('/power', parent_app)
    child_app.run(host='127.0.0.1', port=8080)

The URL I'm trying to call:
http://127.0.0.1:8080/power/restart

The error I got:
Traceback (most recent call last):

File "C:\Python27\lib\site-packages\bottle.py", line 862, in _handle
    return route.call(**args)
File "C:\Python27\lib\site-packages\bottle.py", line 1740, in wrapper
    rv = callback(*a, **ka)
File "C:\Users\morpheus\Desktop\parent.py", line 20, in restart_bazarr
    stop_bazarr()
File "C:\Users\morpheus\Desktop\parent.py", line 16, in stop_bazarr
    sp.Popen.terminate(extProc)
NameError: global name 'extProc' is not defined

What am I doing wrong?

A: In the global scope, you don't need the global keyword. You can define it , and set it to None as a temporary placeholder.
from bottle import route
import bottle
import subprocess as sp

extProc = None

And the terminate function needs to know about the use of extProc
@parent_app.route('/stop')
def stop_bazarr():
    global extProc
    sp.Popen.terminate(extProc)


text:
Q: Is this writing correct Can I define an optimization problem like this to save some space?
$$\min_x f(x)=x^2+1-log(x)\\s.t. ~x>0,$$
or i have to write it as
$$\min_x f(x)\\s.t. ~x>0,$$
where $f(x)=x^2+1-log(x)$?
Update:
In fact, in the real problem, I have a set of constraints like $\{g_i(x)\ge 0\}_{i=1}^k$, and I need to define them in separate lines or with "," in between, but not as the underset of "$\min$".

A: My two pence:
$$\min_{x>0}f(x), f(x):=x^2+1-\log x$$
or just
$$\min_{x>0}(x^2+1-\log x)$$
in case you don't need the function elsewhere (or let it be $f(x)$ implicitly).

A: No, because this writing is ambiguous, because it is unclear whether you are giving the limit of f (not the second expression) or if you ask the limit of the function (like in the second expression).
I recommend the following:
$\min_{x>0} f(x)=\min_{x>0}(x^2+1-log(x))$

A: For $f(x)=x^2+1-\ln{x}$ I like the following.
$$\min_{(0,+\infty)}f.$$


text:
Q: How to negate perl regex with lookbehind? I have this text (file.txt) to inspect:
_abcd
_efgh
#, _1

Now I want to match only words with underscore but that are not preceded with hash #. To mach all, I can do
$perl -nle 'print $1 if /(_\w+)/' file.txt

But I dont want to match the hash, so I will try the lookbehind:
$ perl -nle 'print $1 if /(?<!#.+)(_\w+)/' file.txt

Variable length lookbehind not implemented in regex m/(?<!#.+)(_\w+)/ at -e line 1.

*

*How to implement variable length lookbehind in perl?

For the second, I will try to do lookahead:
$ perl -nle 'print $1 if /(?!#.+)(_\w+)/' file.txt

which will again match all, including the # line, which I do not want.

*How to match all, except the # line (in other words, how to negate regex)?

A: You may use
/#.+(*SKIP)(*F)|_\w+/

Or, to match _ at the word boundary:
/#.+(*SKIP)(*F)|\b_\w+/

The pattern matches

*

*#.+(*SKIP)(*F) - # and any 1 or more chars other than line break chars as many as possible, and then the match is skipped, omitted, discarded and the next  match is searched for from the place where the match was skipped

*| - or

*_\w+ - a _ and then any 1 or more word chars.

A: The following will do:
/^[^#]*(_\w+)/


text:
Q: Appending a class attribute to woocommerce single product image  - $image_title         = esc_attr( get_the_title( get_post_thumbnail_id() ) );
            $image_link         = wp_get_attachment_url( get_post_thumbnail_id() );
            $image              = get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ), array(
                'title' => $image_title
                ) );
            $attachment_count   = count( $product->get_gallery_attachment_ids() );

            if ( $attachment_count > 0 ) {
                $gallery = '[product-gallery]';
            } else {
                $gallery = '';
            }

            echo apply_filters( 'woocommerce_single_product_image_html', sprintf( '%s', $image_link, $image_title, $image ), $post->ID );

Above is the code from product-image.php file of woocommerce. I want to add a class to the image of single product. I am unable to find out the way for it. Please help.
Thanks

A: $image = get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ), array(
'title' => $image_title,
'class' => 'your class here'
));

I added the class key in get_the_post_thumbnail


text:
Q: Update foreach in foreach c# The code snippet shown will compare each element in the first list with one element in the second one. But when the inner foreach finishes, the upper foreach re-enters and the image throws the same guid in both lists.
How can I get it to not do this?
   var listDetail = await _repo.GalleryDetail.GetAllAsync(a => a.GalleryId == request.Id);

        request.GalleryDetails.ToList().ForEach(a =>
        {
            if (a.File == null)
            {
                foreach (var item in listDetail)
                {
                    a.Image = item.Image;
                }
            }
            else
            {
                foreach (var item in listDetail)
                {
                    if (item.Image != null && item.Image != "True")
                        item.Image = a.File.DeleteFtp(url: item.Image.Substring(7),
          cdn).ToString();
                }

                a.Image = a.File.UploadFtp("GalleryDetail", cdn);
            }
        });

A: This overwrites a.Image for every item in listDetail, therefore you get the last Image:
foreach (var item in listDetail)
{
    a.Image = item.Image;
}

As you have an Id property, I suggest using it for synchronization:
foreach (var item in listDetail)
{
    if (item.Id == a.Id)
    {
        a.Image = item.Image;
        break;
    }
}

I added a break; so you break out of the loop as soon as you found a match.


text:
Q: Replacing query_posts() function in Wordpress I'd like to create a custom function to replace query_posts(). This custom function needs to include certain custom post types.
I know that you can use query_posts() and specify post_type array as an argument, but since this particular custom query posts will be used on multiple page templates, I'd like to avoid editing multiple templates when new custom post type is created.
So, I'm looking for something like
mycustom_query_posts($args) to call on my page templates. The question is, how does one create this mycustom_query_posts($args)?
Thanks beforehand!

A: Wordpress already did it for you:
WP_Query


text:
Q: Extração de valor de objeto datetime em Python. Tenho como necessidade extrair somente a hora de um objeto datetime.
Como proceder?
O objeto retorna a seguinte saida: "3 days, 22:01:00"

A: Primeiro você precisa utilizar o seguinte módulo da seguinte biblioteca:
from datetime import datetime

depois é só fazer:
 now = datetime.now()

 print("%s:%s:%s" %(now.hour,now.minute,now.second))

output:
23:4:58

Se quiser somente a hora, é só utilzar o now.hour e printar ele.
seria isto que você queria?

A: Usando o método strftime() com a formatação %H e retornando string:
from datetime import datetime
obj = datetime.now()
hora = datetime.strftime( obj, "%H")
print(hora)

Usando o atributo hour do objeto datetime e retornando um int:
from datetime import datetime
obj = datetime.now()
print(obj.hour)


text:
Q: Same code compiled with different versions provides different result I am using an external library which I do not control nor know the internals (lets call it proprietarycallbacks).
I know that I have a class called callbacks that has two bool variables:
class callbacks : public proprietarycallbacks {
  bool a = false;
  bool b = false;
  virtual callbackHandler() {
    cout "callback received\n";
    b = true;
  }
}

then I have another class which inherits from the callbacks class:
class MyObject : public callbacks {

  void test() {
    while (!b) {
      cout << "test " << a << " " << b << endl;
      usleep(100000);
    }
  }
}

This code compiles correctly in two different linux versions, with two different GCC versions and LIBC versions.
On the most recent one (linux mint, GCC 5.4 LIBC 2.23), I run the app, see the cout in the while and when the callback is called, the code exists the while.
On the older one (debian, GCC 4.9.2, LIBC 2.19), the while never exists, the variable is always false, even though I can see the print from inside the callback.
Is there something wrong with the way I am structuring the code, and the variable inheritance, or does this have something to do with the software versions I am using?
Thank you for your time

A: It is obvious from your test() method that there are multiple execution threads involved. test() is in one execution thread, and the callbacks get invoked by the other execution thread.
Setting the bool flags in the other execution thread, and reading the same flags in the test() execution thread are not sequenced with each other.
The usual solution is to either use std::atomic_bool; or use a std::mutex to implement sequencing, and accessing the variables, either to set them in one execution thread, or read their current values in the other execution thread, only while the mutex is locked.


text:
Q: How to connect a server in simple tunnel? NEVPNManager.sharedManager().enabled = true
        NEVPNManager.sharedManager().loadFromPreferencesWithCompletionHandler{ error in
        print("error",error)
        if error == nil {
            let p = NEVPNProtocolIKEv2()
            p.serverAddress = "116.65.79.28"
            p.authenticationMethod = .SharedSecret
            p.useExtendedAuthentication = true
            let secret = "vpn"
            let secretData = secret.dataUsingEncoding(NSUTF8StringEncoding)
            p.sharedSecretReference = secretData
            p.localIdentifier = "vpn"
            p.username = "vpn"
            p.passwordReference = "vpn".dataUsingEncoding(NSUTF8StringEncoding)//SSKeychain.passwordForService("service", account: "passwordReference").dataUsingEncoding(NSUTF8StringEncoding)!
            p.disconnectOnSleep = false
            NEVPNManager.sharedManager().protocolConfiguration = p
            var rules = [NEOnDemandRule]()
            let connectRule = NEOnDemandRuleConnect()
            rules.append(connectRule)
            NEVPNManager.sharedManager().onDemandRules = rules
            NEVPNManager.sharedManager().localizedDescription = "vpn"

            NEVPNManager.sharedManager().enabled = true
            NEVPNManager.sharedManager().saveToPreferencesWithCompletionHandler{(error) in
                print("Save VPN to preference complete")
                if (error != nil) {
                    print("Save error: \(error)")
                }
                do {
                    try NEVPNManager.sharedManager().connection.startVPNTunnel()
                }
                catch let error as NSError {
                    print("Start error: \(error.localizedDescription)")
                }
            }

        }
}

[https://developer.apple.com/library/mac/samplecode/SimpleTunnel/Introduction/Intro.html]
I am new to vpn connection. I don't know how to connect and run the example provided by apple.
I got the entitlements from the apple. The app is working but nothing is connecting. It doesn't move after the "targetManager.connection.startVPNTunnel()" in StatusViewController. I didn't get any clue to do this and i don't know how to do. please help me to get success.
So I tried run at least the above example. But i also not working... what to do?


text:
Q: Pagination in TypeORM, NestJS I have multiple search condition in my form. if user does not enter anything then all the data should be return. if he gives some search input then only those matching record should be return.
Below code is working fine. the only thing is ,sometimes record are coming around 30-40 with filter condition as well so I have been given requirement to introduce pagination. we have to show 10 record at a time in page with or without filter condition.
Could you please guide me how can I introduce pagination in below code.
async findAll(queryCertificateDto: QueryCertificateDto): Promise<Certificate[]> {

    const { certificateNo, requestStatus, protoColNo, noOfSubjects} =queryCertificateDto

    const query = this.certificateRepository.createQueryBuilder('certificate');

    if (certificateNo) {
        query.andWhere('certificate.certificateNo=:certificateNo', { certificateNo });
    }

    if (requestStatus) {
        query.andWhere('certificate.requestStatus=:requestStatus', {
            requestStatus,
        });
    }

    if (protoColNo) {
        query.andWhere('certificate.protoColNo=:protoColNo', { protoColNo });
    }

    if (noOfSubjects) {
        query.andWhere('certificate.noOfSubjects=:noOfSubjects', { noOfSubjects });
    }
    const certificates = await query.getMany();
    return certificates;
}

A: export const getAllFaqs = () => async (req: Request, res: Response): Promise<void> => {
  const {
    query: { userType ,page ,perPage},
  } = req;
  const faqsPagesRepository = getCustomRepository(FaqsPageRepository);

  let where: FindConditions<Faqs> = {};

  if (userType) {
    where = { ...where, userType };
  }
  const limit =Number(perPage);
  const offset=(Number(page)-1)*limit;
  const result = await faqsPagesRepository.findAndCount({
    where,
    take:limit,
    skip:offset,
  });

  res.status(200).json({ result });
};


text:
Q: psexec command to run bat file present in some directory on remote server I want to achieve following in one single command.
PS D:\custom> .\PsExec.exe \remoteserver -u user -p password -accepteula -s cmd
PsExec v2.34 - Execute processes remotely
Copyright (C) 2001-2021 Mark Russinovich
Sysinternals - www.sysinternals.com
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>D:
D:\ cd test
D:\test>testjob.bat
D:\test>hostname
windowsrundeck
I don't want to copy my bat file from my local machine to remote machine. instead I want to directly execute a bat file present in D:\test folder of remote machine.
Also, Is it possible to run multiple commands in one psexec command ?
Also, If I use this psexec command in automation tool, it just gives me exit code, note verbose of what it has done.. How can I see what my bat file is doing when I run my psexec command from automation tool?

A: I managed to fix it by adding all commands in one bat file. and I was able to execute the batfile in D:\test by using -w parameter in psexec command. -w sets the working directory on remote machine.


text:
Q: How to get notified about changes on SharePoint groups. I'm actual looking for a way to get notified about any changes on a SharePoint group. First I though I would be able to this by attaching a event handler to some kind of group list. But unfortunately there are no such list representing SharePoint groups.
My second attempt was to bind a event handler to the content type SharePointGroup but this didn't work either.
So are there any other options to get notified about events on a SharePoint group?
EDIT:
Thanks for the reply so far.
I forgot to mention that I've already googled and read about the user information list. Sorry.
First I found a forum entry where they post the relative URL to the user information list (_catalogs/users/simple.aspx). When I'm using this link to see the list,it only contains users and no groups. I don't know but perhaps this link does some filtering on the list.
The other information I found about in several blog and forum posts was that a event handler attached to the user information list are not fired up on an events. I have to admit after reading that it doesn't work so many times and even on MSDN (http://msdn.microsoft.com/en-us/library/aa979520.aspx), I didn't try it on my own.
The problem attaching the event handler to the content type wasn't the attaching thing, the handler simply didn't get fired when I for example changed a group name or deleted a user from the group. I don't have an idea why the handler doesn't get called I pretty sure I implemented the right methods and attached them to the right events.
Any other suggestions how to get informed about changes on SharePoint groups?

A: It is really annoying that adding or removing from a group doesn't have an event handler the best work around I have found using Google! is to turn on auditing.
Then periodicaly loop through the audit to fire my event.
            wssQuery = new SPAuditQuery(site);
            wssQuery.AddEventRestriction(SPAuditEventType.SecGroupMemberAdd);
            wssQuery.AddEventRestriction(SPAuditEventType.SecGroupMemberDel);
            wssQuery.SetRangeStart(startTime.AddMinutes(-16));
            auditCol = site.Audit.GetEntries(wssQuery);

            foreach (SPAuditEntry entry in auditCol)
            {
                    xml.LoadXml("<event>" + entry.EventData + "</event>");

                    int userId = Int32.Parse(xml.SelectSingleNode("/event/user").InnerText);
                    int groupId = Int32.Parse(xml.SelectSingleNode("/event/groupid").InnerText);

                    if (entry.Event == SPAuditEventType.SecGroupMemberAdd)
                    {
                       // Do Stuff
                    }

                    if (entry.Event == SPAuditEventType.SecGroupMemberDel)
                    {
                        // Do Stuff
                    }

             }

It does cause a serious delay between the member being added to the group and the event firing though!
I couldn't find an event handler on the audit either so the only option seems to be looping through.
This is expensive for me as we have hundreds of site collections!

A: What do you mean there is no such list for SharePoint groups? You have the User Information List in which both users and SharePoint groups reside. You can attach event receivers there and filter on the items. For example you can filter on the content type id of SharePoint groups, which is 0x010b.
Also, attaching event receivers to SharePoint groups should be possible. What didn't work?
.b

A: Unfortunately, "List events are not raised on the UserInformation list type."
see: http://msdn.microsoft.com/en-us/library/aa979520.aspx
or the discussion here: http://social.msdn.microsoft.com/Forums/en-US/ea2e06fb-63e1-4096-843c-413ddf33f24b/how-to-add-event-receivers-for-spgroup-in-sharepoint
However, there is a solution in case of SP 2013:
http://www.c-sharpcorner.com/UploadFile/anavijai/create-groupuseradded-event-receiver-in-sharepoint-2013/


text:
Q: Efficient way of using tikz when you're doing a lot of diagrams I'm going to do a big project on category theory / algebraic geometry and I need to use a lot of diagrams.
I'd like to now if there are some tricks to make it faster and easier. I assume that it's just a matter of practice but I'd like to know what people do usually in this situations.
Should I define a lot of commands with the most basic diagrams?
I hope this is not too subjective.
As an example of diagram:

A: I'd suggest you to use tikz-cd. This package is built upon TikZ and was designed specifically to draw commutative diagrams. It's very versatile, offers a lot of customization possibilities and it has a very concise and convenient syntax; besides, you have access to a wide variety of arrows (you have all the standard arrows usually found in those diagrams) and can use all the power of TikZ if required.
Here's a simple demonstration with the diagram in your question:
\documentclass{article}
\usepackage{tikz-cd}
\usepackage{amsmath}
\usepackage{mleftright}

\DeclareMathOperator{\Ker}{ker}
\newcommand\TwoMor[2]{
\mleft(\begin{smallmatrix}#1 \\ #2\end{smallmatrix}\mright)
}

\begin{document}

\begin{tikzcd}[row sep=2cm,column sep=1.5cm]
X
  \ar[dr,dotted,"w"]
  \ar[ddr,"v",swap]
  \ar[drr,"u"]
& & &
\\
&
\Ker\TwoMor{f}{g}
  \ar[r,dotted,"b'"]
  \ar[d,dotted,"a'",swap]
  \ar[dr,rightarrowtail,"k"]
&
B
  \ar[d,rightarrowtail,"b"]
\\
&
A
   \ar[r,"a",swap]
&
C
  \ar[r,"f"]
  \ar[d,"g",swap]
  \ar[dr,"\TwoMor{f}{g}"]
&
D
\\
& &
E
&
D\times E
  \ar[u,"p_{D}",swap]
  \ar[l,"p_{E}"]
\end{tikzcd}

\end{document}

Instead of defining commands for diagrams themselves, as you suggested in your question, I'd rather define commands for elements that are often used in your diagrams; as an illustration, I defined \TwoMor:
\newcommand\TwoMor[2]{
\mleft(\begin{smallmatrix}#1 \\ #2\end{smallmatrix}\mright)
}

to quickly build a pair of morphisms.


text:
Q: PySpark/SQL joining on non unique key I have two transaction tables that I need to join; however, there's no clean link between these two tables:
For t1 I have:
unique_id | date | units

for t2 I have:
unique_id | date | store_id | transaction_key

My desired output is to get units in terms of store_id; when I do a left join on t1 with unique_id and date, however, there are cases where customers make multiple transactions on the same day which gives me duplicates on transaction key.
Sample data and output added:
Table 1 and table 2:

Current output:

Desired output:

A: I think that you want a left join, but with row_number() as a matching condition:
select t1.unique_id, t1.date, t1.units, t2.store_id, t2.transaction_key
from (
    select t1.*, row_number() over(partition by unique_id, date order by units) rn
    from table1 t1
) t1
left join (
    select t2.*, row_number() over(partition by unique_id, date order by transaction_key) rn
    from table2 t2
) t2
    on t2.unique_id = t.unique_id and t2.date = t1.date and t2.rn = t1.rn


text:
Q: Need to convert epoch time to EST using pandas I do have a dataframe like this  -> df
     timestamp      values

0    1574288141       34
1    1574288241       23
2    1574288341       22
3    1574288441       10

Here timestamp has the epoch time. I want to convert this into a datetime in the format 2019-11-20 04:03:01. I would like to convert this into a EST date.
When I do
pd.to_datetime(df['timestamp'], unit='s')

I get the conversion and the required format but the time doesn't seem to be in EST. It is 4 hours ahead of EST.
I have tried to convert utc to Eastern using the code
pd.to_datetime(df['timestamp'], unit='s').tz_localize('utc').dt.tz_convert('US/Eastern')
But I am getting an error
TypeError: index is not a valid DatetimeIndex or PeriodIndex

A: You should adding dt , since your input is series not index
pd.to_datetime(df.timestamp,unit='s').dt.tz_localize('utc').dt.tz_convert('US/Eastern')
Out[8]:
0   2019-11-20 17:15:41-05:00
1   2019-11-20 17:17:21-05:00
2   2019-11-20 17:19:01-05:00
3   2019-11-20 17:20:41-05:00
Name: timestamp, dtype: datetime64[ns, US/Eastern]


text:
Q: Python - calculation of surplus I am trying to develop an application to calculate the surplus value on the IRPJ. It consists of, if the value of the IRPJ is greater than 60k, calculate 10% over the excess of 60k, but I am not able to put the second value as a variable, it gives the following error:
l_calcirpj = Label(calc, text='O valor a ser pago de IRPJ é de: {:.2f}'.format(irpj2))
UnboundLocalError: local variable 'irpj2' referenced before assignment

Follow the code below:
from tkinter import *
# ---
calc = Tk()
calc.title('mikaelson')
calc.geometry('350x350')
# ---
l_receita = Label(text='Receita')
l_receita.place(x=15, y=15)
e_receita = Entry(calc)
e_receita.place(x=100, y=15)
# ---
def calcular():

    receita = float(e_receita.get())
    # ---
    irpj = receita * 32 / 100
    if irpj > 60000:
        irpj2 = (irpj - 60000) * 10 / 100
    else:
        print('menor que 60k')

    l_calcirpj = Label(calc, text='O valor a ser pago de IRPJ é de: {:.2f}'.format(irpj2))
    l_calcirpj.place(x=15, y=60)
    # ---
    e_receita.delete(0, END)

bt = Button(calc, text='Calcular', command=calcular)
bt.place(x=15, y=95)

calc.mainloop()

A: The variable irpj2 is only created if irpj>60000.  Try creating the variable and initialising it to a sensible default (e.g. 0) outside of the if statement.


text:
Q: Flink stateful functions : compensating callback on a timeout I am implementing a use case in Flink stateful functions. My specification highlights that starting from  a stateful function f  a business workflow (in other words a group of stateful functions f1, f2, … fn are called either sequentially or in parallel or both ). Stateful function f waits for a result to be returned to update a local state,  it as well starts a timeout callback i.e. a message to itself. At timeout, f checks if the local state is updated (it has received a result), if this is the case life is good.
However, if at timeout f discovers that it has not received a result yet, it has to launch a compensating workflow to undo any changes that stateful functions   f1, f2, … fn might have received.
Does Flink stateful functions framework support such as a design pattern/use case, or it should be implemented at the application level? What is the simplest design to achieve such a solution? For instance, how to know what functions of the workflow stateful functions f1, f2, … fn were affected by the timedout invocation (where the control flow has been timed out)? How does Flink sateful functions and the concept of integrated messaging and state facilitate such a pattern?
Thank you.

A: I posted the question on Apache Flink mailing list and got the following response by Igal Shilman, Thanks to Igal.
The first thing that I would like to mention is that, if your original
motivation for that scenario is a concern of a transient failures such as:

*

*did function Y ever received a message sent by function X ?

*did sending a message failed?

*did the target function is there to accept a message sent to it?

*did the order of message got mixed up?

*etc'

Then, StateFun eliminates all of these problems and a whole class of
transient errors that otherwise you would have to deal with by yourself in
your business logic (like retries, backoffs, service discovery etc').
Now if your motivating scenario is not about transient errors but more
about transactional workflows, then as Dawid mentioned you would have to
implement
this in your application logic. I think that the way you have described the
flow should map directly to a coordinating function (per flow instance)
that keeps track of results/timeouts in its internal state.
Here is a sketch:

*

*A Flow Coordinator Function - it would be invoked with the input
necessary to kick off a flow. It would start invoking the relevant
functions (as defined by the flow's DAG) and would keep an internal state
indicating
what functions (addresses) were invoked and their completion statues.
When the flow completes successfully the coordinator can safely discard its
state.
In any case that the coordinator decides to abort the flow (an internal
timeout / an external message / etc') it would have to check its internal
state and kick off a compensating workflow (sending a special message to
the already succeed/in progress functions)

*Each function in the flow has to accept a message from the coordinator,
in turn, and reply with either a success or a failure.


text:
Q: Looking for recommendations for a .NET CORBA Library I have an upcomming project in which I must interact with an existing CORBA system from a new C# .NET 3.5 full framework application.
Can anyone provide a recent .NET CORBA itneroperability story and recommend a stack to enable our .NET applications to interoperate with a third party CORBA service?  Free would be great, but commercial fine too.

Context
It would seem that WCF does not do CORBA as standard, which is a shame as that would have been my preferred route.  CORBA itself seems very much one of "last years" technologies, and I think thats why Google has fails to be my friend on this topic!
The CORBA client requires secure connections wich seems to be too much for the two OSS COBRA stacks I found to date (IIOP.NET and Remoting.CORBA).  Although this might just be due to ignorance about windows certifciate management rather then the libraries themselves.  Borland's Janeva seems to have dropped of the web.
We do also develop applicaitons in Delphi 6 in house (still) but would ideally like to keep the new stuff 100% .NET if we can.  We can potentially go .NET 4 is this helps but any solution in 3.5 would be easier.

A: I think IIOP is good but you can see similar question here.

A: I would recommend implementing the CORBA interface in C++ (and bridge that into you dotnet code via C++/CLI) if you have any C++ expertise available.
Using a C++ ORB will give you a fully compliant ORB with "all" features, instead of a cut down version.
If you are a non-C++ shop, you still might be better off outsourcing the CORBA / C++ module to interface with the 3rd party CORBA service.
omniORB and TAO are obvious choices for C++ ORBs.
I like omniORBs (relative) simplicity wrt. getting it running and I also have successfully integrated omniORB into a C++ DLL that is loaded by a C#/.NET application.


text:
Q: Thread safety in C++ I have question regarding thread safety as below ( I have only two threads in which one of the threads only read from the map, the other threads would be writing and reading as shown):
//Thread 2: the reading and writing thread
unordered_map<int, unordered_map<classA*>*>testMap;

//need lock because writing to the map?
testMap[1] = new unordered_map<int, classA*>;

//do not need lock because only reading and the other thread is only reading?
unordered_map<classA*>* ptr = testMap[1];

//need lock because writing?
(*ptr)[1] = new classA;

//do not need lock because only reading and the other thread is only reading?
classA* ptr2 = (*ptr)[1];

//din't modify the map, but modify the data pointed by the pointer stored by the map, do I need lock?
ptr2->field1 = 5;
ptr2->field2 = 6;

//end of reading and writing thread

What is the correct way to lock to unordered_map? Also, should I use a single lock or multiple locks?
Thanks.

A: If your map is the only shared resource, a single mutex is sufficient.
You need to lock the writing in the first thread, and lock the reading in the second one. If you lock the map only when writing on it, the second thread could read it while you are writing in it.
You dont need a lock in the last example regarding the pointers, since you dont deal with any data stored in the map.
Edit : in fact, it depends on what your are doing with the pointers and in which thread you do it.
You should read this great article : http://herbsutter.com/2010/09/24/effective-concurrency-know-when-to-use-an-active-object-instead-of-a-mutex/

A: You need to lock both, reading and writing. If you do not lock reading then a write can occur while you are reading and you may access the map in an inconsistent state.
What would be best in your situation would be a reader-writer-lock. Such a lock allows multiple readers to read at the same time but only one writer at the same time and no readers while a writer writes and vice versa.

A: Couple of things:

*

*You should consider smart pointers to store in your map.

*What you are doing is potentially quite dangerous (i.e. you may not be modifying the main map), but you are modifying what's stored there and if you do this outside of a lock, the end result could be anything - let's say that thread one has also read the same pointer and starts iterating whilst thread two is writing the instance of classA - what happens then?

I would have a lock around the main map, and then another lock for each payload map. Any operations on either map should require to obtain the lock at the correct level. I'd also be careful not to return iterators outside of the class that manages the lock, so basically you should implement all the methods you'd need within the class.


text:
Q: For $\frac{1}{x}u_x+u_y=0$, what is the characteristic equation corresponding to $\frac{1}{x}$? For $\frac{1}{x}u_x+u_y=0$, what is the characteristic equation corresponding to $\frac{1}{x}$?
I'm confused, because by this (https://en.wikipedia.org/wiki/Method_of_characteristics) it should be:
$$\frac{dx}{a(x,y,u)}=\frac{dx}{\frac{1}{x}}=xdx$$
But I believe it should be
$$\text{something}=\frac{1}{x}$$
These are two different equations, so which one is right?

A: By the method of characteristics you obtain:
$$\dfrac{dx}{d\tau}=1/x$$
$$\dfrac{dy}{d\tau}=1$$
$$\dfrac{du}{d\tau}=0.$$
Dividing the first two equations you obtain:
$$dy/dx = x \implies dy=xdx \implies y = 1/2x^2+c_2 \implies c_2=y-1/2x^2.$$
From the last equation you obtain $du=0 \implies u = c_1=c_1(c_2)=c_1(y-1/2x^2).$
Hence, the solution $u(x,y)=F(y-1/2x^2)$.

A: $$\frac{1}{x}u_x+u_y=0$$
$$\frac{dx}{\frac{1}{x}}=\frac{dy}{1}=\frac{du}{0}$$
First characteristics curves : $\quad du=0\quad\to\quad u=c_1$
Second characteristics curves : $\quad xdx=dy \quad\to\quad 2y-x^2=c_2$
General solution of the PDE :
$$u=f(2y-x^2)$$
$f$ is an arbitrary function.
This is the same result as MrYouMath's result. But the symbols $f$ and $F$ are for different functions $f(2X)=F(X)$, which doesn't matter since whose functions are arbitrary : $u=f(2y-x^2)=F(y-\frac{1}{2}x^2)$.


text:
Q: Boton HTML que comunica con java para cargar otro archivo HTML en el mismo webView Tengo un activity que carga un webview que ocupa la pantalla entera, y ese webView carga un archivo html que contiene botones que comunican con java mediante JavascriptInterface.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calculadora);

    //--------------------------------------------
    //busco los componentes por su id
    final WebView webView = findViewById(R.id.webView);
    //-----------------------------------------------------

    webView.getSettings().setJavaScriptEnabled(true);//abilito javascript
    webView.getSettings().setBuiltInZoomControls(true);//abilito el zoom

    webView.loadUrl("file:///data/data/com.example.mecamismos/files/mecanismo.html");
    webView.addJavascriptInterface(new WebAppInterface(this, datos), "Android");

Dentro de la clase webAppInterface quiero que al pulsar el boton html me cambie la pagina web, pero no consigo importar el webView a una clase que no sea activity
public class WebAppInterface{
private Context mContext;
private boolean eligeweb = true;

WebAppInterface(Context c, ArrayList<String> d) {
    mContext = c;
}

@JavascriptInterface
public void verHTML() {
    WebView webView = findViewById(R.id.webView);
    if (eligeweb) {
        webView.loadUrl("file:///data/data/com.example.mecamismos/files/mecanismo1.html");
        eligeweb = false;
    } else {
        webView.loadUrl("file:///data/data/com.example.mecamismos/files/mecanismo.html");
        eligeweb = true;
    }
}

Alguna idea de como cargar otra pagina web desde un boton html que comunique con java, y tambien me gustaria crear otro boton html que cambie de activity.

A: Para navegar entre páginas dentro de un mismo webView no hace falta comunicar con java, solo hace falta poner un botón que vincule la dirección donde esta la página web a la que quieres que te envie. Además, aunque la segunda pagina web este guardada en la memoria interna, y no haga falta uso de internet para acceder a ella, para que funcione el vinculo hace falta habilitar el uso de internet en el archivo manifest.
Abrimos el archivo AndroidManifest.xml y escribimos esto:
<uses-permission android:name="android.permission.INTERNET" />


text:
Q: Bootstrap 3: Extending div outside container on right side I'm trying to make a layout which needs a div to extend it outside the .container div only on the right side.
Here's the fiddle: http://jsfiddle.net/krish7878/c5n365ek/1/
HTML Code:

           Left Container

            Right Container

CSS Code:
.left{
    background-color: #999;
    height: 50px;
    padding: 30px 0px;
}
.right{
    background-color: #49c8ff;
    height: 50px;
    padding: 30px 0px;
}

I want the right container with blue background to extend on the right side fully.

A: Is this what you are looking for? You just need to make the .container width:100% and you can add padding-left
.container{
  width: 100%;
  padding-left: 120px; //whatever you want
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

FIDDLE


text:
Q: Searchview issues in fragment I am using a searchview in fragment for search in listview. I am able to perform search, but I am facing two issues.
1) When there are no matching users in the list, it gives the last searched result.
What I want:
I want to display a message saying "No search results"
What I have tried:
I have taken a textview in the same xml in which listview is there andin java file after setting the adapter value, I am using setEmptyView method, still I am not getting the desired results.
XML code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.rider.project.Fragments.UsersListFragment">

<ListView android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="visible"/>

<TextView android:id="@android:id/empty"
    android:gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@android:color/black"
    android:text="No search results"
        android:visibility="gone"/>
</LinearLayout>

Java Code
listView = (ListView) view.findViewById(android.R.id.list);
    adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
    listView.setAdapter(adapter);
    listView.setEmptyView(view.findViewById(android.R.id.empty));

I have tried the various solutions, still I am unable to find the result.
2) I have a userlist in one fragment UserListsFragment.java in which my searchview is there and then if we search some user the lists displays the search results. On clicking on any of the users name a chat screen opens ChatFragment.java. Now when I press back button from the chat screen, only those searched users are available in the list and the search menu gets closed as well.
What I want:
On clicking back button, I want the complete list to be displayed not only the previously searched users.
What I have done
UserListsFragment.java
@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {

    inflater.inflate(R.menu.menu_userlist,menu);
    MenuItem item = menu.findItem(R.id.menuSearch);

    SearchView searchView = (SearchView)item.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            Log.i(TAG,newText);
            adapter.getFilter().filter(newText);
            return true;
        }
    });
    super.onCreateOptionsMenu(menu,inflater);
}

private void logoutUser(){
    Intent I = new Intent(getActivity(), LoginActivity.class);
    startActivity(I);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.menuSearch :
            return true;

        case R.id.menuLogout :
            logoutUser();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }

}

CustomAdapter.java
@Override
public Filter getFilter() {
    Filter filter = new Filter() {

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {

            if (results.values != null) {
                clear();
                addAll((List<UserData>) results.values);
                arrayList = (List<UserData>) results.values;
                notifyDataSetChanged();
            }
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();        // Holds the results of a filtering operation in values
            List<UserData> FilteredArrList = new ArrayList<UserData>();

            if (mOriginalValues == null) {
                mOriginalValues = new ArrayList<UserData>(arrayList); // saves the original data in mOriginalValues
            }

            if (constraint == null || constraint.length() == 0) {

                // set the Original result to return
                results.count = mOriginalValues.size();
                results.values = mOriginalValues;
            } else {
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < mOriginalValues.size(); i++) {
                    String data = mOriginalValues.get(i).getName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        FilteredArrList.add(mOriginalValues.get(i));
                        results.count = FilteredArrList.size();
                        results.values = FilteredArrList;
                    }
                }
                // set the Filtered result to return

            }

            return results;
        }

    };
    return filter;
}
}

A: When ever you search something but don't find anything then, set empty textview to "No search results" and set it to listView again like:
tv.setText("No search results");
listView.setEmptyView(tv);


text:
Q: Pack the whole solution into a single nupkg? I have a number of helper libraries that I would like to turn into a single NuGet package:
ProjectA
ProjectB (references ProjectA)
ProjectC

I can make individual packages of these:
nuget pack ProjectA.nuspec
nuget pack ProjectB.nuspec
nuget pack ProjectC.nuspec

Or I can "bundles" of referencing projects:
nuget pack ProjectB.nuspec -IncludeReferencedProjects
nuget pack ProjectC.nuspec

But I'd very much like a single .nupkg file containing all the projects.
Is this possiblie to achieve?
-S

A: I ended up creating a "bundling project" that only references the other projects:
ProjectA
ProjectB (references ProjectA)
ProjectC
ProjectD (references ProjectA, ProjectB and ProjectC)

With this in place, I can pack everything into a single NuGet package.
nuget pack ProjectD.nuspec -IncludeReferencedProjects

Not super elegant to achieve, but it kind of makes sense to have a neutral project without its own functionality to bundle up the other diverse projects.


text:
Q: Java version does not change on Linux I've installed Java 17 on my Ubuntu, it is in the usr/lib/jvm folder, and I can use it in e.g. Intellij IDEA, but when I check the Java version with 'java -version' or 'javac -version', it still returns 'openjdk version 11.0.14'. And Java 17 is not visible when I tried to change to it in 'sudo update-alternatives --config java'. What can be the problem?

A: It probably in your PATH environment variable there is a path to your old java installation. Update your PATH to have the path to your new java installation to be at least before the old one or better yet remove the path to the old version from your PATH. to check that this IS your problem invoke your new 'java' command with full path:
/path/to/java17/bin/java -version

And see that you will see version 17. If so then it is most likely your PATH still pointing to the old version that is the cause of your problem


text:
Q: Refresh custom Angular directive AngularJS newbie here and would like to get help on the above please.
Basically my app has a directive that loads banner data from an API and applies the flexslider plugin to render the slideshow.
What I'd like to achieve is to refresh or re-trigger this directive when the URL changes, which also re-triggers the flexslider. Apologies for the lack of a better term. The reason is different banners should be displayed on different pages and I'm adjusting the API call accordingly.
Any thoughts on how I might solve the above problem?
Appreciate all the help, thanks!
Here are the code snippets:
index.html

      <hero-container></hero-container>

herocontainer.js directive
'use strict';

/**
 * @ngdoc directive
 * @name loadandgoApp.directive:heroContainer
 * @description
 * # heroContainer
 */
angular.module('loadandgoApp')
  .directive('heroContainer', ['$timeout', function($timeout) {
    return {
      template: '

',
      restrict: 'E',
      controller: function($scope, ContentService) {
        $scope.headerContent = [];
        ContentService.loadHeaders.then(function(data) {
          $scope.headerContent = data;
        });
      },
      link: function(scope, element) {
        scope.$watch('headerContent', function (val) {
          if (val.length) {
            $timeout(function() {
              angular.element(element).children('.flexslider').flexslider({
                selector: '.slides > .slide',
                start: function() {
                  $('.flexslider').show();
                },
              });
            }, 400);
          }
        });
      }
    };
  }])
;

A: If you are using ui-router - whenever you place a link that points to that page, set the reload option to true.


text:
Q: Spring MVC. Выводится только часть форм HTML Можете кто-нибудь посоветовать решение, у меня есть Spring MVC приложение, соединенное с БД PostgreSQL. Возникла проблема, что Spring выводит только часть HTML, когда должен выводить полностью. Далее на фото будет понятнее.

Сейчас, здесь представлена только одна форма, когда их должно быть 5.
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>New coffeeMachine</title>

<form th:method="POST" th:action="@{/coffeeMashine}" th:object="${coffeeMachine}">
    Enter name of the drink:
    <input type="text" th:field="*{nameOfTheDrink}" id="name"/>

Name Error

    Enter sort of coffee:
    <input type="text" th:field="*{sortOfCoffee}" id="sort"/>

Sort Error

    Enter kind of milk:
    <input type="text" th:field="*{kindOfMilk}" id="milk"/>

Milk Error

    Enter amount of drink:
    <input type="text" th:field="*{amountOfDrink}" id="amount1"/>

Amount of drink Error

    Enter amount of coffee:
    <input type="text" th:field="*{amountOfCoffee}" id="amout2"/>

Amount of coffee Error

    <input type="submit" value="Create!"/>
</form>

Контроллер:
@GetMapping("/new")
    public String newPerson(@ModelAttribute("coffeeMachine") CoffeeMachine coffeeMachine) {
        return "coffeeMachine/new";
    }

    @PostMapping()
    public String create(@ModelAttribute("coffeeMachine") @Valid CoffeeMachine coffeeMachine,
                         BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return "coffeeMachine/new";

        coffeeMachineDAO.save(coffeeMachine);
        return "redirect:/coffeeMachine";
    }

И DAO:
public void save(CoffeeMachine coffeeMachine){
        try{
            PreparedStatement statement =
                    connection.prepareStatement("INSERT INTO coffeeMachine3 VALUES(1, ?, ?, ?, ?, ?)");

            statement.setString(1, coffeeMachine.getNameOfTheDrink());
            statement.setString(2, coffeeMachine.getSortOfCoffee());
            statement.setString(3, coffeeMachine.getKindOfMilk());
            statement.setDouble(4, coffeeMachine.getAmountOfDrink());
            statement.setInt(5, coffeeMachine.getAmountOfCoffee());

            statement.executeUpdate();
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
    }

Может кто-нибудь знает, как это можно решить?


text:
Q: Why is drop not called for a logger implementation? I'm trying to use the log crate and implement a logger myself. I call it mylog.
extern crate log;
use log::*;

struct Mylog;

impl log::Log for Mylog {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            println!("hello log");
        }
    }
}
impl Drop for Mylog {
    fn drop(&mut self) {
        println!("dropped"); // This is never called, why?
    }
}
pub fn init() -> Result<(), SetLoggerError> {
    log::set_logger(|max_log_level| {
        max_log_level.set(LogLevelFilter::Info);
        Box::new(Mylog)
    })
}

And in main.rs:
extern crate mylog;
#[macro_use] extern crate log;

fn main() {
    mylog::init().unwrap();
    info!("My info message");
}

Drop is never called and I don't understand why.

A: The logger implementation is given to the logging library and is effectively leaked. This allows the implementation to act as if it has the 'static lifetime, letting it be used in many places.
If you really need it, you can shut down the logger at the end of the program:
fn main() {
    mylog::init().unwrap();
    info!("My info message");
    log::shutdown_logger();
}


text:
Q: Trying to make a sign give me diamonds if i press it with 64 stone I'm trying to use this command to give me the sign with the right "click" command:
/give @p minecraft:oak_sign{BlockEntityTag:{Text1:"{\"text\":\"ex\", \"clickEvent\":{\"action\":\"run_command\", \"value\":\"execute as @p[nbt={SelectedItem:{id:"minecraft:stone", Count:64b}}] run give @p minecraft:diamond\"}}"}}

But Minecraft comes with a error msg that says "Expected '}' at position 175: ...Item:id"<--[HERE]". What is the problem here?
If I use this it runs fine:
execute as @p[nbt={SelectedItem:{id:"minecraft:stone", Count:64b}}] run say hi


text:
Q: filter dataframe by int value
    plz error  turn off
0   11  1     Störung bei Paketabtransport
1   11  1     Störung bei Paketabtransport
2   11  0     Störung bei Paketabtransport
3   127 3     Sicherheitstür (0SS5c.2) bei
4   11  0     Störung bei Paketabtransport

I want to filter the df after the 0's in column 'error' ,how can I get a new df with the 0's and its corespondings rows ?
df = df['error'] < 1 basically like this but only adding the coresponding rows

A: Do you mean something like that?
df = pd.DataFrame(data=[[11,0,'txt'],[11, 1, 'txt'],[11, 1, 'txt'], [11, 0, 'txt']], columns = ['plz', 'error', 'turn_off'])
>>>
    plz  error turn_off
0   11   0     txt
1   11   1     txt
2   11   1     txt
3   11   0     txt

new_df = df[df['error'] == 0]
>>>
    plz  error  turn_off
0   11   0      txt
3   11   0      txt


text:
Q: Pass JavaScript JSON variable from index.js into index.html This is my index.js file:
 function fun()
{
 var obj;
}

This is my index.html file:

I want to use variable obj here.
I saw some solutions to create a variable and pass in index.html but is there any way of injection?
Actually, obj is a JSON object. I forgot to mention that previously. How would I use the JSON object keys and values in my index.html outside of the script tag?

A: Although there isn't any way to inject a JS variable into HTML simply, you can use a javascript function to do the same thing:
In index.js:
function fun()
{
    return obj; // Assuming obj is a defined variable.
}
document.getElementById("toReplace").innerHTML = fun();

In index.html

Essentially, your javascript will replace the content of the
 tag, which has the ID "toReplace", with the value of fun().

A: Try out AngularJS. With this, you can declare variables in $scope and use it in your html like:
JavaScript:
...some angular logic...
$scope.foo = "bar";
...some other angular logic...

HTML:

{{foo}}

There are many tutorials out there. Read the documentation. It may be what you are looking for.


text:
Q: Count of stored procedures generated using SSMS "Generate and Publish Scripts Wizard" differs I have generated stored procedures using SSMS wizard as shown below. There is an option to save each object as a single file. The issue is when I counted procedures using  SELECT count(*) FROM sys.procedures it differs from number files generated.

A: There are 7 procedure under  "system stored procedures" folder starting with dbo. extension.  These will be counted  when we run the query(SELECT count(*) FROM sys.procedures) for count of procs, but won't be part generated script.
sp_alterdiagram
sp_creatediagram
sp_dropdiagram
sp_helpdiagramdefinition
sp_helpdiagrams
sp_renamediagram
sp_upgraddiagrams


text:
Q: WPF - Custom Validation Rule for Record Insertion In DataGrid Now I have a window to operate the records in one of my DB tables, which looks like:

I got this DataGrid control by dragging it from Data Source Tab. And that data source is actually a DataSet item I created in VS 2015, which means some strongly typed database operating classes are automatically generated in a .xsd file. So, you see, basically, everything behind this Datagrid is generated automatically, both the xaml and C# code.

By default, when you insert a new record, the data you type in the cell will be checked against its type, if you type in something not as expected, a red exclamation will show up in the first cell. For example, the IRD column in my table is int type, if you type in some symbols other than digit, you will get that red exclamation.
What I want to do now, is restrain user type in 8 to 9 digits, for example, if user types in only 3 digits: 346, he/she would see the red exclamation, and cannot proceed to insert the record.

A: Am I right that you are using DataTable as ItemsSource for DataGrid? If it is, so let me show how you can validate your cell:
this.YourDataTable.ColumnChanging += YourDataTableColumnChangingStuff;

private void YourDataTableColumnChangingStuff(object sender, DataColumnChangeEventArgs e)
{
   private void EmployeeDataTable_ColumnChanging(object sender, DataColumnChangeEventArgs e)
    {
         //if you want to leave previous value
        if ("incorrect value" != e.ProposedValue.ToString())
            e.ProposedValue = e.Row.ItemArray[e.Column.Ordinal];
        else
        {
            //if you want to set new value
            e.ProposedValue = "new value";
        }
    }
}


text:
Q: Question on schemas and security I need to set some users up to be able to create stored procedures with READ access only.  Also, in production they cannot have SELECT, only EXECUTE on the procs they created.  In development they would have SELECT so they could create their procedures.
I've set up a schema called Reports.  The owner of that schema is a login - Report_Admin.  That user has select access to tables.  I then gave alter and execute on the Reports schema to my report writer account.  Dbo owns the table - so it works if dbo also owns the Reporting schema - but then a delete will also work in the procedure!
We are using reporting services and would like to have all the SQL in the database for maintainability.
Thanks!

A: You're not going to succeed using ownership chaining, as you already discovered. A solution would be like this: report_writer must create its reports with an EXECUTE AS SELF clause so they get executed under the report_writer priviledges. Then the report_reader group will be able to leverage the EXECUTE permission on reports schema to execute said reports, and the reports will be able to read the data because of the execute as clause.

A: You can assign permissions to roles and users, no need for separate schema's.  So I'd only use one schema: "dbo" (the default)
Create a database role for the users.  Grant data_reader to that role on development.  On both development and production, grant execute rights on the stored procedures.  As far as I know, you'll have to grant the execute right for each stored procedure.


text:
Q: Trying to solve the card shuffle and birthday paradox question I'm trying to solve the question as to whether two 52 card shuffles have ever been the same but I can't calculate the final step. Additionally I can't find any answer on the internet that has approached the question in the same way. If anyone can help explain what I'm doing wrong, I'd greatly appreciate it.
Assumptions:

*

*Every card shuffle is independent with probability 1/52!

*There have been $n$ card shuffles in all of history

My solution thus far:
Consider the first person to ever shuffle a deck of cards. Let's call the resulting shuffle X1. What is the probability that X1 is never repeated? This is $(1-1/52!)^{n-1}$
Consider the second person to ever shuffle a deck of cards. Let's call the resulting shuffle X2. What is the probability that X2 is never subsequently (aka given X2 is not itself a repeat of X1) repeated? This is $(1-1/52!)^{n-2}$
If we carry this logic on, then the probability of $(n-1)^{th}$ shuffle (we'll call this Xn) being subsequently repeated will be $(1-1/52!)^{1}$
Therefore the probability that no shuffles has ever been repeated is
$(1-1/52!)^{n-1} \times (1-1/52!)^{n-2}... \times (1-1/52!)^{1}$ = $(1-1/52!)^{(n-1)!}$
Calculations
Now I think the next step would be set this equal to $1/2$ and solve for $n$.
Notice the following:

*

*When $n = 1$, $(1-1/52!)^{(n-1)!} \approx 1$

*As $0 < 1-1/52! < 1$, therefore $\lim_{n\to\infty}(1-1/52!)^{(n-1)!} = 0$
Therefore there must be values of $n$ that we'll call $(a,b)$  (where $a = b+1$) which will give the following result:
$(1-1/52!)^{(a-1)!} > 0.5$
$(1-1/52!)^{(b-1)!} < 0.5$
So my query is:
How do I calculate $(a,b)$? The software I've tried (Excel and R) just simplify $1-1/52! = 1$ so I haven't been able to proceed with the calculation.
Are my workings sound? I can't find anyone else who has $(n-1)!$ as their power. Have I made a logical error?
Thank you.

A: Your approach is fine, but the usual one is to say the first shuffle is guaranteed to be unique, the second is unique so far with probability $1-\frac 1{52!}$, the third is unique so far with probability $1-\frac 2{52!}$ and the $n^{th}$ is unique so far with probability $1-\frac {n-1}{52!}$.  Then you multiply these all together and compare with $\frac 12$.  That doesn't give the $(n-1)!$ in the exponent, which is why you haven't seen it.
The Wikipedia page on the birthday problem shows that for large numbers $n$ of possibilities, and $52!$ is certainly large, the number of tries to get a $50\%$ chance of a match is $\sqrt {2 (\log 2) n}$.  Taking $n=52!$ we get about $1.05\cdot 10^{34}$.  That is huge compared to the number of person-seconds in history, so the chance of a duplicate is miniscule.


text:
Q: Any better panel layout for this situation My page layout requirement is such that, it requires 3 rows. First and third row contains some buttons whereas middle row contains a data grid. This data grid is what will occupy most of space. My page root element is Grid with following row definitions.
<Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="3*" />
            <RowDefinition Height="1*" />
</Grid.RowDefinitions>

The first and third row is just a StackPanel whereas middle row is DataGrid itself. Problem is that when user reize the windows this dooesn't scale very well. Are there any other panels that may be better fit for this scenario?

A: If you want the data grid to use most of the space, use the following XAML
<Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
</Grid.RowDefinitions>


text:
Q: Travis CI build error with gradle and Antlr I have a strange situation where my project builds locally without issue, yet on Travis-CI fails.  I'm unsure how to debug / investigate the issue.

*

*My project: https://github.com/RichTeaLang/RichTea

*Latest build failure: https://travis-ci.org/RichTeaLang/RichTea/builds/142976109
The build fails in the generateGrammarSource task (Part of the ANTLR build process).  This task reads a ANTLR grammar file and outputs Java source code to be compiled later on in the build process:
/home/travis/build/RichTeaLang/RichTea/src/main/antlr/richTea/compiler/RichTea.g:1:1: unexpected token: grammar
error: Token stream error reading grammar(s):
/home/travis/build/RichTeaLang/RichTea/src/main/antlr/richTea/compiler/RichTea.g:23:1: unexpected char: '@'
Just to re-iterate, locally, this task executes successfully (Tested on Linux and Mac).
Thanks for any help.

A: Ok, I've found the issue.
Travis-CI comes bundled with v2.0 of gradle.  The ANTLR plugin for gradle requires a later version of gradle for the type of ANTLR grammar that is being compiled.
The solution to the issue is to bundle the gradle wrapper scripts into your repo.  Travis CI will then use the wrapper scripts rather than its bundled version of gradle.


text:
Q: dealing with ASCII structured data I have a dataset in a mysql DB, where there is no documentation nor anybody who could tell me why things have been done the way they are or how should I deal with certain things - I think one might call this, reverse engineering :)
There are strings that are structured using ASCII control characters. So the string will look like this for exapmle:
^AKEY^BVALUE^AKEY^BVALUE^AKEY^BVALUE
According to https://www.geeksforgeeks.org/control-characters/
^A is "Start of Header"
^B is "Start of Text"
to me, this seems a super old school way to structure data and it is the first time i see something like this.
I am looking for a way how to parse this data, prefarrably a python library that I could parse the string and get some key-value map that I can control programatically.
Any help on how to deal with such data is highly appreciated.

A: Here's an example of a solution in Python:
I create a string like yours:
>>> s="^AKEY1^BVALUE1^AKEY2^BVALUE2^AKEY3^BVALUE3"

Then I use list comprehensions to split the string by the delimiters, and make that into a dict:
>>> {k: v for (k, v) in (kv.split("^B") for kv in s.split("^A")[1:])}
{'KEY1': 'VALUE1', 'KEY2': 'VALUE2', 'KEY3': 'VALUE3'}

A: I call ^A, ^B and so on "caret values" - not sure if that is the correct/official term for them (see caret notation). This is how a tool such as vi displays the related ASCII control characters.
ASSUMPTION: These are single characters - different from a ^ ASCII character followed by an A ASCII character. I am assuming that your source data contains these as control characters, not as ^ followed by A and so on. If my assumption is wrong, then the following will not help you.
As you note, ^A is the caret value for SOH - start of header - which, in turn, can be represented by the hex string x01.
For example, in Python that would be:
my_soh = '\x01'

You can use this (and \x02 for ^B) with Python's split() function.
I don't think you necessarily need a Python library for that. Just use:
key_val_pairs = my_string.split('\x01')

to split the initial string into an array of individual key/value strings - and then split each of those into their separate key and value using:
key_val_pair.split('\x02')

Or maybe create a dictionary:
d = dict(s.split('\x02') for s in key_val_pairs )

If you expect to find missing keys and/or values, you would need code to handle those.
There are various Stack Overflow questions which discuss splitting a Python string into key value pairs.
Those typically use non-control characters for the separators. But you can replace those with the ones you need for your data.

You can see a more complete list of "caret values" here for reference.
Here are some of them:
Name                Abbrev  Caret   Dec  Hex    Oct  Esc
Null                NUL     ^@      0    00     000  \0
Start of heading    SOH     ^A      1    01     001
Start of text       STX     ^B      2    02     002
Line feed           LF      ^J      10   0a     012  \n
Vertical tab        VT      ^K      11   0b     013  \v

Speculating here, since we don't know the origins of your specific data set - but you do sometimes see these control characters used in this way, because these control characters do not typically occur in the data keys and values. They are therefore good candidates to be used as field separators, line terminators, and so on. I have seen this approach used in some enterprise software (Ab Initio is one).


text:
Q: Excel range to use the first column I want to set the range of the excel column to first so I am giving it by using this line of code.
ExcelRange FirstcolumnRange = worksheet.Cells[rowPositionStart + 1, 1, dt.Rows.Count, 1];

because here row position is set to 4, I only want to use this whole column but the exception is thrown:
"Specified argument was out of the range of valid values.
Parameter name: Start cell Address must be less or equal to End cell address."


text:
Q: при пинге пингуется другой ip Добрый день, есть комп в сети с внешним ip. При пинге с пк(за микротиком) пинга нет, непосредственно с микротика ответ идет с адреса городской сети. Физически нахожусь в одной сети этого же провайдера.
ping 80.xxx.xxx.xxx
num/host/time/reply size/ttl
0 10.xxx.xxx.xxx 0ms 50 63
1 10.xxx.xxx.xxx 0ms 50 63
Вопрос, почему так и как заставить пинговаться адрес с локальной машины.


text:
Q: AWS SNS Java program to subscribe
*

*I am publishing a String message as message payload using SNS notification from Raspberry Pi using Python program and I want to pass that message payload to a Lambda function.

*I have configured the requirement in the SNS console on AWS i.e., I have created a topic and added the lambda function to its subscribers.

*Now, I want to get that message payload in the lambda function. But I can't find any method that can help me do that. For example, something like getMessage or something similar to that.

*So my questions are: Since I have configured the publishing and subscription on AWS, can I assume that the clients are connected and if I publish a message I should be getting that at the subscriber's end which is my lambda function here?
Also, what's the technique in which I can get the message payload in my lambda function?
I am adding the below as per cjwfuller's suggestion.

*Below I have written down the method for publishing in Python

client_boto = boto3.client('sns', aws_access_key_id='@@@',
   aws_secret_access_key='@@@', region_name='us-west-2')
REGION = 'us-west-2'
TOPIC = 'arn:aws:sns:us-west-2:***:topic_name'
MSG = ntpath.basename(f_string)
SUBJECT_boto = 'File Name'
pub =client_boto.publish(TopicArn = TOPIC, Message = MSG,
   Subject=SUBJECT_boto)
I am writing the subscribing code in Java.
   Since my lambda func is already subscribed to it on AWS console,
   should my Java program include the subscription again or is there a
   way to get the msg payload directly.

A: Which language are you writing the function in?  JavaScript as an example:
exports.myHandler = function(event, context, callback) {
    console.log("value1 = " + event.key1);
    console.log("value2 = " + event.key2);
    // ...
}

Source: http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
It's useful testing the sort of stuff in the AWS Lambda console before writing all the code.

Since I have configured the publishing and subscription on AWS, can I assume that the clients are connected

Clients aren't really "connected", they're simply subscribed to a topic.

publish a message I should be getting that at the subscriber's end which is my lambda function here?

Sounds like you're doing the right sort of thing - posting example code will help us come up with more precise answers.

A: On searching, I have found the class for SNSEvent which is, https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-events/src/main/java/com/amazonaws/services/lambda/runtime/events/SNSEvent.java
This Class contains all the methods related to and needed to get the message payload.
The Lambda function handler in Java goes something like this,
example;
public void handleRequest(SNSEvent input, Context context){
  String this_takes_message=input.getRecords().get(0).getSNS().getMessage();
}


text:
Q: When its better to write singlethreaded event servers, etc When its better to write single threaded event or multithreaded or fork servers? Which approach more approriate for:

*

*web server who serves statics

*web server who serves statics and proxy requests to other http servers

*previous plus this servers makes some logic in C without attending to harddrive or network

*previous plus makes some requests to MySQL?

For example, the language is C/C++. I want to undestand this question very much. Thank you.

A: Given that modern processors are multicore, you should always write code under the assumption that it may at some point be multithreaded (make things reentrant wherever possible, and where not possible, use interfaces that would make it easy to drop-in an implementation that does the necessary locking).
If you have a fairly small number of queries-per-second (qps), then you might be able to get away with a single threaded event server. I would still recommend writing the code in a way that allows for multithreading, though, in the event that you increase the qps and need to handle more events.
A single threaded server can be scaled up by converting it into a forked server; however, forked servers use more resources -- any memory that is common to all requests ends up duplicated in memory when using forked servers, whereas only one copy of this data is required in a single multithreaded server. Also, a multithreaded server can deliver lower latency if it is taking advantage of true parallelism and can actually perform multiple parts of a single request processing in parallel.

A: There is a nice discussion on Single Thread vs. MultiThreaded server on joelonsoftware,


text:
Q: LocalNotification Event When App is Suspended in Background I have an iOS app which uses local notification. The user can leave the app and check his/her email or do any other stuff. After a while 20 minutes local notification fires and alert the user with some message. At that time when local notification is triggered can I somehow handle any event. The didReceiveLocalNotification is only triggered when the user clicks on the notification.
NOTE: I do not want to fire the event when the user clicks on the notification. I want to fire the event when the local notification is triggered.
Thanks,

A: When the user click then the app will open up via didFinishlaunching you can check whether it is launched because of local notification and do your stuff.
Update: You don't have any delegate to notify you that local notification has fired when the app is in background.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

     UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

}

A: You can not track the event which will let you know that local notification is fired or about to fire.

A: Local notifications are designed to be notifications for the user, not for your app.
You could provide more details of what you are trying to accomplish but you might be better off looking into background app refresh or remote notifications with a content-available flag


text:
Q: Keeping Drop-downs DRY in a web app I'm writing a CMS for various forms and such, and I find I'm creating a lot of drop-downs.  I don't really feel like mucking up my database with tons of random key/string value tables for simple drop-downs with 2-4 options that change very infrequently.  What do you do to manage this in a responsible way?
This is language-agnostic, but I'm working in Rails, if anyone has specific advice.

A: We put everything into a single LookUp table in the database, with a column that mapped to an enum that described which lookup it was for (title, country, etc.).
This enabled us to add the flexibility of an "Other, please specify" option in lookup dropdowns. We made a control that encapsulated this, with a property to turn this behaviour on or off on a case-by-case basis.
If the end user picked "Other, please specify", a textbox would appear for them to enter their own value. This would be added to the lookup table, but flagged as an ad hoc item.
The table contained a flag denoting the status of each lookup value: Active, Inactive, AdHoc. Only Active ones would appear in the dropdown; AdHoc ones were those created via the "Other, please specify" option.
An admin page showed the frequency of usage of the AdHoc values, allowing the administrators of the site to promote common popular values into general usage (i.e. changing their Status flag to Active).
This may well be overkill for your app, but it worked really well for ours: the app was basically almost entirely CRUD operations on very business-specific data. We had dozens of lookups throughout the site that the customer wanted to be able to maintain themselves. This gave them total flexibility with no intervention from us.

A: You cold have one single dropdown table with an extra column to say what the drop down is for... limit the results with a where clause...

A: At my current position, we implemented a LookupCode table that contains a CodeGroup,Code, and Meaning column, as well as some others (like active). That way you have a single table that contains all of your lookup values are in a single location and you can do some quick lookups to bind to your dropdown lists.


text:
Q: How to set frequency in vhdl at 0.01 Hz? I need to divide frequency in vhdl so the resulting frequency will be 0.01 Hz,but I Don't know how to do it. I tried by using generic map, but then I got error. I am using Nexys3. I know Nexys3's frequency is 100 MHz, so I tried to divide it to 0.01.
entity stotinkasekunde is
port (
    izlaz: out std_logic_vector(3 downto 0);
    led: out std_logic_vector(6 downto 0);
    clk, ss: in std_logic
);
end stotinkasekunde;

architecture Behavioral of stotinkasekunde is
signal clk_o: std_logic;
signal temp: std_logic_vector(3 downto 0);
begin
s1: entity work.frekdiv generic map(10000000000) port map(clk, clk_o);
process (clk_o)
begin
    if (clk_o'event and clk_o='1') then
        if (ss='1') then
            temp <= temp+1;
            if (temp >= 1010) then
                temp <= "0000";
            end if;
        end if;
    end if;
end process;

ERROR: Line 18: Literal 10000000000 exceeds maximum integer value.

A: For 100Mhz specifically start by a break down of the problem into two parts

*

*Divide the frequency by a highest divisible power of 2 so that it divides the input clock to an integer highest power of 2 by using an approach from here using a bit magic expression (n & (~(n - 1))) to find that number or trying all series from 1st power till the 26th power of 2 closest to the number but off by a factor below 2, in other words 100000000 / 2^26 = 1.490116 as the upper bound of the series ( https://www.geeksforgeeks.org/highest-power-of-two-that-divides-a-given-number/ )

*Then by non integer power of 2 ( https://www.slideshare.net/DeepakFloria/divide-by-n-clock, https://en.wikipedia.org/wiki/Frequency_divider )

*

*By dividing by powers of 25

*Then by a power of 10

So, the resulting clock frequency division calculation could be written as 100000000 Hz / ((2^8)* (25 ^ 4) * (10)) which exactly equals 0.1 Hz
Notes:
How do we find a number that has same rightmost set bit and all other bits as 0?
Remember: The overall scheme  is to take 100000000Hz  then divide by largest even power of 2 (why even, since power of 2 are already even, hint base 2...)
Then proceed to divide 390625 Hz which is its self a power of 25, specifically because of 625 as the lowest portion of the number 625, 25^2, and 2 390000, the upper remaining portion when you subtract 25, a nice power of 625 itself, making the original divisible by 25.
Take that divide 25, divide by 25, divide by 25, divide by 25
And then divide by 10 to get 0.1 Hz
How to implement:
Divide by 2
can be done by using mod-n counter where n is a power of 2 in our case, or some sort of shift register, Johnson Counter, etc...
Divide by either 25 (or powers of 25), or Divide by 10
Both use example scheme seen below in the link, but not using same numbers though
https://electronics.stackexchange.com/a/61607/20332
Or, use the Xilinx Clocking wizard to generate this block
https://electronics.stackexchange.com/a/61620/20332
Divide by 25 might be available as an existing resource on the FPGA, but if not refer to wiki (https://en.wikipedia.org/wiki/Frequency_divider) for more information.
Finally, make sure to run a behavioral simulation to find the markers to place on the zoomed out resulting clock rising edge, to next rising edge to be able to measure the period of the resulting clock generated in your output waveform, and verify it is correct, based on your VHDL time scale if I am using the right terminology since this is a terminology in Verilog HDL,  for sure when I was using Verilog.


text:
Q: Is there a way to add an https-rss feed to Outlook 2013 (Windows)? I'm having trouble adding an https-rss-feed to Outlook 2013 on Windows.
When I add a http-rss-feed, there's no problem, I can add any http-rss-feeds.
I have to add that this is my pc at work, so I can't install any other software. Add-ins for Outlook are possible though. Also a portable version of an app is possible too.
Only when I add an https-rss-feed, it doesn't show up with the rss-feeds, and I get no error message.
I've looked on the internet, and the problem should not occur with Outlook 2016.
Is there an addon I can use or a script to get this to work?
It's my office-computer, so I'm not able to upgrade to Outlook 2016 myself.
Thank you in advance!

A: You could integrate a live Twitter feed in a Webkit supported email like IOS. When it comes to non-webkit emails, I suggest you consider a dynamic image to present the RSS feed or Twitter feed.

We created a simple web page of just the Twitter feed using the same HTML and CSS from the email. We simply took a screenshot of the feed at the same dimensions of 600×902 through the command line utility wkhtmltoimage and dynamically updated that same image every 10 seconds.

*

*https://litmus.com/blog/how-to-code-a-live-dynamic-twitter-feed-in-html-email
I hope that helps.
Good luck.


text:
Q: How can I type in a virtual machine that is located on a host machine that I remote desktop into? I'm using a remote desktop to log in to another computer and on that computer.
Trying to start up a virtual machine. The problem I'm having is when I try to type in the virtual machine, most of the keys on my keyboard don't work.
For example, certain keys like Space bar will type "d" and my number 1 key would type ";".  Most of the other keys don't work. I can type fine on the host machine, but can't inside the virtual machine. I tried both VirtualBox and HyperV and both are encountering the same problem.
Any idea what might be causing this issue? I also remote into a Windows server and had the same issue. The virtual machine is running Ubuntu 18.


text:
Q: simple_http_dom - how to send request to each url I have got 16 links in my get-listing.php output and I need to send the request to each URL to get the responses, for which I need to receive the list of elements when send the request to each URL.
$base1 = "http://testbox.elementfx.com/get-listing.php";
$html = file_get_html($base1);

$links = $html->find('p[id=links] a');

foreach ($links as $element)
{
  //open each url in each array
  $urls[] = $url = $element->href;
  $data = file_get_html($url);
}

When I use the code as above, it will only send the request to each url to get the response which I have got 9 responses. I should have more than 9 responses.
Can you please tell me how I can send request to every url to get the responses using with simple_http_dom?

A: If your question is to send a simple request to each of the urls you've already parsed and get a response back, try file_get_contents:
foreach ($links as $element)
{
  // This array stack is only necessary if you plan on using it later
  $urls[] = $url = $element->href;

  // $opts and $context are optional for specifying options like method
  $opts = array(
    'http'=>array(
      'method'=>"GET", // "GET" or "POST"
    )
  );
  $context = stream_context_create($opts);

  // Remove context argument if not using options array
  $data = file_get_contents($url, false, $context);

  // ... Do something with $data
}

Your other option is more complex but has more flexibility (depending on the application) is Curl:
foreach ($links as $element)
{
  $urls[] = $url = $element->href;

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  // Used for GET request
  curl_setopt($ch, CURLOPT_POSTFIELDS, null);
  curl_setopt($ch, CURLOPT_POST, FALSE);
  curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
  // Necessary to return data
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $data = curl_exec($ch);
  curl_close($ch);

  // ... Do something with $data
}

This is scratching the surface of Curl, the documentation on PHP's website (linked above) has more information.
If the data being returned from the urls is HTML, you can pass it through PHP's DomDocument to parse after it has been pulled. Documentation and examples are readily available on PHP's site (I can't post more links right now, sorry).


text:
Q: Volley retry policy - cannot resolve host when network down I have to send a background request via Volley, I have set the Retry Policy:
setRetryPolicy(new DefaultRetryPolicy(10000, 5, 2));

However when WIFI and 3G are turned of I get:
.NoConnectionError: java.net.UnknownHostException: Unable to resolve host "example.com": No address associated with hostname

immediately, is there a way to keep the retry mechanism keep retring?

A: The volley retry mechanism doesn't wait, it posts all the requests as soon as possible. thus, when there is no WIFI or 3G it won't even try to post the request. Note that the source code can be modified by adding retry when there is no connection. and adding Thread.sleep() in the retry mechanism

A: Well I think it is retrying and it is doubling the interval after each try up to 5.
If you are testing with emulator you can check with wireshark if request was sent.


text:
Q: Running shell script as admin using expect on OS X I am trying to let non-admin users run a script in a shared environment that requires root privileges. I was going to build either an AppleScript or Automator application that invokes expect in order to pass the login credentials (yes, I know the dangers, it will all be execute only). However I get the login to work, but the shell script I am trying to run doesn't seem to be executing, since it returns instantly. I am new to expect and I believe I have an error in my script. Ideas anyone?
#!/usr/bin/expect
set timeout 60
set password "MyPass"
set command "bash /Applications/mampstack-5.4.36-0/ctlscript.sh start"
eval spawn login admin
expect "assword:"
send "$password\n"
expect "$"
send  "$command\n"
expect "$"
send exit
expect "$"
send exit

A: Don't do it that way. Instead, edit /etc/sudoers to add the following lines (or, on a default config of MacOS, you can create a file in /etc/sudoers.d with the following content):
# allow use by GUI apps (AppleScript, Automator), which don't have a TTY
Defaults:%staff !requiretty

# on MacOS, all humans are members of the staff group
%staff ALL=(ALL) NOPASSWD: /Applications/mampstack-5.4.36-0/ctlscript.sh start

...then, have your AppleScript or Automator code run:
sudo -u admin /Applications/mampstack-5.4.36-0/ctlscript.sh start

...which will require no password at all.


text:
Q: split string into array of hashes with data on delimeter I have a string like the following:
lorep ipsum dolor sitamet, consectetur adipiscing elit.

I need to split it into fragments, but save link classes for fragments inside anchors. So perfect result would be:
['lorep ipsum ', {'link-1' => 'dolor sit'}, 'amet, consectetur', {'link-2' => 'adipiscing'}, ' elit.']

Or:
['lorep ipsum ', ['link-1', 'dolor sit'], 'amet, consectetur', ['link-2', 'adipiscing'], ' elit.']

I've tried using this code:
string.split(/<[^>]>/)

But it returns returns only an array of fragments.

A: I'd do using Nokogiri
require 'nokogiri'

doc = Nokogiri::HTML.parse <<-eot
lorep ipsum dolor sitamet, consectetur adipiscing elit.
eot

ary = doc.search("//a").flat_map do |n,a|
   [n.previous_sibling.text.strip,{n['class'] => n.text.strip},n.next_sibling.text.strip]
end.uniq

p ary

output
["lorep ipsum", {"link-1"=>"dolor sit"}, "amet, consectetur", {"link-2"=>"adipis
cing"}, "elit."]


text:
Q: How to Display CPT Meta on Front End through Query I am working with two custom post types on my site: Team and League. I am creating a page template for the CPT League that will display meta from all of the 'Team' posts for team with a meta value matching the name of the League post type. The query will look through CPT 'team' for the meta value 'team_league'. The value in 'team_league' will match one of the post IDs for the 'league' type. I would then like to print each matching 'team', along with some meta from the team post, on the 'league' page.
I can successfully do this if I print a simple  with just the name of the posts found in the query. The example below successfully queries and prints the post name of each 'team' with a meta value matching the 'league' title. However, I need something far more complicated. I want to pull meta from the 'team' post and print a table containing names from the 'team' CPT.
Working, Simplified Query:
if ( $the_query->have_posts() ) {
  echo '
';
  while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '
' . get_the_title() . '
';
  }
  echo '
';

Desired Query, Currently Doesn't Work:
<?php
/*
Template Name: League Layout
Template Post Type: league
*/

$leaguename = get_the_ID();

$args = array(
    'meta_key' => 'team_league',
    'meta_value' => $leaguename,
    'post_type' => 'team',
    'post_status' => 'any',
    'posts_per_page' => -1
);

$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {

  while ( $the_query->have_posts() ) {
    $the_query->the_post();

    //Get the team data
    $post_status = get_post_status();
    $team_name = get_the_title();
    $captain_id = get_post_meta(get_the_ID(), 'captain_user_id', true);
    $team_captain = get_user_by( 'ID', $captain_id );
    $team_league = get_post(get_post_meta(get_the_ID(), 'team_league', true));
    $team_players = get_post_meta(get_the_ID(), 'team_players_emails', true);
    $team_paid = get_post_meta(get_the_ID(), 'current_paid_amount', true);
    $team_fee = get_post_meta(get_the_ID(), 'payment_product_price', true);
    $team_balance = round( $team_fee - $team_paid , 2);

   echo '
Team Captain: ' . $team_captain->first_name . ' ' . $team_captain->last_name; . '
';
   echo '
Team Balance: $' . $team_balance; . '
';
   echo '
';
   echo '
';
   echo 'Team Roster	';
   echo '
';

   $users_confirmed = 0;
    foreach ($team_players as $team_player) {
        $user = get_user_by( 'email', $team_player['email'] );
        if( $user ){
            if( !$user->first_name && !$user->last_name ){
                continue;
            }
            echo sprintf( "
%s
", $user->first_name . ' ' . $user->last_name );
            $users_confirmed++;
        }
    }
    if( 0 == $users_confirmed ){
        echo sprintf( "
%s
", "No confirmed players for this team" );
    }
    echo '
';
  }
}

else {
  echo '
No Teams in this league
';
}
/* Restore original Post Data */
wp_reset_postdata();

A: For your Query Args.  Try something like this:
$args = array (
    'post_type' => 'team',
    'posts_per_page' => -1,
    'meta_query'  => array(
       'relation' => 'AND',
           array(
            'key'     => 'team_league',
            'value'   => $leaguename,
           ),
    ),
);

I don't think 'post_status' => 'any' works.  This also uses the proper meta query format.

A: For reference, the following solution works to achieve what I was aiming for above. The main change is to the args, where I had to include custom post status for my CPTs:
$leagueid = get_the_ID();

$args = array(
  'post_type'      => 'team',
  'posts_per_page' => - 1,
  'post_status' => array( 'mssl-completed', 'mssl-pending', 'publish' ),
  'meta_query' => array(
     array(
        'key'   => 'team_league',
        'value' => "$leagueid",
     ),
   ),
 );

From here I was able to write the information pulled from the post meta to my custom page template.


text:
Q: WSO2 Api Manager - bypass sign in page when invoking API (oauth2 authorization grant code) I'm facing the same issue as the one posted at (How to get authorize code to dismiss login page with oauth2 wso2 identity server)
I tried to follow the solution instructions, but in my case, the drop-down menu under "Request Path Authentication Configuration" is empty; no options listed.

I checked the application-authentication.xml file under /opt/wso2am-4.1.0/repository/conf/identity and I have this:

I'll apprecitate any support you can provide. Thanks. Daniel

A: Just to close this thread, and as I was not able to get a solution, I solved it by running an instnace of the WSO2 Identity Server and handle the security through this product, instead of using the IS features the API manager has embedded. cheers!


text:
Q: Speech to text using TensorFlow I'm new to TensorFlow and I am looking for help on a speech to text recognition project. Is there an example that showcases how to use TensorFlow for speech to text? I hear that it was used within Google to improve accuracy by 25%

A: Although there is no speech to text demo in tensorflow. There are demos involving sequence-to-sequence modelling which can be easily used in the context of speech to text.


text:
Q: Problemas al hacer push en git, archivos muy grandes Estoy haciendo un proyecto en unity y estoy usando git para las versiones.
Todo funcionaba bien hasta que iba a hacer un push me salió lo siguiente:

No sé como resolverlo,
espero alguien me pueda explicar
gracias y saludos.

A: Lo que sucede es que github (no git, github) tiene un límite en el tamaño que puede tener un objeto a la hora de empujar. Ese límite es 100 MBs. Si alguno de los objetos en la historia de la rama que estás tratando de empujar tiene 100 MBs o más, github rechaza el push. Puedes utilizar lfs, como te recomienda el mensaje de github cuando te rechazó o puedes reescribir la historia del proyecto para eliminar dicho objeto (u objetos, si son varios) de tal forma que al empujar no haya quejas x parte de github (solo borrar un objeto grande en la punta de la rama que estás empujando no basta si ese mismo objeto está presente en revisiones anteriores de la rama).

A: No es un problema de git, pasa que github tiene un limite maximo de subida de 100 MB, puedes usar lfs como te recomiendan o pasarte a un servicio como https://bitbucket.org/ , personalmente uso bitbucket y me resulta mucho mas estable y fiable, saludos!