text:
Q: watching cctv footage without internet explorer long story short, i wanna set up ip cameras around my home. all methods i've found seems to be accessing footage (on microSD in camera) via internet explorer (hikvision cams). i wanna have it on separate LAN preferably on unix & w/o internet explorer.
i want access to live feed & to playback recorded vids.
i really like kerberos.io but it seems like it isnt suitable when i record video on microSD thats in camera. i went over dozen of other software but it all seems like they're focusing on (server and) recording video, i need just to view it.
another way i wanted go was vlc media player. i figured how play there live feed and how play h.246 but it seems you need to download that h.246 file first. plus its on two separate/far from each other (live & recorded) for older person to view.
is there some software for viewing live feed & playback in one place, for unix & without internet? thanks for any ideas :)

A: Viewing the live feed should be easy with VLC or just about any other player that can handle RTSP or ONVIF.
Viewing internally-stored recorded videos will be a bit trickier.  Some cameras might present a playback option via ONVIF, but I don't believe Hikvision cameras do.
Most Hikvision cameras have the option to record to external devices instead of their internal SD cards.  They usually will support both NFS and Samba.  You could have the cameras record to an NFS share and then view the recorded files with VLC or other local media player on linux.
Note that recording video over the network, ie. instead of the internal SD card, can be a heavy network load.  If you have the option, ALWAYS use a wired camera if at all possible (ie. PoE).  If wifi is your only option, plan your access points accordingly in order to handle the load.  If using wifi, you may also find that you need to use lower resolution and lower bitrates in order to get video that flows smoothly.
A high resolution, high bitrate, and high frame rate cameras can easily use 20-30Mbps of bandwidth... that's a lot for a shared wifi AP to handle. Plus, keep in mind that if you are recording over the network and viewing the camera at the same time, you will almost double the traffic.  On top of that, if you're viewing the video on a wifi laptop or mobile device, you'll add even more load to your AP.
I have 20 hikvision cameras around my house... most wired PoE with a few wifi cameras.  They are great cameras and work very well.  Wifi will not be your friend if you have more than a couple wireless cameras.  I really can't stress strongly enough to avoid wireless cameras if you can.  I have 3 commercial-quality Unifi AP's to handle the load and the wireless cameras keep them very, very busy.


text:
Q: Invalid VPN Secrets! No Server Certificate Verification Method Enabled I'm trying to set up a vpn (from VyperVPN) with OpenVPN and keep getting an invalid VPN Secrets error. I've been searching for a solution for a day and a half mow to no avail so i though i would come ask the pros.
I tried restarting network manager as well as the whole system. Also I tried ticking/unticking the all users option in open vpn. both were said to have helped others with this problem.
Heres the syslog:
Dec 16 14:33:13 Penguine-PC NetworkManager[920]: <info> Starting VPN service 'openvpn'...
Dec 16 14:33:13 Penguine-PC NetworkManager[920]: <info> VPN service 'openvpn' started (org.freedesktop.NetworkManager.openvpn), PID 3111
Dec 16 14:33:13 Penguine-PC NetworkManager[920]: <info> VPN service 'openvpn' appeared; activating connections
Dec 16 14:33:13 Penguine-PC NetworkManager[920]: <info> VPN plugin state changed: init (1)
Dec 16 14:33:14 Penguine-PC NetworkManager[920]: <info> VPN plugin state changed: starting (3)
Dec 16 14:33:14 Penguine-PC NetworkManager[920]: <info> VPN connection 'VyprVPN OpenVPN' (Connect) reply received.
Dec 16 14:33:14 Penguine-PC nm-openvpn[3117]: OpenVPN 2.2.1 x86_64-linux-gnu [SSL] [LZO2] [EPOLL] [PKCS11] [eurephia] [MH] [PF_INET6] [IPv6 payload 20110424-2 (2.2RC2)] built on Feb 27 2013
Dec 16 14:33:14 Penguine-PC nm-openvpn[3117]: WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.
Dec 16 14:33:14 Penguine-PC nm-openvpn[3117]: NOTE: the current --script-security setting may allow this configuration to call user-defined scripts
Dec 16 14:33:14 Penguine-PC nm-openvpn[3117]: LZO compression initialized
Dec 16 14:33:14 Penguine-PC nm-openvpn[3117]: UDPv4 link local: [undef]
Dec 16 14:33:14 Penguine-PC nm-openvpn[3117]: UDPv4 link remote: [AF_INET]216.168.3.151:1194
Dec 16 14:33:17 Penguine-PC nm-openvpn[3117]: [us2.vpn.giganews.com] Peer Connection Initiated with [AF_INET]216.168.3.151:1194
Dec 16 14:33:20 Penguine-PC nm-openvpn[3117]: AUTH: Received AUTH_FAILED control message
Dec 16 14:33:20 Penguine-PC nm-openvpn[3117]: SIGTERM[soft,auth-failure] received, process exiting
Dec 16 14:33:20 Penguine-PC NetworkManager[920]: <warn> VPN plugin failed: 0
Dec 16 14:33:20 Penguine-PC NetworkManager[920]: <info> VPN plugin state changed: stopped (6)
Dec 16 14:33:20 Penguine-PC NetworkManager[920]: <info> VPN plugin state change reason: 10
Dec 16 14:33:20 Penguine-PC NetworkManager[920]: <warn> error disconnecting VPN: Could not process the request because no VPN connection was active.
Dec 16 14:33:20 Penguine-PC NetworkManager[920]: <info> Policy set 'ervilla_EXT' (eth1) as default for IPv4 routing and DNS.
Dec 16 14:33:25 Penguine-PC NetworkManager[920]: <info> VPN service 'openvpn' disappeared

After reviewing the logs it would appear the problem is "No server certificate verification method has been enabled." to quote directly from the log. To be honest though i dont know what to make of that, hopefully someone with more know how can inform me.

A: I don't think that No server certificate verification method has been enabled. is the source of the problem. But I fixed this warning by selecting "Verify name exactly" for the option "Server Certificate Check"
To the "Subject Match" field I entered "OpenVPN Server".
Here I paste the screenshot:

But regarding the error message AUTH: Received AUTH_FAILED control message I'd say that your VPN credentials are invalid or you have selected the wrong authentication type. And this seem to be the real issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: heliocentricity and the theory of relativity
Possible Duplicate:
Why do we say that the earth moves around the sun?

I should preface by stating that I'm not a physicist and my knowledge of the theory of relativity is limited to what Encarta told me in the 90's (does everyone know what Encarta was?) and I don't even understand the Wikipedia entry!
Encarta had a video on the theory of relativity that basically explained in part that (i suppose in vacuum) there's no way to tell which body is in motion relative to another (without observing from outside the space in which they are moving i suppose).
so my question is whether this warrants a reassessment of our reliance on a heliocentristic model.  is it possible the planets do not revolve the way we've modeled them?  i'm not necessarily talking geocentric, just different from our current model.  should we be exploring this?
ps -- while researching this question i came across geocentricity.com, the first sentence of which starts "Of all the sciences, the Holy Bible..." I'm really not interested in starting a religious debate so please keep answers strictly physics related (though i hope i don't have to even say that on physics.stackexchange.com!)


text:
Q: How to say if button is released in objective c? I am trying to make a game in which when a button is held down the block moves right, and when a different button is held it moves left.
How do I say when a button is released it should stop?

A: In the Outlets tab of the inspector for the UIButton, connect touchUpInside and touchUpOutside to whatever method you want to run when the UIButton is released.

A: I would do some reading on event listeners, and specifically in objective-c:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html
If you design your event listener such that your 'block' moves ONLY when a button is held down, it should not be moving otherwise.

A: UIButton can be set up to call a method (called an action) in response to a built-in event. There is a Touch Down event when the button is touched, and a Touch Up Inside or Touch Up Outside event when the button is released. So you'd want to set up appropriate methods for all of those, i.e. "start" for the Touch Down event and "stop" for the other two.


text:
Q: xml parsing (.length) when items at differing levels in a tree have the same name I am trying to get a count of messages from the xml below using javascript.
The messages in the abbreviated tree are called "item" and there are two at the highest level. There are also elements called "item" on lower levels metaDataAttributes.

        <getMessagesReturn>
            <messages>
                <item>
                    <metaDataAttributes>
                        <item>
                          ...
                        </item>
                    </metaDataAttributes>
                </item>
                <item>
                    <metaDataAttributes>
                        <item>
                          ...
                        </item>
                    </metaDataAttributes>
                </item>
            </messages>
        </getMessagesReturn>

The following returns 1 (because I guess there's only one messages element.
var xmlMessagesCount = xml.documentElement.getElementsByTagName("messages").length;
I've tried var xmlMessagesCount = xml.documentElement.getElementsByTagName("item").length;
which returns 132 (because there are two messages (items) each with 65 attributes (items)
I am trying to get it to return 2.
There are similar threads, but didn't find a clear answer.  So any advice or request for clarity would be greatly appreciated.


text:
Q: Trend curve through data jumps back and forth when it should be smooth I want to plot a trend curve of my data points.
I did that with this code with an exponential model:
with open(file,'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
next(plots)
x=[]
y=[]
for row in plots:
    x.append(float(row[1]))
    y.append(float(row[3]))
plt.plot(x, y, 'ro',label="Original Data")
x = np.array(x, dtype=float) #transform your data in a numpy array of floats
y = np.array(y, dtype=float) #so the curve_fit can work

def func(x, a, b, c):
    return (a*np.exp(-b*x)+c)

popt, pcov = curve_fit(func, x, y)
ypredict=func(x, *popt)

plt.plot(x, ypredict, '--', label="Fitted Curve")
plt.legend(loc='upper left')
plt.show()

But I obtained this result:
]
Question
How can I obtain a smooth trend curve through this data?

A: One way, you can put x.sort() in before plotting:
x.sort()
ypredict=func(x, *popt)

Another way would be to use something like this (better for a plot in my opinion),
# 1000 evenly spaced points over the range of x values
x_plot = np.linspace(x.min(), x.max(), 1000)
y_plot=func(x_plot, *popt)

Then use x_plot and y_plot for your trend line and it should look fine. The problem is very-likely that your x values are not monotone and so your line plot is connecting points in the order they appear in x.


text:
Q: Thread Monitor class in c# In my c# application multiple clients will access the same server, to process one client ata a time below code is written.In the code i used Moniter class and also the queue class.will this code affect the performance.if i use Monitor class, then shall i remove queue class from the code.
Sometimes my remote server machine where my application running as service is totally down.is the below code is the reasond behind, coz all the clients go in a queue, when i check the netstatus -an command using command prompt, for 8 clients it shows 50 connections are holding in Time-wait...
Below is my code where client acces the server ...
if (Id == "")
{
    System.Threading.Monitor.Enter(this);
    try
    {
        if (Request.AcceptTypes == null)
        {
            queue.Enqueue(Request.QueryString["sessionid"].Value);

            string que = "";

            que = queue.Dequeue();
            TypeController.session_id = que;
            langStr = SessionDatabase.Language;
            filter = new AllThingzFilter(SessionDatabase, parameters, langStr);
            TypeController.session_id = "";

            filter.Execute();
            Request.Clear();

            return filter.XML;
        }
        else
        {
            TypeController.session_id = "";
            filter = new AllThingzFilter(SessionDatabase, parameters, langStr);

            filter.Execute();
        }
    }
    finally
    {
        System.Threading.Monitor.Exit(this);
    }
}

A: Locking this is pretty wrong, it won't work at all if every thread uses a different instance of whatever class this code lives in.  It isn't clear from the snippet if that's the case but fix that first.  Create a separate object just to store the lock and make it static or give it the same scope as the shared object you are trying to protect (also not clear).
You might still have trouble since this sounds like a deadlock rather than a race.  Deadlocks are pretty easy to troubleshoot with the debugger since the code got stuck and is not executing at all.  Debug + Break All, then Debug + Windows + Threads.  Locate the worker threads in the thread list.  Double click one to select it and use Debug + Call Stack to see where it got stuck.  Repeat for other threads.  Look back through the stack trace to see where one of them acquired a lock and compare to other threads to see what lock they are blocking on.
That could still be tricky if the deadlock is intricate and involves multiple interleaved locks.  In which case logging might help.  Really hard to diagnose mandelbugs might require a rewrite that cuts back on the amount of threading.


text:
Q: Problem synchronizing QThreads Apart from main thread, I've ThinkerThread object _thinker whose finished() signal is connected to main thread's slot:
connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove()));

The slot autoMove() causes _thinker to initialize and run again:
_thinker.setState(/* set internal variables to run properly */);
_thinker.start();

This way _thinker can continue to run with new data and give some feedback to user in the main thread with autoMove() slot.
The problem is when user wishes to load a new state for _thinker (may be from file or some other menu action), I cannot synchronous two states of _thinker.
Suppose that _thinker is running, and user loads a new state from a file. Now, when _thinker finished(), it will call autoMove() and show feedback. But it is possible that wrong feedback is given to the user, because, may be loading from file causes internal state to be changed. That means, _thinker's internal state and main thread's internal states are not same.

*

*_thinker starts, with states say, s0.

*User loads another state from file, say s1.

*_thinker finished and autoMove() executes.

So after step 3, autoMove() will give feedback for state s0, which is not expected. What I want to do is to stop execution of _thinker when user loads new state from file. I think my design is poor and I want to know the best practice in this case. My load function initializes _thinker in the same way autoMove() does, calling the same function (there is another function that calles _thinker.setState() and start()).
Right now I've done the following in load() function:
disconnect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove()));
_thinker.terminate();
_thinker.wait();
connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove()));

This does not eliminate the problem completely, that is, autoMove() is still called and gives previous state's feedback. I'm using Qt Creator 1.2.1 with Qt version 4.5.2 in Windows.
Thanks for your time.
Edit
This is the usual execution step (when load() is not called):
_thinker.setState();
_thinker.start();
//when _thinker finished()
autoMove();
    > _thinker.setState();
    > _thinker.start();

When load() is called:
_thinker.setState();
_thinker.start();
load();
    > _thinker.setState();
    > _thinker.start();
//when _thinker finished()
autoMove(); // this is the feedback for previous or current state
    > _thinker.setState();
    > _thinker.start();

Note, load() causes _thinker to restart. Now, where to put a boolean check so that autoMove() should ignore ONLY ONCE?

A: How about using an integer id to determine which state has been computed, to see if it's still valid when computation has finished?

A: Not exactly a best practice, but why don't you mark with a bool (use mutexes if neccesary) that the state has changed during execution and, if so, just restart the thread in autoMove (don't provide any feedback).
Update:
I was thinking something like:
autoMove()
{
    ....
    if (!_thinker.stateChanged())
    {
       // provide feedback
    }
    //restart _thinker -> on restart _thinker.isStateChanged = false;

 }

Of course, if the user changes the state to often, you may never reach the provide feedback branch :P


text:
Q: How to prevent Visual Studio from formatting specific code? I type the code below:
if (rows == 0) break;

and when I add the semicolon at the end, VS springs into action and converts it to:
if (rows == 0)
    break;

Same thing happens with if (rows = 0) return; and some other constructs.
How can I prevent VS from formatting this specific code interaction without messing with all the other niceties that it provides?  I looked in Tools/Options/Text Editor/C#/Code Style/Formatting, but don't see anything obvious.

A: you add pragam waning disable settings, so when you do Ctr+K+D it will not format or whatever shortcut keys you may be using to format.
#pragma warning disable format
public class Item
{
      public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}
#pragma warning disable format

A: You can enable the VS option in main menu:

Tools > Options > Text Editor > C# > Code style > Formatting > Wrapping >
Leave statements and member declarations on the same line

English version of same options dialog (VS2017 version):


text:
Q: HttpWebRequest doesn't work after server IP changed while I use domain Following code worked file until server IP changed. I use domain in URL.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://example.com/oauth/token?grant_type=password&username=" + username + "&password=" + password);
            request.Method = "POST";
            request.Headers.Add("Authorization", "Basic ......");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string result = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();

Error:

The request was aborted: Could not create SSL/TLS channel.

But postman does it.


text:
Q: Iterate list and dictionary at the same time Python I have a list of dictionary(k) and a list(l)
k = [
    {'x': 2.5, 'y': 1.5, 'z': 2},
    {'x': 3, 'z': -1.5},
]

l = [-9, -2, -4, 1, 4, 7]

What will be the easiest way to iterate k and z so together so that we can compute a formula for example using these values?
So far I have been using:
for dic in k:
    for key in dic:
        print(dic[key])

But this only iterates k alone. I need both k and z to iterate together so that we can use subsequent values to compute a function.
Output expected to compute a function for every values:
x + y*l + z*l*l

x,y,z will be 0 where it is not present

A: import itertools

k = [
    {'x': 2.5, 'y': 1.5, 'z': 2},
    {'x': 3, 'z': -1.5},
]

l = [-9, -2, -4, 1, 4, 7]

for d, i in itertools.zip_longest(k, l, fillvalue={}):
    x = d.get('x', 0)
    y = d.get('y', 0)
    z = d.get('z', 0)
    print(x + y*i + z*i*i)

output:
151.0
-3.0
0
0
0
0

constraint: l has to always be longer than k.

A: Try this
for dic, l in zip(k, z):
    x, y, z = dic.get('x', 0), dic.get('y', 0), dic.get('z', 0)
    return x + y*l + z*l*l


text:
Q: Secure Session Cookie + Glassfish 3.1 I'm looking for a solution similar to this:
httpOnly Session Cookie + Servlet 3.0 (e.g. Glassfish v3)
I want to turn the HTTP headers: http-only and Secure off so that authentication with https carries across to http requests.
However,
1  Relating to the other post.  I am not using servlet 3.0.  I may be willing to try to use servlet 3.0 if there was decent documentation somewhere on how to migrate an intellij project from serverl 2.5 to 3.0.  It does not seem obvious how to use this.  Changing my maven pom to javax.servlet 3.0 and then editing my web.xml version to 3.0 doesn't work.  Gives a facet-error on the 3.0 version.  Sigh.

*This is my primary approach to solve this.  I edited domains/domain1/config for default-web.xml and domain.xml to what I thought would work but it doesn't.  Oracle's documentation does not seem very clear to me on this.

domain.xml
<web-container>
    <session-config>
      <session-manager>
        <manager-properties></manager-properties>
        <store-properties></store-properties>
      </session-manager>
      <session-properties>
        <property name="cookieSecure" value="false"></property>
        <property name="cookieHttpOnly" value="false"></property>
      </session-properties>
    </session-config>
      </web-container>

....
<configs>
<config name="server-config">
  <http-service sso-enabled="true">
    <access-log></access-log>
    <virtual-server id="server" sso-cookie-secure="false" sso-cookie-http-only="false" network-listeners="http-listener-1,http-listener-2"></virtual-server>
    <virtual-server id="__asadmin" sso-cookie-http-only="false" network-listeners="admin-listener"></virtual-server>
  </http-service>

default-web.xml
    <session-config>
    <session-timeout>60</session-timeout>
        <cookie-config>
                <http-only>false</http-only>
                <secure>false</secure>
        </cookie-config>
        <cookie-properties>
                <property name="cookieSecure" value="false" />
                <property name="cookieHttpOnly" value="false" />
        </cookie-properties>
        <tracking-mode>COOKIE</tracking-mode>
  </session-config>

A: Okay I feel a bit stupid but I generally have never written to a specific container before to make sure that my code was portable across containers.  However, after some research, I discovered that you can put a WEB-INF/glassfish-web.xml file that looks like this to control your security cookie setting for each WAR file under glassfish.
http://blogs.oracle.com/jluehe/entry/ow_to_configure_the_security
    <?xml version="1.0" encoding="UTF-8"?>
        <glassfish-web-app>
            <session-config>
                <cookie-properties>
                    <b><property name="cookieSecure" value="[true|false|dynamic]"/></b>
               </cookie-properties>
           </session-config>
       </glassfish-web-app>


text:
Q: Finiteness conditions and Veronese subrings Consider a commutative group $G$ of finite type, a subgroup of finite index $H\subseteq G$, a noetherian commutative ring $A$, and a $G$-graded $A$-algebra $R=\bigoplus_{g\in G}R_g$ with no zero-divisors, and denote by $R_H=\bigoplus_{g\in H}R_g$ the degree restriction of $R$ to $H$.
It is well-known that if $R$ is of finite type over $A$, then so is $R_H$. So, we can ask whether the following statement is true:

(+) If $R_H$ is of finite type over $A$, then so is $R$.

Using the fact that $R$ is integral over $R_H$, one can show that (+) holds in the following two cases:

*

*$R_H$ is integrally closed and the field of fractions of $R$ is a separable extension of the field of fractions of $R_H$;

*$R_H$ is a japanese ring (see EGA 0$_{\rm IV}$.23).
In particular, (+) holds if $A$ is universally japanese, e.g. excellent, e.g. of finite type over a field.
My question is now as follows:

Is there an example where (+) does not hold?

A: In case $G$ is finite, this cannot happen.
(This might extend to the general case of finitely generated groups, as Fred told me when we talked about this in my office :-) )

First, let me show that $R$ is of finite type over $R_0$ in case $R_0$ is noetherian and $G$ is finite. For that, it suffices to show that every $R_g$, $g \in G$ is finitely generated as an $R_0$-module.
Now fix some $g \in G$. In case $R_g = \{ 0 \}$, we are done. Otherwise, let $\alpha \in R_g \setminus \{ 0 \}$. As $G$ is a finite group, there exists some $n > 0$ such that $n g = 0$. As $R$ is integral, $\beta := \alpha^{n-1} \neq 0$ is a non-trivial element of $R_{g^{-1}}$.
Now the map $\varphi : R_g \to R_0$, $x \mapsto \beta x$ is an injective $R_0$-module homomorphism. The image, $\beta R_g$, is therefore isomorphic to $R_g$ as an $R_0$-module. As $R_0$ is noetherian, every $R_0$-submodule of $R_0$ is finitely generated, whence $\beta R_g$ and thus $R_g$ is a finitely generated $R_0$-module.
This shows that $R$ is of finite type over $R_0$.

Now let me go back to the original problem. As $R_0$ is a subring of both $R$ and $R_{(H)}$, it is of finite type over the noetherian ring $A$. Therefore, $R_0$ is noetherian as well. So in case $G$ is finite, the above shows that $R$ is of finite type over $R_0$, and thus also over $A$.


text:
Q: Arch Linux not picking up static DHCP lease from DD-WRT I have a Arch Linux system on my home network and its MAC address is setup in my Linksys running DD-WRT to receive a static lease. However, this system is not getting the static lease from the DD-WRT, but rather a random ip from the dynamic pool. I tried various things, like forcing a lease renewal, but to no avail. How should I go about troubleshooting this problem? Running Arch Linux 201404 with a wired connection. I am new to Arch, but been a long time Debian user, so the Arch ip toolset is not too familiar to me.

A: I did this exact thing this morning.
First, double check that the lease isn't allocated. Go to the Status page and then the LAN page on DD-WRT. Check the lease in the list of DHCP clients. If it's allocated, click the trash can.
I also have my lease set to 5 minutes. If I left it for a whole day, which is the default, I found that if the signal got disrupted, my computer would disconnect and when it reconnected, the lease would still be allocated and so it would take an address from the pool. That messed with my port forwards. Setting it to 5 minutes prevented that.
Then, following from this part of the wiki, you need to find the name and MAC of your wireless NIC:
$ iw dev
Make sure you're using that MAC in your static lease on DD-WRT as the wired one will be different (I've made that mistake before).
Checking the status of your link is done via:
$ iw dev wlan0 link
It will either say Not Connected or give you information about your access point. At this point you don't want to be connected so if you are, issue:
# iw dev wlan0 disconnect
The wiki says that interface activation is not usually necessary, though for me it was. You can check the status with:
# ip link show wlan0
Don't pay attention to the state but look for the word UP inside the <...>.
If it's not up, use:
# ip link set wlan0 up
I'm going to assume that you know your SSID. In which case to connect to the access point, you can use:
# iw dev wlan0 connect your_essid
if it's open or:
# wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf
if you're using WPA, after providing the appropriate details in wpa_supplicant.conf.
Now recheck that you're associated with the access point by reissuing:
$ iw dev wlan0 link
Finally, you'll want to obtain an IP address by issuing:
# dhcpcd wlan0
DD-WRT should then match the MAC of your wireless NIC and issue the static lease address to you.


text:
Q: Select intent not triggered if selection is not immediately followed by carousel I am facing a problem with listening to User Selection when we show a carousel. We are using askWithCarousel with dialogFlow and listening to click of a carousel item using actions_intent_option event. When a carousel is displayed to user, assistant starts listening to user input using mic, if mic gets a random input from user (which doesn't match any of our synonyms for the carousel items) and then the user taps on any carousel item or says any of the synonyms, actions_intent_option event is not getting fired. It works fine if this interaction is immediately followed by showing of carousel. Else, it will take carousel title as user input and resolves to a different intent.
Not able to get the id of the carousel item because of this. Is there a way to disable mic or emit actions_intent_option even when the user clicks on carousel item later. Please help with this flow.

A: Selection events are only emitted, as you've discovered, right after the carousel or list has been sent to the user.
I'd recommend setting up a fallback intent to check for the titles of the list items or prompting the user with a carousel or list again.


text:
Q: Postgres unpack element I've a field in a table that contains packed data sent from a lora device. The device packs it like this:
# LoRa payload format
# (2 Bytes for device ID, 8 float numbers: temp humid ph1 ph2 ph3 volt1 volt2 volt3)
LORA_PKG_FORMAT = "!Hffffffff"
msg = struct.pack(LORA_PKG_FORMAT, config.DEVICE_ID, temp_read, humid_read, ph1_read, ph2_read, ph3_read, volt1_read, volt2_read, volt3_read)

A python application on the receiving end is able to decode and unpack it like this:
dev_msg = base64.b64decode(rx_pkt["data"])
focus_data = struct.unpack(config.LORA_PKG_FORMAT, dev_msg)

The packed data in the postgres table is like this:
\x000141a4000042a0e3884147fd0f41477c3b4147a5303e0895213e0895213e089521

while the values unpacked from the python application are:
logging.info('Decoded payload: ' + str(focus_data))

Decoded payload: (1, 20.5, 80.44439697265625, 12.499281883239746,
12.467829704284668, 12.477828979492188, 0.13338138163089752, 0.13338138163089752, 0.13338138163089752)

How can I achieve the same result as the struct.unpack function but with a postgres query? I need to extract every element in order to create a panel on grafana.

A: Write a database function in PL/Python and call it in an SQL query.
Database functions run inside the database and can be used in SQL.


text:
Q: AWS Codepipeline Multiple Output Artifacts Still fairly new to AWS Codepipeline and I am trying to pass an output artifact out into the next stage of my build.  In this particular case, I want to do two artifacts for the builds phase which is the only part I am focusing on right now.  I have included my codepipeline code for reference:
resource "aws_codepipeline" "cp_plan_pipeline" {

  name     = "${local.name_prefix_H}-${var.cp_name}"
  role_arn = aws_iam_role.cp_service_role.arn

  artifact_store {
    type     = var.cp_artifact_type
    location = module.S3.bucket_name
  }

  stage {
    name = "Clone"

      action {
        name                = "Source"
        category            = "Source"
        owner               = "AWS"
        provider            = "CodeCommit"
        input_artifacts     = []
        version             = "1"
        output_artifacts    = ["CodeWorkspace"]

        configuration = {
          RepositoryName        = var.cp_repo_name
          BranchName            = var.cp_branch_name
          PollForSourceChanges  = var.cp_poll_sources
          OutputArtifactFormat  = var.cp_ouput_format
        }

        run_order = "1"
      }
  }

  stage {
    name = "Plan"

      action {
          name              = "Terraform-Plan"
          category          = "Build"
          owner             = "AWS"
          provider          = "CodeBuild"
          version           = "1"
          input_artifacts   = ["CodeWorkspace"]
          output_artifacts  = ["CodeSource","TerraformPlanFile"]

          configuration = {
            ProjectName          = var.cp_plan_project_name
            EnvironmentVariables = jsonencode([
              {
                name  = "PIPELINE_EXECUTION_ID"
                value = "#{codepipeline.PipelineExecutionId}"
                type  = "PLAINTEXT"
              }
            ])
          }
      }
  }

  stage {
      name = "Test"

      action {
        name              = "Testing"
        category          = "Test"
        owner             = "AWS"
        provider          = "CodeBuild"
        input_artifacts   = ["CodeSource"]
        output_artifacts  = ["TestOutput"]
        version           = "1"

        configuration = {
          ProjectName = var.cp_test_project_name
          EnvironmentVariables = jsonencode([
              {
                name  = "PIPELINE_EXECUTION_ID"
                value = "#{codepipeline.PipelineExecutionId}"
                type  = "PLAINTEXT"
              }
          ])
        }
      }
  }

  stage {
    name = "Manual-Approval"

    action {
      run_order = 1
      name                = "AWS-Admin-Approval"
      category            = "Approval"
      owner               = "AWS"
      provider            = "Manual"
      version             = "1"
      input_artifacts     = []
      output_artifacts    = []

      configuration  = {
          CustomData      = "Please verify the terraform plan output on the Plan stage and only approve this step if you see expected changes!"
      }
    }
  }

  stage {
    name = "Deploy"

    action {
      run_order           = 1
      name                = "Terraform-Apply"
      category            = "Build"
      owner               = "AWS"
      provider            = "CodeBuild"
      input_artifacts     = ["TerraformPlanFile"]
      output_artifacts    = []
      version             = "1"

      configuration = {
        ProjectName          = var.cp_apply_project_name
        PrimarySource        = "CodeWorkspace"
        EnvironmentVariables = jsonencode([
          {
            name  = "PIPELINE_EXECUTION_ID"
            value = "#{codepipeline.PipelineExecutionId}"
            type  = "PLAINTEXT"
          }
        ])
      }
    }
    }

}

So the pipeline works fine as far as the deployment of the pipeline goes.  My buildspec works great up until the point where I get to the artifact stage of the buildspec where i get the following error:  Phase context status code: CLIENT_ERROR Message: no definition for secondary artifact CodeSource in buildspec  My issue is the buildspec and trying to output the second source so i can upload it for the second phase.  Please note some parts of the buildspec such as variables have been scrubbed.  Buildspec below:
version: 0.2
env:
  variables:
    TF_VERSION: "1.0.7"
    PY_VERSION: "3.9.6"
    GIT_VERSION: "2.9.5"
    PACKER_VERSION: "1.7.8"
    JQ_VERSION: "1.6"
    TFLINT_VERSION: "0.34.0"
    PERMISSION_SETS_DIR: "CodeSource"

phases:
  install:
    commands:
      # iNSTALL/UPDATE SSH CLIENT
      - echo UPDATING SSH CLIENT
      - "which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )"

      # iNSTALL JQ JSON PARSER
      - curl -s -qL -o jq https://github.com/stedolan/jq/releases/download/jq-${JQ_VERSION}/jq-linux64
      - chmod +x ./jq
      - cp jq /usr/bin

      # INSTALL TERRAFORM
      - echo STARTING TERRAFORM INSTALLATION
      - curl -s -qL -o terraform.zip https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_amd64.zip
      - unzip terraform -d /usr/bin/
      - "chmod +x /usr/bin/terraform"
      - "/usr/bin/terraform --version"

      # INSTALL Packer
      - echo STARTING PACKER INSTALLATION
      - curl -s -qL -o packer.zip https://releases.hashicorp.com/packer/${PACKER_VERSION}/packer_${PACKER_VERSION}_linux_amd64.zip
      - unzip packer -d /usr/bin/
      - "chmod +x /usr/bin/packer"
      - "/usr/bin/packer --version"

      # INSTALL PYTHON
      - echo "STARTING PYTHON INSTALLATION"
      - "curl -s -qL -o python.tgz https://www.python.org/ftp/python/${PY_VERSION}/Python-${PY_VERSION}.tgz"
      - "tar xf python.tgz -C /usr/bin/"
      - "python --version"
      - python -m pip install -U pip

      # ADD PYTHON MODULES
      - echo "INSTALL PYTHON MODULES"
      - pip install git-remote-codecommit

  pre_build:
    commands:
      # Adds a private SSH key to allow us to clone or npm install Git repositories
      - rootpath=$(pwd)
      - eval $(ssh-agent -s)
      - mkdir -p ~/.ssh

      # Configure SSH Key
      - echo "$ssh_key" > ~/.ssh/cc_rsa
      - cd ~/.ssh/
      - cat cc_rsa
      - |
        echo "Multiline command"
        cat > ~/.ssh/config <<EOL
        Host idt-codecommit
            Hostname git-codecommit.us-east-1.amazonaws.com
            User ${cc_user}
            IdentityFile ~/.ssh/cc_rsa
        EOL
      - cat ~/.ssh/config

      # Configure SSH Permissions
      - echo +++++++++CONFIG SSH+++++++++
      - chmod 700 ~/.ssh
      - chmod 600 ~/.ssh/config
      - chmod 600 ~/.ssh/cc_rsa
      - ssh-keyscan -t rsa1,rsa,dsa git-codecommit.us-east-1.amazonaws.com >> ~/.ssh/known_hosts

      # Clone directories
      - echo +++++++++CLONE DIRECTORIES+++++++++
      - mkdir -p ${CODEBUILD_SRC_DIR}/configurations/${PERMISSION_SETS_DIR}
      - cd ${CODEBUILD_SRC_DIR}/configurations/${PERMISSION_SETS_DIR}
      - git clone codecommit://sourcerepo local_primary_repo
      - git clone -b development ssh://sourcerepo2/v1/repos/sourcerepo2

      # GET AWS ACCOUNT VARIABLES
      - aws_region=$AWS_DEFAULT_REGION
      - awsaccountnumber=$(aws sts get-caller-identity --query "Account")
      - awsaccountname=$(aws iam list-account-aliases | jq -r '.AccountAliases | .[]')
      - |
            if [[ "$awsaccountname" == *"prod"* ]]; then
              appenv="prod"
            else
              if [[ "$awsaccountname" == *"test"* ]]; then
                appenv="test"
              else
                if [[ "$awsaccountname" == *"dev"* ]]; then
                  appenv="dev"
                else
                  if [[ "$awsaccountname" == *"sbx"* ]]; then
                    appenv="sbx"
                  else
                    appenv="other"
                  fi
                fi
              fi
            fi

  build:
    on-failure: ABORT
    commands:
      # Import S3 Folder Location Variable
      - cd ${CODEBUILD_SRC_DIR}/configurations/${PERMISSION_SETS_DIR}/local_primary_repo
      - CODEBUILD_GIT_BRANCH=`git symbolic-ref HEAD --short 2>/dev/null`

      # CHECK TERRAFORM CODE
      - cd ${CODEBUILD_SRC_DIR}/configurations/${PERMISSION_SETS_DIR}/local_primary_repo
      - echo "yes" | terraform init
      - terraform validate > ${bucketconfig}-tfvalidateexport.txt
      - terraform validate
      - terraform plan -out=tfplan_commitid_${CODEBUILD_RESOLVED_SOURCE_VERSION}_pipelineid_${PIPELINE_EXECUTION_ID}
      - cp ${bucketconfig}-tfvalidateexport.txt ${CODEBUILD_SRC_DIR}/
      - cp tfplan_commitid_${CODEBUILD_RESOLVED_SOURCE_VERSION}_pipelineid_${PIPELINE_EXECUTION_ID} ${CODEBUILD_SRC_DIR}/

  post_build:
    commands:
      - echo "Terraform plan completed on `date`"

artifacts:
  files:
    - tfplan_commitid_${CODEBUILD_RESOLVED_SOURCE_VERSION}_pipelineid_${PIPELINE_EXECUTION_ID}
  name: TerraformPlanFile
  secondary-artifacts:
    artifact_1:
      files:
        - '**/*'
      name: CodeSource
      base-directory: ${CODEBUILD_SRC_DIR}/configurations/${PERMISSION_SETS_DIR}

Links or advice of what i am doing wrong would be very helpful.  Thank you!!

A: First of I wanted to thank Antonio González for his post.  It was exactly what I needed for the solution.  I would like to recap the solution here for any other folks looking for an answer to the same issue.  I have a working understanding that will help beginners.  When Outputting multiple artifacts you have to use the secondary artifacts: action within the phase of the artifacts.  See the example below as you follow along:
artifacts:
  base-directory: ${CODEBUILD_SRC_DIR}/
  files:
    - '**/*'

  secondary-artifacts:
    ARTIFACT1:
      base-directory: DIRECTORY_FOR_ARTIFACT_1/
      files:
        - FILES_YOU_LOOKING_TO_OUTPUT
      name: ARTIFACT_1_NAME_ANYTHING_YOU_WANT

    ARTIFACT2:
      base-directory: DIRECTORY_FOR_ARTIFACT_2/
      files:
        - FILES_YOU_LOOKING_TO_OUTPUT
      name: ARTIFACT_2_NAME_ANYTHING_YOU_WANT

So this is the basic setup for multiple artifacts, if you wanted to do another artifact you would do a third.  Now the key to this setup is mapping the secondary-artifacts headings to the outputs that you defined in your codepipeline output.  Recall my pipeline build phase:
stage {
name = "Plan"
  action {
      name              = "Terraform-Plan"
      category          = "Build"
      owner             = "AWS"
      provider          = "CodeBuild"
      version           = "1"
      input_artifacts   = ["CodeWorkspace"]
      output_artifacts  = ["CodeSource","TerraformPlanFile"]

The output artifacts MUST be associated with the secondary-artifacts heading as shown below:
  secondary-artifacts:
      TerraformPlanFile:
          base-directory: ${CODEBUILD_SRC_DIR}/
          files:
            - tfplan_commitid_${CODEBUILD_RESOLVED_SOURCE_VERSION}_pipelineid_${PIPELINE_EXECUTION_ID}
          name: TerraformPlanFile

       CodeSource:
          base-directory: ${CODEBUILD_SRC_DIR}/configurations/${PERMISSION_SETS_DIR}/
          files:
            - '**/*'
          name: CodeSource

Notice how the secondary artifact heading matches the output_artifacts.  By ensuring that those heading match with the headings you ensure that the files passed are outputted correctly.


text:
Q: Default Date Formatting in SQL Server 2017 I am currently debugging a scenario in which dates need to be read from a string in a stored procedure.
The code that we have used is a simple convert statement.
e.g.
SELECT CONVERT(DATETIME, @dateInput)

The problem comes when I need to test the dates coming from the Chinese date format (yyyy.mm.dd) which is ISO 102.
What settings in Windows 10 / SQL Server must be set so that running  SELECT CONVERT(DATETIME, '2020.05.16')  will not return
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
I understand that using SELECT CONVERT(DATETIME, '2020.05.16', 102) would work but that would make the universal stored procedure incorrect when running with different windows date formats

A: Along with changing my windows settings to reflect the same date format I also changed:

*

*My default language of my SQLEXPRESS server in Properties > Advanced > Default Language

*My default language of my SQL User Login Properties > General > Default Language
This meant that it could read the direct string value without needed the ISO 102 identifier.

A: If the input value is always in the format yyyy.MM.dd then use the appropriate style code (don't rely on the language setting of the LOGIN):
DECLARE @StringInput varchar(10) = '2020.05.16';
SELECT CONVERT(datetime,@StringInput,102);

Ideally, however, instead of defining your parameter as a varchar define it as a datetime in the first place and have the application pass the correct data type; not a string. But that is a different question for the language your application is written in.


text:
Q: how to markdown multiple email blade? i have multiple email template blade view which i want to markdown but laravel defualt mail method have one build method like this
   /**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->markdown('view-to-mail', [
            'messageBody' => $this->data['message'],
        ]);
}

but i have multiple email template like this
  mail1.blade.php
    mail2.blade.php
    mail3.blade.php

i wnat to make all of them as markdown something like this
    public function build()
{
    return $this->markdown('mail1.blade.php', [
            'messageBody' => $this->data['message'],
        ]);
    return $this->markdown('mail2.blade.php', [
            'messageBody' => $this->data['message'],
        ]);
    return $this->markdown('mail3.blade.php', [
            'messageBody' => $this->data['message'],
        ]);
}

how i can do that something like above?


text:
Q: $firebaseUtils.toJSON throwing Maximum call stack size exceeded I'm extending a really basic $firebaseObject with a toJSON function which looks exactly like:
toJSON: function() {
  var data = $firebaseUtils.toJSON(this);
  return data;
}

I oriented myself after the gist of Katowulf but I keep getting this error:
RangeError: Maximum call stack size exceeded
    at Object.isObject (angular.js:590)
    at Object.toJSON (angularfire.min.js:1)
    at a.toJSON (tournament.js:375)
    at Object.toJSON (angularfire.min.js:1)
    at a.toJSON (tournament.js:375)
    at Object.toJSON (angularfire.min.js:1)
    at a.toJSON (tournament.js:375)
    at Object.toJSON (angularfire.min.js:1)
    at a.toJSON (tournament.js:375)
    at Object.toJSON (angularfire.min.js:1)

When I took a deeper look, with console.trace(), it shows that my toJSON function calls itself again and again which creates an infinite loop.
It starts from:
toJSON  @   tournament.js:375
toJSON  @   angularfire.min.js:1
...

and goes on like:
toJSON  @   tournament.js:375
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
...

up to:
toJSON  @   tournament.js:375
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
toJSON  @   tournament.js:376
toJSON  @   angularfire.min.js:1
...

When removing toJSON it works fine, but I really need to do some work before saving to firebase.
Edit: After taking a closer look into the $firebaseUtils.toJSON() source code, I see why I get an infinite loop here, but I wonder how kato's version works?


text:
Q: AWS CloudWatch metrics: How are Network metrics calculated? How does AWS calculates the network in and network out metrics?
I have two instances, one running application and another running database. I want to know the network traffic between these two instances. What is the best way to get that?

A: To discover traffic between two specific locations, you would need to activate VPC Flow Logs - Amazon Virtual Private Cloud:

VPC Flow Logs is a feature that enables you to capture information about the IP traffic going to and from network interfaces in your VPC. Flow log data can be published to Amazon CloudWatch Logs or Amazon S3. After you've created a flow log, you can retrieve and view its data in the chosen destination.

VPC Flow Logs can be activated on the whole VPC, a subnet, or a specific Elastic Network Interface ENI). The Flow Log will show information about each packet, but not the contents of the packet.
You would need to use a tool to then gather and aggregate information from the logs, such as: Querying Amazon VPC Flow Logs - Amazon Athena


text:
Q: ViewPager with items preview I want to show a ViewPager with all the days of the week with a preview of the following and previous item of the current one.
I've tried a lot of solutions suggested from stackoverflow but none of them is working. I don't wont to use fragments in the ViewPager so I've used a PagerAdapter.
See this image:

My starting point is:

*

*activity_main.xml

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Choose a day of the week:" />
<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/weekOfTheDayPager"/>

*MainActivity.java
public class MainActivity extends AppCompatActivity {

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

private void setUpAdapter() {
    ViewPager _mViewPager = (ViewPager) findViewById(R.id.weekOfTheDayPager);

    final String[] daysOfTheWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    final Context myContext = getBaseContext();

    _mViewPager.setAdapter(new PagerAdapter() {
        @Override
        public int getCount() {
            return daysOfTheWeek.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup collection, int position) {
            LayoutInflater inflater = LayoutInflater.from(myContext);
            ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.dayoftheweeklayout, collection, false);
            ((TextView) layout.findViewById(R.id.dayOfTheWeekTextView)).setText(daysOfTheWeek[position]);
            collection.addView(layout);
            return layout;
        }

        @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }
    });
}}

and finally the layout for the ViewPager item:

*

*dayoftheweeklayout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/dayOfTheWeekTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Sunday"
        android:layout_gravity="center_horizontal"/>
</FrameLayout>

Any suggestion will be appreciated.

A: So it looks like you want a carousel view.
Here's the recipe:
First, in order to show pages to the side in ViewPager, you need to provide some padding on the sides and then set clipToPadding to false:
    <android.support.v4.view.ViewPager
        android:id="@+id/weekOfTheDayPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:paddingEnd="@dimen/view_pager_padding"
        android:paddingLeft="@dimen/view_pager_padding"
        android:paddingRight="@dimen/view_pager_padding"
        android:paddingStart="@dimen/view_pager_padding"/>

Next, you need to override getPageWidth in your PagerAdapter to tell the ViewPager that you want to display three pages at a time:
    @Override
    public float getPageWidth(int position) {
        return 1F / 3F;
    }

Then you need to tell the ViewPager to use a custom PageTransformer:
    viewPager.setPageTransformer(false, new MyPageTransformer());

...
public static class MyPageTransformer implements ViewPager.PageTransformer {

    private ArgbEvaluator mColorFade = new ArgbEvaluator();

    @Override
    public void transformPage(View page, float position) {

         // position is 0 when page is centered (current)
         // -1 when page is all the way to the left
         // +1 when page is all the way to right

         // Here's an example of how you might morph the color
         int color = mColorFade(Math.abs(position), Color.RED, Color.GRAY);
         TextView tv = (TextView) page.findViewById(R.id.dayOfTheWeekTextView);
         tv.setTextColor(color);
    }
}

There's probably something I forgot, but search SO for "android viewpager carousel" and you will find an answer in there somewhere.


text:
Q: How to do Dynamic sortBy in F# LINQ to SQL Is there a way to do dynamic sorting - ala dyanmic LINQ in C# - when using F# LINQ to SQL query expressions. In particular I am looking to do the following,
open System
open Microsoft.FSharp.Data.TypeProviders
open System.Data.Linq.SqlClient
open System.Linq
open Microsoft.FSharp.Linq

type schema = SqlDataConnection<"Data Source=SERVER\INSTANCE;InitialCatalog=MyDatabase;Integrated Security=SSPI;">

let db = schema.GetDataContext()
query {
  for student in db.Student do
    sortBy "Name"  //provide column name as string rather than expr
    select student
}

A: DynamicLinq is implemented with Extension methods, those should work in F# 3.0, so why not just use DynamicLinq like you would in C#?
open System.Linq.Dynamic

...
let db = schema.GetDataContext()
db.Student.OrderBy("Name")


text:
Q: Split a string by Regex I'm currently thinking of how to split this kind of string into regex using c#.
[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]

Can someone knowledgeable on regex can point me on how to achieved this goal?
sample regex pattern that don't work:
[\dd,\dd,\dd]

sample output:
[01,01,01]
[02,03,00]
[03,07,00]
[04,06,00]
[05,02,00]
[06,04,00]
[07,08,00]
[08,05,00]

A: This will do the job in C# (\[.+?\]), e.g.:
var s = @"[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]";
var reg = new Regex(@"(\[.+?\])");
var matches = reg.Matches(s);
foreach(Match m in matches)
{
    Console.WriteLine($"{m.Value}");
}

EDIT This is how the expression (\[.+?\]) works

*

*first the outter parenthesis, ( and ), means to capture whatever the inside pattern matched

*then the escaped square brackets, \[ and \], is to match the [ and ] in the source string

*finally the .+? means to match one or more characters, but as few times as possible, so that it won't match all the characters before the first [ and the last ]

A: I know you stipulated Regex, however it's worth looking at Split again, if for only for academic purposes:
Code
var input = "[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]";

var output = input.Split(']',StringSplitOptions.RemoveEmptyEntries)
                     .Select(x  => x + "]") // the bracket back
                     .ToList();

foreach(var o in output)
   Console.WriteLine(o);

Output

[01,01,01]
[02,03,00]
[03,07,00]
[04,06,00]
[05,02,00]
[06,04,00]
[07,08,00]
[08,05,00]

A: The Regex solution below is restricted to 3 values of only 2 digits seperated by comma. Inside the foreach loop you can access the matching value via match.Value. >> Refiddle example
Remember to include using System.Text.RegularExpressions;
var input = "[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]";
foreach(var match in Regex.Matches(input, @"(\[\d{2},\d{2},\d{2}\])+"))
{
  // do stuff
}

A: Thanks all for the answer i also got it working by using this code
string pattern = @"\[\d\d,\d\d,\d\d]";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

MatchCollection matches = rgx.Matches(myResult);

Debug.WriteLine(matches.Count);

foreach (Match match in matches)
   Debug.WriteLine(match.Value);


text:
Q: Passing arguments to a remote machine? I am trying to pass arguments to a remote machine using the attached script. But it is throwing exception saying: "cannot index into null array". Where am i going wrong ?
param(
[Parameter(Mandatory = $True, Position = 0)][ValidateNotNull()]$server = $(throw "Please provide Environment name. Ex: cyclone,jwoww or joker"),
[Parameter(Mandatory = $true, position = 1)][string]$logType = $(throw "Please provide type of log you want"),
[Parameter(Mandatory = $true, position = 2)][string]$howMany = $(throw "Please provide number of log rows you want")
)

invoke-command -computername $server -credential abc\def{

Get-EventLog -logname $arg[0] -newest $arg[1] | Out-File c:\EventLogs.txt

} -argumentlist $logType,$howMany

A: Just add the Param block to the Invoke-Command cmdlet and use the parameter names instead of $arg[0] and $arg[1]
invoke-command -computername $server -credential abc\def{
    Param($logType, $howMany)

Get-EventLog -logname $logType -newest $howMany | Out-File c:\EventLogs.txt

} -argumentlist $logType,$howMany


text:
Q: Magento configuration popup window - where should html file go in module hierarchy? In my module config, I have a button. When that button is clicked I pop up a window that gathers some more input. That file is just an html file, but where should it live in the directory structure of the module?
To give a bit more info - just to see something working, I defined my field as follows:
<button_url_test_window_open><![CDATA[/px.html]]></button_url_test_window_open>
<frontend_model>mymodule/adminhtml_system_config_testWindowOpenDialog</frontend_model>

and I put the px.html file in my htdocs/magento folder. When I click the button it results in /px.html being opened, but that doesn't seem right. I'm not sure how to word the question, but I feel I should be doing something more like 'open the file called px.html for mymodule' and magento would then look in the right place. Sorry about the terminology, I'm still getting to grips with Magento/PHP/Apache.
Just to complete the picture of what I currently have, the frontend_model block is:
protected function _prepareLayout()
{
    parent::_prepareLayout();
    if (!$this->getTemplate()) {
        $this->setTemplate('mypackage/system/config/test_window_open_dialog.phtml');
    }
    return $this;
}

public function render(Varien_Data_Form_Element_Abstract $element)
{
    $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
    return parent::render($element);
}

protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    $originalData = $element->getOriginalData();
    $this->addData(array(
        'button_label_test_window_open' => Mage::helper('mymodule')->__($originalData['button_label_test_window_open']),
        'button_url_test_window_open'   => $originalData['button_url_test_window_open'],
        'html_id' => $element->getHtmlId(),
    ));
    return $this->_toHtml();
}

and the test_window_open_dialog.phtml file contains:

            <button style="" onclick="javascript:window.open('<?php echo $this->getButtonUrlTestWindowOpen()?>', 'testing','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, ,left=100, top=100, width=600, height=470'); return false;" class="scalable" type="button" id="<?php echo $this->getHtmlId() ?>">
                <?php echo $this->escapeHtml($this->getButtonLabelTestWindowOpen()); ?>
            </button>

A: phtml files don't go anywhere within your module directory.  Module directories house your Blocks, Helpers, Models, Controllers, Sql installation/upgrade files, and your configuration xml files.  Template files go in either app/design/adminhtml (if it is an admin template), or in app/design/frontend if it will be used on the frontend of the site.


text:
Q: Will Kinect v2 support multiple sensors? Working with multiple Kinect v1 sensors is very difficult because of the IR interference between the sensors.
Based on what I read on this gamastura article, Microsoft got rid of the interference problem with the time-of-flight mechanism that Kinect v2 sensor uses to gauge depth.
Does that mean I could use multiple Kinect v2 sensors at the same time, or did I misunderstand the article?
Thanks for the help!

A: I asked this question, in person, of the dev team at the meetup in San Francisco in April. The answer I got was:
"This feature is 3+ months away. We want to prioritize single-Kinect features before working on multiple Kinects."
I'm a researcher, and my goal is to have a bunch of odd setups, so this is a frustrating answer, but I understand that they need to prioritize usage that will be immediately useful to a larger market.
Could you connect them to multiple computers and stream data back and forth?

A: As @escapecharacter mentioned not likely to have support for multiple kinect v2 sensors in the very near future.
I can also confirm, one of the Kinect V2 SDK samples has this comment:
// for Alpha, one sensor is supported
this.kinectSensor = KinectSensor.Default;

I think the hardware itself is capable of avoiding the interference problem. Hopefully the slightly larger amount of data (higher res RGB stream) won't be a problem with multiple sensors(and available USB bandwidth) and it would be a matter of enabling the SDK to safely handle multiple sensor instances in the future.
I wouldn't expect a fast/quick update to the SDK enabling though, so in the meantime, although not ideal you could try either:

*

*Using multiple V2 sensors on multiple machines communicating over a
local network, passing only processed/minimal data (to keep the delay
as small as possible)

*Using multiple V1 sensors using Shake'n'Sense (pdf link to paper) to reduce interference

At least you would to a certain extent make some progress testing some of your assumptions for your project with multiple sensors, and update the project when the updated SDK is out.

A: I realize I misread your question, and interpreted it as "how can I connect to Kinect 2's to a computer" when you were actually asking about how to avoid interference, and Kinect 2 was your hoped-for solution.
You can hack avoiding Kinect 1 interference by lighting shaking one of them independent of the other. See here:
http://channel9.msdn.com/coding4fun/kinect/Shaking-some-sense-into-using-multiple-Kinects-with-Shake-n-Sense
One of the craziest things I've ever seen that actually worked. I was at Microsoft Research when they figured this out, and it works quite well.

A: You can have a Kinect v1 viewing the same scene as a Kinect v2 without interference.  I know this isn't exactly what you're looking for, but it could be useful.

A: 2 Years later, and this still cannot be done.
See:

*

*https://social.msdn.microsoft.com/Forums/en-US/8e2233b6-3c4f-485b-a683-6bacd6a74d53/how-to-prevent-interference-between-multiple-kinect-v2-sensors?forum=kinectv2sdk

*https://github.com/OpenKinect/libfreenect2/issues/424
As stated in the second link,

What happens is this: Each Kinect v2 continuously switches between different modulation frequencies. When two Kinects switch to the same frequency range, the interference occurs. They typically gradually drift into the same range and after a while drift out of that range again. So, theoretically, you just have to wait a bit until the interference is gone. The only way I found to stop the interference immediately was to disconnect (and reconnect) the concerned Kinect from its power supply
...
Quite unfortunate that these modulation frequencies aren't controllable at this time. Let's hope MS surprises us with that custom firmware

IIRC, I came across a group at MIT that got custom firmware from MS which solved the problem, but I can't seem to find the reference. Unfortunately, it is not available to the public.

A: I think we cant use multiple Kinect v2 in same environment because they will interfere lot comparatively kinect v1. As Kinect v2 depth sensing based on time of flight principle, multiple kinect v2 will interfere lot. For kinect v1 interference is not that much severe.


text:
Q: Can I set session variables for Postgres from the JDBC Connection For performance reasons, I'm trying to limit the round trips I make to the database. Currently I connect and the issue a series of statements like SET TIMEZONE='America/New_York' to postgres. Many databases allow session variables and similar settings to be passed to the database either as part of the jdbc url i.e. jdbc:postgresql://localhost:5435/test?timezone=America/New_York or by adding the it to the property list like this...
String url = "jdbc:postgresql://localhost/test:5435";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("timezone","America/New_York");
Connection conn = DriverManager.getConnection(url, props);

I can't find definitive information if this is supported by postgres and tests have failed.

A: The documentation says:

Connection Parameters
[...]

*

*options = String

  Specify 'options' connection initialization parameter.
The value of this property may contain spaces or other special characters, and it should be properly encoded if provided in the connection URL. Spaces are considered to separate command-line arguments, unless escaped with a backslash (\); \\ represents a literal backslash.

So you should use
props.setProperty("options", "-c timezone=America/New_York");


text:
Q: How To Down and store the Text File on Local Cache I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:@"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:@"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];

NSLog(@"%@",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];

A: iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
    NSLog(@"error: %@", error)
}


text:
Q: Script load on xhr response i have problem with responseText.
I want to load script from includes/dodaj-slike.php (which is echo)
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        alert(xhr.responseText);
    }
};

xhr.open('POST', 'includes/dodaj-slike.php', true);
xhr.send(formdata);

Alert responseText is (example) :

I get this and I want to somehow load this script immediately after response.
My question is how to load script on this way?

A: You can do it with
document.head.appendChild(responseText);

Correct way would be as suggested
$("head").append(xhr.responseText);


text:
Q: Elasticsearch completion suggester phrase instead of terms I am developing a search engine with Elasticsearch 1.6 and it's all working great. I get the data from my MySQL database with the JDBC importer from Jorg Prante. I would like to use the Elasticsearch complete suggester like documented here. The problem is only that I cannot find out how to do this without having tags like shwown in the examples everywhere. I only have the title of a product which is a quite long title.
So I would like to know how to make this work like expected by using the full phrase of the title or otherwise how to split the titlephrase into tags and adding them.
This is my current mapping for the field 'title' but that does only return a (not very relevant) whole phrase.
  curl -XPUT "http://localhost:9200/jdbc/" -d'
{
   "mappings": {
      "jdbc": {
         "properties": {
            "title": {
               "type": "completion",
               "index_analyzer": "simple",
               "search_analyzer": "simple",
               "payloads": true
            }
         }
      }
   }
}'


text:
Q: How to use different reporters in scalameter? I want to try using some reporters in my benchmark for function Main.lengthOfUUID.

object Main {

  def lengthOfUUID(s : Int) = {
    val x = List.fill(100000)(1)
    val sum = x.sum
  }
}

Firstly I tried ChartReporter
import org.scalameter.api._
import org.scalameter.picklers.Implicits._

object UUIDBench extends Bench[Double] {

  lazy val executor = LocalExecutor(
    new Executor.Warmer.Default,
    Aggregator.min[Double],
    measurer)
  lazy val measurer = new Measurer.Default
  lazy val reporter = ChartReporter(ChartFactory.XYLine())
  lazy val persistor = Persistor.None
  val sizes: Gen[Int] = Gen.range("size")(1, 8, 1)
  val ranges: Gen[Range] = for {
    size <- sizes
  } yield 0 until size
  performance of "Batches" config (
    exec.benchRuns -> 4
    ) in {
    measure method "main" in {
      using(sizes) in { s =>
        Main.lengthOfUUID(s)
      }
    }
  }
}

But it throws a error
Error:(14, 36) ambiguous implicit values:
 both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
 and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
 match expected type Numeric[T]
Error occurred in an application involving default arguments.
  lazy val reporter = ChartReporter(ChartFactory.XYLine())
Error:(14, 36) could not find implicit value for evidence parameter of type Numeric[T]
Error occurred in an application involving default arguments.
  lazy val reporter = ChartReporter(ChartFactory.XYLine())
Error:(14, 36) not enough arguments for method apply: (implicit evidence$1: Numeric[T])org.scalameter.reporting.ChartReporter[T] in object ChartReporter.
Unspecified value parameter evidence$1.
Error occurred in an application involving default arguments.
  lazy val reporter = ChartReporter(ChartFactory.XYLine())

I saw this issue. Code there is not available now, but it is said to use HTMLReporter, so I tried it
lazy val reporter = Reporter.Composite(
    new RegressionReporter(
      RegressionReporter.Tester.OverlapIntervals(),
      RegressionReporter.Historian.ExponentialBackoff() ),
    HtmlReporter(true)
  )

But got similar errors
Error:(15, 5) ambiguous implicit values:
 both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
 and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
 match expected type Numeric[T]
    new RegressionReporter(
Error:(15, 5) could not find implicit value for evidence parameter of type Numeric[T]
    new RegressionReporter(
Error:(15, 5) not enough arguments for constructor RegressionReporter: (implicit evidence$1: Numeric[T])org.scalameter.reporting.RegressionReporter[T].
Unspecified value parameter evidence$1.
    new RegressionReporter(
Error:(18, 17) ambiguous implicit values:
 both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
 and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
 match expected type Numeric[T]
    HtmlReporter(true)
Error:(18, 17) could not find implicit value for evidence parameter of type Numeric[T]
    HtmlReporter(true)
Error:(18, 17) not enough arguments for method apply: (implicit evidence$1: Numeric[T])org.scalameter.reporting.HtmlReporter[T] in object HtmlReporter.
Unspecified value parameter evidence$1.
    HtmlReporter(true)

How should I use these reporters?


text:
Q: How to Create a single Trigger on multiple Database Tables I have a database which contains some tables such as article, news, projects,...
I want to save a record to another table (Activity) when a record inserted into each table in database without activity
I don't want to create a trigger for each table.
How can I do it?

A: If you were to use an intermediate layer, such as an ORM like Entity Framework, you could, in effect, have a "database wide" trigger, by overriding the OnSaveChanges event to add a log record anytime something is committed to the database.
My answer on This Question does exactly that


text:
Q: Drupal Search API Solr - Long strings I am using Search API Solr (Solr v4.9.0) for my Drupal Search. A customer just informed us that they found out that Solr does not show search results for strings that are longer then 15 characters.
The weired thing is, that we also use Search API Autocomplete in this project and all the long strings like for example "dampfschifffahrtsgesellschaft" are shown as a suggestion for the user when they start typing characters. But after selecting the string from the autocomplete suggestion, the searched term cant be found by Solr on the search result page.
It works without any problems for all strings with less then 15 characters. Someone got an idea?

A: I found out that this was my own configuration fault ... I added part word search using this filters:
    <!-- Word Part Search Filter: -->
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="15" side="front"/>
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="15" side="back"/>

As the maxGramSize was limited to 15 it couldnt work... I raised it up to 30 so now its working without any problems.


text:
Q: How do i count str_split output according to required In my achievement i want to get the result of total  complete number of      $disp[$i] output
    example
      $txt = "12345678910";
      $disp = str_split($txt, 4);
      for($i = 0; $i < 3; $i++)           {
       echo $disp[$i];

       }

In result i have 1234, 5678, 910 that is 2 completed result output
    and 1 uncompleted result output can i just count the completed result output only?
    Example i want to count the complete result only like 1234, 5678 only i have tried:
       $txt = "12345678910";
       $disp = str_split($txt, 4);
       $countA = count($disp);
       for($i = 0; $i < 3; $i++)          {
      if(strlen($disp[$i]) != 4)
       {
      $countb += count($disp[$i]);
       echo "$countb"; #Unknow result
       }
      else
       {
       echo "$counta"; #Good result
       }
       }

thanks for reading and your impact in my solution

A: <?php
$txt = "12345678910";
$disp = str_split($txt, 4);
$counta='';
$countb='';

foreach($disp as $disper){
    if(strlen($disper) != 4)
    {
        $countb += count($disper);

    }
    else
    {
        $counta += count($disper);

    }
}
echo $countb ."unknown result"; #Unknow result
echo '
';
echo $counta ."good result" . "\r\n"; #Good result
echo '
';

And the output is :
1unknown result
2good result

if you don't want to see unknown result just remove the echo for it. $countb variable will still have the actual value if you need to use it.


text:
Q: Obtener datos de una relación de muchos a muchos buen dia
tengo unos select dependientes  al escoger una maquina se debe listar en otro select los productos relacionados a esa maquina seria una relacion mucho a muchos para este tengo una tabla pivote donde estan las diferentes combinaciones  funciona bien al escojer la maquina me lista solo las combinaciones de la tabla pivote pero me aparece el id como hago para aceder al nombre del producto  ???
gracias de antemano
base

select

aqui me aparece el id de la columna producto de la tabla pivote como hago para traer el nombre de la tabla producto por medio de la tabla pivote
ajax
<script type="text/javascript">
    $(document).ready(function() {
        // asignar los select a las variables
        var plantSelect = $('#maquina');
        var areaSelect = $('#id_producto');
        // obteniendo las maquinas y llenando el select
        function populatePlantSelect() {
            $.ajax({
                url: "{{ route('getmaquinas') }}",
                type: 'GET',
                dataType: 'json',
                success: function (response) {
                    $.each(response.data, function (key, value) {
                        plantSelect.append("<option value='" + value.id + "'>" + value.nombre_maquina + "</option>");
                    });
                },
                error: function () {
                    alert('Hubo un error obteniendo las maquinas!');
                }
            });
        }
        populatePlantSelect();
        // indica la maquina y lista los productos asignados a esa maquina
        plantSelect.change(function(){
            var plantId = $(this).val();
            areaSelect.empty();

            if (plantId) {
                $.ajax({
                    url: "{{ route('getproducto') }}",
                    type: 'GET',
                    data: { maquina: plantId },
                    dataType: 'json',
                    success: function (response) {
                        areaSelect.append('<option value=""></option>')
                        $.each(response.data, function (key, value) {
                            areaSelect.append("<option value='" + value.id + "'>" + value.codigo    +'__'+ value.producto  + "</option>");
                        });
                    },
                    error : function(){
                        alert('Hubo un error obteniendo los productos!');
                    }
                });
            }
        });
        // despues de selecionar le producto asigna codigo de producto para llenar campo de la imagen y cargar

    });
    </script>

controlador
 public function getmaquinas(){

    try{
        $linea = linea::all();
        $response = ['data' => $linea];
    }catch (\Exception $exception){

        return response ()->json(['mensaje'=>'upps hubo un error'],500);
    }
    return response()->json($response);
}

public function getproducto(Request $request)
{
    try{
        $id_maquina = $request->input('maquina');
        $producto = pivote_m_p::when($id_maquina, function ($query) use ($id_maquina)
         {
            $query->where('maquina', $id_maquina);
        })->get();

        $response = ['data'=> $producto];
    }
    catch (\Exception $exception){

        return response ()->json(['mensaje'=>'upps hubo un error'],500);
    }

    return response ()->json($response);
}

esto ya tiene las rutas en web php
creo que la solucion esta en acomodar $producto pero no se como
modelo
    class pivote_m_p extends Model
{
    use HasFactory;

    protected $table='PIVOTE_M_P';

    public function productos(){

        return $this->hasMany(Registrouno::class);
    }

    public function maquina(){

        return $this->hasMany(linea::class);
    }
}

modelo de la maquina
    class linea extends Model
{
    use HasFactory;

    protected $table="TABLA-MAQUINAS";

}

modelo productos
    class Registrouno extends Model
{
    use HasFactory;

    protected $table="PRODUCTO";

}

ayuda :(

A: Te hago los siguientes comentarios:

*

*No es necesario un modelo para la tabla intermedia entonces yo optaría por eliminarlo, aunque si decides usarlo entonces trata de ajustar a lo indicado por Eloquent

*Las relaciones que defines en el modelo antes mencionado no se ajustan a tu escenario

*En los modelos Producto y Maquina debes declarar la relación que los vincula con la tabla intermedia (dicha relación es belongsToMany) de esta forma:

Nota importante: Para la propuesta de solución yo no haré uso de un modelo para la tabla PIVOTE_M_P
Modelo Producto:
class Producto extends Model
{
    /*
        Resto de tu código
    */
    public function maquinas()
    {
        return $this->belongsToMany(Maquina::class, 'PIVOTE_M_P', 'producto', 'maquina');
    }
}

Modelo Maquina:
class Maquina extends Model
{
    /*
        Resto de tu código
    */
    public function productos()
    {
        return $this->belongsToMany(Producto::class, 'PIVOTE_M_P', 'maquina', 'producto');
    }
}

Como notas en ambos casos:

*

*Tuvimos que pasar 3 argumentos extra, sugiero leas este recurso
Entonces la consulta debe ser tan simple como:
$maquinaConProductos = Maquina::with('productos')->findOrFail($idMaquina);

O bien si quieres todas las máquinas con todos sus productos vinculados:
$maquinasConProductos = Maquina::with('productos')->get();

Donde:

*

*Para el primer caso obtendrías un objeto con los datos de la maquina recuperada y una colección con los productos asociados

*Para el segundo caso obtendrías una colección de todas las máquinas y por cada objeto una colección asociada con los productos asociados


text:
Q: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable
Compile time error:
"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'Domain.User'.
An explicit conversion exists (are you missing a cast?)"

User newUser = uow.UserRepository.Get(u => u.FirstName == "Joah");

Then I get a runtime error if I add a cast:

"Unable to cast object of type 'System.Collections.Generic.List`1[Domain.User]' to type 'Domain.User'."

User newUser = (User)uow.UserRepository.Get(u => u.FirstName == "Joah");

If I use "var" I see the object being returned but I need to cast it as "User" :-(
Why this happens?

A: This happens because you are querying and the result is a set where anyone that has the first name of Joah gets returned. What happens if there are multiple results? That is something you may want to consider here.
However, a simple way to fix this is to just take the first one
User newUser = uow.UserRepository.Get(u => u.FirstName == "Joah").FirstOrDefault();

A: uow.UserRepository.Get(u => u.FirstName == "Joah");
this is returning a List of things (all the people with that first name).
if you just want the first one, use
User newUser = uow.UserRepository.Get(u => u.FirstName == "Joah").FirstOrDefault();

A: Your call toe Get(u => u.FirstName == "Joah") is returning a collection (all users with the first name Joah) and you're trying to set that to the newUser variable.
So that's what's happening.
What will make the code compile is
User newUser = uow.UserRepository.Get(u => u.FirstName == "Joah").FirstOrDefault();

But remember...

*

*That's just the first one it finds. If you have more than 1 user named "Joah" then you might not return the right user.

*FirstOrDefault() could return null if no item was found. You could use First() instead, which doesn't return null, but does throw an exception when there is nothing found (ie. no User with first name "Joah")


text:
Q: Libgit2sharp, Pushing a specific branch to new remote I am writing a dotnet api to clone from github, then push a specific branch to AWS codecommit using the Libgit2sharp library.

*

*I have two branches in the gitHubRepo, origin/release and origin/refactor.

*origin/release is the DEFAULT git branch

*I want to clone the gitHubRepo, and push the origin/refactor branch to codecommit

Problem:
I can't seem to get it to push my specified branch to codecommit, it always seems to push what is set to HEAD. I don't know how to change the HEAD, or even know if this is the issue.
Code Snippet:
var baseRefBranch = gitHubRepo.Branches[$"origin/refactor"];
if (baseRefBranch == null) throw new Exception("refactor branch was null...");

logger.LogInformation($"Checking out branch: {baseRefBranch.CanonicalName}");
Commands.Checkout(gitHubRepo, baseRefBranch);

logger.LogInformation($"Update branch {baseRefBranch.CanonicalName}, set remote name {codeCommitRemote.Name}, set upstreamBranch to {baseRefBranch.CanonicalName}");
        gitHubRepo.Branches.Update(baseRefBranch,
            b => b.Remote = codeCommitRemote.Name,
            b => b.UpstreamBranch = baseRefBranch.CanonicalName);

var refSpec = $"+{baseRefBranch.CanonicalName}";
logger.LogInformation($"Trying to push to remote: {codeCommitRemote.Name}, refSpec: {refSpec}");
gitHubRepo.Network.Push(codeCommitRemote, refSpec, pushOptions);

Any help appreciated... Cheers

A: Try and use a complete refsepc when pushing

The format of a <refspec> parameter is an optional plus +, followed by the source object <src>, followed by a colon :, followed by the destination ref <dst>.

In your case:
+refs/heads/refactor:refs/heads/refactor


text:
Q: Crear fichero de logs en xamarin forms para aplicación multiplataforma estoy tratando de añadir una forma de deputar los fallos que se den en mi aplicación multiplataforma desarrollada en xamarin forms.
Al depurar en visual studio es fácil ver donde se encuentras los errores, o donde saltan las excepciones ya que la consola te da la información a cerca de ello, pero ahora el siguiente paso el archivar la aplicación y ejecutarla en un móvil Android o en un ordenador con Windows 10 a fin de probarla a fondo. Aquí es donde viene el problema ya que cuando salta un error en plena ejecución únicamente obtienes el mensaje de que surgió un problema y se cierra la aplicación o se cierra la aplicación directamente sin previo aviso.
Conocéis algún método mas eficaz que crear un fichero a mano y escribirlo cada poco para que pueda crear un log en cada plataforma con cada ejecución de la aplicación?
Muchas gracias de antemano, ojala alguien sepa de alguna posible solución.

A: Te recomiendo que uses alguna plataforma que te permita gestionar errores. A mi personalmente me gusta mucho https://appcenter.ms/
Das de alta en la web tu aplicación y te da una ID, bajas su sdk y pones la ID y en cuanto se use la aplicación empezara a recopilar información.
Sin que hagas nada más ya te dira información de uso (cantidad de usuarios, duración de sesiones, dispositivos, version, etc...) y ademas te dara un registro de excepciones no controladas.
Ademas puedes añadir tu tanto control de excepciones como de eventos concretos (los eventos los puedes ver en tiempo real).
Esa plataforma tambien te permite desplegar a usuarios en pruebas (sin pasar por la store) y probar notificaciones push.


text:
Q: why do we need word && '' in {text.split(' ').map((word) => word && '').join(' ') I am following react native docs and I came across this code which converts words to . I tried to modify the code line {text.split(' ').map((word) => word && '').join(' ')} to {text.split(' ').map((word) =>'').join(' ')} (I removed "word &&" ) and it is working exactly same. My doubt is why we need what is the functionality of word && ''. I know "&&" is conditional and, but I am not getting its purpose

import React, { useState } from 'react';
import { Text, TextInput, View } from 'react-native';

const PizzaTranslator = () => {
  const [text, setText] = useState('helloworld');
  return (
    <View style={{padding: 10}}>
      <TextInput
        style={{height: 80}}
        placeholder="Type here to translate!"
        onChangeText={(text) =>{ setText(text)}}
        defaultValue={text}
      />
      <Text style={{padding: 10, fontSize: 42}}>
        {text.split(' ').map((word) => word && '').join(' ')}
      </Text>
    </View>
  );
}

export default PizzaTranslator;

A: It's there to avoid translating double spaces into an extraneous pizza (since the empty string is falsy).
>>> "hello world".split(' ').map((word) => word && '').join(' ')
" "
>>> "hello    world".split(' ').map((word) => word && '').join(' ')
"    "
>>> "hello    world".split(' ').map((word) => '').join(' ')
"    "


text:
Q: COUNT for every GROUP BY with non existent values I have the following table
id  rid     eId     vs  isN
24  3   22  2   1
25  3   21  2   1
26  60  21  2   1
27  60  21  2   1
28  60  21  2   1
29  60  21  2   1
30  60  21  2   1
31  60  21  2   1
32  81  21  2   1
35  60  22  2   1
36  81  22  2   1
37  0   22  2   1
38  60  22  2   1
39  81  22  2   1
40  0   22  2   1
41  60  22  2   1
42  81  22  2   1
43  3   22  2   1

On eId i have 8 different numbers
I want to count this eight different eid , even counted as "0" what i want to get is an array contain 8 values and the keys should be the eight different names. "vs" is 3 different numbers every time i count
i want for this on "rid" = %d and "vs" = %d  ( specific rid and specific vs)
SELECT count(*) as count FROM notification
WHERE rid = 60 AND vs = 2 AND isN = 1 GROUP BY eId

rid=>60,21=>6,22=>3,vs=>2,isN=>1

(this is what i get with the above)
rid=>60,21=>6,22=>3,23=>0,33=>0,34=>0,35=>0,36=>0,41=>0,42=>0,vs=>2,isN=>1

(this is what i want. eight counted, of course this numbers counted not existed on eId so i want to return as a zero)

A: What you need is a driver table that has all the values you want to output.  You can then left outer join this to the actual data:
SELECT count(notification.eid) as count
FROM (select distinct eid
      from notification
     ) drivers left outer join
     (select *
      from notification
      WHERE rid = %d AND vs = %d AND isN = 1
     ) n
     on driver.eid = notification.eid
GROUP BY driver.eId

You should also include the eid in the select clause, unless you are depending on the final ordering of the output (MySQL, unlike any other database, does guarantee the ordering of results after a group by.)

A: Here's one way to get the specified resultset:
 SELECT d.rid           AS `rid`
      , SUM(n.eid<=>21) AS `21`
      , SUM(n.eid<=>22) AS `22`
      , SUM(n.eid<=>23) AS `23`
      , SUM(n.eid<=>33) AS `33`
      , SUM(n.eid<=>34) AS `34`
      , SUM(n.eid<=>35) AS `35`
      , SUM(n.eid<=>36) AS `36`
      , SUM(n.eid<=>41) AS `41`
      , SUM(n.eid<=>42) AS `42`
      , d.vs            AS `vs`
      , d.isN           AS `isN`
   FROM ( SELECT %d AS rid, %d AS vs, 1 AS isN ) d
   LEFT
   JOIN notification n
     ON n.rid = d.rid
    AND n.vs  = d.vs
    AND n.isN = d.isN
  GROUP
     BY d.rid
      , d.vs
      , d.isN

Note: the expression (n.eid<=>21) is shorthand for IF(n.eid=21,1,0), or the more ANSI-standard CASE WHEN n.eid = 21 THEN 1 ELSE 0 END.  That gives a 0 or a 1, which can then be aggregated with a SUM function.
You could get equivalent results using any of these forms:
     , SUM(n.eid<=>21)                             AS `21`
     , COUNT(IF(n.eid=22,1,NULL))                  AS `22`
     , SUM(IF(n.eid=23,1,0))                       AS `23`
     , COUNT(CASE WHEN n.eid = 33 THEN 1 END)      AS `33`
     , SUM(CASE WHEN n.eid = 34 THEN 1 ELSE 0 END) AS `34`

The "trick" we are using here is that we are guaranteed that the inline view aliased as d will return one row. Then we are using a LEFT JOIN operator to pick up all "matching" rows from the notification table. The GROUP BY is going to force all those rows to be collapsed (aggregated) back down to a single row. And we are using a conditional test on each row to see if it is to be included in a given count or not, the "trick" is to return a 0 or a 1, for each row, and then add up all the 0s and 1s to get a count.
NOTE: If you use a COUNT(expr) aggregate, you want that expr to return a non-NULL when the row is to be included in the count, and a NULL when the row is not to be included in the count.
If you use a SUM(expr), then you want expr to return a 1 when the row is to be included in the count, and return a 0 when it's not.  (We want a 0 rather than a NULL so that we will be guaranteed that SUM(expr) will return a "zero count" (i.e a 0 rather than a NULL)  when there are no rows to be included.  (Of course, we could use an IFNULL function to replace a NULL with a 0, but in this case it's simple enough to avoid the need for that.)

Note that one advantage of this approach to "counting" is that it can easily extended to get "combined" counts, or to include a row in several different counts. e.g.
    , SUM(IF(n.eid IN (41,42),1,0)) AS `total_41_and_42`

would get us a total count of eid=41 and eid=42 rows. (That's not such a great example, because we could just as easily calculate that on the client side by adding the two counts together. But that really becomes an advantage if you were doing more elaborate counts, and wanted to count a single row in multiple columns ...
   , SUM(IF(n.eid=42,1,0))            AS eid_42
   , SUM(IF(n.eid=42 AND foo=1,1,0)   AS eid_42_foo_1
   , SUM(IF(n.eid=42 AND foo=2,1,0))  AS eid_42_foo_2

We can get all those separate counts with just "one pass" through notification table. If we tried to do those checks in the WHERE clause, we'd likely need multiple passes through the table.

A: So, essentially what you're looking for is this?...
 SELECT rid,eid,vs, COUNT(*) FROM notification GROUP BY rid,eid,vs;
 +-----+-----+----+----------+
 | rid | eid | vs | COUNT(*) |
 +-----+-----+----+----------+
 |   0 |  22 |  2 |        2 |
 |   3 |  21 |  2 |        1 |
 |   3 |  22 |  2 |        2 |
 |  60 |  21 |  2 |        6 |
 |  60 |  22 |  2 |        3 |
 |  81 |  21 |  2 |        1 |
 |  81 |  22 |  2 |        3 |
 +-----+-----+----+----------+
 7 rows in set (0.11 sec)


text:
Q: about a criterion for compacted and connected sets in $\mathbb{R^{n}}$ The next exercise had been difficult for me. Any help is welcome, thanks.
Be $K$ a subset sequentially compact of $\mathbb{R^{n}}$. Proof that $K$ is not connected iff exist two nonempty subsets  $A$ and $B$ of $K$, disjoint, with $A \cup B = K$ and  $\varepsilon > 0$ such that $||u-v||> \varepsilon$ for all $u \in A$ and $v \in B$.
At the end also have to respond this question: is needed the assumption of sequential compactness for the existence of such an $\varepsilon$?
i attempted to prove it first supposing that if this set is not connected then there exists two open sets U and V that separate the set K and supposing that there is no such an $\varepsilon$ that arrives two sequences one in $U \cap K$ and the other in $V \cap K$ that converge to the same point. From there i know that this limit is in $K$ but i don't know where comes the contradiction i need.

A: The fact is that $A$ and $B$ are closed by the assumption that $K$ is not connected. But closed in compact set implies compact and two disjoint compact set in a metric space have always positive distance. We can use the following:
Lemma: if $A \subset \mathbb{R}^n$ is compact, $B \subset \mathbb{R}^n$ is closed and $A \cap B = \emptyset$ then $d(A,B)>0$.
Proof: the function $f(x)=d(x,B)$ for $x \in \mathbb{R}^n$ is well defined and since A is compact $f$ has a minimum in $A$, which is strictly positive since $A$ and $B$ are disjoint sets.
Remark 1: the "if" proof is clearer. In fact you might consider $U = \{x \in K : d(x,A) < \frac{\varepsilon}{2}$ and $V= U = \{x \in K: d(x,B) < \frac{\varepsilon}{2}$ which are an open partition of $K$
Remark 2: in a metric space sequentially compact and compact are equivalent.
Remark 3: you need compactness because you might think of $A= \mathbb{R} \times \{0\} \subset \mathbb{R} \times \mathbb{R}$ and $B = graph(exp) \subset \mathbb{R} \times \mathbb{R}$. $K = A \cap B$ have not that property.


text:
Q: Using postgis functions in hibernate SQL Query I need to execute select ST_AsText(column_name) from table using hibernate createSQlQuery().
When i executed that query, it shows that the column name is not found in the result set.
But when i execute the same query in my PGAdmin browser, the query works.
Query query = session.createSQLQuery("select ST_AsText(END2536) from country   where        object='something'");
((SQLQuery) query).addScalar(column, Hibernate.STRING);
String geomValue = (String) query.uniqueResult();
query.setCacheable(true);
query.setCacheRegion("query.CommonManagement");

Error Msg:
16:56:27,076 INFO  [org.hibernate.type.StringType] (http--172.20.211.235-8080-1) could not read column value from result set: END2536; The column name END2536 was not found in this ResultSet.
16:56:27,077 WARN  [org.hibernate.util.JDBCExceptionReporter] (http--172.20.211.235-8080-1) SQL Error: 0, SQLState: 42703
16:56:27,077 ERROR [org.hibernate.util.JDBCExceptionReporter] (http--172.20.211.235-8080-1) The column name END2536 was not found in this ResultSet.
16:56:27,080 ERROR [stderr] (http--172.20.211.235-8080-1) org.hibernate.exception.SQLGrammarException: could not execute query

What am i missing here?

A: The error message is quite clear - says

The column name END2536 was not found in this ResultSet.

So if you say it work in the client, it seems that Hibernate changes the query somehow.
Enable SQL queries logging as described here and check what Hibernate sends.

A: You need to add additional quotes since you are using capital letter(s) for the column name.
Query query = session.createSQLQuery("select ST_AsText(\"END2536\") from country   where        object='something'");

A: Thanks guys.I figured out the problem. It was because the result set had an alias name and I had enabled query caching. So the column name (END2536) was not in the result set. When i commented the query caching part, it works fine.


text:
Q: Mysql error 1054 in When statement Doing an inventory migration to a new schema. The old schema had one table, where the new schema has two and a foreign key linking the types of assets. Problem is with the foreign key part. I can't seem to get the foreign key to post on the asset table. I mostly have the logic figured out, but I'm running into an issue where the migration hits a 1054 error on a column that should exist.
Part throwing error is the " SELECT CASE WHEN (asset.category " bit.
ALTER TABLE `foreignkeytest`.`asset`
    ADD COLUMN `category` VARCHAR(255) NULL AFTER `parent_asset_id_asset_id`,
    ADD COLUMN `subcategory` VARCHAR(255) NULL AFTER `category`,
    ADD COLUMN `brand` VARCHAR(255) NULL AFTER `subcategory`,
    ADD COLUMN `model` VARCHAR(255) NULL AFTER `brand`;
ALTER TABLE `foreignkeytest`.`asset_type`;
ALTER TABLE `inventory`.`inv`;
INSERT IGNORE INTO `foreignkeytest`.`asset`
    (asset_id, category, subcategory, location, serial_number, brand, model, purchase_date, glacct, barcode_attached)
    SELECT id, category, subcategory, location, serialnumber, brand, itemtype, from_unixtime(purchasedate), glacct, barcode
    FROM `inventory`.`inv`;
INSERT IGNORE INTO `foreignkeytest`.`asset_type` (category, subcategory, brand, model)
    SELECT category, subcategory, brand, itemtype FROM `inventory`.`inv`;
INSERT INTO `foreignkeytest`.`asset` (asset_type_id)
    SELECT
        CASE
            WHEN (`asset`.`category` = `asset_type`.`category` AND
                `asset`.`subcategory` = `asset_type`.`subcategory` AND
                `asset`.`brand` = `asset_type`.`brand` AND
                `asset`.`model` = `asset_type`.`brand`) THEN 1
            ELSE 0
        END
    type_id FROM `foreignkeytest`.`asset_type`;
ALTER TABLE `foreignkeytest`.`asset` DROP COLUMN `category`, DROP COLUMN `subcategory`, DROP COLUMN `brand`, DROP COLUMN `model`;

Any reason why this wouldn't be working?
Edit: Fix for this issue was that I wasn't referencing the asset table for the select. Second to last line changed to:
type_id FROM `foreignkeytest`.`asset_type`, `foreignkeytest`.`asset`;

A: You  are referring to asset table but you are selecting  from  foreignkeytest
so the case column are wrongs try select from asset
    INSERT INTO `foreignkeytest`.`asset` (asset_type_id)
    SELECT
        CASE
            WHEN (`asset`.`category` = `asset_type`.`category` AND
                `asset`.`subcategory` = `asset_type`.`subcategory` AND
                `asset`.`brand` = `asset_type`.`brand` AND
                `asset`.`model` = `asset_type`.`brand`) THEN 1
            ELSE 0
        END
    type_id FROM `asset`.`asset_type`;